code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# -*- coding: utf-8 -*- # from datetime import datetime, timedelta from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.db import transaction from django.http import HttpResponse from django.shortcuts import render, redirect, get_object_or_404 as getObj from django.utils import timezone from django.utils.translation import ugettext from openpyxl import Workbook from openpyxl.writer.excel import save_virtual_workbook from webframe.functions import getDateTime, getDate, FMT_DATE, FMT_DATETIME, getEndOfDay from .models import Record import logging logger=logging.getLogger('sugar.views') def _getUser(req, username=None): if username: if req.user.is_superuser or req.user.username==username: return getObj(get_user_model(), username=username) else: return req.user raise PermissionDenied() def index(req): if req.user.is_authenticated(): return redirect('dashboard', username=req.user.username) return render(req, 'webframe/empty.html') @login_required def dashboard(req, username=None): user=_getUser(req, username) if req.method=='POST': logger.info('Saving record to user<%s>:%s...'%(user.id, user.username)) with transaction.atomic(): r=Record() r.owner=user r.date=getDateTime(req.POST.get('date')) r.sugar=req.POST.get('sugar', '0') r.sugar=float(r.sugar) if r.sugar else 0 r.pulse=req.POST.get('pulse', '0') r.pulse=int(r.pulse) if r.pulse else 0 r.sys=req.POST.get('sys', '0') r.sys=int(r.sys) if r.sys else 0 r.dia=req.POST.get('dia', '0') r.dia=int(r.dia) if r.dia else 0 r.save() return redirect('reports-user', username=username) if username else redirect('reports') return render(req, 'sugar/dashboard.html', {}) @login_required def reports(req, username=None): user=_getUser(req, username) params=dict() params['to']=getDate(req.GET.get('to', None), timezone.now()) params['to']=getEndOfDay(params['to']) #Due to the system should include the selected date instead params['from']=getDate(req.GET.get('from', None), params['to']-timedelta(days=30)) params['target']=Record.objects.filter(owner=user, date__range=(params['from'], params['to'])).order_by('date') return render(req, 'sugar/reports.html', params) @login_required def downloads(req, username=None): user=_getUser(req, username) params=dict() params['to']=getDate(req.GET.get('to', None), datetime.now()) params['from']=getDate(req.GET.get('from', None), params['to']-timedelta(days=30)) params['target']=Record.objects.filter(owner=user, date__range=(params['from'], params['to'])).order_by('date') logger.debug(params['target']) filename=ugettext('From %(from)s to %(to)s'%params) wb=Workbook() ws=wb.active ws.merge_cells('A1:G1') ws['A1']=filename ws['A2']=ugettext('Record.owner') ws['B2']=user.get_full_name() if user.get_full_name() else user.username ws['A3']=ugettext('from') ws['B3']=params['from'].strftime(FMT_DATE) ws['A4']=ugettext('to') ws['B4']=params['to'].strftime(FMT_DATE) ws.cell(row=5, column=3, value=ugettext('Record.date')) ws.cell(row=5, column=4, value=ugettext('Record.sugar')) ws.cell(row=5, column=5, value=ugettext('Record.pulse')) ws.cell(row=5, column=6, value=ugettext('Record.sys')) ws.cell(row=5, column=7, value=ugettext('Record.dia')) row=6 for r in params['target']: ws.cell(row=row, column=3, value=timezone.localtime(r.date).strftime(FMT_DATETIME)) ws.cell(row=row, column=4, value=r.sugar) ws.cell(row=row, column=5, value=r.pulse) ws.cell(row=row, column=6, value=r.sys) ws.cell(row=row, column=7, value=r.dia) row+=1 rst=HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') rst['Content-Disposition'] = 'attachment; filename=\"%s.xlsx\"'%filename return rst
kensonman/mansonsolutions.sugar
src/sugar/views.py
Python
apache-2.0
4,129
<?php /** * This file is part of the SfAdvanced package. * (c) SfAdvanced Project (http://www.sfadvanced.jp/) * * For the full copyright and license information, please view the LICENSE * file and the NOTICE file that were distributed with this source code. */ class saPluginDeactivateTask extends sfBaseTask { protected function configure() { $this->addArguments(array( new sfCommandArgument('name', sfCommandArgument::REQUIRED, 'The plugin name'), )); $this->addOptions(array( new sfCommandOption('application', null, sfCommandOption::PARAMETER_OPTIONAL, 'The application name', null), new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'prod'), )); $this->namespace = 'saPlugin'; $this->name = 'deactivate'; $this->briefDescription = 'Deactivates the installed plugin.'; $this->detailedDescription = <<<EOF The [saPlugin:deactivate|INFO] task deactivates the installed plugin. Call it with: [./symfony saPlugin:deactivate saSamplePlugin|INFO] EOF; } protected function execute($arguments = array(), $options = array()) { $configuration = $this->createConfiguration('pc_frontend', 'cli'); $name = $arguments['name']; if (!$configuration->isPluginExists($name)) { throw new sfException(sprintf('Plugin "%s" does not installed', $name)); } if ($configuration->isDisabledPlugin($name)) { throw new sfException(sprintf('Plugin "%s" is already disactivated', $name)); } saPlugin::getInstance($name)->setIsActive(false); $cc = new sfCacheClearTask($this->dispatcher, $this->formatter); $cc->run(); } }
kashiwasan/symfony-advanced
lib/task/saPluginDeactivateTask.class.php
PHP
apache-2.0
1,691
import mongo.MongoOperations import org.chepurnoy.timeseries.{TimeSeriesDatum, TimeSeriesStringDatum, TimeSeriesDoubleDatum} import org.joda.time.DateTime import org.specs2.mutable.Specification import scala.concurrent.Await import scala.concurrent.duration._ class IntegrationSpec extends Specification{ val db = new MongoOperations(List("localhost"),"test") val duration = Duration(1, SECONDS) def testWriteMongo(basket:String, timeSeries:TimeSeriesDatum) = { val writeResult = timeSeries match { case d:TimeSeriesDoubleDatum => Await.result(db.put(basket,d),duration) case s:TimeSeriesStringDatum => Await.result(db.put(basket,s),duration) } writeResult mustEqual true } "montool" should { "correctly write and read double and string in org.chepurnoy.timeseries.mongo" in { val basket = "basket" val timeSeriesTest1 = TimeSeriesDoubleDatum(6.0,new DateTime(1381436764)) val timeSeriesTest2 = TimeSeriesStringDatum("string",new DateTime(1381436763)) val timeSeriesTest3 = TimeSeriesStringDatum("str",new DateTime(1381436767)) testWriteMongo(basket,timeSeriesTest1) testWriteMongo(basket,timeSeriesTest2) testWriteMongo(basket,timeSeriesTest3) val f = db.get(basket,2) val results = Await.result(f, duration) new DropCollectionMongo(List("localhost"),"test").dropCollection(basket) results.data.map{datum =>{ datum match{ case d:TimeSeriesDoubleDatum=> d.value mustEqual 6.0 case s:TimeSeriesStringDatum=> s.value must contain("string") case _=> throw new Exception } } } } } }
kushti/timeseries
src/test/scala/IntegrationSpec.scala
Scala
apache-2.0
1,669
#/bin/sh #start or stop the im-server LOGIN_SERVER=login_server MSG_SERVER=msg_server ROUTE_SERVER=route_server HTTP_MSG_SERVER=http_msg_server FILE_SERVER=file_server PUSH_SERVER=push_server DB_PROXY_SERVER=db_proxy_server MSFS=msfs function restart() { cd $1 if [ ! -e *.conf ] then echo "no config file" return fi if [ -e server.pid ]; then pid=`cat server.pid` echo "kill pid=$pid" kill $pid while true do oldpid=`pgrep $1`; if [ $oldpid" " == $pid" " ]; then echo $oldpid" "$pid sleep 1 else break fi done ../daeml ./$1 else ../daeml ./$1 fi } case $1 in $LOGIN_SERVER) restart $1 ;; $MSG_SERVER) restart $1 ;; $ROUTE_SERVER) restart $1 ;; $HTTP_MSG_SERVER) restart $1 ;; $FILE_SERVER) restart $1 ;; $PUSH_SERVER) restart $1 ;; $DB_PROXY_SERVER) restart $1 ;; $MSFS) restart $1 ;; all) restart $LOGIN_SERVER cd .. restart $MSG_SERVER cd .. restart $ROUTE_SERVER cd .. restart $MSFS cd .. restart $HTTP_MSG_SERVER cd .. restart $FILE_SERVER cd .. restart $PUSH_SERVER cd .. restart $DB_PROXY_SERVER ;; *) echo "Usage: " echo " ./restart.sh (login_server|msg_server|route_server|http_msg_server|file_server|push_server|msfs|all)" ;; esac
zqiang/TeamTalk
server/run/restart.sh
Shell
apache-2.0
1,434
/* * Copyright 2019 EPAM Systems * * 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. */ export { InputCheckbox } from './inputCheckbox';
reportportal/service-ui
app/src/components/inputs/inputCheckbox/index.js
JavaScript
apache-2.0
642
package model // ArgBind bind args. type ArgBind struct { OpenID string OutOpenID string AppID int64 } // ArgBindInfo bind info args. type ArgBindInfo struct { Mid int64 AppID int64 } // ArgThirdPrizeGrant prize grant args. type ArgThirdPrizeGrant struct { Mid int64 `form:"mid" validate:"required"` PrizeKey int64 `form:"prize_key"` UniqueNo string `form:"unique_no" validate:"required"` PrizeType int8 `form:"prize_type" validate:"required"` Appkey string `form:"appkey" validate:"required"` Remark string `form:"remark" validate:"required"` AppID int64 } // ArgBilibiliPrizeGrant args. type ArgBilibiliPrizeGrant struct { PrizeKey string UniqueNo string OpenID string AppID int64 } // BilibiliPrizeGrantResp resp. type BilibiliPrizeGrantResp struct { Amount float64 FullAmount float64 Description string }
LQJJ/demo
126-go-common-master/app/service/main/vip/model/associate_params.go
GO
apache-2.0
875
package com.f2prateek.rx.preferences2; import android.annotation.TargetApi; import android.content.SharedPreferences; import androidx.annotation.NonNull; import java.util.Set; import static android.os.Build.VERSION_CODES.HONEYCOMB; import static java.util.Collections.unmodifiableSet; @TargetApi(HONEYCOMB) final class StringSetAdapter implements RealPreference.Adapter<Set<String>> { static final StringSetAdapter INSTANCE = new StringSetAdapter(); @NonNull @Override public Set<String> get(@NonNull String key, @NonNull SharedPreferences preferences, @NonNull Set<String> defaultValue) { return unmodifiableSet(preferences.getStringSet(key, defaultValue)); } @Override public void set(@NonNull String key, @NonNull Set<String> value, @NonNull SharedPreferences.Editor editor) { editor.putStringSet(key, value); } }
f2prateek/rx-preferences
rx-preferences/src/main/java/com/f2prateek/rx/preferences2/StringSetAdapter.java
Java
apache-2.0
852
#ifndef DOBBY_SYMBOL_RESOLVER_H #define DOBBY_SYMBOL_RESOLVER_H #ifdef __cplusplus extern "C" { #endif void *DobbySymbolResolver(const char *image_name, const char *symbol_name); #ifdef __cplusplus } #endif #endif
jmpews/HookZz
builtin-plugin/SymbolResolver/dobby_symbol_resolver.h
C
apache-2.0
217
# Heterococcus fuornensis Vischer SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Chromista/Ochrophyta/Xanthophyceae/Tribonematales/Heteropediaceae/Heterococcus/Heterococcus fuornensis/README.md
Markdown
apache-2.0
189
'use strict'; const nock = require('nock'); const watson = require('../../index'); const authHelper = require('./auth_helper.js'); const auth = authHelper.auth; const describe = authHelper.describe; // this runs describe.skip if there is no auth.js file :) const TWENTY_SECONDS = 20000; const TWO_SECONDS = 2000; describe('language_translator_integration', function() { this.timeout(TWENTY_SECONDS * 2); this.slow(TWO_SECONDS); // this controls when the tests get a colored warning for taking too long this.retries(1); let language_translator; before(function() { language_translator = watson.language_translator(auth.language_translator); nock.enableNetConnect(); }); after(function() { nock.disableNetConnect(); }); it('getModels()', function(done) { language_translator.getModels(null, done); }); it('translate()', function(done) { const params = { text: 'this is a test', source: 'en', target: 'es' }; language_translator.translate(params, done); }); it('getIdentifiableLanguages()', function(done) { language_translator.getIdentifiableLanguages(null, done); }); it('identify()', function(done) { const params = { text: 'this is an important test that needs to work' }; language_translator.identify(params, done); }); });
JohnBorkowski/node-sdk
test/integration/test.language_translator.js
JavaScript
apache-2.0
1,335
package org.gradle.test.performance.mediummonolithicjavaproject.p383; public class Production7669 { private Production7666 property0; public Production7666 getProperty0() { return property0; } public void setProperty0(Production7666 value) { property0 = value; } private Production7667 property1; public Production7667 getProperty1() { return property1; } public void setProperty1(Production7667 value) { property1 = value; } private Production7668 property2; public Production7668 getProperty2() { return property2; } public void setProperty2(Production7668 value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
oehme/analysing-gradle-performance
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p383/Production7669.java
Java
apache-2.0
1,963
/* Copyright 2019 The TensorFlow 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. ==============================================================================*/ #include "tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" // TF:llvm-project #include "mlir/IR/Function.h" // TF:llvm-project #include "mlir/IR/MLIRContext.h" // TF:llvm-project #include "mlir/IR/OpDefinition.h" // TF:llvm-project #include "mlir/IR/StandardTypes.h" // TF:llvm-project #include "mlir/Parser.h" // TF:llvm-project #include "mlir/Pass/Pass.h" // TF:llvm-project #include "mlir/Pass/PassManager.h" // TF:llvm-project #include "mlir/Transforms/Passes.h" // TF:llvm-project #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/shape_inference.h" #include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h" #include "tensorflow/compiler/mlir/tensorflow/utils/convert_type.h" #include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/translate_utils.h" #include "tensorflow/compiler/mlir/xla/mlir_hlo_to_hlo.h" #include "tensorflow/compiler/mlir/xla/transforms/passes.h" #include "tensorflow/compiler/mlir/xla/type_to_shape.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { namespace { // Parses the MLIR module from the mlir_module_string. Status ParseMlirModule(llvm::StringRef mlir_module_string, mlir::MLIRContext* mlir_context, mlir::OwningModuleRef* mlir_module) { TF_RET_CHECK(!mlir_module_string.empty()) << "unexpected empty serialized MLIR module string"; TF_RET_CHECK(mlir_module) << "unexpected null MLIR module pointer"; // Make sure we catch any error reported by MLIR and forward it to the TF // error reporting system. mlir::StatusScopedDiagnosticHandler error_handler(mlir_context); // Parse the module. *mlir_module = mlir::parseSourceString(mlir_module_string, mlir_context); if (!*mlir_module) { return error_handler.Combine( errors::InvalidArgument("could not parse MLIR module")); } return Status::OK(); } // Converts arg_shapes to xla::Shape's and store into xla_input_shapes. Status GetXlaInputShapes( mlir::ModuleOp module, llvm::ArrayRef<TensorShape> arg_shapes, const xla::CustomShapeRepresentationFn shape_representation_fn, std::vector<xla::Shape>* xla_input_shapes) { xla_input_shapes->clear(); mlir::FuncOp main_func = module.lookupSymbol<mlir::FuncOp>("main"); mlir::FunctionType func_type = main_func.getType(); int num_args = func_type.getNumInputs(); xla_input_shapes->reserve(num_args); std::vector<xla::Shape> individual_arg_shapes; individual_arg_shapes.reserve(num_args); for (int i = 0; i < num_args; ++i) { individual_arg_shapes.emplace_back(); xla::Shape& xla_shape = individual_arg_shapes.back(); DataType dtype; TF_RETURN_IF_ERROR(ConvertToDataType(func_type.getInput(i), &dtype)); TF_ASSIGN_OR_RETURN(xla_shape, shape_representation_fn(arg_shapes[i], dtype)); } xla_input_shapes->push_back( xla::ShapeUtil::MakeTupleShape(individual_arg_shapes)); return Status::OK(); } // Calculates computation output shape and build OutputDescription for each // output based on static shapes in MLIR module Status GetOutputInfo( mlir::ModuleOp module, const xla::CustomShapeRepresentationFn shape_representation_fn, xla::Shape* xla_output_shape, std::vector<XlaCompiler::OutputDescription>* outputs) { mlir::FuncOp main_func = module.lookupSymbol<mlir::FuncOp>("main"); mlir::FunctionType func_type = main_func.getType(); outputs->clear(); outputs->reserve(func_type.getNumResults()); std::vector<xla::Shape> shapes; shapes.reserve(func_type.getNumResults()); for (mlir::Type type : func_type.getResults()) { TF_ASSIGN_OR_RETURN(xla::Shape shape, TypeToShape(type, shape_representation_fn)); auto tensor_type = type.dyn_cast<mlir::RankedTensorType>(); shapes.push_back(shape); // Construct OutputDescription for result. outputs->emplace_back(); XlaCompiler::OutputDescription& out_desc = outputs->back(); TF_RETURN_IF_ERROR(ConvertToDataType(tensor_type, &out_desc.type)); // TODO(ycao): Support constant output. out_desc.is_constant = false; TF_RETURN_IF_ERROR(XLAShapeToTensorShape(shape, &out_desc.shape)); // Input_index is only meaningful for resource output. Since MLIR-based // TF-Compiler bridge doesn't support resource output yet. Setting it to // meaningless value -1. // TODO(ycao): Support resource-type output. out_desc.input_index = -1; // MLIR-based TF-Compiler bridge doesn't support tensorlist output yet. // TODO(ycao): Support tensorlist-type output. out_desc.is_tensor_list = false; } // XLA computation always uses Tuple shape. *xla_output_shape = xla::ShapeUtil::MakeTupleShape(shapes); return Status::OK(); } // Gets information about how computation updates Tensorflow resources. // TODO(ycao): Implement logic to compute resource updates when we need to // support graphs with resource updates in MLIR-based TF compiler bridge. void GetResourceUpdatesForMlir( std::vector<XlaCompiler::ResourceUpdate>* resource_updates) { resource_updates->clear(); } // Creates a vector that maps from the parameters of the XLA computation to // their original argument positions. // MLIR-based TF-Compiler bridge doesn't have constant analysis yet, thus no // inputs are known constants. Therefore, the input mapping between input to // computation arguments is a trivial in-order 1-1 mapping. // TODO(ycao): Support computation with compile-time constant, which requires // non-trivial input mapping as implemented now. void GetInputMappingForMlir(int num_inputs, std::vector<int>* input_mapping) { input_mapping->resize(num_inputs, 0); std::iota(input_mapping->begin(), input_mapping->end(), 0); } // Refine MLIR types based on new shape information. Status RefineShapes(llvm::ArrayRef<TensorShape> arg_shapes, mlir::ModuleOp module) { auto producer_or = GetTfGraphProducerVersion(module); if (!producer_or.ok()) return producer_or.status(); int64_t producer_version = producer_or.ValueOrDie(); llvm::SmallVector<int64_t, 16> shape_backing; llvm::SmallVector<llvm::ArrayRef<int64_t>, 4> arg_shapes_copy; { // Convert arg_shapes to a mlir friendly format. size_t count = 0; for (const TensorShape& shape : arg_shapes) { count += shape.dims(); } shape_backing.resize(count); arg_shapes_copy.reserve(arg_shapes.size()); size_t offset = 0; for (const TensorShape& shape : arg_shapes) { size_t start = offset; for (tensorflow::TensorShapeDim dim : shape) { shape_backing[offset] = dim.size; ++offset; } if (offset == start) { arg_shapes_copy.push_back(llvm::ArrayRef<int64_t>()); } else { arg_shapes_copy.push_back( llvm::ArrayRef<int64_t>(&shape_backing[start], offset - start)); } } } auto main_func = module.lookupSymbol<mlir::FuncOp>("main"); mlir::StatusScopedDiagnosticHandler error_handler(module.getContext()); mlir::LogicalResult result = mlir::TF::InferShapeForFunction( main_func, arg_shapes_copy, producer_version); if (failed(result)) { return error_handler.Combine( errors::Internal("MLIR Shape refinement failed")); } return Status::OK(); } } // namespace Status ConvertMLIRToXlaComputation(mlir::ModuleOp module_op, xla::XlaComputation* xla_computation, bool use_tuple_args, bool return_tuple) { mlir::PassManager tf2xla(module_op.getContext()); tf2xla.addPass(mlir::tf_executor::CreateTFExecutorGraphPruningPass()); tf2xla.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass()); tf2xla.addPass(mlir::TF::CreateTensorListOpsDecompositionPass()); tf2xla.addPass(mlir::TF::CreateStackOpsDecompositionPass()); tf2xla.addPass(mlir::TFDevice::CreateDecomposeResourceOpsPass()); tf2xla.addPass(mlir::TF::CreatePromoteResourcesToArgsPass()); // LegalizeTFControlFlow encapsulates arguments for control flow operations // with a tuple argument which break the assumption of resource lifting // inside PromoteResourcesToArgs. tf2xla.addPass(mlir::xla_hlo::createLegalizeTFControlFlowPass()); // We need to run LegalizeTFPass 2 times because first // LegalizeTFPass(allow_partial_conversion=true) can expose more graph pruning // and canonicalization opportunities that are necessary for the second // LegalizeTFPass(allow_partial_conversion=false) invocation. tf2xla.addNestedPass<mlir::FuncOp>(mlir::xla_hlo::createLegalizeTFPass(true)); tf2xla.addPass(mlir::tf_executor::CreateTFExecutorGraphPruningPass()); tf2xla.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass()); tf2xla.addNestedPass<mlir::FuncOp>( mlir::xla_hlo::createLegalizeTFPass(false)); if (VLOG_IS_ON(1)) { // Print the whole module after each pass which requires disabling // multi-threading as well. tf2xla.disableMultithreading(); tf2xla.enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>( /*print_module_scope=*/true)); } // Make sure we catch any error reported by MLIR and forward it to the TF // error reporting system. Report a generic error if pass manager failed // without emitting a diagnostic. mlir::StatusScopedDiagnosticHandler error_handler(module_op.getContext()); if (failed(tf2xla.run(module_op))) { return error_handler.Combine( errors::Internal("MLIR TF to XLA legalization failed")); } if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_legalize_hlo", module_op); xla::HloProto hlo_proto; TF_RETURN_IF_ERROR(mlir::ConvertMlirHloToHlo(module_op, &hlo_proto, use_tuple_args, return_tuple)); *xla_computation = xla::XlaComputation(hlo_proto.hlo_module()); return Status::OK(); } Status CompileSerializedMlirToXlaHlo( llvm::StringRef mlir_module_string, llvm::ArrayRef<TensorShape> arg_shapes, const XlaCompiler::ShapeRepresentationFn shape_representation_fn, XlaCompiler::CompilationResult* compilation_result) { mlir::MLIRContext mlir_context; mlir::OwningModuleRef mlir_module; TF_RETURN_IF_ERROR( ParseMlirModule(mlir_module_string, &mlir_context, &mlir_module)); auto module_op = mlir_module.get(); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_before", module_op); // Use arg_shapes to improve the mlir type information of `main` in module_op. TF_RETURN_IF_ERROR(RefineShapes(arg_shapes, module_op)); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_shape_refiner", module_op); // Convert MLIR module to XLA HLO proto contained in XlaComputation. compilation_result->computation = std::make_shared<xla::XlaComputation>(); TF_RETURN_IF_ERROR(ConvertMLIRToXlaComputation( module_op, compilation_result->computation.get(), /*use_tuple_args=*/true, /*return_tuple=*/true)); // Construct mapping from XlaComputation's arg to input edges of execute // node. GetInputMappingForMlir(arg_shapes.size(), &compilation_result->input_mapping); auto shape_representation_fn_no_fast_memory = [shape_representation_fn](const TensorShape& shape, DataType dtype) { return shape_representation_fn(shape, dtype, /*use_fast_memory=*/false); }; // Compute all input shapes. TF_RETURN_IF_ERROR(GetXlaInputShapes(module_op, arg_shapes, shape_representation_fn_no_fast_memory, &compilation_result->xla_input_shapes)); // Compute all output descriptions. TF_RETURN_IF_ERROR(GetOutputInfo( module_op, shape_representation_fn_no_fast_memory, &compilation_result->xla_output_shape, &compilation_result->outputs)); // Compute what resource variables need to be updated after XlaComputation's // execution. GetResourceUpdatesForMlir(&compilation_result->resource_updates); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_after", module_op); return Status::OK(); } } // namespace tensorflow
xzturn/tensorflow
tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.cc
C++
apache-2.0
13,146
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>JsonException - com.ligadata.Serialize.JsonException</title> <meta name="description" content="JsonException - com.ligadata.Serialize.JsonException" /> <meta name="keywords" content="JsonException com.ligadata.Serialize.JsonException" /> <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"> if(top === self) { var url = '../../../index.html'; var hash = 'com.ligadata.Serialize.JsonException'; 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="type"> <div id="definition"> <img src="../../../lib/class_big.png" /> <p id="owner"><a href="../../package.html" class="extype" name="com">com</a>.<a href="../package.html" class="extype" name="com.ligadata">ligadata</a>.<a href="package.html" class="extype" name="com.ligadata.Serialize">Serialize</a></p> <h1>JsonException</h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">case class</span> </span> <span class="symbol"> <span class="name">JsonException</span><span class="params">(<span name="message">message: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result"> extends <span class="extype" name="scala.Exception">Exception</span> with <span class="extype" name="scala.Product">Product</span> with <span class="extype" name="scala.Serializable">Serializable</span></span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><span class="extype" name="scala.Serializable">Serializable</span>, <span class="extype" name="scala.Product">Product</span>, <span class="extype" name="scala.Equals">Equals</span>, <span class="extype" name="java.lang.Exception">Exception</span>, <span class="extype" name="java.lang.Throwable">Throwable</span>, <span class="extype" name="java.io.Serializable">Serializable</span>, <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="com.ligadata.Serialize.JsonException"><span>JsonException</span></li><li class="in" name="scala.Serializable"><span>Serializable</span></li><li class="in" name="scala.Product"><span>Product</span></li><li class="in" name="scala.Equals"><span>Equals</span></li><li class="in" name="java.lang.Exception"><span>Exception</span></li><li class="in" name="java.lang.Throwable"><span>Throwable</span></li><li class="in" name="java.io.Serializable"><span>Serializable</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> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </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="constructors" class="members"> <h3>Instance Constructors</h3> <ol><li name="com.ligadata.Serialize.JsonException#&lt;init&gt;" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="&lt;init&gt;(message:String):com.ligadata.Serialize.JsonException"></a> <a id="&lt;init&gt;:JsonException"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">new</span> </span> <span class="symbol"> <span class="name">JsonException</span><span class="params">(<span name="message">message: <span class="extype" name="scala.Predef.String">String</span></span>)</span> </span> </h4> </li></ol> </div> <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:AnyRef):Boolean"></a> <a id="!=(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 title="gt4s: $bang$eq" class="name">!=</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> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#!=" 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> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>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> <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:AnyRef):Boolean"></a> <a id="==(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 title="gt4s: $eq$eq" class="name">==</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> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#==" 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> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="java.lang.Throwable#addSuppressed" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="addSuppressed(x$1:Throwable):Unit"></a> <a id="addSuppressed(Throwable):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">addSuppressed</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.lang.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</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> <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> <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> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="java.lang.Throwable#fillInStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="fillInStackTrace():Throwable"></a> <a id="fillInStackTrace():Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">fillInStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</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> <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="java.lang.Throwable#getCause" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getCause():Throwable"></a> <a id="getCause():Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getCause</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</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> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="java.lang.Throwable#getLocalizedMessage" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getLocalizedMessage():String"></a> <a id="getLocalizedMessage():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">getLocalizedMessage</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getMessage" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getMessage():String"></a> <a id="getMessage():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">getMessage</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getStackTrace():Array[StackTraceElement]"></a> <a id="getStackTrace():Array[StackTraceElement]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.StackTraceElement">StackTraceElement</span>]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getSuppressed" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getSuppressed():Array[Throwable]"></a> <a id="getSuppressed():Array[Throwable]"></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">getSuppressed</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.Throwable">Throwable</span>]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#initCause" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="initCause(x$1:Throwable):Throwable"></a> <a id="initCause(Throwable):Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">initCause</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.lang.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</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> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="com.ligadata.Serialize.JsonException#message" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="message:String"></a> <a id="message:String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">val</span> </span> <span class="symbol"> <span class="name">message</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span> </span> </h4> </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> <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> <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> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace(x$1:java.io.PrintWriter):Unit"></a> <a id="printStackTrace(PrintWriter):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">printStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.io.PrintWriter">PrintWriter</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace(x$1:java.io.PrintStream):Unit"></a> <a id="printStackTrace(PrintStream):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">printStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.io.PrintStream">PrintStream</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace():Unit"></a> <a id="printStackTrace():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">printStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#setStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="setStackTrace(x$1:Array[StackTraceElement]):Unit"></a> <a id="setStackTrace(Array[StackTraceElement]):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">setStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.StackTraceElement">StackTraceElement</span>]</span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;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> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="java.lang.Throwable#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> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable → 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> <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> <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> <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="scala.Serializable"> <h3>Inherited from <span class="extype" name="scala.Serializable">Serializable</span></h3> </div><div class="parent" name="scala.Product"> <h3>Inherited from <span class="extype" name="scala.Product">Product</span></h3> </div><div class="parent" name="scala.Equals"> <h3>Inherited from <span class="extype" name="scala.Equals">Equals</span></h3> </div><div class="parent" name="java.lang.Exception"> <h3>Inherited from <span class="extype" name="java.lang.Exception">Exception</span></h3> </div><div class="parent" name="java.lang.Throwable"> <h3>Inherited from <span class="extype" name="java.lang.Throwable">Throwable</span></h3> </div><div class="parent" name="java.io.Serializable"> <h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></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> <script defer="defer" type="text/javascript" id="jquery-js" src="../../../lib/jquery.js"></script><script defer="defer" type="text/javascript" id="jquery-ui-js" src="../../../lib/jquery-ui.js"></script><script defer="defer" type="text/javascript" id="tools-tooltip-js" src="../../../lib/tools.tooltip.js"></script><script defer="defer" type="text/javascript" id="template-js" src="../../../lib/template.js"></script> </body> </html>
traytonwhite/Kamanja
trunk/Documentation/KamanjaAPIDocs/com/ligadata/Serialize/JsonException.html
HTML
apache-2.0
32,984
# 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 mock import tuskarclient.tests.utils as tutils from tuskarclient.v1 import resource_classes class ResourceClassManagerTest(tutils.TestCase): def setUp(self): super(ResourceClassManagerTest, self).setUp() self.api = mock.Mock() self.rcm = resource_classes.ResourceClassManager(self.api) def test_get(self): self.rcm._get = mock.Mock(return_value='fake_resource_class') self.assertEqual(self.rcm.get(42), 'fake_resource_class') self.rcm._get.assert_called_with('/v1/resource_classes/42') def test_list(self): self.rcm._list = mock.Mock(return_value=['fake_resource_class']) self.assertEqual(self.rcm.list(), ['fake_resource_class']) self.rcm._list.assert_called_with('/v1/resource_classes') def test_create(self): self.rcm._create = mock.Mock(return_value=['fake_resource_class']) self.assertEqual( self.rcm.create(dummy='dummy resource class data'), ['fake_resource_class']) self.rcm._create.assert_called_with( '/v1/resource_classes', {'dummy': 'dummy resource class data'}) def test_update(self): self.rcm._update = mock.Mock(return_value=['fake_resource_class']) self.assertEqual( self.rcm.update(42, dummy='dummy resource class data'), ['fake_resource_class']) self.rcm._update.assert_called_with( '/v1/resource_classes/42', {'dummy': 'dummy resource class data'}) def test_delete(self): self.rcm._delete = mock.Mock(return_value=None) self.assertEqual(self.rcm.delete(42), None) self.rcm._delete.assert_called_with('/v1/resource_classes/42')
ccrouch/python-tuskarclient
tuskarclient/tests/v1/test_resource_class.py
Python
apache-2.0
2,273
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\VarDumper\Caster; use Symfony\Component\VarDumper\Cloner\Stub; /** * Casts Amqp related classes to array representation. * * @author Grégoire Pineau <lyrixx@lyrixx.info> */ class AmqpCaster { private static $flags = array( AMQP_DURABLE => 'AMQP_DURABLE', AMQP_PASSIVE => 'AMQP_PASSIVE', AMQP_EXCLUSIVE => 'AMQP_EXCLUSIVE', AMQP_AUTODELETE => 'AMQP_AUTODELETE', AMQP_INTERNAL => 'AMQP_INTERNAL', AMQP_NOLOCAL => 'AMQP_NOLOCAL', AMQP_AUTOACK => 'AMQP_AUTOACK', AMQP_IFEMPTY => 'AMQP_IFEMPTY', AMQP_IFUNUSED => 'AMQP_IFUNUSED', AMQP_MANDATORY => 'AMQP_MANDATORY', AMQP_IMMEDIATE => 'AMQP_IMMEDIATE', AMQP_MULTIPLE => 'AMQP_MULTIPLE', AMQP_NOWAIT => 'AMQP_NOWAIT', AMQP_REQUEUE => 'AMQP_REQUEUE', ); private static $exchangeTypes = array( AMQP_EX_TYPE_DIRECT => 'AMQP_EX_TYPE_DIRECT', AMQP_EX_TYPE_FANOUT => 'AMQP_EX_TYPE_FANOUT', AMQP_EX_TYPE_TOPIC => 'AMQP_EX_TYPE_TOPIC', AMQP_EX_TYPE_HEADERS => 'AMQP_EX_TYPE_HEADERS', ); public static function castConnection(\AMQPConnection $c, array $a, Stub $stub, $isNested) { $prefix = Caster::PREFIX_VIRTUAL; // BC layer in the ampq lib if (method_exists($c, 'getReadTimeout')) { $timeout = $c->getReadTimeout(); } else { $timeout = $c->getTimeout(); } $a += array( $prefix.'isConnected' => $c->isConnected(), $prefix.'login' => $c->getLogin(), $prefix.'password' => $c->getPassword(), $prefix.'host' => $c->getHost(), $prefix.'port' => $c->getPort(), $prefix.'vhost' => $c->getVhost(), $prefix.'readTimeout' => $timeout, ); return $a; } public static function castChannel(\AMQPChannel $c, array $a, Stub $stub, $isNested) { $prefix = Caster::PREFIX_VIRTUAL; $a += array( $prefix.'isConnected' => $c->isConnected(), $prefix.'channelId' => $c->getChannelId(), $prefix.'prefetchSize' => $c->getPrefetchSize(), $prefix.'prefetchCount' => $c->getPrefetchCount(), $prefix.'connection' => $c->getConnection(), ); return $a; } public static function castQueue(\AMQPQueue $c, array $a, Stub $stub, $isNested) { $prefix = Caster::PREFIX_VIRTUAL; $a += array( $prefix.'name' => $c->getName(), $prefix.'flags' => self::extractFlags($c->getFlags()), $prefix.'arguments' => $c->getArguments(), $prefix.'connection' => $c->getConnection(), $prefix.'channel' => $c->getChannel(), ); return $a; } public static function castExchange(\AMQPExchange $c, array $a, Stub $stub, $isNested) { $prefix = Caster::PREFIX_VIRTUAL; $a += array( $prefix.'name' => $c->getName(), $prefix.'flags' => self::extractFlags($c->getFlags()), $prefix.'type' => isset(self::$exchangeTypes[$c->getType()]) ? new ConstStub(self::$exchangeTypes[$c->getType()], $c->getType()) : $c->getType(), $prefix.'arguments' => $c->getArguments(), $prefix.'channel' => $c->getChannel(), $prefix.'connection' => $c->getConnection(), ); return $a; } public static function castEnvelope(\AMQPEnvelope $c, array $a, Stub $stub, $isNested, $filter = 0) { $prefix = Caster::PREFIX_VIRTUAL; if (!($filter & Caster::EXCLUDE_VERBOSE)) { $a += array($prefix.'body' => $c->getBody()); } $a += array( $prefix.'routingKey' => $c->getRoutingKey(), $prefix.'deliveryTag' => $c->getDeliveryTag(), $prefix.'deliveryMode' => new ConstStub($c->getDeliveryMode().(2 === $c->getDeliveryMode() ? ' (persistent)' : ' (non-persistent)'), $c->getDeliveryMode()), $prefix.'exchangeName' => $c->getExchangeName(), $prefix.'isRedelivery' => $c->isRedelivery(), $prefix.'contentType' => $c->getContentType(), $prefix.'contentEncoding' => $c->getContentEncoding(), $prefix.'type' => $c->getType(), $prefix.'timestamp' => $c->getTimestamp(), $prefix.'priority' => $c->getPriority(), $prefix.'expiration' => $c->getExpiration(), $prefix.'userId' => $c->getUserId(), $prefix.'appId' => $c->getAppId(), $prefix.'messageId' => $c->getMessageId(), $prefix.'replyTo' => $c->getReplyTo(), $prefix.'correlationId' => $c->getCorrelationId(), $prefix.'headers' => $c->getHeaders(), ); return $a; } private static function extractFlags($flags) { $flagsArray = array(); foreach (self::$flags as $value => $name) { if ($flags & $value) { $flagsArray[] = $name; } } if (!$flagsArray) { $flagsArray = array('AMQP_NOPARAM'); } return new ConstStub(implode('|', $flagsArray), $flags); } }
focuslife/v0.1
vendor/symfony/var-dumper/Caster/AmqpCaster.php
PHP
apache-2.0
5,642
# only processes a single environment as the placeholder is not preserved function prepareEnv() { unset HTTPS_NAME unset HTTPS_PASSWORD unset HTTPS_KEYSTORE_DIR unset HTTPS_KEYSTORE unset HTTPS_KEYSTORE_TYPE } function configure() { configure_https } function configureEnv() { configure } function configure_https() { local ssl="<!-- No SSL configuration discovered -->" local https_connector="<!-- No HTTPS configuration discovered -->" if [ "${CONFIGURE_ELYTRON_SSL}" == "true" ]; then echo "Using Elytron for SSL configuration." return fi if [ -n "${HTTPS_PASSWORD}" -a -n "${HTTPS_KEYSTORE_DIR}" -a -n "${HTTPS_KEYSTORE}" ]; then if [ -n "$HTTPS_KEYSTORE_TYPE" ]; then keystore_provider="provider=\"${HTTPS_KEYSTORE_TYPE}\"" fi ssl="<server-identities>\n\ <ssl>\n\ <keystore ${keystore_provider} path=\"${HTTPS_KEYSTORE_DIR}/${HTTPS_KEYSTORE}\" keystore-password=\"${HTTPS_PASSWORD}\"/>\n\ </ssl>\n\ </server-identities>" https_connector="<https-listener name=\"https\" socket-binding=\"https\" security-realm=\"ApplicationRealm\"/>" elif [ -n "${HTTPS_PASSWORD}" -o -n "${HTTPS_KEYSTORE_DIR}" -o -n "${HTTPS_KEYSTORE}" ]; then echo "WARNING! Partial HTTPS configuration, the https connector WILL NOT be configured." fi sed -i "s|<!-- ##SSL## -->|${ssl}|" $CONFIG_FILE sed -i "s|<!-- ##HTTPS_CONNECTOR## -->|${https_connector}|" $CONFIG_FILE }
bdecoste/cct_module
os-eap7-launch/added/launch/https.sh
Shell
apache-2.0
1,504
# Hecatoncheir: The Data Stewardship Studio ## About Hecatoncheir Hecatoncheir is software that helps data stewards to ensure data quality management and data governance with using database metadata, statistics and data profiles. ## Key Features Hecatoncheir allows you to: * Collect metadata from database dictionaries/catalogs * Profile database tables and columns * Validate data with several business rules * Catalog data sets by tagging and importing additional metadata * Build a business glossary * Curate everything which needs to be shared with data developers and users ## Screenshots ### Data Catalog Top Page ![Data Catalog](doc/screenshots/screenshot1.png "Data Catalog Top Page") ### Metadata and Statistics ![Metadata and Statistics](doc/screenshots/screenshot2.png) ### Data Validation ![Data Validation (1)](doc/screenshots/screenshot3.png) ![Data Validation (2)](doc/screenshots/screenshot4.png) ### Business Glossary ![Business Glossary](doc/screenshots/screenshot5.png) ## Requirements ### Target databases The latest version supports following databases: * Oracle Database / Oracle Exadata * SQL Server * PostgreSQL * MySQL * Amazon Redshift * Google BigQuery Following databases are coming in the future releases: * DB2 * DB2 PureScale (Neteeza) * Apache Hive * Apache Spark * Vertica ### Operating Systems Hecatoncheir can work on following operating systems. * Red Hat Enterprise Linux 6 (x86_64) * Red Hat Enterprise Linux 7 (x86_64) * Windows 7 (64bit / 32bit) ### Python Hecatoncheir requires python 2.7. Also you need to have one or more database drivers for the databases you want to connect to: * cx-Oracle: Oracle Database / Oracle Exadata * MySQL-python: MySQL * psycopg2: PostgreSQL, Amazon Redshift * pymssql: SQL Server ## Installation To install Hecatoncheir, clone the git repository and install it with the pip command as following. ``` git clone https://github.com/snaga/Hecatoncheir.git cd Hecatoncheir pip install -r requirements.txt pip install . ``` ## Quick Start * [Quick Start [EN]](http://hecatoncheir.readthedocs.io/en/latest/quick-start.html) * [Quick Start [JA]](http://hecatoncheir-ja.readthedocs.io/ja/latest/quick-start.html) ## Documentation * [Hecatoncheir: The Data Stewardship Studio [EN]](http://hecatoncheir.readthedocs.io/) * [Hecatoncheir: The Data Stewardship Studio [JA]](http://hecatoncheir-ja.readthedocs.io/) ## License Apache License Version 2.0. See the [LICENSE](LICENSE) file for more information.
snaga/Hecatoncheir
README.md
Markdown
apache-2.0
2,511
# Cissus hochstetteri Planch. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Vitales/Vitaceae/Cissus/Cissus hochstetteri/README.md
Markdown
apache-2.0
177
{% extends '_layouts/base.html' %} {% set title = 'Ionic Enterprise Edition: Trusted Solution for Building Enterprise Apps' %} {% set meta_image = 'https://ionicframework.com/img/meta/products-ee-og.png' %} {% set meta_description = "Ionic Enterprise Edition is a trusted foundation and full-stack solution to build and power your company's mission-critical, enterprise apps that impact digital transformation." %} {% set id = 'products-enterprise-engine' %} {% set header_style = 'transparent light' %} {% set stickyNav = false %} {% set cssPath = 'products/enterprise-edition' %} {% set hide_pre_header = true %} {% set pre_footer = false %} {% block main %} <svg style="display: none;"></svg> <div class="top"> <div class="container"> <hgroup class="measure"> <h4>Ionic Enterprise Edition</h4> <h1>The best way to build with Ionic.</h1> <p>Accelerate app development with a solution that’s optimized for enterprise and backed by Ionic Experts.</p> <a href="#" class="btn uppercase rounded cta-link" id="btn-enterprise-engine-hero-buy">Chat with us</a> </hgroup> </div> </div> <main> <div class="page-nav-wrap"> <div class="page-nav"> <div class="page-nav__inner"> <ul> <li> <a href="#front-end-framework" class="page-nav__link page-nav__icon page-nav__icon--framework" id="btn-enterprise-edition-nav-ui-toolkit"> Cross-Platform UI Toolkit </a> </li> <li> <a href="#native-device-features" class="page-nav__link page-nav__icon page-nav__icon--native" id="btn-enterprise-edition-nav-native-features"> Native Device <br/> Features </a> </li> <li> <a href="#pre-built-solutions" class="page-nav__link page-nav__icon page-nav__icon--solutions" id="btn-enterprise-edition-nav-pre-built-solutions"> Pre-built <br/> Solutions </a> </li> <li> <a href="#expert-services" class="page-nav__link page-nav__icon page-nav__icon--services" id="btn-enterprise-edition-nav-expert-services"> Expert <br/> Services </a> </li> </ul> </div> </div> <section class="overview"> <div class="container"> <div> <h3><em>Ionic Enterprise Edition</em> empowers your app development teams with everything they need to deliver the mission-critical apps that keep your business running.</h3> <img src="/img/products/enterprise-engine/enterprise-edition-logo-sprite.png" alt=""> </div> <div> <div class="chart"> <h5><span>What you get</span></h5> <div class="chart__box"> <ul class="chart__card-list"> <li class="chart__card"> Ionic Framework Enterprise Edition </li> <li class="chart__card"> Core Native Features </li> <li class="chart__card"> Customer Success & Advisory </li> </ul> <h6>Advanced Mobile Solutions</h6> <ul class="checkmark-list checkmark-list--small checkmark-list--orange"> <li> <ion-icon name="checkmark"></ion-icon> Authentication </li> <li> <ion-icon name="checkmark"></ion-icon> Payments </li> <li> <ion-icon name="checkmark"></ion-icon> Media </li> <li> <ion-icon name="checkmark"></ion-icon> Printing & Scanning</li> <li> <ion-icon name="checkmark"></ion-icon> Biometrics </li> <li> <ion-icon name="checkmark"></ion-icon> Notifications </li> <li> <ion-icon name="checkmark"></ion-icon> Communications </li> <li> <ion-icon name="checkmark"></ion-icon> Offline Data </li> </ul> </div> <h5><span>For Cross Platform Development across</span></h5> <ul class="platform-list"> <li class="platform platform--ios">Native iOS</li> <li class="platform platform--android">Native Android</li> <li class="platform platform--electron">Electron</li> <li class="platform platform--pwa">PWA</li> <li class="platform platform--browser">Browser</li> </ul> </div> </div> </div> </section> <section id="front-end-framework" class="nav-section"> <div class="container two-col"> <hgroup> <h3>Cross-Platform UI Toolkit</h3> <h2>One UI library for all your team’s projects and applications.</h2> <p class="large">Develop award-winning mobile and desktop apps, with one shared codebase across projects and a single design language for your entire organization. Ionic Enterprise Edition comes with an enterprise-ready version of the open source Framework, backed by long-term support and migration assistance to keep you moving forward.</p> <ul class="checkmark-list checkmark-list--large"> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> Timely support and troubleshooting for issues with Ionic Framework. </li> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> Long-term support for previous versions for up to 5 years. </li> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> Priority fixes to keep your development on track. </li> </ul> </hgroup> <div class="graphics--framework activateOnScroll"> <div class="shadow"></div> </div> </div> </section> <section id="native-device-features" class="nav-section"> <div class="container"> <h3>Native Device Features</h3> <hgroup class="two-col"> <div> <h2>Easy access to device features</h2> </div> <div> <p class="large">Need access to native mobile device features like Camera and GPS? Ionic Enterprise Edition provides a core library of native functionality that you can easily add to any Ionic app, with active maintenance and security patching to keep your projects running smoothly.</p> </div> </hgroup> <h3 class="large">Your native library comes with: </h3> <ul class="feature-list"> <li> <hgroup class="feature-icon feature-icon--updates"> <h4>Regular Release Cycles & updates</h4> <p>A release timeline you can count on, as opposed to a community maintainers schedule. Think days instead of months or years.</p> </hgroup> </li> <li> <hgroup class="feature-icon feature-icon--sla"> <h4>Guaranteed Support SLA & Ticketing</h4> <p>Ability to communicate directly with the Ionic team with guaranteed response times, so you can be sure you will get answers & fixes ASAP.</p> </hgroup> </li> <li> <hgroup class="feature-icon feature-icon--advisory"> <h4>Access to Advisory & Implementation Guidance</h4> <p>Ensuring your team is utilizing best practices and functionality from both the framework & native side with ease, enabling you to meet your deadlines while avoiding costly tech debt.</p> </hgroup> </li> <li> <hgroup class="feature-icon feature-icon--security"> <h4>Critical Security & Hot Bug Fixes</h4> <p>The plugins that Ionic maintains will be guaranteed to work with future OS releases, patches, continued development, and more. There’s no fear of community plugin abandonement.</p> </hgroup> </li> <li> <hgroup class="feature-icon feature-icon--issues"> <h4>Issues & Feature Prioritization</h4> <p>An Open Source plugin may have many open issues that will impact your team's ability to use the plugin, delaying your ability to ship new features. Ensure that your team remains agile by having Ionic fix the issues most important to you.</p> </hgroup> </li> <li> <hgroup class="feature-icon feature-icon--guaranteed"> <h4>Guaranteed Product Lifespan</h4> <p>The plugins that Ionic maintains will be guaranteed to work with future operating system releases, patches, continued development, and more. There’s no fear of a plugin being abandoned by its original author.</p> </hgroup> </li> <li> <hgroup class="feature-icon feature-icon--discussions"> <h4>Influence & Improvement Discussions</h4> <p>If a plugin doesn’t do what you need it to do, Ionic is always open to chat about modifications and how the plugin can work better for you.</p> </hgroup> </li> <li> <hgroup class="feature-icon feature-icon--protection"> <h4>Protection Against Changing Ecosystem</h4> <p>The frontend and mobile app ecosystems are always changing, and you’re not in control of them like you would be with your backend choices. Ionic will ensure that future software releases are supported by our maintained.</p> </hgroup> </li> </ul> </div> </section> <section id="pre-built-solutions" class="nav-section"> <div class="container" > <div class="two-col"> <div class="integrations"> <a class="integrations__identity-vault"> <i></i> Identity Vault </a> <a class="integrations__aws-amplify"> <i></i> AWS Amplify </a> <a class="integrations__couchbase"> <i></i> Couchbase </a> <a class="integrations__active-directory"> <i></i> Active Directory </a> </div> <div> <hgroup > <h3>Pre-built Solutions</h3> <h2>Lightning-fast development with pre-built solutions</h2> <p class="large">Accelerate development with powerful solutions to common enterprise use cases - all built and supported by the Ionic team. Ionic’s growing library of solutions are ready to deploy in any of the apps you build with Enterprise Edition.</p> <ul class="checkmark-list checkmark-list--large"> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> Biometrics & user authentication </li> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> Secure offline storage </li> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> Mobile payment </li> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> Notifications </li> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> Barcode scanning </li> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> Cross-app communications </li> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> And more </li> </ul> </hgroup> </div> </div> </div> </section> <section id="expert-services" class="nav-section"> <div class="container"> <hgroup> <h3>Advisory & Training</h3> <div class="two-col"> <div> <h2>Your trusted development partner</h2> <p class="large">Ionic Enterprise Edition customers get exclusive access to Ionic’s Advisory Services and Trainings.</p> </div> </div> </hgroup> <div class="two-col"> <ul class="feature-list feature-list--large"> <li> <i class="feature-icon feature-icon--advisory"></i> <hgroup> <h4>Ionic Advisory Services</h4> <p>Our mobile experts become your development partner to ensure on-time app delivery, avoid technical debt, and eliminate risk. Examples include code reviews, architecture reviews, security audits, custom development solutions, and more.</p> </hgroup> </li> <li> <i class="feature-icon feature-icon--training"></i> <hgroup> <h4>Customized Team Training</h4> <p>Our dedicated advisors are available for on-site or remote training to help your team get up-to-speed quickly on Ionic and provide our recommended best practices for building and delivering stellar mobile apps.</p> </hgroup> </li> </ul> <ul class="checkmark-list checkmark-list--large"> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> <hgroup> <h5>Private Slack</h5> <p>Unlock realtime access to Ionic engineers and native mobile experts via a dedicated Slack channel.</p> </hgroup> </li> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> <hgroup> <h5>Code Reviews</h5> <p>Go line-by-line with our experts as they share coding best practices and advice.</p> </hgroup> </li> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> <hgroup> <h5>Custom Training</h5> <p>Give your team the skills and tools they need to be successful building apps on day one.</p> </hgroup> </li> <li> <i> <ion-icon name="checkmark"></ion-icon> </i> <hgroup> <h5>Expert Advisory</h5> <p>Our mobile experts are on-hand to help your development team tackle any aspect of app development.</p> </hgroup> </li> </ul> </div> </div> </section> </div> <section id="comparison-table" class="divider"> <div class="container"> <hgroup> <h2><em>Everything you need.</em> From front to back.</h2> </hgroup> <div class="comp-table-wrapper"> <table class="comp-table"> <thead> <tr> <th></th> <th>Ionic Community Edition</th> <th>Ionic Enterprise Edition</th> </tr> </thead> <tbody> <tr class="comp-table__section"> <td>Cross-Platform UI Toolkit</td> <td></td> <td></td> </tr> <tr class="stripe"> <td>Ionic Framework</td> <td><ion-icon name="checkmark"></ion-icon></td> <td><ion-icon name="checkmark"></ion-icon></td> </tr> <tr> <td>Long-Term Support</td> <td><i class="dash"></i></td> <td><ion-icon name="checkmark"></ion-icon></td> </tr> <tr class="stripe"> <td>Version Migration Assistance</td> <td><i class="dash"></i></td> <td><ion-icon name="checkmark"></ion-icon></td> </tr> <tr> <td>Priority Fixes</td> <td><i class="dash"></i></td> <td><ion-icon name="checkmark"></ion-icon></td> </tr> <tr class="comp-table__section"> <td>Core Device Functionality</td> <td></td> <td></td> </tr> <tr class="stripe"> <td>Native Feature Library that includes GPS, Camera, InAppBrowser, Accelerometer, and more.</td> <td>Community Plugins</td> <td><ion-icon name="checkmark"></ion-icon></td> </tr> <tr> <td>Active Maintenance & Support</td> <td><i class="dash"></i></td> <td><ion-icon name="checkmark"></ion-icon></td> </tr> <tr class="comp-table__section"> <td>Pre-Built Mobile Solutions</td> <td></td> <td></td> </tr> <tr class="stripe"> <td>Security & Authentication </td> <td><i class="dash"></i></td> <td><span class="pill">Add-on available</span></td> </tr> <tr> <td>Mobile Payments </td> <td><i class="dash"></i></td> <td><span class="pill">Add-on available</span></td> </tr> <tr class="stripe"> <td>Offline Data</td> <td><i class="dash"></i></td> <td><span class="pill">Add-on available</span></td> </tr> <tr> <td>Media</td> <td><i class="dash"></i></td> <td><span class="pill">Add-on available</span></td> </tr> <tr class="stripe"> <td>Notifications</td> <td><i class="dash"></i></td> <td><span class="pill">Add-on available</span></td> </tr> <tr> <td>Printing & Scanning</td> <td><i class="dash"></i></td> <td><span class="pill">Add-on available</span></td> </tr> <tr class="comp-table__section comp-table__section--pad"> <td>Enterprise Customer Success</td> <td><i class="dash"></i></td> <td><ion-icon name="checkmark"></ion-icon></td> </tr> <tr class="comp-table__section comp-table__section--pad"> <td>Advisory Services</td> <td><i class="dash"></i></td> <td><span class="pill">Add-on available</span></td> </tr> </tbody> </table> </div> </div> </section> <section class="offwhite call-to-action"> <div class="container"> <hgroup class="center"> <h3>Ready to get started?</h3> <p> Connect with us today to see how you can get started with <b>Ionic Enterprise Edition</b>. </p> </hgroup> <div class="hubspot-override hubspot-override--large"> <!--[if lte IE 8]> <script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2-legacy.js"></script> <![endif]--> <script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js"></script> <script> hbspt.forms.create({ portalId: "3776657", formId: "1d517034-0dcd-4e0d-bbf3-554e8c919701", css: "" }); </script> </div> </div> </section> </main> {% include '../_includes/promos/tri-cta.html' %} {% endblock %} {% block modals %} {% endblock %} {% block scripts %} <script> function scrollToSelector(selector, offset){ var offset = offset || 0; window.scrollToY(document.querySelector(selector).getBoundingClientRect().top + window.scrollY + offset, 200, 'easeOutExpo'); } // main cta scroll to document.querySelectorAll('.cta-link').forEach(function(ctaLink){ ctaLink.addEventListener('click', function(ev){ ev.preventDefault(); scrollToSelector('.call-to-action'); }); }); // page nav scroll to document.querySelectorAll('.page-nav__link').forEach(function(navLink){ navLink.addEventListener('click', function(ev){ ev.preventDefault(); var anchorId = ev.target.getAttribute("href"); scrollToSelector(anchorId, -60); }); }) // nav highlighting var threshold = window.innerHeight * 0.33; var sectionOffsets = []; function updateSectionOffsets(){ requestAnimationFrame(function(){ document.querySelectorAll('.nav-section').forEach(function(section){ sectionOffsets.push({ id: section.id, top: section.getBoundingClientRect().top + window.scrollY, bottom: section.getBoundingClientRect().bottom + window.scrollY, anchor: document.querySelector('[href="#' + section.id + '"]'), isActive: false }) }); }); } function checkOffsets(){ var scroll = window.scrollY + threshold; sectionOffsets.forEach(function(section){ if (section.top < scroll && section.bottom > scroll) { section.anchor.classList.add('active'); section.isActive = true; } else { section.anchor.classList.remove('active'); section.isActive = false; } }); if (sectionOffsets.filter(function(o){return o.isActive === true}).length) { document.querySelector('.page-nav').classList.add('active'); } else { document.querySelector('.page-nav').classList.remove('active'); } } updateSectionOffsets(); checkOffsets(); window.addEventListener('scroll', checkOffsets); window.addEventListener('resize', updateSectionOffsets); </script> {% endblock %}
driftyco/ionic-site
server/pages/products/enterprise-edition.html
HTML
apache-2.0
22,403
import React from 'react' import Paper from 'material-ui/Paper'; import Grid from 'material-ui/Grid'; import Button from 'material-ui/Button'; import Card from 'material-ui/Card'; import TextField from 'material-ui/TextField'; import Typography from 'material-ui/Typography' import Api from '../../../data/api' import {CircularProgress} from "material-ui/Progress"; import {withStyles} from 'material-ui/styles'; import PropTypes from 'prop-types'; import List, { ListItem, ListItemText } from 'material-ui/List'; import Avatar from 'material-ui/Avatar'; import ImageIcon from 'material-ui-icons/Image'; // TODO: need to add alert library to store as well // import Alert from '../../Shared/alert' const styles = theme => ({ titleBar: { display: 'flex', justifyContent: 'space-between', borderBottomWidth: '1px', borderBottomStyle: 'solid', borderColor: theme.palette.text.secondary, marginBottom: 20, } }); class Forum extends React.Component { constructor(props) { super(props); this.state = { commentList: null, comment: '', api: {} }; this.api_uuid = this.props.match.params.api_uuid; this.updateCommentString = this.updateCommentString.bind(this); this.handleAddComment = this.handleAddComment.bind(this); this.getAllComments(); } getAllComments() { let api = new Api(); let promise_get = api.getAllComments(this.api_uuid); promise_get.then( response => { this.setState({commentList: response.obj.list}); }).catch( error => { console.error(error); /* TODO: Uncomment below line when Alert library is added to store */ // Alert.error("Error occurred while retrieving comments!"); } ); } updateCommentString(event) { this.setState({comment: event.target.value}); } handleAddComment() { let api = new Api(); let commentInfo = {"commentText": this.state.comment}; let promise = api.addComment(this.api_uuid, commentInfo); promise.then( response => { this.getAllComments(); this.setState({comment: ''}); // TODO: uncomment below once the alert library is added to store // Alert.success("Comment added successfully"); }).catch( error => { // TODO: uncomment below once the alert library is added to store ~tmkb // Alert.error("Error occurred while adding comments!"); } ); } render() { const {commentList, comment, api} = this.state; const { classes } = this.props; return ( <Grid container> <Grid item xs={12} sm={12} md={12} lg={11} xl={10} > <TextField label="Comment" InputLabelProps={{ shrink: true, }} helperText="Please proved your comments on this API " fullWidth name="name" multiline rows="4" onChange={this.updateCommentString} placeholder="Type your comments here" autoFocus={true} className={classes.inputText} /> </Grid> <Grid item xs={12} sm={12} md={12} lg={11} xl={10} > <Button variant="raised" color="primary" onClick={this.handleAddComment}> Add New Comment </Button> </Grid> <Grid item xs={12}> <Paper> <List> {commentList ? commentList.map((comment,index) => ( <ListItem key={index}> <Avatar> <ImageIcon /> </Avatar> <ListItemText primary={comment.commentText} secondary={ "Posted By " + comment.createdBy + " at " + comment.createdTime } /> </ListItem>)) : <CircularProgress/> } </List> </Paper> </Grid> </Grid> ); } } Forum.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(Forum);
Minoli/carbon-apimgt
features/apimgt/org.wso2.carbon.apimgt.store.feature/src/main/resources/store/source/src/app/components/Apis/Details/Forum.js
JavaScript
apache-2.0
4,865
using Misakai.Kafka; namespace Misakai.Kafka { public interface IPartitionSelector { /// <summary> /// Select the appropriate partition post a message based on topic and key data. /// </summary> /// <param name="topic">The topic at which the message will be sent.</param> /// <param name="key">The data used to consistently route a message to a particular partition. Value can be null.</param> /// <returns>The partition to send the message to.</returns> Partition Select(Topic topic, byte[] key); } }
Kelindar/misakai-kafka
Misakai.Kafka/Contracts/IPartitionSelector.cs
C#
apache-2.0
574
# AUTOGENERATED FILE FROM balenalib/var-som-mx6-ubuntu:bionic-run # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/* # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.8.9 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.0.1 ENV SETUPTOOLS_VERSION 56.0.0 RUN set -x \ && buildDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && echo "c5b7c118af6ad28d1b978513451b47e5acca51e3fc469dfc95ccf0ee9036bd82 Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH 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/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh 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: Ubuntu bionic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.8.9, Pip v21.0.1, Setuptools v56.0.0 \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/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/python/var-som-mx6/ubuntu/bionic/3.8.9/run/Dockerfile
Dockerfile
apache-2.0
4,070
/* * Copyright 2013 Monoscape * * 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. * * History: * 2011/11/10 Imesh Gunaratne <imesh@monoscape.org> Created. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Monoscape.Common.Model; using System.Runtime.Serialization; namespace Monoscape.CloudController.Api.Services.Dashboard.Model { [DataContract] public class CcGetSubscriptionResponse : AbstractResponse { [DataMember] public Subscription Subscription { get; set; } } }
monoscape/monoscape
Monoscape.CloudController.Api/Services/Dashboard/Model/CcGetSubscriptionResponse.cs
C#
apache-2.0
1,074
/* * 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. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.error; import java.util.concurrent.atomic.AtomicStampedReference; public class ShouldHaveStamp extends BasicErrorMessageFactory { private static final String SHOULD_HAVE_STAMP = "%nExpecting%n %s%nto have stamp:%n %s%nbut had:%n %s"; private ShouldHaveStamp(AtomicStampedReference<?> actual, int expectedStamp) { super(SHOULD_HAVE_STAMP, actual, expectedStamp, actual.getStamp()); } public static ErrorMessageFactory shouldHaveStamp(AtomicStampedReference<?> actual, int expectedStamp) { return new ShouldHaveStamp(actual, expectedStamp); } }
hazendaz/assertj-core
src/main/java/org/assertj/core/error/ShouldHaveStamp.java
Java
apache-2.0
1,201
<!DOCTYPE html PUBLIC "-//W3C//Dtd XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/Dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <!-- Mirrored from scaikeqc.org/xxxv/detail.php?Human=Ragnar%20Bloodaxe by HTTrack Website Copier/3.x [XR&CO'2014], Sun, 26 Feb 2017 10:32:00 GMT --> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <link rel="stylesheet" type="text/css" href="../shiny.css"/> <title>IKEqC Score Detail for A.S. XXXV</title> </head> <body> <div id="overalls"> <!-- defines the overall content area --> <!-- shared header for all first subdir files --> <div id="header"> <div id="headerleftsquare"> <img src="../scaequestrian.gif" alt="SCA Interkingdom Equestrian Competition" /> </div> <!-- close headerleftsquare --> <div id="headercontent"><h1>Interkingdom Equestrian Competition</h1> <div id="hnav1"> <p><a href="index-2.html">Home</a></p> <p><a href="index.html">AS XXXV (35)</a></p> <p><a href="../xxxvi/index.html">AS XXXVI (36)</a></p> <p><a href="../xxxvii/index.html">AS XXXVII (37)</a></p> <p><a href="../xxxviii/index.html">AS XXXVIII (38)</a></p> </div> <!-- close hnav1 --> <div id="hnav2"> <p><a href="../xxxix/index.html">AS XXXIX (39)</a></p> <p><a href="../xl/index.html">AS XL (40)</a></p> <p><a href="../xli/index.html">AS XLI (41)</a></p> <p><a href="../xlii/index.html">AS XLII (42)</a></p> <p><a href="../xliii/index.html">AS XLIII (43)</a></p> </div> <!-- close hnav2 --> <div id="hnav3"> <p><a href="../xliv/index.html">AS XLIV (44)</a></p> <p><a href="../xlv/index.html">AS XLV (45)</a></p> <p><a href="../xlvi/index.html">AS XLVI (46)</a></p> <p><a href="../xlvii/index.html">AS XLVII (47)</a></p> <p><a href="../xlviii/index.html">AS XLVIII (48)</a></p> </div> <!-- close hnav3 --> <div id="hnav4"> <p><a href="../xlix/index.html">AS XLIX (49)</a></p> <p><strong><a href="../l/index.html">AS L (50)</a></strong></p> </div> <!-- close hnav4 --> </div> <!-- close headercontent --> </div> <!-- close header --> <p/> <div id="main-text"> <h2>Score Detail for AS XXXV</h2> <div id="scoredetail"> <table class="competitordetail"> <tr><th colspan=2 class="sgh">Score Details for Ragnar Bloodaxe</th></tr> <tr><td class="right"> Participant:<br/> Horse:<br/> Kingdom:<br/> Event:<br/> Division:<br/> </td><td class="left"> Ragnar Bloodaxe<br/> .<br/> Middle<br/> Rivenstar Fall Frolic<br/> Intermediate, 30 feet<br/> </td></tr><tr><td colspan=2 td class="sg1"><br/><hr width=80%> <CENTER><H2>Behead the Target!</H2></CENTER> Course Time in Seconds: 36.03<br/> Penalty: 10 Bonus: <br/> Behead the Target Score: <BR CLEAR=ALL><br/> <HR WIDTH=80%> <CENTER><H2>Tilting at the Rings!</H2></CENTER> Number of rings of each size collected:<br/> 1" Rings: 0 2" Rings: 2 3" Rings: 1<br/> 4" Rings: 0 5" Rings: 0 6" Rings: 0 <br/> Rings Score: <br/><hr width=80%> Total Score: 94 </td></tr></table> </div> <!-- closes scoredetail --> <p class="footer">This page, and its scripts, are based on code created by Sandor Dosa.<br/> Emails sent to lord (dot) sandor (dot) dosa (at) gmail (dot) com will find him.<br/> This is version 0.93a of the scorekeeper script, last updated 27 August 2001. &copy;2001 ADG<br/> <br/> HTML and CSS by Doucette de Verdun, chestnutmare at gmail (dot) com, &copy;2015<br/> Site last updated 13 June 2015</p></div> <!-- closes scores --> </div> <!-- closes main-text --> </div> <!-- closes overalls --> </body> <!-- Mirrored from scaikeqc.org/xxxv/detail.php?Human=Ragnar%20Bloodaxe by HTTrack Website Copier/3.x [XR&CO'2014], Sun, 26 Feb 2017 10:32:00 GMT --> </html>
SandorDosa/ikeqc_historical
xxxv/detail92b9.html
HTML
apache-2.0
3,619
package com.google.api.ads.dfp.jaxws.v201602; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * Updates the specified {@link Company} objects. * * @param companies the companies to update * @return the updated companies * * * <p>Java class for updateCompanies element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="updateCompanies"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="companies" type="{https://www.google.com/apis/ads/publisher/v201602}Company" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "companies" }) @XmlRootElement(name = "updateCompanies") public class CompanyServiceInterfaceupdateCompanies { protected List<Company> companies; /** * Gets the value of the companies property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the companies property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCompanies().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Company } * * */ public List<Company> getCompanies() { if (companies == null) { companies = new ArrayList<Company>(); } return this.companies; } }
gawkermedia/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201602/CompanyServiceInterfaceupdateCompanies.java
Java
apache-2.0
2,179
# Senecio dealbatus Phil. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Senecio/Senecio dealbatus/README.md
Markdown
apache-2.0
173
package test; import java.util.List; import news_type_mine_tool.HomePageMineUtil; public class TestHomePageMineUtil { public static void main(String[] args) { System.setProperty("http.proxyHost","10.10.10.78"); System.setProperty("http.proxyPort","8080"); // String newsPageUrl = "http://www.banyuetan.org/chcontent/sz/szgc/2015121/123434.html"; // String homePageUrl = "http://www.banyuetan.org/chcontent/sz/szgc/index.html"; // String newsPageUrl = "http://urakanji.com/wp/5051/"; // String homePageUrl = "http://urakanji.com/"; // String newsPageUrl = "http://developer.51cto.com/art/201501/464174.htm"; // String homePageUrl = "http://www.51cto.com/"; String newsPageUrl = "http://www.moonmile.net/blog/archives/6782"; String homePageUrl = "http://www.moonmile.net/blog/"; // String newsPageUrl = "http://opinion.people.com.cn/n/2015/0127/c1003-26459377.html"; // String homePageUrl = "http://opinion.people.com.cn/"; System.out.println(newsPageUrl); String newsPageReg = HomePageMineUtil.reglizeNewsPageUrl(newsPageUrl); System.out.println(newsPageReg); List<String> newsList = HomePageMineUtil.getNewsList(homePageUrl, newsPageReg); for(String newsUrl : newsList){ System.out.println(newsUrl); } } }
sakuraloku/NewsTypeMineTool
test/TestHomePageMineUtil.java
Java
apache-2.0
1,266
--- layout: post title: "关于MySQL在日常使用中遇到的一些问题" subtitle: "" description: "MySQL 问题 无法插入 中文 乱码 Error Code:1093 " date: 2016-07-24 01:00:00 author: "Scalpel" header-img: "img/home-bg-o.jpg" tags: - 数据库 - Linux - 软件使用 --- ### 问题一 由于MySQL默认字符编码为Latin,不支持中文,所以会遇到无法插入中文数据或者中文乱码的情况,这时我们可以更改其默认字符编码:打开`/etc/mysql/my.cnf`,添加 ``` [mysqld] character-set-server=utf8 ``` ### 问题二 在做课程设计的时候,发现无法执行下述语句: ``` update 账单 set 耗水量 = 当前水表数 - (select 当前水表数 from 账单 where 日期 = (select date_add('2016-01-01', interval -1 month))) where 日期 = '2016-01-01' ``` 错误信息:`Error Code: 1093. You can't specify target table '账单' for update in FROM clause` 经过查阅资料得知,原来MySQL不能在同一语句中先select出同一表中的某些值,再update这个表(SQL Server可以),可以搞个中间表,设个别名过渡一下: ``` update 账单 set 耗水量 = 当前水表数 - (select 当前水表数 from (select tmp.* from 账单 tmp)a where a.日期 = (select date_add('2016-01-01', interval -1 month))) where 日期 = '2016-01-01'; ``` ### 问题三: 在删除数据库中的一条记录的时候,一直不能删除,提示错误信息:`Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Editor -> Query Editor and reconnect.` 后来通过搜索资料,发现mysql有个叫SQL_SAFE_UPDATES的变量,SQL_SAFE_UPDATES有两个取值0和1,SQL_SAFE_UPDATES = 1时,不带where和limit条件的update和delete操作语句是无法执行的,即使是有where和limit条件但不带key column的update和delete也不能执行,为了数据库更新操作的安全性,此值默认为1,所以才会出现更新失败的情况。所以可以先执行`SQL_SAFE_UPDATES = 0;`或者在Workbench -> Edit -> Preferences -> SQL Editor中取消勾选Safe Updates。
scalpelx/scalpelx.github.io
_posts/2016-07-24-mysqlproblem.markdown
Markdown
apache-2.0
2,226
# Episcia subacaulis Griseb. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Gesneriaceae/Episcia/Episcia subacaulis/README.md
Markdown
apache-2.0
176
/* * Copyright (C) 2012 The Guava 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.common.math; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.math.DoubleUtils.ensureNonNegative; import static com.google.common.math.StatsAccumulator.calculateNewMeanNonFinite; import static com.google.common.primitives.Doubles.isFinite; import static java.lang.Double.NaN; import static java.lang.Double.doubleToLongBits; import static java.lang.Double.isNaN; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Iterator; import java.util.stream.Collector; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.common.value.qual.MinLen; /** * A bundle of statistical summary values -- sum, count, mean/average, min and max, and several * forms of variance -- that were computed from a single set of zero or more floating-point values. * * <p>There are two ways to obtain a {@code Stats} instance: * * <ul> * <li>If all the values you want to summarize are already known, use the appropriate {@code * Stats.of} factory method below. Primitive arrays, iterables and iterators of any kind of * {@code Number}, and primitive varargs are supported. * <li>Or, to avoid storing up all the data first, create a {@link StatsAccumulator} instance, * feed values to it as you get them, then call {@link StatsAccumulator#snapshot}. * </ul> * * <p>Static convenience methods called {@code meanOf} are also provided for users who wish to * calculate <i>only</i> the mean. * * <p><b>Java 8 users:</b> If you are not using any of the variance statistics, you may wish to use * built-in JDK libraries instead of this class. * * @author Pete Gillin * @author Kevin Bourrillion * @since 20.0 */ @Beta @GwtIncompatible public final class Stats implements Serializable { private final long count; private final double mean; private final double sumOfSquaresOfDeltas; private final double min; private final double max; /** * Internal constructor. Users should use {@link #of} or {@link StatsAccumulator#snapshot}. * * <p>To ensure that the created instance obeys its contract, the parameters should satisfy the * following constraints. This is the callers responsibility and is not enforced here. * * <ul> * <li>If {@code count} is 0, {@code mean} may have any finite value (its only usage will be to * get multiplied by 0 to calculate the sum), and the other parameters may have any values * (they will not be used). * <li>If {@code count} is 1, {@code sumOfSquaresOfDeltas} must be exactly 0.0 or {@link * Double#NaN}. * </ul> */ Stats(long count, double mean, double sumOfSquaresOfDeltas, double min, double max) { this.count = count; this.mean = mean; this.sumOfSquaresOfDeltas = sumOfSquaresOfDeltas; this.min = min; this.max = max; } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) */ public static Stats of(Iterable<? extends Number> values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. The iterator will be completely * consumed by this method. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) */ public static Stats of(Iterator<? extends Number> values) { StatsAccumulator accumulator = new StatsAccumulator(); accumulator.addAll(values); return accumulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values */ public static Stats of(double... values) { StatsAccumulator acummulator = new StatsAccumulator(); acummulator.addAll(values); return acummulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values */ public static Stats of(int... values) { StatsAccumulator acummulator = new StatsAccumulator(); acummulator.addAll(values); return acummulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15)) */ public static Stats of(long... values) { StatsAccumulator acummulator = new StatsAccumulator(); acummulator.addAll(values); return acummulator.snapshot(); } /** * Returns statistics over a dataset containing the given values. The stream will be completely * consumed by this method. * * <p>If you have a {@code Stream<Double>} rather than a {@code DoubleStream}, you should collect * the values using {@link #toStats()} instead. * * @param values a series of values * @since 28.2 */ public static Stats of(DoubleStream values) { return values .collect(StatsAccumulator::new, StatsAccumulator::add, StatsAccumulator::addAll) .snapshot(); } /** * Returns statistics over a dataset containing the given values. The stream will be completely * consumed by this method. * * <p>If you have a {@code Stream<Integer>} rather than an {@code IntStream}, you should collect * the values using {@link #toStats()} instead. * * @param values a series of values * @since 28.2 */ public static Stats of(IntStream values) { return values .collect(StatsAccumulator::new, StatsAccumulator::add, StatsAccumulator::addAll) .snapshot(); } /** * Returns statistics over a dataset containing the given values. The stream will be completely * consumed by this method. * * <p>If you have a {@code Stream<Long>} rather than a {@code LongStream}, you should collect the * values using {@link #toStats()} instead. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15)) * @since 28.2 */ public static Stats of(LongStream values) { return values .collect(StatsAccumulator::new, StatsAccumulator::add, StatsAccumulator::addAll) .snapshot(); } /** * Returns a {@link Collector} which accumulates statistics from a {@link java.util.stream.Stream} * of any type of boxed {@link Number} into a {@link Stats}. Use by calling {@code * boxedNumericStream.collect(toStats())}. The numbers will be converted to {@code double} values * (which may cause loss of precision). * * <p>If you have any of the primitive streams {@code DoubleStream}, {@code IntStream}, or {@code * LongStream}, you should use the factory method {@link #of} instead. * * @since 28.2 */ public static Collector<Number, StatsAccumulator, Stats> toStats() { return Collector.of( StatsAccumulator::new, (a, x) -> a.add(x.doubleValue()), (l, r) -> { l.addAll(r); return l; }, StatsAccumulator::snapshot, Collector.Characteristics.UNORDERED); } /** Returns the number of values. */ public long count() { return count; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>If these values are a sample drawn from a population, this is also an unbiased estimator of * the arithmetic mean of the population. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains both {@link Double#POSITIVE_INFINITY} and {@link Double#NEGATIVE_INFINITY} then the * result is {@link Double#NaN}. If it contains {@link Double#POSITIVE_INFINITY} and finite values * only or {@link Double#POSITIVE_INFINITY} only, the result is {@link Double#POSITIVE_INFINITY}. * If it contains {@link Double#NEGATIVE_INFINITY} and finite values only or {@link * Double#NEGATIVE_INFINITY} only, the result is {@link Double#NEGATIVE_INFINITY}. * * <p>If you only want to calculate the mean, use {@link #meanOf} instead of creating a {@link * Stats} instance. * * @throws IllegalStateException if the dataset is empty */ public double mean() { checkState(count != 0); return mean; } /** * Returns the sum of the values. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains both {@link Double#POSITIVE_INFINITY} and {@link Double#NEGATIVE_INFINITY} then the * result is {@link Double#NaN}. If it contains {@link Double#POSITIVE_INFINITY} and finite values * only or {@link Double#POSITIVE_INFINITY} only, the result is {@link Double#POSITIVE_INFINITY}. * If it contains {@link Double#NEGATIVE_INFINITY} and finite values only or {@link * Double#NEGATIVE_INFINITY} only, the result is {@link Double#NEGATIVE_INFINITY}. */ public double sum() { return mean * count; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Variance#Population_variance">population * variance</a> of the values. The count must be non-zero. * * <p>This is guaranteed to return zero if the dataset contains only exactly one finite value. It * is not guaranteed to return zero when the dataset consists of the same value multiple times, * due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty */ public double populationVariance() { checkState(count > 0); if (isNaN(sumOfSquaresOfDeltas)) { return NaN; } if (count == 1) { return 0.0; } return ensureNonNegative(sumOfSquaresOfDeltas) / count(); } /** * Returns the <a * href="http://en.wikipedia.org/wiki/Standard_deviation#Definition_of_population_values"> * population standard deviation</a> of the values. The count must be non-zero. * * <p>This is guaranteed to return zero if the dataset contains only exactly one finite value. It * is not guaranteed to return zero when the dataset consists of the same value multiple times, * due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty */ public double populationStandardDeviation() { return Math.sqrt(populationVariance()); } /** * Returns the <a href="http://en.wikipedia.org/wiki/Variance#Sample_variance">unbiased sample * variance</a> of the values. If this dataset is a sample drawn from a population, this is an * unbiased estimator of the population variance of the population. The count must be greater than * one. * * <p>This is not guaranteed to return zero when the dataset consists of the same value multiple * times, due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty or contains a single value */ public double sampleVariance() { checkState(count > 1); if (isNaN(sumOfSquaresOfDeltas)) { return NaN; } return ensureNonNegative(sumOfSquaresOfDeltas) / (count - 1); } /** * Returns the <a * href="http://en.wikipedia.org/wiki/Standard_deviation#Corrected_sample_standard_deviation"> * corrected sample standard deviation</a> of the values. If this dataset is a sample drawn from a * population, this is an estimator of the population standard deviation of the population which * is less biased than {@link #populationStandardDeviation()} (the unbiased estimator depends on * the distribution). The count must be greater than one. * * <p>This is not guaranteed to return zero when the dataset consists of the same value multiple * times, due to numerical errors. However, it is guaranteed never to return a negative result. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty or contains a single value */ public double sampleStandardDeviation() { return Math.sqrt(sampleVariance()); } /** * Returns the lowest value in the dataset. The count must be non-zero. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains {@link Double#NEGATIVE_INFINITY} and not {@link Double#NaN} then the result is {@link * Double#NEGATIVE_INFINITY}. If it contains {@link Double#POSITIVE_INFINITY} and finite values * only then the result is the lowest finite value. If it contains {@link * Double#POSITIVE_INFINITY} only then the result is {@link Double#POSITIVE_INFINITY}. * * @throws IllegalStateException if the dataset is empty */ public double min() { checkState(count != 0); return min; } /** * Returns the highest value in the dataset. The count must be non-zero. * * <h3>Non-finite values</h3> * * <p>If the dataset contains {@link Double#NaN} then the result is {@link Double#NaN}. If it * contains {@link Double#POSITIVE_INFINITY} and not {@link Double#NaN} then the result is {@link * Double#POSITIVE_INFINITY}. If it contains {@link Double#NEGATIVE_INFINITY} and finite values * only then the result is the highest finite value. If it contains {@link * Double#NEGATIVE_INFINITY} only then the result is {@link Double#NEGATIVE_INFINITY}. * * @throws IllegalStateException if the dataset is empty */ public double max() { checkState(count != 0); return max; } /** * {@inheritDoc} * * <p><b>Note:</b> This tests exact equality of the calculated statistics, including the floating * point values. Two instances are guaranteed to be considered equal if one is copied from the * other using {@code second = new StatsAccumulator().addAll(first).snapshot()}, if both were * obtained by calling {@code snapshot()} on the same {@link StatsAccumulator} without adding any * values in between the two calls, or if one is obtained from the other after round-tripping * through java serialization. However, floating point rounding errors mean that it may be false * for some instances where the statistics are mathematically equal, including instances * constructed from the same values in a different order... or (in the general case) even in the * same order. (It is guaranteed to return true for instances constructed from the same values in * the same order if {@code strictfp} is in effect, or if the system architecture guarantees * {@code strictfp}-like semantics.) */ @Override public boolean equals(@Nullable Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Stats other = (Stats) obj; return count == other.count && doubleToLongBits(mean) == doubleToLongBits(other.mean) && doubleToLongBits(sumOfSquaresOfDeltas) == doubleToLongBits(other.sumOfSquaresOfDeltas) && doubleToLongBits(min) == doubleToLongBits(other.min) && doubleToLongBits(max) == doubleToLongBits(other.max); } /** * {@inheritDoc} * * <p><b>Note:</b> This hash code is consistent with exact equality of the calculated statistics, * including the floating point values. See the note on {@link #equals} for details. */ @Override public int hashCode() { return Objects.hashCode(count, mean, sumOfSquaresOfDeltas, min, max); } @Override public String toString() { if (count() > 0) { return MoreObjects.toStringHelper(this) .add("count", count) .add("mean", mean) .add("populationStandardDeviation", populationStandardDeviation()) .add("min", min) .add("max", max) .toString(); } else { return MoreObjects.toStringHelper(this).add("count", count).toString(); } } double sumOfSquaresOfDeltas() { return sumOfSquaresOfDeltas; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(Iterable<? extends Number> values) { return meanOf(values.iterator()); } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision) * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(Iterator<? extends Number> values) { checkArgument(values.hasNext()); long count = 1; double mean = values.next().doubleValue(); while (values.hasNext()) { double value = values.next().doubleValue(); count++; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / count; } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(double @MinLen(1)... values) { checkArgument(values.length > 0); double mean = values[0]; for (int index = 1; index < values.length; index++) { double value = values[index]; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / (index + 1); } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(int @MinLen(1)... values) { checkArgument(values.length > 0); double mean = values[0]; for (int index = 1; index < values.length; index++) { double value = values[index]; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / (index + 1); } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of the * values. The count must be non-zero. * * <p>The definition of the mean is the same as {@link Stats#mean}. * * @param values a series of values, which will be converted to {@code double} values (this may * cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15)) * @throws IllegalArgumentException if the dataset is empty */ public static double meanOf(long @MinLen(1)... values) { checkArgument(values.length > 0); double mean = values[0]; for (int index = 1; index < values.length; index++) { double value = values[index]; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / (index + 1); } else { mean = calculateNewMeanNonFinite(mean, value); } } return mean; } // Serialization helpers /** The size of byte array representation in bytes. */ static final int BYTES = (Long.SIZE + Double.SIZE * 4) / Byte.SIZE; /** * Gets a byte array representation of this instance. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. */ public byte[] toByteArray() { ByteBuffer buff = ByteBuffer.allocate(BYTES).order(ByteOrder.LITTLE_ENDIAN); writeTo(buff); return buff.array(); } /** * Writes to the given {@link ByteBuffer} a byte representation of this instance. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. * * @param buffer A {@link ByteBuffer} with at least BYTES {@link ByteBuffer#remaining}, ordered as * {@link ByteOrder#LITTLE_ENDIAN}, to which a BYTES-long byte representation of this instance * is written. In the process increases the position of {@link ByteBuffer} by BYTES. */ void writeTo(ByteBuffer buffer) { checkNotNull(buffer); checkArgument( buffer.remaining() >= BYTES, "Expected at least Stats.BYTES = %s remaining , got %s", BYTES, buffer.remaining()); buffer .putLong(count) .putDouble(mean) .putDouble(sumOfSquaresOfDeltas) .putDouble(min) .putDouble(max); } /** * Creates a Stats instance from the given byte representation which was obtained by {@link * #toByteArray}. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. */ public static Stats fromByteArray(byte[] byteArray) { checkNotNull(byteArray); checkArgument( byteArray.length == BYTES, "Expected Stats.BYTES = %s remaining , got %s", BYTES, byteArray.length); return readFrom(ByteBuffer.wrap(byteArray).order(ByteOrder.LITTLE_ENDIAN)); } /** * Creates a Stats instance from the byte representation read from the given {@link ByteBuffer}. * * <p><b>Note:</b> No guarantees are made regarding stability of the representation between * versions. * * @param buffer A {@link ByteBuffer} with at least BYTES {@link ByteBuffer#remaining}, ordered as * {@link ByteOrder#LITTLE_ENDIAN}, from which a BYTES-long byte representation of this * instance is read. In the process increases the position of {@link ByteBuffer} by BYTES. */ static Stats readFrom(ByteBuffer buffer) { checkNotNull(buffer); checkArgument( buffer.remaining() >= BYTES, "Expected at least Stats.BYTES = %s remaining , got %s", BYTES, buffer.remaining()); return new Stats( buffer.getLong(), buffer.getDouble(), buffer.getDouble(), buffer.getDouble(), buffer.getDouble()); } private static final long serialVersionUID = 0; }
typetools/guava
guava/src/com/google/common/math/Stats.java
Java
apache-2.0
25,362
# Clerodendrum illustre N.E.Br. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Clerodendrum/Clerodendrum illustre/README.md
Markdown
apache-2.0
179
package ch.plusminus.control.commands; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.plugin.Plugin; import ch.plusminus.control.Control; public class worlds implements CommandExecutor { private Plugin plugin; public worlds(Control control) { this.plugin = control; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(cmd.getName().equalsIgnoreCase("worlds")){ if(sender.isOp()){ List<World> w = Bukkit.getServer().getWorlds(); for(int x = 0 ; x == w.size() + 1 ; x++){ sender.sendMessage(w.get(x).getName() + " Players: " + w.get(x).getPlayers() + " Loaded Chunks: " + w.get(x).getLoadedChunks().length); } } } return true; } }
silvan201/CTRL
src/ch/plusminus/control/commands/worlds.java
Java
apache-2.0
1,000
#ifndef Alchemy_ElePanda #define Alchemy_ElePanda #include "Common.h" #include "../Monster.h" class ElePanda : public Monster { public: ElePanda(); ~ElePanda(); static Monster* create(void); static PE_s_monster param_ElePanda; private: }; #endif
kkh029/Alchemy
Alchemy/Classes/Object/Monster/ElePanda.h
C
apache-2.0
280
using System.Diagnostics; using System.IO; using MO.Common.Lang; namespace MO.Common.IO { //============================================================ // <T>目录工具类。</T> //============================================================ public static class RDirectory { //============================================================ // <T>判断目录是否存在。</T> //============================================================ public static bool Exists(string directory) { return Directory.Exists(directory); } //============================================================ // <T>判断指定文件是否存在。</T> // // @param 文件地址 // @return 结果 //============================================================ public static bool IsFileExists(string directory) { int dirIndex = directory.LastIndexOf("\\"); string dirPath = directory.Substring(0, directory.Length - (directory.Length - dirIndex - 1)); if (Directory.Exists(dirPath)) { string[] filePaths = Directory.GetFiles(dirPath); foreach (string path in filePaths) { if (directory.Equals(path)) { return true; } } } return false; } //============================================================ // <T>获得文件夹下文件列表。</T> // // @param paths 文件列表 // @param directory 文件夹 // @param deep 深度 //============================================================ private static bool InnerListFiles(FStrings paths, string directory, bool deep, string extension, bool constainsDir, bool constainsFile) { if(!Directory.Exists(directory)){ return false; } // 搜索子文件夹 foreach (string dir in Directory.GetDirectories(directory)) { if (constainsDir) { paths.Push(dir); } if (deep) { InnerListFiles(paths, dir, deep, extension, constainsDir, constainsFile); } } // 搜索文件列表 if (constainsFile) { foreach (string file in Directory.GetFiles(directory)) { if (null == extension) { paths.Push(file); } else if (file.EndsWith(extension)) { paths.Push(file); } } } return true; } //============================================================ // <T>列出文件夹下所有文件。</T> // // @param directory 文件夹 // @param deep 深度 //============================================================ public static FStrings ListFiles(string directory, bool deep = false, string extension = null) { FStrings files = new FStrings(); InnerListFiles(files, directory, deep, extension, false, true); files.Sort(); return files; } //============================================================ // <T>列出文件夹下所有子文件夹。</T> // // @param directory 文件夹 // @param deep 深度 //============================================================ public static FStrings ListDirectories(string directory, bool deep = false) { FStrings directories = new FStrings(); InnerListFiles(directories, directory, deep, null, true, false); directories.Sort(); return directories; } //============================================================ // <T>如果目录中文件夹不存在则创建文件夹。</T> // // @param directory 文件夹目录 //============================================================ public static void MakeDirectories(string directory) { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } } //============================================================ // <T>如果目录中文件夹不存在则创建文件夹。</T> // // @param directory 文件夹目录 //============================================================ public static void MakeDirectoriesForFile(string fileName) { fileName = fileName.Replace('/', '\\'); int index = fileName.LastIndexOf('\\'); if (-1 != index) { string directory = fileName.Substring(0, index); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } } } //============================================================ // <T>打开指定路径。</T> //============================================================ public static void ProcessOpen(string path) { Process.Start(new ProcessStartInfo(path)); } //============================================================ // <T>复制来源路径所有文件到目标路径。</T> // // @param sourcePath 来源路径 // @param targetPath 目标路径 // @param includes 包含列表 // @param excludes 排除列表 //============================================================ public static void Copy(string sourcePath, string targetPath, FStrings includes, FStrings excludes) { } //============================================================ // <T>清空指定目录内所有文件。</T> // // @param path 指定目录 //============================================================ public static void Clear(string path) { if (Directory.Exists(path)) { string[] fileNames = Directory.GetFiles(path); foreach (string fileName in fileNames) { File.Delete(fileName); } } } //============================================================ // <T>删除指定目录。</T> // // @param path 指定目录 //============================================================ public static void Delete(string path) { if (Directory.Exists(path)) { Directory.Delete(path, true); } } } }
favedit/MoCross
Tools/1 - Common/MoCommon/IO/RDirectory.cs
C#
apache-2.0
6,367
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2016.09.10 um 03:14:29 AM CEST // package com.laegler.microservice.adapter.lib.javaee.v7; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * * * This type adds an "id" attribute to xsd:string. * * * * <p>Java-Klasse für xsdStringType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="xsdStringType"> * &lt;simpleContent> * &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>string"> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "xsdStringType", propOrder = { "value" }) @XmlSeeAlso({ DescriptionType.class }) public class XsdStringType { @XmlValue protected java.lang.String value; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; /** * Ruft den Wert der value-Eigenschaft ab. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getValue() { return value; } /** * Legt den Wert der value-Eigenschaft fest. * * @param value * allowed object is * {@link java.lang.String } * */ public void setValue(java.lang.String value) { this.value = value; } /** * Ruft den Wert der id-Eigenschaft ab. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Legt den Wert der id-Eigenschaft fest. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } }
thlaegler/microservice
microservice-adapter/src/main/java/com/laegler/microservice/adapter/lib/javaee/v7/XsdStringType.java
Java
apache-2.0
2,838
/* * Copyright 2007-2009 Hidekatsu Izuno * * 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. */ /** * Extension classes for Web Service. */ package net.arnx.jsonic.web.extension;
hisataka/altxt2db
target/altxt2db-0.0.1-jar-with-dependencies/net/arnx/jsonic/web/extension/package-info.java
Java
apache-2.0
709
/** * Copyright (C) 2016 Dourachok 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.ivan.dourachok.engine.runtime.utils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import com.ivan.dourachok.Engine; import com.ivan.dourachok.annotation.TimeStamp; import com.ivan.dourachok.annotation.Ttl; import com.ivan.dourachok.engine.runtime.exception.DourachokRuntimeException; /** * util class for getting timestamp of an object, storing/getting it, etc. * @author Christophe Dame */ public class FactUtils { private static Map<Class<?>, Method> timestampClassMap = new HashMap<>(); public static long computeFactTimeStamp(Object fact, Engine engine) throws DourachokRuntimeException { Method tmstmpMethod = getTimeStampMethod(fact.getClass()); long timeStamp = 0; if (tmstmpMethod==null) { timeStamp = engine.getCurrentTime(); } else { try { timeStamp = (Long) tmstmpMethod.invoke(fact); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new DourachokRuntimeException("@TimeStamp method in "+fact.getClass()+" should return a long and have no parameters ",e); } } return timeStamp; } public static long computeTtl(Ttl ttlAnotation) { long result = ttlAnotation.days()*86400000; result += ttlAnotation.hours()*3600000; result += ttlAnotation.minutes()*60000; result += ttlAnotation.seconds()*1000; result += ttlAnotation.milliseconds(); return result; } private static Method getTimeStampMethod(Class<?> type) { Method tmstmpMethod = timestampClassMap.get(type); if (tmstmpMethod==null) { Class<?> klass = type; while (klass != Object.class) { Method[] allMethods = type.getDeclaredMethods(); for (final Method method : allMethods) { if (method.isAnnotationPresent(TimeStamp.class)) { tmstmpMethod = method; timestampClassMap.put(type, tmstmpMethod); return tmstmpMethod; } } klass = klass.getSuperclass(); } } return tmstmpMethod; } }
pyaniyMedved/dourachok
dourachok-core/src/main/java/com/ivan/dourachok/engine/runtime/utils/FactUtils.java
Java
apache-2.0
2,677
/* * This file is part of the PSL software. * Copyright 2011-2013 University of Maryland * * 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 edu.umd.cs.psl.optimizer.lbfgs; /** * User: Stanley Kok * Date: 12/20/10 * Time: 7:08 PM */ public interface ConvexFunc { /** * Returns the value and gradients with respect to each parameter. * @param g array storing returned gradients * @param wts array storing weights (parameters of function) * @return value of function */ public double getValueAndGradient(double[] g, final double[] wts); }
JackSullivan/psl
psl-core/src/main/java/edu/umd/cs/psl/optimizer/lbfgs/ConvexFunc.java
Java
apache-2.0
1,116
/* * Copyright (c) 2007 Mike Heath. 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 org.adbcj; public interface PreparedUpdate extends PreparedStatement { DbFuture<Result> execute(Object... params); }
taojiaenx/tjeadbc
api/src/main/java/org/adbcj/PreparedUpdate.java
Java
apache-2.0
775
<!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_25) on Mon Jun 02 17:48:59 PDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase (jackson-databind 2.4.0 API)</title> <meta name="date" content="2014-06-02"> <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.databind.jsontype.impl.TypeIdResolverBase (jackson-databind 2.4.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/databind/jsontype/impl/TypeIdResolverBase.html" title="class in com.fasterxml.jackson.databind.jsontype.impl">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/databind/jsontype/impl/class-use/TypeIdResolverBase.html" target="_top">Frames</a></li> <li><a href="TypeIdResolverBase.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.databind.jsontype.impl.TypeIdResolverBase" class="title">Uses of Class<br>com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase</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/databind/jsontype/impl/TypeIdResolverBase.html" title="class in com.fasterxml.jackson.databind.jsontype.impl">TypeIdResolverBase</a></span><span class="tabEnd">&nbsp;</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.databind.jsontype.impl">com.fasterxml.jackson.databind.jsontype.impl</a></td> <td class="colLast"> <div class="block">Package that contains standard implementations for <a href="../../../../../../../com/fasterxml/jackson/databind/jsontype/TypeResolverBuilder.html" title="interface in com.fasterxml.jackson.databind.jsontype"><code>TypeResolverBuilder</code></a> and <a href="../../../../../../../com/fasterxml/jackson/databind/jsontype/TypeIdResolver.html" title="interface in com.fasterxml.jackson.databind.jsontype"><code>TypeIdResolver</code></a>.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.fasterxml.jackson.databind.jsontype.impl"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../com/fasterxml/jackson/databind/jsontype/impl/TypeIdResolverBase.html" title="class in com.fasterxml.jackson.databind.jsontype.impl">TypeIdResolverBase</a> in <a href="../../../../../../../com/fasterxml/jackson/databind/jsontype/impl/package-summary.html">com.fasterxml.jackson.databind.jsontype.impl</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../com/fasterxml/jackson/databind/jsontype/impl/TypeIdResolverBase.html" title="class in com.fasterxml.jackson.databind.jsontype.impl">TypeIdResolverBase</a> in <a href="../../../../../../../com/fasterxml/jackson/databind/jsontype/impl/package-summary.html">com.fasterxml.jackson.databind.jsontype.impl</a></span><span class="tabEnd">&nbsp;</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>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/fasterxml/jackson/databind/jsontype/impl/ClassNameIdResolver.html" title="class in com.fasterxml.jackson.databind.jsontype.impl">ClassNameIdResolver</a></strong></code> <div class="block"><a href="../../../../../../../com/fasterxml/jackson/databind/jsontype/TypeIdResolver.html" title="interface in com.fasterxml.jackson.databind.jsontype"><code>TypeIdResolver</code></a> implementation that converts between fully-qualified Java class names and (JSON) Strings.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/fasterxml/jackson/databind/jsontype/impl/MinimalClassNameIdResolver.html" title="class in com.fasterxml.jackson.databind.jsontype.impl">MinimalClassNameIdResolver</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../com/fasterxml/jackson/databind/jsontype/impl/TypeNameIdResolver.html" title="class in com.fasterxml.jackson.databind.jsontype.impl">TypeNameIdResolver</a></strong></code>&nbsp;</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/databind/jsontype/impl/TypeIdResolverBase.html" title="class in com.fasterxml.jackson.databind.jsontype.impl">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/databind/jsontype/impl/class-use/TypeIdResolverBase.html" target="_top">Frames</a></li> <li><a href="TypeIdResolverBase.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 &#169; 2014 <a href="http://fasterxml.com/">FasterXML</a>. All Rights Reserved.</small></p> </body> </html>
FasterXML/jackson-databind
docs/javadoc/2.4/com/fasterxml/jackson/databind/jsontype/impl/class-use/TypeIdResolverBase.html
HTML
apache-2.0
8,382
/* * 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. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.internal.strings; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.error.ShouldBeUpperCase.shouldBeUpperCase; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.util.FailureMessages.actualIsNull; import org.assertj.core.internal.StringsBaseTest; import org.junit.jupiter.api.Test; /** * @author Marcel Overdijk */ class Strings_assertIsUpperCase_Test extends StringsBaseTest { @Test void should_pass_if_actual_is_uppercase() { strings.assertUpperCase(someInfo(), "LEGO"); } @Test void should_pass_if_actual_is_empty() { strings.assertUpperCase(someInfo(), ""); } @Test void should_fail_if_actual_is_not_only_uppercase() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertUpperCase(someInfo(), "Lego")) .withMessage(shouldBeUpperCase("Lego").create()); } @Test void should_fail_if_actual_is_lowercase() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertUpperCase(someInfo(), "lego")) .withMessage(shouldBeUpperCase("lego").create()); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertUpperCase(someInfo(), null)) .withMessage(actualIsNull()); } }
hazendaz/assertj-core
src/test/java/org/assertj/core/internal/strings/Strings_assertIsUpperCase_Test.java
Java
apache-2.0
2,119
# -*- coding: utf-8 -*- # # Baobab documentation build configuration file, created by # sphinx-quickstart on Tue Dec 7 00:44:28 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.todo','jsonext'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates/sphinxdoc'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Baobab' copyright = u'2010, Riccardo Attilio Galli' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.3.1' # The full version, including alpha/beta/rc tags. release = '1.3.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinxdoc' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. html_logo = "logo_baobab_200.png" # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = 'favicon.png' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { '*': ['globaltoc.html', 'sourcelink.html', 'searchbox.html'], 'index': ['download.html','globaltoc.html', 'sourcelink.html', 'searchbox.html'] } # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = {'example_animals':'animals.html','example_forum':'forum.html'} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Baobabdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Baobab.tex', u'Baobab Documentation', u'Riccardo Attilio Galli', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'baobab', u'Baobab Documentation', [u'Riccardo Attilio Galli'], 1) ]
riquito/Baobab
doc/source/conf.py
Python
apache-2.0
7,266
/*! * Font Awesome 3.2.1 * the iconsic font designed for Bootstrap * ------------------------------------------------------------------------------ * The full suite of pictographic iconss, examples, and documentation can be * found at http://fontawesome.io. Stay up to date on Twitter at * http://twitter.com/fontawesome. * * License * ------------------------------------------------------------------------------ * - The Font Awesome font is licensed under SIL OFL 1.1 - * http://scripts.sil.org/OFL * - Font Awesome CSS, LESS, and SASS files are licensed under MIT License - * http://opensource.org/licenses/mit-license.html * - Font Awesome documentation licensed under CC BY 3.0 - * http://creativecommons.org/licenses/by/3.0/ * - Attribution is no longer required in Font Awesome 3.0, but much appreciated: * "Font Awesome by Dave Gandy - http://fontawesome.io" * * Author - Dave Gandy * ------------------------------------------------------------------------------ * Email: dave@fontawesome.io * Twitter: http://twitter.com/davegandy * Work: Lead Product Designer @ Kyruus - http://kyruus.com */ /* FONT PATH * -------------------------- */ @font-face { font-family: 'FontAwesome'; src: url('../fonts/fontawesome-webfont.eot?v=3.2.1'); src: url('../fonts/fontawesome-webfont.eot?#iefix&v=3.2.1') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff?v=3.2.1') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=3.2.1') format('truetype'), url('../fonts/fontawesome-webfont.svg#fontawesomeregular?v=3.2.1') format('svg'); font-weight: normal; font-style: normal; } /* FONT AWESOME CORE * -------------------------- */ [class^="icons-"], [class*=" icons-"] { font-family: FontAwesome; font-weight: normal; font-style: normal; text-decoration: inherit; -webkit-font-smoothing: antialiased; *margin-right: .3em; } [class^="icons-"]:before, [class*=" icons-"]:before { text-decoration: inherit; display: inline-block; speak: none; } /* makes the font 33% larger relative to the icons container */ .icons-large:before { vertical-align: -10%; font-size: 1.3333333333333333em; } /* makes sure iconss active on rollover in links */ a [class^="icons-"], a [class*=" icons-"] { display: inline; } /* increased font size for icons-large */ [class^="icons-"].icons-fixed-width, [class*=" icons-"].icons-fixed-width { display: inline-block; width: 1.1428571428571428em; text-align: right; padding-right: 0.2857142857142857em; } [class^="icons-"].icons-fixed-width.icons-large, [class*=" icons-"].icons-fixed-width.icons-large { width: 1.4285714285714286em; } .iconss-ul { margin-left: 2.142857142857143em; list-style-type: none; } .iconss-ul > li { position: relative; } .iconss-ul .icons-li { position: absolute; left: -2.142857142857143em; width: 2.142857142857143em; text-align: center; line-height: inherit; } [class^="icons-"].hide, [class*=" icons-"].hide { display: none; } .icons-muted { color: #eeeeee; } .icons-light { color: #ffffff; } .icons-dark { color: #333333; } .icons-border { border: solid 1px #eeeeee; padding: .2em .25em .15em; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .icons-2x { font-size: 2em; } .icons-2x.icons-border { border-width: 2px; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .icons-3x { font-size: 3em; } .icons-3x.icons-border { border-width: 3px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } .icons-4x { font-size: 4em; } .icons-4x.icons-border { border-width: 4px; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .icons-5x { font-size: 5em; } .icons-5x.icons-border { border-width: 5px; -webkit-border-radius: 7px; -moz-border-radius: 7px; border-radius: 7px; } .pull-right { float: right; } .pull-left { float: left; } [class^="icons-"].pull-left, [class*=" icons-"].pull-left { margin-right: .3em; } [class^="icons-"].pull-right, [class*=" icons-"].pull-right { margin-left: .3em; } /* BOOTSTRAP SPECIFIC CLASSES * -------------------------- */ /* Bootstrap 2.0 sprites.less reset */ [class^="icons-"], [class*=" icons-"] { display: inline; width: auto; height: auto; line-height: normal; vertical-align: baseline; background-image: none; background-position: 0% 0%; background-repeat: repeat; margin-top: 0; } /* more sprites.less reset */ .icons-white, .nav-pills > .active > a > [class^="icons-"], .nav-pills > .active > a > [class*=" icons-"], .nav-list > .active > a > [class^="icons-"], .nav-list > .active > a > [class*=" icons-"], .navbar-inverse .nav > .active > a > [class^="icons-"], .navbar-inverse .nav > .active > a > [class*=" icons-"], .dropdown-menu > li > a:hover > [class^="icons-"], .dropdown-menu > li > a:hover > [class*=" icons-"], .dropdown-menu > .active > a > [class^="icons-"], .dropdown-menu > .active > a > [class*=" icons-"], .dropdown-submenu:hover > a > [class^="icons-"], .dropdown-submenu:hover > a > [class*=" icons-"] { background-image: none; } /* keeps Bootstrap styles with and without iconss the same */ .btn [class^="icons-"].icons-large, .nav [class^="icons-"].icons-large, .btn [class*=" icons-"].icons-large, .nav [class*=" icons-"].icons-large { line-height: .9em; } .btn [class^="icons-"].icons-spin, .nav [class^="icons-"].icons-spin, .btn [class*=" icons-"].icons-spin, .nav [class*=" icons-"].icons-spin { display: inline-block; } .nav-tabs [class^="icons-"], .nav-pills [class^="icons-"], .nav-tabs [class*=" icons-"], .nav-pills [class*=" icons-"], .nav-tabs [class^="icons-"].icons-large, .nav-pills [class^="icons-"].icons-large, .nav-tabs [class*=" icons-"].icons-large, .nav-pills [class*=" icons-"].icons-large { line-height: .9em; } .btn [class^="icons-"].pull-left.icons-2x, .btn [class*=" icons-"].pull-left.icons-2x, .btn [class^="icons-"].pull-right.icons-2x, .btn [class*=" icons-"].pull-right.icons-2x { margin-top: .18em; } .btn [class^="icons-"].icons-spin.icons-large, .btn [class*=" icons-"].icons-spin.icons-large { line-height: .8em; } .btn.btn-small [class^="icons-"].pull-left.icons-2x, .btn.btn-small [class*=" icons-"].pull-left.icons-2x, .btn.btn-small [class^="icons-"].pull-right.icons-2x, .btn.btn-small [class*=" icons-"].pull-right.icons-2x { margin-top: .25em; } .btn.btn-large [class^="icons-"], .btn.btn-large [class*=" icons-"] { margin-top: 0; } .btn.btn-large [class^="icons-"].pull-left.icons-2x, .btn.btn-large [class*=" icons-"].pull-left.icons-2x, .btn.btn-large [class^="icons-"].pull-right.icons-2x, .btn.btn-large [class*=" icons-"].pull-right.icons-2x { margin-top: .05em; } .btn.btn-large [class^="icons-"].pull-left.icons-2x, .btn.btn-large [class*=" icons-"].pull-left.icons-2x { margin-right: .2em; } .btn.btn-large [class^="icons-"].pull-right.icons-2x, .btn.btn-large [class*=" icons-"].pull-right.icons-2x { margin-left: .2em; } /* Fixes alignment in nav lists */ .nav-list [class^="icons-"], .nav-list [class*=" icons-"] { line-height: inherit; } /* EXTRAS * -------------------------- */ /* Stacked and layered icons */ .icons-stack { position: relative; display: inline-block; width: 2em; height: 2em; line-height: 2em; vertical-align: -35%; } .icons-stack [class^="icons-"], .icons-stack [class*=" icons-"] { display: block; text-align: center; position: absolute; width: 100%; height: 100%; font-size: 1em; line-height: inherit; *line-height: 2em; } .icons-stack .icons-stack-base { font-size: 2em; *line-height: 1em; } /* Animated rotating icons */ .icons-spin { display: inline-block; -moz-animation: spin 2s infinite linear; -o-animation: spin 2s infinite linear; -webkit-animation: spin 2s infinite linear; animation: spin 2s infinite linear; } /* Prevent stack and spinners from being taken inline when inside a link */ a .icons-stack, a .icons-spin { display: inline-block; text-decoration: none; } @-moz-keyframes spin { 0% { -moz-transform: rotate(0deg); } 100% { -moz-transform: rotate(359deg); } } @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(359deg); } } @-o-keyframes spin { 0% { -o-transform: rotate(0deg); } 100% { -o-transform: rotate(359deg); } } @-ms-keyframes spin { 0% { -ms-transform: rotate(0deg); } 100% { -ms-transform: rotate(359deg); } } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(359deg); } } /* icons rotations and mirroring */ .icons-rotate-90:before { -webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); -ms-transform: rotate(90deg); -o-transform: rotate(90deg); transform: rotate(90deg); filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); } .icons-rotate-180:before { -webkit-transform: rotate(180deg); -moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); transform: rotate(180deg); filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2); } .icons-rotate-270:before { -webkit-transform: rotate(270deg); -moz-transform: rotate(270deg); -ms-transform: rotate(270deg); -o-transform: rotate(270deg); transform: rotate(270deg); filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); } .icons-flip-horizontal:before { -webkit-transform: scale(-1, 1); -moz-transform: scale(-1, 1); -ms-transform: scale(-1, 1); -o-transform: scale(-1, 1); transform: scale(-1, 1); } .icons-flip-vertical:before { -webkit-transform: scale(1, -1); -moz-transform: scale(1, -1); -ms-transform: scale(1, -1); -o-transform: scale(1, -1); transform: scale(1, -1); } /* ensure rotation occurs inside anchor tags */ a .icons-rotate-90:before, a .icons-rotate-180:before, a .icons-rotate-270:before, a .icons-flip-horizontal:before, a .icons-flip-vertical:before { display: inline-block; } /* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen readers do not read off random characters that represent iconss */ .icons-glass:before { content: "\f000"; } .icons-music:before { content: "\f001"; } .icons-search:before { content: "\f002"; } .icons-envelope-alt:before { content: "\f003"; } .icons-heart:before { content: "\f004"; } .icons-star:before { content: "\f005"; } .icons-star-empty:before { content: "\f006"; } .icons-user:before { content: "\f007"; } .icons-film:before { content: "\f008"; } .icons-th-large:before { content: "\f009"; } .icons-th:before { content: "\f00a"; } .icons-th-list:before { content: "\f00b"; } .icons-ok:before { content: "\f00c"; } .icons-remove:before { content: "\f00d"; } .icons-zoom-in:before { content: "\f00e"; } .icons-zoom-out:before { content: "\f010"; } .icons-power-off:before, .icons-off:before { content: "\f011"; } .icons-signal:before { content: "\f012"; } .icons-gear:before, .icons-cog:before { content: "\f013"; } .icons-trash:before { content: "\f014"; } .icons-home:before { content: "\f015"; } .icons-file-alt:before { content: "\f016"; } .icons-time:before { content: "\f017"; } .icons-road:before { content: "\f018"; } .icons-download-alt:before { content: "\f019"; } .icons-download:before { content: "\f01a"; } .icons-upload:before { content: "\f01b"; } .icons-inbox:before { content: "\f01c"; } .icons-play-circle:before { content: "\f01d"; } .icons-rotate-right:before, .icons-repeat:before { content: "\f01e"; } .icons-refresh:before { content: "\f021"; } .icons-list-alt:before { content: "\f022"; } .icons-lock:before { content: "\f023"; } .icons-flag:before { content: "\f024"; } .icons-headphones:before { content: "\f025"; } .icons-volume-off:before { content: "\f026"; } .icons-volume-down:before { content: "\f027"; } .icons-volume-up:before { content: "\f028"; } .icons-qrcode:before { content: "\f029"; } .icons-barcode:before { content: "\f02a"; } .icons-tag:before { content: "\f02b"; } .icons-tags:before { content: "\f02c"; } .icons-book:before { content: "\f02d"; } .icons-bookmark:before { content: "\f02e"; } .icons-print:before { content: "\f02f"; } .icons-camera:before { content: "\f030"; } .icons-font:before { content: "\f031"; } .icons-bold:before { content: "\f032"; } .icons-italic:before { content: "\f033"; } .icons-text-height:before { content: "\f034"; } .icons-text-width:before { content: "\f035"; } .icons-align-left:before { content: "\f036"; } .icons-align-center:before { content: "\f037"; } .icons-align-right:before { content: "\f038"; } .icons-align-justify:before { content: "\f039"; } .icons-list:before { content: "\f03a"; } .icons-indent-left:before { content: "\f03b"; } .icons-indent-right:before { content: "\f03c"; } .icons-facetime-video:before { content: "\f03d"; } .icons-picture:before { content: "\f03e"; } .icons-pencil:before { content: "\f040"; } .icons-map-marker:before { content: "\f041"; } .icons-adjust:before { content: "\f042"; } .icons-tint:before { content: "\f043"; } .icons-edit:before { content: "\f044"; } .icons-share:before { content: "\f045"; } .icons-check:before { content: "\f046"; } .icons-move:before { content: "\f047"; } .icons-step-backward:before { content: "\f048"; } .icons-fast-backward:before { content: "\f049"; } .icons-backward:before { content: "\f04a"; } .icons-play:before { content: "\f04b"; } .icons-pause:before { content: "\f04c"; } .icons-stop:before { content: "\f04d"; } .icons-forward:before { content: "\f04e"; } .icons-fast-forward:before { content: "\f050"; } .icons-step-forward:before { content: "\f051"; } .icons-eject:before { content: "\f052"; } .icons-chevron-left:before { content: "\f053"; } .icons-chevron-right:before { content: "\f054"; } .icons-plus-sign:before { content: "\f055"; } .icons-minus-sign:before { content: "\f056"; } .icons-remove-sign:before { content: "\f057"; } .icons-ok-sign:before { content: "\f058"; } .icons-question-sign:before { content: "\f059"; } .icons-info-sign:before { content: "\f05a"; } .icons-screenshot:before { content: "\f05b"; } .icons-remove-circle:before { content: "\f05c"; } .icons-ok-circle:before { content: "\f05d"; } .icons-ban-circle:before { content: "\f05e"; } .icons-arrow-left:before { content: "\f060"; } .icons-arrow-right:before { content: "\f061"; } .icons-arrow-up:before { content: "\f062"; } .icons-arrow-down:before { content: "\f063"; } .icons-mail-forward:before, .icons-share-alt:before { content: "\f064"; } .icons-resize-full:before { content: "\f065"; } .icons-resize-small:before { content: "\f066"; } .icons-plus:before { content: "\f067"; } .icons-minus:before { content: "\f068"; } .icons-asterisk:before { content: "\f069"; } .icons-exclamation-sign:before { content: "\f06a"; } .icons-gift:before { content: "\f06b"; } .icons-leaf:before { content: "\f06c"; } .icons-fire:before { content: "\f06d"; } .icons-eye-open:before { content: "\f06e"; } .icons-eye-close:before { content: "\f070"; } .icons-warning-sign:before { content: "\f071"; } .icons-plane:before { content: "\f072"; } .icons-calendar:before { content: "\f073"; } .icons-random:before { content: "\f074"; } .icons-comment:before { content: "\f075"; } .icons-magnet:before { content: "\f076"; } .icons-chevron-up:before { content: "\f077"; } .icons-chevron-down:before { content: "\f078"; } .icons-retweet:before { content: "\f079"; } .icons-shopping-cart:before { content: "\f07a"; } .icons-folder-close:before { content: "\f07b"; } .icons-folder-open:before { content: "\f07c"; } .icons-resize-vertical:before { content: "\f07d"; } .icons-resize-horizontal:before { content: "\f07e"; } .icons-bar-chart:before { content: "\f080"; } .icons-twitter-sign:before { content: "\f081"; } .icons-facebook-sign:before { content: "\f082"; } .icons-camera-retro:before { content: "\f083"; } .icons-key:before { content: "\f084"; } .icons-gears:before, .icons-cogs:before { content: "\f085"; } .icons-comments:before { content: "\f086"; } .icons-thumbs-up-alt:before { content: "\f087"; } .icons-thumbs-down-alt:before { content: "\f088"; } .icons-star-half:before { content: "\f089"; } .icons-heart-empty:before { content: "\f08a"; } .icons-signout:before { content: "\f08b"; } .icons-linkedin-sign:before { content: "\f08c"; } .icons-pushpin:before { content: "\f08d"; } .icons-external-link:before { content: "\f08e"; } .icons-signin:before { content: "\f090"; } .icons-trophy:before { content: "\f091"; } .icons-github-sign:before { content: "\f092"; } .icons-upload-alt:before { content: "\f093"; } .icons-lemon:before { content: "\f094"; } .icons-phone:before { content: "\f095"; } .icons-unchecked:before, .icons-check-empty:before { content: "\f096"; } .icons-bookmark-empty:before { content: "\f097"; } .icons-phone-sign:before { content: "\f098"; } .icons-twitter:before { content: "\f099"; } .icons-facebook:before { content: "\f09a"; } .icons-github:before { content: "\f09b"; } .icons-unlock:before { content: "\f09c"; } .icons-credit-card:before { content: "\f09d"; } .icons-rss:before { content: "\f09e"; } .icons-hdd:before { content: "\f0a0"; } .icons-bullhorn:before { content: "\f0a1"; } .icons-bell:before { content: "\f0a2"; } .icons-certificate:before { content: "\f0a3"; } .icons-hand-right:before { content: "\f0a4"; } .icons-hand-left:before { content: "\f0a5"; } .icons-hand-up:before { content: "\f0a6"; } .icons-hand-down:before { content: "\f0a7"; } .icons-circle-arrow-left:before { content: "\f0a8"; } .icons-circle-arrow-right:before { content: "\f0a9"; } .icons-circle-arrow-up:before { content: "\f0aa"; } .icons-circle-arrow-down:before { content: "\f0ab"; } .icons-globe:before { content: "\f0ac"; } .icons-wrench:before { content: "\f0ad"; } .icons-tasks:before { content: "\f0ae"; } .icons-filter:before { content: "\f0b0"; } .icons-briefcase:before { content: "\f0b1"; } .icons-fullscreen:before { content: "\f0b2"; } .icons-group:before { content: "\f0c0"; } .icons-link:before { content: "\f0c1"; } .icons-cloud:before { content: "\f0c2"; } .icons-beaker:before { content: "\f0c3"; } .icons-cut:before { content: "\f0c4"; } .icons-copy:before { content: "\f0c5"; } .icons-paperclip:before, .icons-paper-clip:before { content: "\f0c6"; } .icons-save:before { content: "\f0c7"; } .icons-sign-blank:before { content: "\f0c8"; } .icons-reorder:before { content: "\f0c9"; } .icons-list-ul:before { content: "\f0ca"; } .icons-list-ol:before { content: "\f0cb"; } .icons-strikethrough:before { content: "\f0cc"; } .icons-underline:before { content: "\f0cd"; } .icons-table:before { content: "\f0ce"; } .icons-magic:before { content: "\f0d0"; } .icons-truck:before { content: "\f0d1"; } .icons-pinterest:before { content: "\f0d2"; } .icons-pinterest-sign:before { content: "\f0d3"; } .icons-google-plus-sign:before { content: "\f0d4"; } .icons-google-plus:before { content: "\f0d5"; } .icons-money:before { content: "\f0d6"; } .icons-caret-down:before { content: "\f0d7"; } .icons-caret-up:before { content: "\f0d8"; } .icons-caret-left:before { content: "\f0d9"; } .icons-caret-right:before { content: "\f0da"; } .icons-columns:before { content: "\f0db"; } .icons-sort:before { content: "\f0dc"; } .icons-sort-down:before { content: "\f0dd"; } .icons-sort-up:before { content: "\f0de"; } .icons-envelope:before { content: "\f0e0"; } .icons-linkedin:before { content: "\f0e1"; } .icons-rotate-left:before, .icons-undo:before { content: "\f0e2"; } .icons-legal:before { content: "\f0e3"; } .icons-dashboard:before { content: "\f0e4"; } .icons-comment-alt:before { content: "\f0e5"; } .icons-comments-alt:before { content: "\f0e6"; } .icons-bolt:before { content: "\f0e7"; } .icons-sitemap:before { content: "\f0e8"; } .icons-umbrella:before { content: "\f0e9"; } .icons-paste:before { content: "\f0ea"; } .icons-lightbulb:before { content: "\f0eb"; } .icons-exchange:before { content: "\f0ec"; } .icons-cloud-download:before { content: "\f0ed"; } .icons-cloud-upload:before { content: "\f0ee"; } .icons-user-md:before { content: "\f0f0"; } .icons-stethoscope:before { content: "\f0f1"; } .icons-suitcase:before { content: "\f0f2"; } .icons-bell-alt:before { content: "\f0f3"; } .icons-coffee:before { content: "\f0f4"; } .icons-food:before { content: "\f0f5"; } .icons-file-text-alt:before { content: "\f0f6"; } .icons-building:before { content: "\f0f7"; } .icons-hospital:before { content: "\f0f8"; } .icons-ambulance:before { content: "\f0f9"; } .icons-medkit:before { content: "\f0fa"; } .icons-fighter-jet:before { content: "\f0fb"; } .icons-beer:before { content: "\f0fc"; } .icons-h-sign:before { content: "\f0fd"; } .icons-plus-sign-alt:before { content: "\f0fe"; } .icons-double-angle-left:before { content: "\f100"; } .icons-double-angle-right:before { content: "\f101"; } .icons-double-angle-up:before { content: "\f102"; } .icons-double-angle-down:before { content: "\f103"; } .icons-angle-left:before { content: "\f104"; } .icons-angle-right:before { content: "\f105"; } .icons-angle-up:before { content: "\f106"; } .icons-angle-down:before { content: "\f107"; } .icons-desktop:before { content: "\f108"; } .icons-laptop:before { content: "\f109"; } .icons-tablet:before { content: "\f10a"; } .icons-mobile-phone:before { content: "\f10b"; } .icons-circle-blank:before { content: "\f10c"; } .icons-quote-left:before { content: "\f10d"; } .icons-quote-right:before { content: "\f10e"; } .icons-spinner:before { content: "\f110"; } .icons-circle:before { content: "\f111"; } .icons-mail-reply:before, .icons-reply:before { content: "\f112"; } .icons-github-alt:before { content: "\f113"; } .icons-folder-close-alt:before { content: "\f114"; } .icons-folder-open-alt:before { content: "\f115"; } .icons-expand-alt:before { content: "\f116"; } .icons-collapse-alt:before { content: "\f117"; } .icons-smile:before { content: "\f118"; } .icons-frown:before { content: "\f119"; } .icons-meh:before { content: "\f11a"; } .icons-gamepad:before { content: "\f11b"; } .icons-keyboard:before { content: "\f11c"; } .icons-flag-alt:before { content: "\f11d"; } .icons-flag-checkered:before { content: "\f11e"; } .icons-terminal:before { content: "\f120"; } .icons-code:before { content: "\f121"; } .icons-reply-all:before { content: "\f122"; } .icons-mail-reply-all:before { content: "\f122"; } .icons-star-half-full:before, .icons-star-half-empty:before { content: "\f123"; } .icons-location-arrow:before { content: "\f124"; } .icons-crop:before { content: "\f125"; } .icons-code-fork:before { content: "\f126"; } .icons-unlink:before { content: "\f127"; } .icons-question:before { content: "\f128"; } .icons-info:before { content: "\f129"; } .icons-exclamation:before { content: "\f12a"; } .icons-superscript:before { content: "\f12b"; } .icons-subscript:before { content: "\f12c"; } .icons-eraser:before { content: "\f12d"; } .icons-puzzle-piece:before { content: "\f12e"; } .icons-microphone:before { content: "\f130"; } .icons-microphone-off:before { content: "\f131"; } .icons-shield:before { content: "\f132"; } .icons-calendar-empty:before { content: "\f133"; } .icons-fire-extinguisher:before { content: "\f134"; } .icons-rocket:before { content: "\f135"; } .icons-maxcdn:before { content: "\f136"; } .icons-chevron-sign-left:before { content: "\f137"; } .icons-chevron-sign-right:before { content: "\f138"; } .icons-chevron-sign-up:before { content: "\f139"; } .icons-chevron-sign-down:before { content: "\f13a"; } .icons-html5:before { content: "\f13b"; } .icons-css3:before { content: "\f13c"; } .icons-anchor:before { content: "\f13d"; } .icons-unlock-alt:before { content: "\f13e"; } .icons-bullseye:before { content: "\f140"; } .icons-ellipsis-horizontal:before { content: "\f141"; } .icons-ellipsis-vertical:before { content: "\f142"; } .icons-rss-sign:before { content: "\f143"; } .icons-play-sign:before { content: "\f144"; } .icons-ticket:before { content: "\f145"; } .icons-minus-sign-alt:before { content: "\f146"; } .icons-check-minus:before { content: "\f147"; } .icons-level-up:before { content: "\f148"; } .icons-level-down:before { content: "\f149"; } .icons-check-sign:before { content: "\f14a"; } .icons-edit-sign:before { content: "\f14b"; } .icons-external-link-sign:before { content: "\f14c"; } .icons-share-sign:before { content: "\f14d"; } .icons-compass:before { content: "\f14e"; } .icons-collapse:before { content: "\f150"; } .icons-collapse-top:before { content: "\f151"; } .icons-expand:before { content: "\f152"; } .icons-euro:before, .icons-eur:before { content: "\f153"; } .icons-gbp:before { content: "\f154"; } .icons-dollar:before, .icons-usd:before { content: "\f155"; } .icons-rupee:before, .icons-inr:before { content: "\f156"; } .icons-yen:before, .icons-jpy:before { content: "\f157"; } .icons-renminbi:before, .icons-cny:before { content: "\f158"; } .icons-won:before, .icons-krw:before { content: "\f159"; } .icons-bitcoin:before, .icons-btc:before { content: "\f15a"; } .icons-file:before { content: "\f15b"; } .icons-file-text:before { content: "\f15c"; } .icons-sort-by-alphabet:before { content: "\f15d"; } .icons-sort-by-alphabet-alt:before { content: "\f15e"; } .icons-sort-by-attributes:before { content: "\f160"; } .icons-sort-by-attributes-alt:before { content: "\f161"; } .icons-sort-by-order:before { content: "\f162"; } .icons-sort-by-order-alt:before { content: "\f163"; } .icons-thumbs-up:before { content: "\f164"; } .icons-thumbs-down:before { content: "\f165"; } .icons-youtube-sign:before { content: "\f166"; } .icons-youtube:before { content: "\f167"; } .icons-xing:before { content: "\f168"; } .icons-xing-sign:before { content: "\f169"; } .icons-youtube-play:before { content: "\f16a"; } .icons-dropbox:before { content: "\f16b"; } .icons-stackexchange:before { content: "\f16c"; } .icons-instagram:before { content: "\f16d"; } .icons-flickr:before { content: "\f16e"; } .icons-adn:before { content: "\f170"; } .icons-bitbucket:before { content: "\f171"; } .icons-bitbucket-sign:before { content: "\f172"; } .icons-tumblr:before { content: "\f173"; } .icons-tumblr-sign:before { content: "\f174"; } .icons-long-arrow-down:before { content: "\f175"; } .icons-long-arrow-up:before { content: "\f176"; } .icons-long-arrow-left:before { content: "\f177"; } .icons-long-arrow-right:before { content: "\f178"; } .icons-apple:before { content: "\f179"; } .icons-windows:before { content: "\f17a"; } .icons-android:before { content: "\f17b"; } .icons-linux:before { content: "\f17c"; } .icons-dribbble:before { content: "\f17d"; } .icons-skype:before { content: "\f17e"; } .icons-foursquare:before { content: "\f180"; } .icons-trello:before { content: "\f181"; } .icons-female:before { content: "\f182"; } .icons-male:before { content: "\f183"; } .icons-gittip:before { content: "\f184"; } .icons-sun:before { content: "\f185"; } .icons-moon:before { content: "\f186"; } .icons-archive:before { content: "\f187"; } .icons-bug:before { content: "\f188"; } .icons-vk:before { content: "\f189"; } .icons-weibo:before { content: "\f18a"; } .icons-renren:before { content: "\f18b"; }
wirekom/pantauharga
web-app/css/font-awesome.css
CSS
apache-2.0
27,772
package main import ( "crypto/sha1" "fmt" "os" "time" "github.com/op/go-logging" ) type Pinger interface { Id() string Ping() } type Radio struct { Name string Uri string } type Server struct { Name string Host string Port int Internal bool LastPing int64 RadioId string RadioUri string } type Receiver struct { Name string Host string LastPing int64 Volume int ServerId string } type Config struct { Radios map[string]*Radio Receivers map[string]*Receiver Servers map[string]*Server } var ( log = logging.MustGetLogger("main") backendTimeout = 1 * time.Minute ) // ----- interfaces ------------------------------- func (e *Server) Ping() { e.LastPing = time.Now().Unix() } func (e *Receiver) Ping() { e.LastPing = time.Now().Unix() } func (s *Server) Id() string { return fmt.Sprintf("server-%s:%d", s.Host, s.Port) } func (r *Receiver) Id() string { return fmt.Sprintf("receiver-%s", r.Name) } func (r *Radio) Id() string { return fmt.Sprintf("radio-%x", sha1.Sum([]byte(r.Uri))) } // ----- logging ------------------------------- func initLogger(verbose bool) { format := logging.MustStringFormatter("%{color}%{time:15:04:05} %{level:.6s} ▶ %{shortfunc} %{color:reset} %{message}") backend := logging.NewLogBackend(os.Stderr, "", 0) formatter := logging.NewBackendFormatter(backend, format) leveled := logging.AddModuleLevel(formatter) if verbose { leveled.SetLevel(logging.DEBUG, "") } else { leveled.SetLevel(logging.INFO, "") } log.SetBackend(leveled) }
felixb/ub0r-streaming
go/common.go
GO
apache-2.0
1,573
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphdb.mockfs; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import org.neo4j.function.Function; import org.neo4j.io.fs.FileSystemAbstraction; import org.neo4j.io.fs.StoreChannel; public class DelegatingFileSystemAbstraction implements FileSystemAbstraction { private final FileSystemAbstraction delegate; public DelegatingFileSystemAbstraction( FileSystemAbstraction delegate ) { this.delegate = delegate; } @Override public StoreChannel open( File fileName, String mode ) throws IOException { return delegate.open( fileName, mode ); } @Override public void moveToDirectory( File file, File toDirectory ) throws IOException { delegate.moveToDirectory( file, toDirectory ); } @Override public boolean mkdir( File fileName ) { return delegate.mkdir( fileName ); } @Override public void copyFile( File from, File to ) throws IOException { delegate.copyFile( from, to ); } @Override public <K extends FileSystemAbstraction.ThirdPartyFileSystem> K getOrCreateThirdPartyFileSystem( Class<K> clazz, Function<Class<K>, K> creator ) { return delegate.getOrCreateThirdPartyFileSystem( clazz, creator ); } @Override public void truncate( File path, long size ) throws IOException { delegate.truncate( path, size ); } @Override public boolean renameFile( File from, File to ) throws IOException { return delegate.renameFile( from, to ); } @Override public StoreChannel create( File fileName ) throws IOException { return delegate.create( fileName ); } @Override public void mkdirs( File fileName ) throws IOException { delegate.mkdirs( fileName ); } @Override public boolean deleteFile( File fileName ) { return delegate.deleteFile( fileName ); } @Override public InputStream openAsInputStream( File fileName ) throws IOException { return delegate.openAsInputStream( fileName ); } @Override public boolean fileExists( File fileName ) { return delegate.fileExists( fileName ); } @Override public File[] listFiles( File directory, FilenameFilter filter ) { return delegate.listFiles( directory, filter ); } @Override public boolean isDirectory( File file ) { return delegate.isDirectory( file ); } @Override public long getFileSize( File fileName ) { return delegate.getFileSize( fileName ); } @Override public Writer openAsWriter( File fileName, String encoding, boolean append ) throws IOException { return delegate.openAsWriter( fileName, encoding, append ); } @Override public File[] listFiles( File directory ) { return delegate.listFiles( directory ); } @Override public void deleteRecursively( File directory ) throws IOException { delegate.deleteRecursively( directory ); } @Override public OutputStream openAsOutputStream( File fileName, boolean append ) throws IOException { return delegate.openAsOutputStream( fileName, append ); } @Override public Reader openAsReader( File fileName, String encoding ) throws IOException { return delegate.openAsReader( fileName, encoding ); } @Override public void copyRecursively( File fromDirectory, File toDirectory ) throws IOException { delegate.copyRecursively( fromDirectory, toDirectory ); } }
HuangLS/neo4j
community/io/src/test/java/org/neo4j/graphdb/mockfs/DelegatingFileSystemAbstraction.java
Java
apache-2.0
4,641
package edu.samplu.admin.test; import org.junit.Test; import org.openqa.selenium.By; import java.util.HashMap; import java.util.Map; import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue; /** * @author Kuali Rice Team (rice.collab@kuali.org) */ public class DocumentSearchURLParametersIT_testAdvancedSearchFieldsAndExecuteSearch extends DocumentSearchURLParametersITBase { @Test public void testAdvancedSearchFieldsAndExecuteSearch() throws InterruptedException{ // criteria.initiator=delyea&criteria.docTypeFullName=" + documentTypeName + Map<String, String> expected = new HashMap<String, String>(BASIC_FIELDS); expected.putAll(ADVANCED_FIELDS); Map<String, String> values = new HashMap<String, String>(expected); values.put("methodToCall", "search"); driver.get(getDocSearchURL(values)); assertInputValues(expected); // verify that it attempted the search assertTrue(driver.getPageSource().contains("No values match this search")); driver.findElement(By.id("toggleAdvancedSearch")).click(); assertInputValues(BASIC_FIELDS); } }
ua-eas/ksd-kc5.2.1-rice2.3.6-ua
rice-middleware/sampleapp/src/it/java/edu/samplu/admin/test/DocumentSearchURLParametersIT_testAdvancedSearchFieldsAndExecuteSearch.java
Java
apache-2.0
1,156
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (version 1.7.0_80) on Sat Jun 18 13:56:55 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.codehaus.plexus.archiver.snappy.SnappyArchiver (Plexus Archiver Component 3.4 API)</title> <meta name="date" content="2016-06-18"> <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.codehaus.plexus.archiver.snappy.SnappyArchiver (Plexus Archiver Component 3.4 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/codehaus/plexus/archiver/snappy/SnappyArchiver.html" title="class in org.codehaus.plexus.archiver.snappy">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?org/codehaus/plexus/archiver/snappy/class-use/SnappyArchiver.html" target="_top">Frames</a></li> <li><a href="SnappyArchiver.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.codehaus.plexus.archiver.snappy.SnappyArchiver" class="title">Uses of Class<br>org.codehaus.plexus.archiver.snappy.SnappyArchiver</h2> </div> <div class="classUseContainer">No usage of org.codehaus.plexus.archiver.snappy.SnappyArchiver</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/codehaus/plexus/archiver/snappy/SnappyArchiver.html" title="class in org.codehaus.plexus.archiver.snappy">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?org/codehaus/plexus/archiver/snappy/class-use/SnappyArchiver.html" target="_top">Frames</a></li> <li><a href="SnappyArchiver.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 &#169; 2001&#x2013;2016 <a href="http://codehaus-plexus.github.io/">Codehaus Plexus</a>. All rights reserved.</small></p> </body> </html>
play2-maven-plugin/play2-maven-plugin.github.io
external-apidocs/org/codehaus/plexus/plexus-archiver/3.4/org/codehaus/plexus/archiver/snappy/class-use/SnappyArchiver.html
HTML
apache-2.0
4,621
package org.etl.config import java.sql._ import org.slf4j.Logger import com.typesafe.config._ import com.typesafe.scalalogging.LazyLogging /** * @author jpvel TODO I would like to use immutable map instead of mutable map */ case class Resource(configType:String, auth_info:String, url:String, name:String) object ConfigurationService extends LazyLogging { //config_type, auth_info, resource_url private val conf = ConfigFactory.parseResources("configstore.props") logger.info("Initializing the config store from config file"+ conf.origin().url()) private val url = conf.getString("mysql.url") private val driver = conf.getString("mysql.driver") private val user = conf.getString("mysql.user") private val password = conf.getString("mysql.passwd") private val keyQueryBatch = conf.getString("mysql.key_global_sql") private val keyQueryProces = conf.getString("mysql.key_process_sql") private val keyQueryInstance = conf.getString("mysql.key_instance_sql") private val allQueryBatch = conf.getString("mysql.batch_sql") private val allQueryProcess= conf.getString("mysql.process_sql") private val allQueryInstance= conf.getString("mysql.instance_sql") private val resourceConfig = conf.getString("mysql.resource_sql") Class.forName(driver) def getConfig(processName:String, key:String): String = { val conn = DriverManager.getConnection(url,user, password) var value:String=null try { value = getProcessConfigValue(conn, processName, key) if(value==null || value.isEmpty()) value= getBatchConfigValue(conn, key) } catch { case t: Throwable => logger.error("Error reading information from config store{}", url,t) } finally { conn.close() } value } def getGlobalconfig():scala.collection.immutable.Map[String, String]= { val conn = DriverManager.getConnection(url,user, password) val valueList= getAllBatchConfigValue(conn) valueList } def getAllConfig(instanceName:String):scala.collection.immutable.Map[String, String]= { val conn = DriverManager.getConnection(url,user, password) val processName = findProcessName(instanceName) val valueList= getAllBatchConfigValue(conn)++getAllProcessConfigValue(conn, processName) ++ getAllInstanceConfigValue(conn, instanceName) valueList } private def getBatchConfigValue(conn:Connection, key:String):String = { val stmt = conn.prepareStatement(keyQueryBatch) var valueRet:String=null try { stmt.setString(1, key) val rs = stmt.executeQuery() try { if(rs.next()) { val value = rs.getString(1) valueRet=value } } finally { rs.close() } } finally{ stmt.closeOnCompletion() } valueRet } private def getProcessConfigValue(conn:Connection, processName:String, key:String):String= { val stmt = conn.prepareStatement(keyQueryProces) var valueRet:String=null try { stmt.setString(1, processName) stmt.setString(2,key) val rs = stmt.executeQuery() try { if(rs.next()) { val value = rs.getString(1) valueRet=value } } finally { rs.close() } } finally { stmt.closeOnCompletion() } valueRet } private def getInstanceConfigVaue(conn:Connection, instanceName:String, key:String):String = { val stmt = conn.prepareStatement(keyQueryInstance) var valueRet:String=null try { stmt.setString(1, instanceName) stmt.setString(2,key) val rs = stmt.executeQuery() try { if(rs.next()) { val value = rs.getString(1) valueRet=value } } finally { rs.close() } } finally { stmt.closeOnCompletion() } valueRet } private def getAllBatchConfigValue(conn:Connection):scala.collection.immutable.HashMap[String, String]= { val stmt=conn.createStatement() var configInfo = scala.collection.immutable.HashMap[String,String]() try { val rs = stmt.executeQuery(allQueryBatch) try{ while(rs.next()){ configInfo+=((rs.getString(1), rs.getString(2))) } }finally{ rs.close() } }finally{ stmt.closeOnCompletion() } configInfo } private def getAllProcessConfigValue(conn:Connection, processFqn:String):scala.collection.immutable.HashMap[String, String]= { val stmt = conn.prepareStatement(allQueryProcess) var configInfo = scala.collection.immutable.HashMap[String,String]() try { stmt.setString(1, processFqn) val rs = stmt.executeQuery() try { while(rs.next()) { configInfo+=((rs.getString(1), rs.getString(2))) } } finally { rs.close() } } finally{ stmt.closeOnCompletion() } configInfo } private def getAllInstanceConfigValue(conn:Connection, instanceFqn:String):scala.collection.immutable.HashMap[String, String]= { val stmt = conn.prepareStatement(allQueryInstance) var configInfo = scala.collection.immutable.HashMap[String,String]() try { stmt.setString(1, instanceFqn) val rs = stmt.executeQuery() try { while(rs.next()) { configInfo+=((rs.getString(1), rs.getString(2))) } } finally { rs.close() } } finally{ stmt.closeOnCompletion() } configInfo } def findProcessName(instanceName: String) = { if(instanceName.contains("#")) instanceName.substring(0, instanceName.lastIndexOf("#")) else instanceName } def getResourceConfig(name:String) :Resource = { val conn = DriverManager.getConnection(url,user, password) val stmt = conn.prepareStatement(resourceConfig) try { stmt.setString(1, name) val rs = stmt.executeQuery() try { rs.next() Resource(rs.getString(1), rs.getString(2), rs.getString(3),name) } finally { rs.close() } } finally{ stmt.closeOnCompletion() conn.close } } }
jpvelsamy/sparrow
sparrow-server/src/main/scala/org/etl/config/ConfigurationService.scala
Scala
apache-2.0
6,489
/** * 日 期:12-5-29 */ package com.appleframework.rest.marshaller; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator; import com.appleframework.rest.MessageFormat; import com.appleframework.rest.RestException; import com.appleframework.rest.RestRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Map; /** * <pre> * 对请求响应的对象转成相应的报文。 * </pre> * * @author 陈雄华 * @version 1.0 */ public class MessageMarshallerUtils { protected static final Logger logger = LoggerFactory.getLogger(MessageMarshallerUtils.class); private static final String UTF_8 = "utf-8"; private static ObjectMapper jsonObjectMapper = new ObjectMapper(); static { jsonObjectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); jsonObjectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); } private static XmlMapper xmlObjectMapper = new XmlMapper(); static { xmlObjectMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, false); xmlObjectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); } /** * 将请求对象转换为String * * @param request * @param format * @return */ public static String getMessage(RestRequest request, MessageFormat format) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); if (format == MessageFormat.json) { if (request.getRestRequestContext() != null) { jsonObjectMapper.writeValue(bos, request.getRestRequestContext().getAllParams()); } else { return ""; } } else { if (request.getRestRequestContext() != null) { xmlObjectMapper.writeValue(bos, request.getRestRequestContext().getAllParams()); } else { return ""; } } return bos.toString(UTF_8); } catch (Exception e) { throw new RestException(e); } } /** * 将请求对象转换为String * * @param allParams * @return */ public static String asUrlString(Map<String,String> allParams) { StringBuilder sb = new StringBuilder(256); boolean first = true; for (Map.Entry<String, String> entry : allParams.entrySet()) { if (!first) { sb.append("&"); } first = false; sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); } return sb.toString(); } /** * 将{@link RestRequest}转换为字符串 * * @param object * @param format * @return */ @SuppressWarnings("deprecation") public static String getMessage(Object object, MessageFormat format) { if (object == null) { return "NONE MSG"; } ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); try { JsonGenerator jsonGenerator = jsonObjectMapper.getJsonFactory().createJsonGenerator(bos, JsonEncoding.UTF8); jsonObjectMapper.writeValue(jsonGenerator, object); return bos.toString(UTF_8); } catch (Throwable e) { throw new RestException(e); } finally { try { bos.close(); } catch (IOException ee) { logger.error("消息转换异常", ee); } } } }
xushaomin/apple-rest
src/main/java/com/appleframework/rest/marshaller/MessageMarshallerUtils.java
Java
apache-2.0
3,931
package com.fionapet.business.service; import com.fionapet.business.entity.UserDict; import com.fionapet.business.repository.UserDictDao; import com.fionapet.business.repository.UserDictDetailDao; import org.dubbo.x.repository.DaoBase; import org.dubbo.x.service.CURDServiceBase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 用户字典 Created by tom on 2016-07-31 16:36:24. */ @Transactional @Service public class UserDictServiceImpl extends CURDServiceBase<UserDict> implements UserDictService { private static final Logger LOGGER = LoggerFactory.getLogger(UserDictServiceImpl.class); @Autowired private UserDictDao userDictDao; @Autowired private UserDictDetailDao userDictDetailDao; @Override public DaoBase<UserDict> getDao() { return userDictDao; } @Override public Map<String, Collection> selects(Map<String, String> params) { LOGGER.debug("selects params:{}", params); Map<String, String> paramKeyToValue = new HashMap<String, String>(); for (Map.Entry<String, String> param : params.entrySet()) { paramKeyToValue.put(param.getValue(), param.getKey()); } List<UserDict> dictTypes = userDictDao.findByDictNameIn(paramKeyToValue.keySet()); Map<String, Collection> result = new HashMap<String, Collection>(); for (UserDict dictType : dictTypes) { result.put(paramKeyToValue.get(dictType.getDictName()), userDictDetailDao.findByDictTypeId(dictType.getId())); } return result; } }
fiona-pet/business
fionapet-business-service-provider/src/main/java/com/fionapet/business/service/UserDictServiceImpl.java
Java
apache-2.0
1,862
#include "TransparentVRPSolver.h" namespace Scheduler { void TransparentVRPSolver::optimize(Scene& scene) const { } }
Eaglegor/SchedulerEngine
Engine/Algorithms/VRPSolvers/Utilitary/Transparent/TransparentVRPSolver.cpp
C++
apache-2.0
122
/* * customgroupservice.java * * Created on July 17, 2007, 9:30 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package tutorial.customgroupservice; import java.io.File; import java.net.URI; import java.util.Arrays; import net.jxta.document.AdvertisementFactory; import net.jxta.document.MimeMediaType; import net.jxta.document.XMLDocument; import net.jxta.document.XMLElement; import net.jxta.id.IDFactory; import net.jxta.peergroup.PeerGroup; import net.jxta.platform.NetworkManager; import net.jxta.protocol.ModuleImplAdvertisement; import net.jxta.protocol.PeerGroupAdvertisement; // Please read the @deprecation warning carefully. import net.jxta.impl.peergroup.StdPeerGroupParamAdv; import net.jxta.peergroup.PeerGroupID; import net.jxta.platform.ModuleSpecID; /** * This sample shows how to define a Peer Group with custom services. In this * case we add a simple demonstration service "Gossip" to the peer group. */ public class CustomGroupService { /** * The ID that our custom peer group will use. We use a hardcoded id so that all instances use the same value. * This ID was generated using the <tt>newpgrp -s</tt> JXSE Shell command. */ private final static PeerGroupID CUSTOM_PEERGROUP_ID = PeerGroupID.create(URI.create("urn:jxta:uuid-425A5C703CD5454F9C03938A0D65BD5002")); /** * The MSID that our custom peer group will use. We use a hardcoded id so that all instances use the same value. * This ID was generated using the <tt>newpgrp -s</tt> JXSE Shell command. */ private final static ModuleSpecID CUSTOM_PEERGROUP_MSID = ModuleSpecID.create(URI.create("urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE00000001ACEFC090A5D74844A9DEF43F3003D35A06")); /** * Main method * * @param args none defined */ public static void main(String args[]) { try { // Set the main thread name for debugging. Thread.currentThread().setName(CustomGroupService.class.getSimpleName()); // Configure JXTA NetworkManager manager = new NetworkManager(NetworkManager.ConfigMode.ADHOC, "customgroupservice", new File(new File(".cache"), "customgroupservice").toURI()); manager.setPeerID(IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID)); // create a random peer id. // Start JXTA. System.out.println("Starting JXTA"); PeerGroup npg = manager.startNetwork(); System.out.println("JXTA Started : " + npg); // Register the Gossip Service Configuration Advertisement with the advertisement factory. // This would normally be done by defining the GossipServiceConfigAdv in the META-INF/services/net.jxta.document.Advertisement // file of the jar containing the gossip service. AdvertisementFactory.registerAdvertisementInstance(GossipServiceConfigAdv.getAdvertisementType(), new GossipServiceConfigAdv.Instantiator()); // Create the Module Impl Advertisement for our custom group. // Start with a standard peer group impl advertisement. ModuleImplAdvertisement customGroupImplAdv = npg.getAllPurposePeerGroupImplAdvertisement(); // It's custom so we have to change the module spec ID. customGroupImplAdv.setModuleSpecID(CUSTOM_PEERGROUP_MSID); // StdPeerGroup uses the ModuleImplAdvertisement param section to describe what services to run. StdPeerGroupParamAdv customGroupParamAdv = new StdPeerGroupParamAdv(customGroupImplAdv.getParam()); // Add our Gossip Service to the group customGroupParamAdv.addService(GossipService.GOSSIP_SERVICE_MCID, GossipService.GOSSIP_SERVICE_MSID); // update the customGroupImplAdv by updating its param customGroupImplAdv.setParam((XMLElement) customGroupParamAdv.getDocument(MimeMediaType.XMLUTF8)); // publish the ModuleImplAdvertisement for our custom peer group. npg.getDiscoveryService().publish(customGroupImplAdv); // Create the module Impl Advertisement for our custom service. // Create a new ModuleImplAdvertisement instance. ModuleImplAdvertisement gossipImplAdv = (ModuleImplAdvertisement) AdvertisementFactory.newAdvertisement(ModuleImplAdvertisement.getAdvertisementType()); // Our implementation implements the given ModuleSpecID. gossipImplAdv.setModuleSpecID(GossipService.GOSSIP_SERVICE_MSID); // copy compatibility statement from the peer group impl advertisement. gossipImplAdv.setCompat(customGroupImplAdv.getCompat()); // The code for the implementation is the "tutorial.customgroupservice.GossipService" class. gossipImplAdv.setCode(GossipService.class.getName()); // If the code needed to be downloaded, where should it be downloaded from. This is not normally used. gossipImplAdv.setUri("http://jxta-jxse.dev.java.net/download/jxta.jar"); // The provider of the implementation. gossipImplAdv.setProvider("JXTA Orgainzation."); // A description of the service. (optional) gossipImplAdv.setDescription("Tutorial Gossip Service"); // publish the gossip service module implementation advertisement. npg.getDiscoveryService().publish(gossipImplAdv); // Create the Peer Group Advertisement. // Crete a new PeerGroupAdvertisement instance. PeerGroupAdvertisement customGroupAdv = (PeerGroupAdvertisement) AdvertisementFactory.newAdvertisement(PeerGroupAdvertisement.getAdvertisementType()); // Set our chosen peer group ID. customGroupAdv.setPeerGroupID(CUSTOM_PEERGROUP_ID); // Set the peer group name. customGroupAdv.setName("Custom Gossip Peer Group"); // The custom group uses our custom Module Specification. customGroupAdv.setModuleSpecID(customGroupImplAdv.getModuleSpecID()); // Add Gossip Service configuration parameters to the group adv. GossipServiceConfigAdv gossipConfig = (GossipServiceConfigAdv) AdvertisementFactory.newAdvertisement(GossipServiceConfigAdv.getAdvertisementType()); if(args.length != 0) { // Use the command line parameters as the gossip text. StringBuilder gossipText = new StringBuilder(); for(String arg : Arrays.asList(args)) { if(0 != gossipText.length()) { gossipText.append(" "); } gossipText.append(arg); } gossipConfig.setGossip(gossipText.toString()); } else { // Use default gossip text. gossipConfig.setGossip("Custom Peer Group Services are fun!"); } gossipConfig.setShowOwn(true); // Save the gossip config into the peer group advertisement. XMLDocument asDoc = (XMLDocument) gossipConfig.getDocument(MimeMediaType.XMLUTF8); customGroupAdv.putServiceParam(GossipService.GOSSIP_SERVICE_MCID, asDoc); // publish the peer group advertisement. npg.getDiscoveryService().publish(customGroupAdv); // Now we can instantiate the peer group. PeerGroup cpg = npg.newGroup(customGroupAdv); cpg.startApp(new String[0]); System.out.println("Started Custom Peer Group : " + cpg); // Sleep for a while. The Gossip Service will do it's gossiping. try { Thread.sleep( 2 * 60 * 1000); } catch(InterruptedException woken) { Thread.interrupted(); } System.out.println("Stopping Custom Peer Group : " + cpg); cpg.stopApp(); System.out.println("Stopping JXTA"); manager.stopNetwork(); } catch (Throwable e) { System.err.println("Fatal error -- quitting."); e.printStackTrace(System.err); System.exit(-1); } } }
johnjianfang/jxse
tutorials/src/main/java/tutorial/customgroupservice/CustomGroupService.java
Java
apache-2.0
8,249
/* * Copyright 2013 Simone Campagna * * 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. */ #ifndef configment_base_h_20130426 #define configment_base_h_20130426 #include<string> #include<ios> #include<iostream> #include<iomanip> #include<cassert> #include<sstream> #include<typeinfo> #include<algorithm> #include <configment/configment.h> #include <configment/debug.h> #include <configment/enum.h> #include <configment/error.h> #include <configment/string/string.h> #include <configment/mpl/mpl.h> namespace configment { /// \brief This is the superclass of the Object class, used principally to apply the Barton-Nackman trick. /// This base class is used to apply the Barton-Nackman trick for the binary operators, /// consisting in defining friend external operators in the body of a base class using /// the CRTP. /// All these binary operators are defined as methods of the Object classes; so, expressions /// like `o == 3` can be evaluated as `o.operator ==(3)`, which is then evaluated as /// `o2.operator ==(Object(3))`. The friend external operators are needed to cope with /// mixed expressions where the left-hand side is not an Object, for instance `3 == o`, /// where `o` is an Object. Some metaprogramming is needed to avoid unwanted conversions, /// in particular to avoid ADL lookup problems; these functions apply only when the left-hand /// side class is not an Object's subclass. template<typename DERIVED> class Base { // comparison template<typename TYPE> friend typename mpl::enable_if<! mpl::is_base_of<DERIVED, TYPE>::value, bool>::type operator ==(const TYPE & a, const DERIVED & b) { return DERIVED(a).operator ==(b); } template<typename TYPE> friend typename mpl::enable_if<! mpl::is_base_of<DERIVED, TYPE>::value, bool>::type operator !=(const TYPE & a, const DERIVED & b) { return DERIVED(a).operator !=(b); } template<typename TYPE> friend typename mpl::enable_if<! mpl::is_base_of<DERIVED, TYPE>::value, bool>::type operator < (const TYPE & a, const DERIVED & b) { return DERIVED(a).operator < (b); } template<typename TYPE> friend typename mpl::enable_if<! mpl::is_base_of<DERIVED, TYPE>::value, bool>::type operator <=(const TYPE & a, const DERIVED & b) { return DERIVED(a).operator <=(b); } template<typename TYPE> friend typename mpl::enable_if<! mpl::is_base_of<DERIVED, TYPE>::value, bool>::type operator > (const TYPE & a, const DERIVED & b) { return DERIVED(a).operator > (b); } template<typename TYPE> friend typename mpl::enable_if<! mpl::is_base_of<DERIVED, TYPE>::value, bool>::type operator >=(const TYPE & a, const DERIVED & b) { return DERIVED(a).operator >=(b); } // arithmetic template<typename TYPE> friend typename mpl::enable_if<! mpl::is_base_of<DERIVED, TYPE>::value, DERIVED>::type operator + (const TYPE & a, const DERIVED & b) { return DERIVED(a).operator + (b); } // do not invert (Sequence) template<typename TYPE> friend typename mpl::enable_if<! mpl::is_base_of<DERIVED, TYPE>::value, DERIVED>::type operator * (const TYPE & a, const DERIVED & b) { return DERIVED(a).operator * (b); } // do not invert (Sequence) template<typename TYPE> friend typename mpl::enable_if<! mpl::is_base_of<DERIVED, TYPE>::value, DERIVED>::type operator - (const TYPE & a, const DERIVED & b) { return DERIVED(a).operator - (b); } template<typename TYPE> friend typename mpl::enable_if<! mpl::is_base_of<DERIVED, TYPE>::value, DERIVED>::type operator / (const TYPE & a, const DERIVED & b) { return DERIVED(a).operator / (b); } public: virtual ~Base() { } /// \brief Class name /// This function returns the actual class name // \return the class name virtual str_type class_name() const =0; /// \brief Write to an output stream the generalized representation of the actual object /// The 'grepr_s()' method is used to implement all other representations. /// \param[in] os the output stream /// \param[in] rtype the representation type /// \param[in] pretty pretty mode /// \param[in] dump_options the dump options /// \param[in] level the depth level /// \return the output stream virtual std::ostream & grepr_s(std::ostream & os, ReprType::enum_type rtype, bool pretty=false, const DumpOptions & dump_options=DEFAULT_DUMP_OPTIONS, int level=0) const { os << this->class_name() << "()"; return os; } /// \brief Write to an output stream the 'repr' representation of the actual object /// \param[in] os the output stream /// \return the output stream virtual std::ostream & repr_s(std::ostream & os) const { return this->grepr_s(os, ReprType::CONFIG, false, DEFAULT_DUMP_OPTIONS, 0); } /// \brief Write to an output stream the 'pretty' representation of the actual object /// \param[in] os the output stream /// \param[in] level the depth level /// \return the output stream virtual std::ostream & pretty_s(std::ostream & os, int level=0) const { return this->grepr_s(os, ReprType::CONFIG, true, DEFAULT_DUMP_OPTIONS, level); } /// \brief Write to an output stream the 'str' representation of the actual object /// \param[in] os the output stream /// \return the output stream virtual std::ostream & str_s(std::ostream & os) const { return this->repr_s(os); } /// \brief The generalized representation of the actual object /// \param[in] rtype the representation type /// \param[in] pretty pretty mode /// \param[in] level the depth level /// \return the generalized representation virtual str_type grepr(ReprType::enum_type rtype, bool pretty=false, const DumpOptions & dump_options=DEFAULT_DUMP_OPTIONS, int level=0) const { std::ostringstream os; this->grepr_s(os, rtype, pretty, dump_options, level); return os.str(); } /// \brief The 'pretty' representation of the actual object /// \param[in] level the depth level /// \return the 'pretty' representation virtual str_type pretty(int level=0) const { std::ostringstream os; this->pretty_s(os, level); return os.str(); } /// \brief The 'repr' representation of the actual object /// \return the 'repr' representation virtual str_type repr() const { std::ostringstream os; this->repr_s(os); return os.str(); } /// \brief The 'str' representation of the actual object /// \return the 'str' representation virtual str_type str() const { std::ostringstream os; this->str_s(os); return os.str(); } /// \brief The 'hash' representation of the actual object /// \return the 'hash' representation virtual hash_type hash() const { return this->grepr(ReprType::CPP, false, DEFAULT_DUMP_OPTIONS, 0); } }; template<typename TYPE> std::ostream & operator <<(std::ostream & os, const Base<TYPE> & b) { return b.str_s(os); } } // namespace configment #endif // #define configment_base_h_20130426
simone-campagna/Configment
configment/configment/base.h
C
apache-2.0
7,689
Starting with Babylon.js 2.3 the loading screen (the screen used when loading assets or a scene) can be changed by the developer. To create a new loading screen, you will have to create a simple class, implementing the following interface: ```javascript interface ILoadingScreen { //What happens when loading starts displayLoadingUI: () => void; //What happens when loading stops hideLoadingUI: () => void; //default loader support. Optional! loadingUIBackgroundColor: string; loadingUIText: string; } ``` In plain JavaScript, your loader code will look like this: ```javascript function MyLoadingScreen( /* variables needed, for example:*/ text) { //init the loader this.loadingUIText = text; } MyLoadingScreen.prototype.displayLoadingUI = function() { alert(this.loadingUIText); }; MyLoadingScreen.prototype.hideLoadingUI = function() { alert("Loaded!"); }; ``` In TypeScript the same will look like this: ```javascript class MyLoadingScreen implements ILoadingScreen { //optional, but needed due to interface definitions public loadingUIBackgroundColor: string constructor(public loadingUIText: string) {} public displayLoadingUI() { alert(this.loadingUIText); } public hideLoadingUI() { alert("Loaded!"); } } ``` The usage is the same in both languages: ```javascript var loadingScreen = new MyLoadingScreen("I'm loading!!"); //Set the loading screen in the engine to replace the default one engine.loadingScreen = loadingScreen; ```
h53d/babylonjs-doc-cn
target/tutorials/02_Mid_Level/Creating_a_custom_loading_screen.md
Markdown
apache-2.0
1,490
/* * PowerAuth Web Flow and related software components * Copyright (C) 2019 Wultra s.r.o. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.getlime.security.powerauth.lib.webflow.authentication.method.loginsca.controller; import io.getlime.core.rest.model.base.response.ObjectResponse; import io.getlime.security.powerauth.lib.dataadapter.client.DataAdapterClient; import io.getlime.security.powerauth.lib.dataadapter.client.DataAdapterClientErrorException; import io.getlime.security.powerauth.lib.dataadapter.model.converter.FormDataConverter; import io.getlime.security.powerauth.lib.dataadapter.model.converter.UserAccountStatusConverter; import io.getlime.security.powerauth.lib.dataadapter.model.entity.FormData; import io.getlime.security.powerauth.lib.dataadapter.model.entity.OperationContext; import io.getlime.security.powerauth.lib.dataadapter.model.enumeration.AccountStatus; import io.getlime.security.powerauth.lib.dataadapter.model.enumeration.CertificateVerificationResult; import io.getlime.security.powerauth.lib.dataadapter.model.response.InitAuthMethodResponse; import io.getlime.security.powerauth.lib.dataadapter.model.response.UserDetailResponse; import io.getlime.security.powerauth.lib.dataadapter.model.response.VerifyCertificateResponse; import io.getlime.security.powerauth.lib.nextstep.client.NextStepClient; import io.getlime.security.powerauth.lib.nextstep.client.NextStepClientException; import io.getlime.security.powerauth.lib.nextstep.model.entity.ApplicationContext; import io.getlime.security.powerauth.lib.nextstep.model.entity.CredentialDetail; import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.CredentialType; import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.UserAccountStatus; import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.UserIdentityStatus; import io.getlime.security.powerauth.lib.nextstep.model.enumeration.*; import io.getlime.security.powerauth.lib.nextstep.model.exception.UserNotFoundException; import io.getlime.security.powerauth.lib.nextstep.model.response.*; import io.getlime.security.powerauth.lib.webflow.authentication.base.AuthStepResponse; import io.getlime.security.powerauth.lib.webflow.authentication.configuration.WebFlowServicesConfiguration; import io.getlime.security.powerauth.lib.webflow.authentication.controller.AuthMethodController; import io.getlime.security.powerauth.lib.webflow.authentication.exception.AuthStepException; import io.getlime.security.powerauth.lib.webflow.authentication.exception.AuthenticationFailedException; import io.getlime.security.powerauth.lib.webflow.authentication.exception.CommunicationFailedException; import io.getlime.security.powerauth.lib.webflow.authentication.exception.MaxAttemptsExceededException; import io.getlime.security.powerauth.lib.webflow.authentication.method.loginsca.model.request.LoginScaAuthRequest; import io.getlime.security.powerauth.lib.webflow.authentication.method.loginsca.model.request.LoginScaInitRequest; import io.getlime.security.powerauth.lib.webflow.authentication.method.loginsca.model.response.LoginScaAuthResponse; import io.getlime.security.powerauth.lib.webflow.authentication.method.loginsca.model.response.LoginScaInitResponse; import io.getlime.security.powerauth.lib.webflow.authentication.model.AuthOperationResponse; import io.getlime.security.powerauth.lib.webflow.authentication.model.HttpSessionAttributeNames; import io.getlime.security.powerauth.lib.webflow.authentication.model.OrganizationDetail; import io.getlime.security.powerauth.lib.webflow.authentication.model.converter.OrganizationConverter; import io.getlime.security.powerauth.lib.webflow.authentication.service.AuthMethodQueryService; import io.getlime.security.powerauth.lib.webflow.authentication.service.AuthenticationManagementService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; import javax.validation.Valid; import java.util.Collections; import java.util.List; /** * Controller for initialization of SCA login. * * @author Roman Strobl, roman.strobl@wultra.com */ @RestController @RequestMapping(value = "/api/auth/login-sca") public class LoginScaController extends AuthMethodController<LoginScaAuthRequest, LoginScaAuthResponse, AuthStepException> { private static final Logger logger = LoggerFactory.getLogger(LoginScaController.class); private final DataAdapterClient dataAdapterClient; private final NextStepClient nextStepClient; private final AuthMethodQueryService authMethodQueryService; private final AuthenticationManagementService authenticationManagementService; private final HttpSession httpSession; private final WebFlowServicesConfiguration configuration; private final OrganizationConverter organizationConverter = new OrganizationConverter(); private final UserAccountStatusConverter statusConverter = new UserAccountStatusConverter(); /** * Controller constructor. * @param dataAdapterClient Data Adapter client. * @param nextStepClient Next Step client. * @param authMethodQueryService Service for querying authentication methods. * @param authenticationManagementService Authentication management service. * @param httpSession HTTP session. * @param configuration Web Flow configuration. */ @Autowired public LoginScaController(DataAdapterClient dataAdapterClient, NextStepClient nextStepClient, AuthMethodQueryService authMethodQueryService, AuthenticationManagementService authenticationManagementService, HttpSession httpSession, WebFlowServicesConfiguration configuration) { this.dataAdapterClient = dataAdapterClient; this.nextStepClient = nextStepClient; this.authMethodQueryService = authMethodQueryService; this.authenticationManagementService = authenticationManagementService; this.httpSession = httpSession; this.configuration = configuration; } /** * Initialize SCA login for given username. * @param request Initialization request. * @return SCA login initialization response. * @throws AuthStepException In case SCA login initialization fails. */ @RequestMapping(value = "/authenticate", method = RequestMethod.POST) public LoginScaAuthResponse authenticateScaLogin(@Valid @RequestBody LoginScaAuthRequest request) throws AuthStepException { GetOperationDetailResponse operation = getOperation(); logger.info("Step authentication started, operation ID: {}, authentication method: {}", operation.getOperationId(), getAuthMethodName().toString()); try { FormData formData = new FormDataConverter().fromOperationFormData(operation.getFormData()); ApplicationContext applicationContext = operation.getApplicationContext(); OperationContext operationContext = new OperationContext(operation.getOperationId(), operation.getOperationName(), operation.getOperationData(), operation.getExternalTransactionId(), formData, applicationContext); String userId = operation.getUserId(); String organizationId = request.getOrganizationId(); boolean userIdAlreadyAvailable; boolean userAuthenticatedUsingCertificate = false; UserIdentityStatus status = null; if (userId == null) { // First time invocation, user ID is not available yet userIdAlreadyAvailable = false; String clientCertificate = getClientCertificateFromHttpSession(); String username = request.getUsername(); // Check that either certificate or username is available if (clientCertificate == null && username == null) { logger.warn("Both username and client certificate are unknown"); LoginScaAuthResponse response = new LoginScaAuthResponse(); response.setResult(AuthStepResult.AUTH_FAILED); response.setMessage("login.userNotFound"); return response; } if (clientCertificate != null) { // Client certificates are implemented in DA, use lookup via DA ObjectResponse<UserDetailResponse> objectResponse = dataAdapterClient.lookupUser(username, organizationId, clientCertificate, operationContext); UserDetailResponse userDetailResponse = objectResponse.getResponseObject(); userId = userDetailResponse.getId(); AccountStatus accountStatus = userDetailResponse.getAccountStatus(); userAuthenticatedUsingCertificate = verifyClientCertificate(operation.getOperationId(), userId, organizationId, clientCertificate, accountStatus, operationContext); } else { // Lookup user via NS GetOrganizationDetailResponse organization = nextStepClient.getOrganizationDetail(organizationId).getResponseObject(); String credentialName = organization.getDefaultCredentialName(); if (credentialName == null) { logger.warn("Default credential name is not configured for organization: " + request.getOrganizationId()); throw new AuthStepException("User authentication failed", "error.communication"); } LookupUserResponse lookupResponse; try { lookupResponse = nextStepClient.lookupUser(username, credentialName, operation.getOperationId()).getResponseObject(); GetUserDetailResponse userDetail = lookupResponse.getUser(); // The temporary credential type should can be checked, if required by Web Flow configuration if (!configuration.isAuthenticationWithTemporaryCredentialsAllowed()) { List<CredentialDetail> credentials = lookupResponse.getUser().getCredentials(); if (credentials != null && !credentials.isEmpty()) { // Lookup returns either empty credentials when Data Adapter proxy is enabled // or exactly one credential for queried credential definition in Next Step. if (credentials.size() != 1) { logger.warn("Unexpected credential count in Next Step response: {}", credentials.size()); throw new AuthStepException("User authentication failed", "error.communication"); } CredentialDetail credentialDetail = credentials.get(0); if (credentialDetail.getCredentialType() != CredentialType.TEMPORARY) { // Lookup succeeded and credential type is not temporary, use user ID from lookup response userId = userDetail.getUserId(); } } else { // Lookup succeeded and Data Adapter proxy is enabled userId = userDetail.getUserId(); } } else { // Lookup succeeded, use user ID from lookup response userId = userDetail.getUserId(); } status = userDetail.getUserIdentityStatus(); } catch (NextStepClientException ex) { if (ex.getNextStepError() == null || !UserNotFoundException.CODE.equals(ex.getNextStepError().getCode())) { // Unexpected error occurred in Next Step throw ex; } // Expected case when user is not found, continue with authentication to avoid leaking information } updateUsernameInHttpSession(username); } } else { // User ID is already set, this can happen when the user refreshes the page or another authentication method set the user ID userIdAlreadyAvailable = true; } LoginScaAuthResponse response = new LoginScaAuthResponse(); if (!userIdAlreadyAvailable && userId != null) { // User ID lookup succeeded, update user ID in operation so that Push Server can deliver the personal push message authenticationManagementService.updateAuthenticationWithUserDetails(userId, organizationId); authenticationManagementService.upgradeToStrongCustomerAuthentication(); UserAccountStatus accountStatus = statusConverter.toUserAccountStatus(status); nextStepClient.updateOperationUser(operation.getOperationId(), userId, organizationId, accountStatus); } if (userAuthenticatedUsingCertificate) { logger.debug("Step authentication succeeded with client certificate, operation ID: {}, authentication method: {}", operation.getOperationId(), getAuthMethodName().toString()); return authenticateStepUsingClientCertificate(operation.getOperationId(), userId, organizationId); } if (userId == null || status != UserIdentityStatus.ACTIVE) { // User ID is not available or user identity is not ACTIVE, mock SMS and password fallback to avoid fishing for active accounts response.setResult(AuthStepResult.CONFIRMED); response.setMobileTokenEnabled(false); logger.debug("Step authentication succeeded with fake SMS authorization, operation ID: {}, authentication method: {}", operation.getOperationId(), getAuthMethodName().toString()); } else { // Find out whether mobile token is enabled boolean mobileTokenEnabled = false; try { if (authMethodQueryService.isMobileTokenAvailable(userId, operation.getOperationId())) { nextStepClient.updateMobileToken(operation.getOperationId(), true); mobileTokenEnabled = true; } } catch (NextStepClientException ex) { logger.error("Error occurred in Next Step server", ex); } response.setMobileTokenEnabled(mobileTokenEnabled); response.setResult(AuthStepResult.CONFIRMED); if (mobileTokenEnabled) { logger.debug("Step authentication succeeded with mobile token, operation ID: {}, authentication method: {}", operation.getOperationId(), getAuthMethodName().toString()); } else { logger.debug("Step authentication succeeded with SMS authorization, operation ID: {}, authentication method: {}", operation.getOperationId(), getAuthMethodName().toString()); } } return response; } catch (NextStepClientException | DataAdapterClientErrorException ex) { logger.error(ex.getMessage(), ex); // Send error to client LoginScaAuthResponse response = new LoginScaAuthResponse(); response.setResult(AuthStepResult.AUTH_FAILED); if (ex instanceof DataAdapterClientErrorException) { DataAdapterClientErrorException ex2 = (DataAdapterClientErrorException) ex; response.setRemainingAttempts(ex2.getError().getRemainingAttempts()); response.setMessage(ex2.getError().getMessage()); } else { response.setMessage("error.communication"); } return response; } } /** * Prepare login form data. * @param request Prepare login form data request. * @return Prepare login form response. * @throws AuthStepException Thrown when request is invalid or communication with Next Step fails. */ @RequestMapping(value = "/init", method = RequestMethod.POST) public LoginScaInitResponse initScaLogin(@RequestBody LoginScaInitRequest request) throws AuthStepException { final LoginScaInitResponse response = new LoginScaInitResponse(); final GetOperationDetailResponse operation = getOperation(); try { logger.info("Step init started, operation ID: {}, authentication method: {}", operation.getOperationId(), getAuthMethodName().toString()); // Set chosen authentication method to LOGIN_SCA nextStepClient.updateChosenAuthMethod(operation.getOperationId(), AuthMethod.LOGIN_SCA); FormData formData = new FormDataConverter().fromOperationFormData(operation.getFormData()); ApplicationContext applicationContext = operation.getApplicationContext(); OperationContext operationContext = new OperationContext(operation.getOperationId(), operation.getOperationName(), operation.getOperationData(), operation.getExternalTransactionId(), formData, applicationContext); ObjectResponse<InitAuthMethodResponse> objectResponse = dataAdapterClient.initAuthMethod(operation.getUserId(), operation.getOrganizationId(), AuthMethod.LOGIN_SCA, operationContext); InitAuthMethodResponse initResponse = objectResponse.getResponseObject(); switch (initResponse.getCertificateAuthenticationMode()) { case ENABLED: response.setClientCertificateAuthenticationAvailable(true); response.setClientCertificateAuthenticationEnabled(true); break; case DISABLED: response.setClientCertificateAuthenticationAvailable(true); response.setClientCertificateAuthenticationEnabled(false); break; default: response.setClientCertificateAuthenticationAvailable(false); response.setClientCertificateAuthenticationEnabled(false); } response.setClientCertificateVerificationUrl(initResponse.getCertificateVerificationUrl()); if (operation.getUserId() != null && operation.getOrganizationId() != null) { // Username form can be skipped response.setUserAlreadyKnown(true); // Find out whether mobile token is enabled boolean mobileTokenEnabled = false; try { if (authMethodQueryService.isMobileTokenAvailable(operation.getUserId(), operation.getOperationId())) { mobileTokenEnabled = true; } } catch (NextStepClientException ex) { logger.error("Error occurred in Next Step server", ex); } response.setMobileTokenEnabled(mobileTokenEnabled); logger.info("Step init skipped, user and organization is already known, operation ID: {}, authentication method: {}", operation.getOperationId(), getAuthMethodName().toString()); return response; } ObjectResponse<GetOrganizationListResponse> nsObjectResponse = nextStepClient.getOrganizationList(); List<GetOrganizationDetailResponse> nsResponseList = nsObjectResponse.getResponseObject().getOrganizations(); for (GetOrganizationDetailResponse nsResponse: nsResponseList) { // Show only organizations which have a display name key set to avoid broken UI if (nsResponse.getDisplayNameKey() != null) { OrganizationDetail organization = organizationConverter.fromNSOrganization(nsResponse); response.addOrganization(organization); } } } catch (NextStepClientException ex) { logger.error("Error occurred in Next Step server", ex); throw new CommunicationFailedException("Communication with Next Step service failed"); } catch (DataAdapterClientErrorException ex) { logger.error("Error occurred in Data Adapter", ex); throw new CommunicationFailedException("Communication with Data Adapter service failed"); } logger.info("Step authentication succeeded, operation ID: {}, authentication method: {}", operation.getOperationId(), getAuthMethodName().toString()); return response; } /** * Get current authentication method name. * @return Current authentication method name. */ @Override protected AuthMethod getAuthMethodName() { return AuthMethod.LOGIN_SCA; } /** * Set username in HTTP session. * @param username Username supplied by user. */ private void updateUsernameInHttpSession(String username) { synchronized (httpSession.getServletContext()) { httpSession.setAttribute(HttpSessionAttributeNames.USERNAME, username); } } /** * Get client TLS certificate from HTTP session. * @return Client certificate. */ private String getClientCertificateFromHttpSession() { synchronized (httpSession.getServletContext()) { return (String) httpSession.getAttribute(HttpSessionAttributeNames.CLIENT_CERTIFICATE); } } /** * Cancel operation. * @return Object response. * @throws AuthStepException Thrown when operation could not be canceled. */ @RequestMapping(value = "/cancel", method = RequestMethod.POST) public AuthStepResponse cancelAuthentication() throws AuthStepException { try { final GetOperationDetailResponse operation = getOperation(); cancelAuthorization(operation.getOperationId(), operation.getUserId(), OperationCancelReason.UNKNOWN, null, true); final AuthStepResponse response = new AuthStepResponse(); response.setResult(AuthStepResult.CANCELED); response.setMessage("operation.canceled"); logger.info("Step result: CANCELED, operation ID: {}, authentication method: {}", operation.getOperationId(), getAuthMethodName().toString()); return response; } catch (CommunicationFailedException ex) { final AuthStepResponse response = new AuthStepResponse(); response.setResult(AuthStepResult.AUTH_FAILED); response.setMessage("error.communication"); logger.info("Step result: AUTH_FAILED, authentication method: {}", getAuthMethodName().toString()); return response; } } /** * Authenticate client TLS certificate using Data Adapter. * @param operationId Operation ID. * @param userId User ID. * @param organizationId Organization ID. * @param clientCertificate Client TLS certificate. * @param accountStatus Account status. * @param operationContext Operation context. * @return Whether authentication using client TLS certificate succeeded. * @throws DataAdapterClientErrorException In case communication with Data Adapter fails. * @throws NextStepClientException In case communication with Next Step service fails. * @throws AuthStepException In case step authentication fails. */ private boolean verifyClientCertificate(String operationId, String userId, String organizationId, String clientCertificate, AccountStatus accountStatus, OperationContext operationContext) throws DataAdapterClientErrorException, NextStepClientException, AuthStepException { ObjectResponse<VerifyCertificateResponse> objectResponseCert = dataAdapterClient.verifyClientCertificate(userId, organizationId, clientCertificate, getAuthMethodName(), accountStatus, operationContext); VerifyCertificateResponse certResponse = objectResponseCert.getResponseObject(); CertificateVerificationResult verificationResult = certResponse.getCertificateVerificationResult(); if (verificationResult == CertificateVerificationResult.SUCCEEDED) { return true; } logger.debug("Step authentication failed with client certificate, operation ID: {}, authentication method: {}", operationId, getAuthMethodName().toString()); List<AuthInstrument> authInstruments = Collections.singletonList(AuthInstrument.CLIENT_CERTIFICATE); AuthOperationResponse response = failAuthorization(operationId, userId, authInstruments, null, null); Integer remainingAttemptsDA = certResponse.getRemainingAttempts(); if (response.getAuthResult() == AuthResult.FAILED || (remainingAttemptsDA != null && remainingAttemptsDA == 0)) { // FAILED result instead of CONTINUE means the authentication method is failed throw new MaxAttemptsExceededException("Maximum number of authentication attempts exceeded"); } boolean showRemainingAttempts = certResponse.getShowRemainingAttempts(); UserAccountStatus userAccountStatus = statusConverter.fromAccountStatus(certResponse.getAccountStatus()); String errorMessage = "login.authenticationFailed"; if (certResponse.getErrorMessage() != null) { errorMessage = certResponse.getErrorMessage(); } AuthenticationFailedException authEx = new AuthenticationFailedException("Authentication failed", errorMessage); if (showRemainingAttempts) { GetOperationDetailResponse updatedOperation = getOperation(); Integer remainingAttemptsNS = updatedOperation.getRemainingAttempts(); Integer remainingAttempts = resolveRemainingAttempts(remainingAttemptsDA, remainingAttemptsNS); authEx.setRemainingAttempts(remainingAttempts); } authEx.setAccountStatus(userAccountStatus); throw authEx; } /** * User was successfully authenticated using client TLS certificate. Move user to the next step. * @return Login SCA authentication response. */ private LoginScaAuthResponse authenticateStepUsingClientCertificate(String operationId, String userId, String organizationId) { List<AuthInstrument> authInstruments = Collections.singletonList(AuthInstrument.CLIENT_CERTIFICATE); try { AuthOperationResponse updateResponse = authorize(operationId, userId, organizationId, authInstruments, null, null); final LoginScaAuthResponse response = new LoginScaAuthResponse(); response.setResult(AuthStepResult.CONFIRMED); response.setMessage("authentication.success"); response.getNext().addAll(updateResponse.getSteps()); logger.info("Step result: CONFIRMED, operation ID: {}, authentication method: {}", operationId, AuthMethod.LOGIN_SCA); return response; } catch (AuthStepException ex) { logger.error("Error while building authorization response for client TLS certificate verification", ex); final LoginScaAuthResponse response = new LoginScaAuthResponse(); response.setResult(AuthStepResult.AUTH_FAILED); response.setMessage("authentication.fail"); return response; } catch (NextStepClientException ex) { logger.error("Error while communicating with Next Step service", ex); final LoginScaAuthResponse response = new LoginScaAuthResponse(); response.setResult(AuthStepResult.AUTH_FAILED); response.setMessage("error.communication"); return response; } } }
lime-company/powerauth-webflow
powerauth-webflow-authentication-login-sca/src/main/java/io/getlime/security/powerauth/lib/webflow/authentication/method/loginsca/controller/LoginScaController.java
Java
apache-2.0
28,707
# TODO: Yes need to fix this violation of visibility from functools import partial from jarvis_cli.client.common import _get_jarvis_resource, _post_jarvis_resource, \ _put_jarvis_resource, query def _construct_log_entry_endpoint(event_id): return "events/{0}/logentries".format(event_id) def get_log_entry(event_id, conn, log_entry_id): return _get_jarvis_resource(_construct_log_entry_endpoint(event_id), conn, log_entry_id) def post_log_entry(event_id, conn, log_entry_request, quiet=False, skip_tags_check=False): return _post_jarvis_resource(_construct_log_entry_endpoint(event_id), conn, log_entry_request, quiet, skip_tags_check) def put_log_entry(event_id, conn, log_entry_id, log_entry_request): return _put_jarvis_resource(_construct_log_entry_endpoint(event_id), conn, log_entry_id, log_entry_request) query_log_entries = partial(query, "search/logentries")
clb6/jarvis-cli
jarvis_cli/client/log_entry.py
Python
apache-2.0
938
/* Copyright 2019 The Vitess 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 wrangler import ( "context" "fmt" "hash/fnv" "math" "sort" "strings" "sync" "text/template" "google.golang.org/protobuf/encoding/prototext" "google.golang.org/protobuf/proto" "vitess.io/vitess/go/json2" "vitess.io/vitess/go/sqltypes" "vitess.io/vitess/go/vt/binlog/binlogplayer" "vitess.io/vitess/go/vt/concurrency" "vitess.io/vitess/go/vt/key" "vitess.io/vitess/go/vt/log" "vitess.io/vitess/go/vt/mysqlctl/tmutils" "vitess.io/vitess/go/vt/schema" "vitess.io/vitess/go/vt/sqlparser" "vitess.io/vitess/go/vt/topo" "vitess.io/vitess/go/vt/topotools" "vitess.io/vitess/go/vt/vtctl/schematools" "vitess.io/vitess/go/vt/vtctl/workflow" "vitess.io/vitess/go/vt/vterrors" "vitess.io/vitess/go/vt/vtgate/evalengine" "vitess.io/vitess/go/vt/vtgate/vindexes" "vitess.io/vitess/go/vt/vttablet/tabletmanager/vreplication" binlogdatapb "vitess.io/vitess/go/vt/proto/binlogdata" querypb "vitess.io/vitess/go/vt/proto/query" vschemapb "vitess.io/vitess/go/vt/proto/vschema" vtctldatapb "vitess.io/vitess/go/vt/proto/vtctldata" ) type materializer struct { wr *Wrangler ms *vtctldatapb.MaterializeSettings targetVSchema *vindexes.KeyspaceSchema sourceShards []*topo.ShardInfo targetShards []*topo.ShardInfo } const ( createDDLAsCopy = "copy" createDDLAsCopyDropConstraint = "copy:drop_constraint" ) // addTablesToVSchema adds tables to an (unsharded) vschema. Depending on copyAttributes It will also add any sequence info // that is associated with a table by copying it from the vschema of the source keyspace. // For a migrate workflow we do not copy attributes since the source keyspace is just a proxy to import data into Vitess // Todo: For now we only copy sequence but later we may also want to copy other attributes like authoritative column flag and list of columns func (wr *Wrangler) addTablesToVSchema(ctx context.Context, sourceKeyspace string, targetVSchema *vschemapb.Keyspace, tables []string, copyAttributes bool) error { if targetVSchema.Tables == nil { targetVSchema.Tables = make(map[string]*vschemapb.Table) } for _, table := range tables { targetVSchema.Tables[table] = &vschemapb.Table{} } if copyAttributes { // if source keyspace is provided, copy over the sequence info. srcVSchema, err := wr.ts.GetVSchema(ctx, sourceKeyspace) if err != nil { return err } for _, table := range tables { srcTable, ok := srcVSchema.Tables[table] if ok { targetVSchema.Tables[table].AutoIncrement = srcTable.AutoIncrement } } } return nil } func shouldInclude(table string, excludes []string) bool { // We filter out internal tables elsewhere when processing SchemaDefinition // structures built from the GetSchema database related API calls. In this // case, however, the table list comes from the user via the -tables flag // so we need to filter out internal table names here in case a user has // explicitly specified some. // This could happen if there's some automated tooling that creates the list of // tables to explicitly specify. // But given that this should never be done in practice, we ignore the request. if schema.IsInternalOperationTableName(table) { return false } for _, t := range excludes { if t == table { return false } } return true } // MoveTables initiates moving table(s) over to another keyspace func (wr *Wrangler) MoveTables(ctx context.Context, workflow, sourceKeyspace, targetKeyspace, tableSpecs, cell, tabletTypes string, allTables bool, excludeTables string, autoStart, stopAfterCopy bool, externalCluster string) error { //FIXME validate tableSpecs, allTables, excludeTables var tables []string var externalTopo *topo.Server var err error if externalCluster != "" { // when the source is an external mysql cluster mounted using the Mount command externalTopo, err = wr.ts.OpenExternalVitessClusterServer(ctx, externalCluster) if err != nil { return err } wr.sourceTs = externalTopo log.Infof("Successfully opened external topo: %+v", externalTopo) } var vschema *vschemapb.Keyspace vschema, err = wr.ts.GetVSchema(ctx, targetKeyspace) if err != nil { return err } if vschema == nil { return fmt.Errorf("no vschema found for target keyspace %s", targetKeyspace) } if strings.HasPrefix(tableSpecs, "{") { if vschema.Tables == nil { vschema.Tables = make(map[string]*vschemapb.Table) } wrap := fmt.Sprintf(`{"tables": %s}`, tableSpecs) ks := &vschemapb.Keyspace{} if err := json2.Unmarshal([]byte(wrap), ks); err != nil { return err } for table, vtab := range ks.Tables { vschema.Tables[table] = vtab tables = append(tables, table) } } else { if len(strings.TrimSpace(tableSpecs)) > 0 { tables = strings.Split(tableSpecs, ",") } ksTables, err := wr.getKeyspaceTables(ctx, sourceKeyspace, wr.sourceTs) if err != nil { return err } if len(tables) > 0 { err = wr.validateSourceTablesExist(ctx, sourceKeyspace, ksTables, tables) if err != nil { return err } } else { if allTables { tables = ksTables } else { return fmt.Errorf("no tables to move") } } var excludeTablesList []string excludeTables = strings.TrimSpace(excludeTables) if excludeTables != "" { excludeTablesList = strings.Split(excludeTables, ",") err = wr.validateSourceTablesExist(ctx, sourceKeyspace, ksTables, excludeTablesList) if err != nil { return err } } var tables2 []string for _, t := range tables { if shouldInclude(t, excludeTablesList) { tables2 = append(tables2, t) } } tables = tables2 if len(tables) == 0 { return fmt.Errorf("no tables to move") } log.Infof("Found tables to move: %s", strings.Join(tables, ",")) if !vschema.Sharded { if err := wr.addTablesToVSchema(ctx, sourceKeyspace, vschema, tables, externalTopo == nil); err != nil { return err } } } if externalTopo == nil { // Save routing rules before vschema. If we save vschema first, and routing rules // fails to save, we may generate duplicate table errors. rules, err := topotools.GetRoutingRules(ctx, wr.ts) if err != nil { return err } for _, table := range tables { toSource := []string{sourceKeyspace + "." + table} rules[table] = toSource rules[table+"@replica"] = toSource rules[table+"@rdonly"] = toSource rules[targetKeyspace+"."+table] = toSource rules[targetKeyspace+"."+table+"@replica"] = toSource rules[targetKeyspace+"."+table+"@rdonly"] = toSource rules[targetKeyspace+"."+table] = toSource rules[sourceKeyspace+"."+table+"@replica"] = toSource rules[sourceKeyspace+"."+table+"@rdonly"] = toSource } if err := topotools.SaveRoutingRules(ctx, wr.ts, rules); err != nil { return err } if vschema != nil { // We added to the vschema. if err := wr.ts.SaveVSchema(ctx, targetKeyspace, vschema); err != nil { return err } } } if err := wr.ts.RebuildSrvVSchema(ctx, nil); err != nil { return err } ms := &vtctldatapb.MaterializeSettings{ Workflow: workflow, MaterializationIntent: vtctldatapb.MaterializationIntent_MOVETABLES, SourceKeyspace: sourceKeyspace, TargetKeyspace: targetKeyspace, Cell: cell, TabletTypes: tabletTypes, StopAfterCopy: stopAfterCopy, ExternalCluster: externalCluster, } for _, table := range tables { buf := sqlparser.NewTrackedBuffer(nil) buf.Myprintf("select * from %v", sqlparser.NewTableIdent(table)) ms.TableSettings = append(ms.TableSettings, &vtctldatapb.TableMaterializeSettings{ TargetTable: table, SourceExpression: buf.String(), CreateDdl: createDDLAsCopy, }) } mz, err := wr.prepareMaterializerStreams(ctx, ms) if err != nil { return err } tabletShards, err := wr.collectTargetStreams(ctx, mz) if err != nil { return err } migrationID, err := getMigrationID(targetKeyspace, tabletShards) if err != nil { return err } if externalCluster == "" { exists, tablets, err := wr.checkIfPreviousJournalExists(ctx, mz, migrationID) if err != nil { return err } if exists { wr.Logger().Errorf("Found a previous journal entry for %d", migrationID) msg := fmt.Sprintf("found an entry from a previous run for migration id %d in _vt.resharding_journal of tablets %s,", migrationID, strings.Join(tablets, ",")) msg += fmt.Sprintf("please review and delete it before proceeding and restart the workflow using the Workflow %s.%s start", workflow, targetKeyspace) return fmt.Errorf(msg) } } if autoStart { return mz.startStreams(ctx) } wr.Logger().Infof("Streams will not be started since -auto_start is set to false") return nil } func (wr *Wrangler) validateSourceTablesExist(ctx context.Context, sourceKeyspace string, ksTables, tables []string) error { // validate that tables provided are present in the source keyspace var missingTables []string for _, table := range tables { if schema.IsInternalOperationTableName(table) { continue } found := false for _, ksTable := range ksTables { if table == ksTable { found = true break } } if !found { missingTables = append(missingTables, table) } } if len(missingTables) > 0 { return fmt.Errorf("table(s) not found in source keyspace %s: %s", sourceKeyspace, strings.Join(missingTables, ",")) } return nil } func (wr *Wrangler) getKeyspaceTables(ctx context.Context, ks string, ts *topo.Server) ([]string, error) { shards, err := ts.GetServingShards(ctx, ks) if err != nil { return nil, err } if len(shards) == 0 { return nil, fmt.Errorf("keyspace %s has no shards", ks) } primary := shards[0].PrimaryAlias if primary == nil { return nil, fmt.Errorf("shard does not have a primary: %v", shards[0].ShardName()) } allTables := []string{"/.*/"} ti, err := ts.GetTablet(ctx, primary) if err != nil { return nil, err } schema, err := wr.tmc.GetSchema(ctx, ti.Tablet, allTables, nil, false) if err != nil { return nil, err } log.Infof("got table schemas from source primary %v.", primary) var sourceTables []string for _, td := range schema.TableDefinitions { sourceTables = append(sourceTables, td.Name) } return sourceTables, nil } func (wr *Wrangler) checkIfPreviousJournalExists(ctx context.Context, mz *materializer, migrationID int64) (bool, []string, error) { forAllSources := func(f func(*topo.ShardInfo) error) error { var wg sync.WaitGroup allErrors := &concurrency.AllErrorRecorder{} for _, sourceShard := range mz.sourceShards { wg.Add(1) go func(sourceShard *topo.ShardInfo) { defer wg.Done() if err := f(sourceShard); err != nil { allErrors.RecordError(err) } }(sourceShard) } wg.Wait() return allErrors.AggrError(vterrors.Aggregate) } var ( mu sync.Mutex exists bool tablets []string ws = workflow.NewServer(wr.ts, wr.tmc) ) err := forAllSources(func(si *topo.ShardInfo) error { tablet, err := wr.ts.GetTablet(ctx, si.PrimaryAlias) if err != nil { return err } if tablet == nil { return nil } _, exists, err = ws.CheckReshardingJournalExistsOnTablet(ctx, tablet.Tablet, migrationID) if err != nil { return err } if exists { mu.Lock() defer mu.Unlock() tablets = append(tablets, tablet.AliasString()) } return nil }) return exists, tablets, err } // CreateLookupVindex creates a lookup vindex and sets up the backfill. func (wr *Wrangler) CreateLookupVindex(ctx context.Context, keyspace string, specs *vschemapb.Keyspace, cell, tabletTypes string, continueAfterCopyWithOwner bool) error { ms, sourceVSchema, targetVSchema, err := wr.prepareCreateLookup(ctx, keyspace, specs, continueAfterCopyWithOwner) if err != nil { return err } if err := wr.ts.SaveVSchema(ctx, ms.TargetKeyspace, targetVSchema); err != nil { return err } ms.Cell = cell ms.TabletTypes = tabletTypes if err := wr.Materialize(ctx, ms); err != nil { return err } if err := wr.ts.SaveVSchema(ctx, keyspace, sourceVSchema); err != nil { return err } return wr.ts.RebuildSrvVSchema(ctx, nil) } // prepareCreateLookup performs the preparatory steps for creating a lookup vindex. func (wr *Wrangler) prepareCreateLookup(ctx context.Context, keyspace string, specs *vschemapb.Keyspace, continueAfterCopyWithOwner bool) (ms *vtctldatapb.MaterializeSettings, sourceVSchema, targetVSchema *vschemapb.Keyspace, err error) { // Important variables are pulled out here. var ( // lookup vindex info vindexName string vindex *vschemapb.Vindex targetKeyspace string targetTableName string vindexFromCols []string vindexToCol string // source table info sourceTableName string // sourceTable is the supplied table info sourceTable *vschemapb.Table // sourceVSchemaTable is the table info present in the vschema sourceVSchemaTable *vschemapb.Table // sourceVindexColumns are computed from the input sourceTable sourceVindexColumns []string // target table info createDDL string materializeQuery string ) // Validate input vindex if len(specs.Vindexes) != 1 { return nil, nil, nil, fmt.Errorf("only one vindex must be specified in the specs: %v", specs.Vindexes) } for name, vi := range specs.Vindexes { vindexName = name vindex = vi } if !strings.Contains(vindex.Type, "lookup") { return nil, nil, nil, fmt.Errorf("vindex %s is not a lookup type", vindex.Type) } strs := strings.Split(vindex.Params["table"], ".") if len(strs) != 2 { return nil, nil, nil, fmt.Errorf("vindex 'table' must be <keyspace>.<table>: %v", vindex) } targetKeyspace, targetTableName = strs[0], strs[1] vindexFromCols = strings.Split(vindex.Params["from"], ",") if strings.Contains(vindex.Type, "unique") { if len(vindexFromCols) != 1 { return nil, nil, nil, fmt.Errorf("unique vindex 'from' should have only one column: %v", vindex) } } else { if len(vindexFromCols) < 2 { return nil, nil, nil, fmt.Errorf("non-unique vindex 'from' should have more than one column: %v", vindex) } } vindexToCol = vindex.Params["to"] // Make the vindex write_only. If one exists already in the vschema, // it will need to match this vindex exactly, including the write_only setting. vindex.Params["write_only"] = "true" // See if we can create the vindex without errors. if _, err := vindexes.CreateVindex(vindex.Type, vindexName, vindex.Params); err != nil { return nil, nil, nil, err } // Validate input table if len(specs.Tables) != 1 { return nil, nil, nil, fmt.Errorf("exactly one table must be specified in the specs: %v", specs.Tables) } // Loop executes once. for k, ti := range specs.Tables { if len(ti.ColumnVindexes) != 1 { return nil, nil, nil, fmt.Errorf("exactly one ColumnVindex must be specified for the table: %v", specs.Tables) } sourceTableName = k sourceTable = ti } // Validate input table and vindex consistency if sourceTable.ColumnVindexes[0].Name != vindexName { return nil, nil, nil, fmt.Errorf("ColumnVindex name must match vindex name: %s vs %s", sourceTable.ColumnVindexes[0].Name, vindexName) } if vindex.Owner != "" && vindex.Owner != sourceTableName { return nil, nil, nil, fmt.Errorf("vindex owner must match table name: %v vs %v", vindex.Owner, sourceTableName) } if len(sourceTable.ColumnVindexes[0].Columns) != 0 { sourceVindexColumns = sourceTable.ColumnVindexes[0].Columns } else { if sourceTable.ColumnVindexes[0].Column == "" { return nil, nil, nil, fmt.Errorf("at least one column must be specified in ColumnVindexes: %v", sourceTable.ColumnVindexes) } sourceVindexColumns = []string{sourceTable.ColumnVindexes[0].Column} } if len(sourceVindexColumns) != len(vindexFromCols) { return nil, nil, nil, fmt.Errorf("length of table columns differes from length of vindex columns: %v vs %v", sourceVindexColumns, vindexFromCols) } // Validate against source vschema sourceVSchema, err = wr.ts.GetVSchema(ctx, keyspace) if err != nil { return nil, nil, nil, err } if sourceVSchema.Vindexes == nil { sourceVSchema.Vindexes = make(map[string]*vschemapb.Vindex) } // If source and target keyspaces are same, Make vschemas point to the same object. if keyspace == targetKeyspace { targetVSchema = sourceVSchema } else { targetVSchema, err = wr.ts.GetVSchema(ctx, targetKeyspace) if err != nil { return nil, nil, nil, err } } if targetVSchema.Vindexes == nil { targetVSchema.Vindexes = make(map[string]*vschemapb.Vindex) } if targetVSchema.Tables == nil { targetVSchema.Tables = make(map[string]*vschemapb.Table) } if existing, ok := sourceVSchema.Vindexes[vindexName]; ok { if !proto.Equal(existing, vindex) { return nil, nil, nil, fmt.Errorf("a conflicting vindex named %s already exists in the source vschema", vindexName) } } sourceVSchemaTable = sourceVSchema.Tables[sourceTableName] if sourceVSchemaTable == nil { if !schema.IsInternalOperationTableName(sourceTableName) { return nil, nil, nil, fmt.Errorf("source table %s not found in vschema", sourceTableName) } } for _, colVindex := range sourceVSchemaTable.ColumnVindexes { // For a conflict, the vindex name and column should match. if colVindex.Name != vindexName { continue } colName := colVindex.Column if len(colVindex.Columns) != 0 { colName = colVindex.Columns[0] } if colName == sourceVindexColumns[0] { return nil, nil, nil, fmt.Errorf("ColumnVindex for table %v already exists: %v, please remove it and try again", sourceTableName, colName) } } // Validate against source schema sourceShards, err := wr.ts.GetServingShards(ctx, keyspace) if err != nil { return nil, nil, nil, err } onesource := sourceShards[0] if onesource.PrimaryAlias == nil { return nil, nil, nil, fmt.Errorf("source shard has no primary: %v", onesource.ShardName()) } tableSchema, err := schematools.GetSchema(ctx, wr.ts, wr.tmc, onesource.PrimaryAlias, []string{sourceTableName}, nil, false) if err != nil { return nil, nil, nil, err } if len(tableSchema.TableDefinitions) != 1 { return nil, nil, nil, fmt.Errorf("unexpected number of tables returned from schema: %v", tableSchema.TableDefinitions) } // Generate "create table" statement lines := strings.Split(tableSchema.TableDefinitions[0].Schema, "\n") if len(lines) < 3 { // Unreachable return nil, nil, nil, fmt.Errorf("schema looks incorrect: %s, expecting at least four lines", tableSchema.TableDefinitions[0].Schema) } var modified []string modified = append(modified, strings.Replace(lines[0], sourceTableName, targetTableName, 1)) for i := range sourceVindexColumns { line, err := generateColDef(lines, sourceVindexColumns[i], vindexFromCols[i]) if err != nil { return nil, nil, nil, err } modified = append(modified, line) } if vindex.Params["data_type"] == "" || strings.EqualFold(vindex.Type, "consistent_lookup_unique") || strings.EqualFold(vindex.Type, "consistent_lookup") { modified = append(modified, fmt.Sprintf(" `%s` varbinary(128),", vindexToCol)) } else { modified = append(modified, fmt.Sprintf(" `%s` `%s`,", vindexToCol, vindex.Params["data_type"])) } buf := sqlparser.NewTrackedBuffer(nil) fmt.Fprintf(buf, " PRIMARY KEY (") prefix := "" for _, col := range vindexFromCols { fmt.Fprintf(buf, "%s`%s`", prefix, col) prefix = ", " } fmt.Fprintf(buf, ")") modified = append(modified, buf.String()) modified = append(modified, ")") createDDL = strings.Join(modified, "\n") // Generate vreplication query buf = sqlparser.NewTrackedBuffer(nil) buf.Myprintf("select ") for i := range vindexFromCols { buf.Myprintf("%v as %v, ", sqlparser.NewColIdent(sourceVindexColumns[i]), sqlparser.NewColIdent(vindexFromCols[i])) } if strings.EqualFold(vindexToCol, "keyspace_id") || strings.EqualFold(vindex.Type, "consistent_lookup_unique") || strings.EqualFold(vindex.Type, "consistent_lookup") { buf.Myprintf("keyspace_id() as %v ", sqlparser.NewColIdent(vindexToCol)) } else { buf.Myprintf("%v as %v ", sqlparser.NewColIdent(vindexToCol), sqlparser.NewColIdent(vindexToCol)) } buf.Myprintf("from %v", sqlparser.NewTableIdent(sourceTableName)) if vindex.Owner != "" { // Only backfill buf.Myprintf(" group by ") for i := range vindexFromCols { buf.Myprintf("%v, ", sqlparser.NewColIdent(vindexFromCols[i])) } buf.Myprintf("%v", sqlparser.NewColIdent(vindexToCol)) } materializeQuery = buf.String() // Update targetVSchema var targetTable *vschemapb.Table if targetVSchema.Sharded { // Choose a primary vindex type for target table based on source specs var targetVindexType string var targetVindex *vschemapb.Vindex for _, field := range tableSchema.TableDefinitions[0].Fields { if sourceVindexColumns[0] == field.Name { targetVindexType, err = vindexes.ChooseVindexForType(field.Type) if err != nil { return nil, nil, nil, err } targetVindex = &vschemapb.Vindex{ Type: targetVindexType, } break } } if targetVindex == nil { // Unreachable. We validated column names when generating the DDL. return nil, nil, nil, fmt.Errorf("column %s not found in schema %v", sourceVindexColumns[0], tableSchema.TableDefinitions[0]) } if existing, ok := targetVSchema.Vindexes[targetVindexType]; ok { if !proto.Equal(existing, targetVindex) { return nil, nil, nil, fmt.Errorf("a conflicting vindex named %v already exists in the target vschema", targetVindexType) } } else { targetVSchema.Vindexes[targetVindexType] = targetVindex } targetTable = &vschemapb.Table{ ColumnVindexes: []*vschemapb.ColumnVindex{{ Column: vindexFromCols[0], Name: targetVindexType, }}, } } else { targetTable = &vschemapb.Table{} } if existing, ok := targetVSchema.Tables[targetTableName]; ok { if !proto.Equal(existing, targetTable) { return nil, nil, nil, fmt.Errorf("a conflicting table named %v already exists in the target vschema", targetTableName) } } else { targetVSchema.Tables[targetTableName] = targetTable } ms = &vtctldatapb.MaterializeSettings{ Workflow: targetTableName + "_vdx", MaterializationIntent: vtctldatapb.MaterializationIntent_CREATELOOKUPINDEX, SourceKeyspace: keyspace, TargetKeyspace: targetKeyspace, StopAfterCopy: vindex.Owner != "" && !continueAfterCopyWithOwner, TableSettings: []*vtctldatapb.TableMaterializeSettings{{ TargetTable: targetTableName, SourceExpression: materializeQuery, CreateDdl: createDDL, }}, } // Update sourceVSchema sourceVSchema.Vindexes[vindexName] = vindex sourceVSchemaTable.ColumnVindexes = append(sourceVSchemaTable.ColumnVindexes, sourceTable.ColumnVindexes[0]) return ms, sourceVSchema, targetVSchema, nil } func generateColDef(lines []string, sourceVindexCol, vindexFromCol string) (string, error) { source := fmt.Sprintf("`%s`", sourceVindexCol) target := fmt.Sprintf("`%s`", vindexFromCol) for _, line := range lines[1:] { if strings.Contains(line, source) { line = strings.Replace(line, source, target, 1) line = strings.Replace(line, " AUTO_INCREMENT", "", 1) line = strings.Replace(line, " DEFAULT NULL", "", 1) return line, nil } } return "", fmt.Errorf("column %s not found in schema %v", sourceVindexCol, lines) } // ExternalizeVindex externalizes a lookup vindex that's finished backfilling or has caught up. func (wr *Wrangler) ExternalizeVindex(ctx context.Context, qualifiedVindexName string) error { splits := strings.Split(qualifiedVindexName, ".") if len(splits) != 2 { return fmt.Errorf("vindex name should be of the form keyspace.vindex: %s", qualifiedVindexName) } sourceKeyspace, vindexName := splits[0], splits[1] sourceVSchema, err := wr.ts.GetVSchema(ctx, sourceKeyspace) if err != nil { return err } sourceVindex := sourceVSchema.Vindexes[vindexName] if sourceVindex == nil { return fmt.Errorf("vindex %s not found in vschema", qualifiedVindexName) } qualifiedTableName := sourceVindex.Params["table"] splits = strings.Split(qualifiedTableName, ".") if len(splits) != 2 { return fmt.Errorf("table name in vindex should be of the form keyspace.table: %s", qualifiedTableName) } targetKeyspace, targetTableName := splits[0], splits[1] workflow := targetTableName + "_vdx" targetShards, err := wr.ts.GetServingShards(ctx, targetKeyspace) if err != nil { return err } // Create a parallelizer function. forAllTargets := func(f func(*topo.ShardInfo) error) error { var wg sync.WaitGroup allErrors := &concurrency.AllErrorRecorder{} for _, targetShard := range targetShards { wg.Add(1) go func(targetShard *topo.ShardInfo) { defer wg.Done() if err := f(targetShard); err != nil { allErrors.RecordError(err) } }(targetShard) } wg.Wait() return allErrors.AggrError(vterrors.Aggregate) } err = forAllTargets(func(targetShard *topo.ShardInfo) error { targetPrimary, err := wr.ts.GetTablet(ctx, targetShard.PrimaryAlias) if err != nil { return err } p3qr, err := wr.tmc.VReplicationExec(ctx, targetPrimary.Tablet, fmt.Sprintf("select id, state, message, source from _vt.vreplication where workflow=%s and db_name=%s", encodeString(workflow), encodeString(targetPrimary.DbName()))) if err != nil { return err } qr := sqltypes.Proto3ToResult(p3qr) for _, row := range qr.Rows { id, err := evalengine.ToInt64(row[0]) if err != nil { return err } state := row[1].ToString() message := row[2].ToString() var bls binlogdatapb.BinlogSource sourceBytes, err := row[3].ToBytes() if err != nil { return err } if err := prototext.Unmarshal(sourceBytes, &bls); err != nil { return err } if sourceVindex.Owner == "" || !bls.StopAfterCopy { // If there's no owner or we've requested that the workflow NOT be stopped // after the copy phase completes, then all streams need to be running. if state != binlogplayer.BlpRunning { return fmt.Errorf("stream %d for %v.%v is not in Running state: %v", id, targetShard.Keyspace(), targetShard.ShardName(), state) } } else { // If there is an owner, all streams need to be stopped after copy. if state != binlogplayer.BlpStopped || !strings.Contains(message, "Stopped after copy") { return fmt.Errorf("stream %d for %v.%v is not in Stopped after copy state: %v, %v", id, targetShard.Keyspace(), targetShard.ShardName(), state, message) } } } return nil }) if err != nil { return err } if sourceVindex.Owner != "" { // If there is an owner, we have to delete the streams. err := forAllTargets(func(targetShard *topo.ShardInfo) error { targetPrimary, err := wr.ts.GetTablet(ctx, targetShard.PrimaryAlias) if err != nil { return err } query := fmt.Sprintf("delete from _vt.vreplication where db_name=%s and workflow=%s", encodeString(targetPrimary.DbName()), encodeString(workflow)) _, err = wr.tmc.VReplicationExec(ctx, targetPrimary.Tablet, query) if err != nil { return err } return nil }) if err != nil { return err } } // Remove the write_only param and save the source vschema. delete(sourceVindex.Params, "write_only") if err := wr.ts.SaveVSchema(ctx, sourceKeyspace, sourceVSchema); err != nil { return err } return wr.ts.RebuildSrvVSchema(ctx, nil) } // func (wr *Wrangler) collectTargetStreams(ctx context.Context, mz *materializer) ([]string, error) { var shardTablets []string var mu sync.Mutex err := mz.forAllTargets(func(target *topo.ShardInfo) error { var qrproto *querypb.QueryResult var id int64 var err error targetPrimary, err := mz.wr.ts.GetTablet(ctx, target.PrimaryAlias) if err != nil { return vterrors.Wrapf(err, "GetTablet(%v) failed", target.PrimaryAlias) } query := fmt.Sprintf("select id from _vt.vreplication where db_name=%s and workflow=%s", encodeString(targetPrimary.DbName()), encodeString(mz.ms.Workflow)) if qrproto, err = mz.wr.tmc.VReplicationExec(ctx, targetPrimary.Tablet, query); err != nil { return vterrors.Wrapf(err, "VReplicationExec(%v, %s)", targetPrimary.Tablet, query) } qr := sqltypes.Proto3ToResult(qrproto) for i := 0; i < len(qr.Rows); i++ { id, err = evalengine.ToInt64(qr.Rows[i][0]) if err != nil { return err } mu.Lock() shardTablets = append(shardTablets, fmt.Sprintf("%s:%d", target.ShardName(), id)) mu.Unlock() } return nil }) if err != nil { return nil, err } return shardTablets, nil } // getMigrationID produces a reproducible hash based on the input parameters. func getMigrationID(targetKeyspace string, shardTablets []string) (int64, error) { sort.Strings(shardTablets) hasher := fnv.New64() hasher.Write([]byte(targetKeyspace)) for _, str := range shardTablets { hasher.Write([]byte(str)) } // Convert to int64 after dropping the highest bit. return int64(hasher.Sum64() & math.MaxInt64), nil } func (wr *Wrangler) prepareMaterializerStreams(ctx context.Context, ms *vtctldatapb.MaterializeSettings) (*materializer, error) { if err := wr.validateNewWorkflow(ctx, ms.TargetKeyspace, ms.Workflow); err != nil { return nil, err } mz, err := wr.buildMaterializer(ctx, ms) if err != nil { return nil, err } if err := mz.deploySchema(ctx); err != nil { return nil, err } insertMap := make(map[string]string, len(mz.targetShards)) for _, targetShard := range mz.targetShards { inserts, err := mz.generateInserts(ctx, targetShard) if err != nil { return nil, err } insertMap[targetShard.ShardName()] = inserts } if err := mz.createStreams(ctx, insertMap); err != nil { return nil, err } return mz, nil } // Materialize performs the steps needed to materialize a list of tables based on the materialization specs. func (wr *Wrangler) Materialize(ctx context.Context, ms *vtctldatapb.MaterializeSettings) error { mz, err := wr.prepareMaterializerStreams(ctx, ms) if err != nil { return err } return mz.startStreams(ctx) } func (wr *Wrangler) buildMaterializer(ctx context.Context, ms *vtctldatapb.MaterializeSettings) (*materializer, error) { vschema, err := wr.ts.GetVSchema(ctx, ms.TargetKeyspace) if err != nil { return nil, err } targetVSchema, err := vindexes.BuildKeyspaceSchema(vschema, ms.TargetKeyspace) if err != nil { return nil, err } if targetVSchema.Keyspace.Sharded { for _, ts := range ms.TableSettings { if targetVSchema.Tables[ts.TargetTable] == nil { return nil, fmt.Errorf("table %s not found in vschema for keyspace %s", ts.TargetTable, ms.TargetKeyspace) } } } sourceShards, err := wr.sourceTs.GetServingShards(ctx, ms.SourceKeyspace) if err != nil { return nil, err } targetShards, err := wr.ts.GetServingShards(ctx, ms.TargetKeyspace) if err != nil { return nil, err } return &materializer{ wr: wr, ms: ms, targetVSchema: targetVSchema, sourceShards: sourceShards, targetShards: targetShards, }, nil } func (mz *materializer) getSourceTableDDLs(ctx context.Context) (map[string]string, error) { sourceDDLs := make(map[string]string) allTables := []string{"/.*/"} sourcePrimary := mz.sourceShards[0].PrimaryAlias if sourcePrimary == nil { return nil, fmt.Errorf("source shard must have a primary for copying schema: %v", mz.sourceShards[0].ShardName()) } ti, err := mz.wr.sourceTs.GetTablet(ctx, sourcePrimary) if err != nil { return nil, err } sourceSchema, err := mz.wr.tmc.GetSchema(ctx, ti.Tablet, allTables, nil, false) if err != nil { return nil, err } for _, td := range sourceSchema.TableDefinitions { sourceDDLs[td.Name] = td.Schema } return sourceDDLs, nil } func (mz *materializer) deploySchema(ctx context.Context) error { var sourceDDLs map[string]string var mu sync.Mutex return mz.forAllTargets(func(target *topo.ShardInfo) error { allTables := []string{"/.*/"} hasTargetTable := map[string]bool{} targetSchema, err := schematools.GetSchema(ctx, mz.wr.ts, mz.wr.tmc, target.PrimaryAlias, allTables, nil, false) if err != nil { return err } for _, td := range targetSchema.TableDefinitions { hasTargetTable[td.Name] = true } targetTablet, err := mz.wr.ts.GetTablet(ctx, target.PrimaryAlias) if err != nil { return err } var applyDDLs []string for _, ts := range mz.ms.TableSettings { if hasTargetTable[ts.TargetTable] { // Table already exists. continue } if ts.CreateDdl == "" { return fmt.Errorf("target table %v does not exist and there is no create ddl defined", ts.TargetTable) } var err error mu.Lock() if len(sourceDDLs) == 0 { //only get ddls for tables, once and lazily: if we need to copy the schema from source to target //we copy schemas from primaries on the source keyspace //and we have found use cases where user just has a replica (no primary) in the source keyspace sourceDDLs, err = mz.getSourceTableDDLs(ctx) } mu.Unlock() if err != nil { log.Errorf("Error getting DDLs of source tables: %s", err.Error()) return err } createDDL := ts.CreateDdl if createDDL == createDDLAsCopy || createDDL == createDDLAsCopyDropConstraint { if ts.SourceExpression != "" { // Check for table if non-empty SourceExpression. sourceTableName, err := sqlparser.TableFromStatement(ts.SourceExpression) if err != nil { return err } if sourceTableName.Name.String() != ts.TargetTable { return fmt.Errorf("source and target table names must match for copying schema: %v vs %v", sqlparser.String(sourceTableName), ts.TargetTable) } } ddl, ok := sourceDDLs[ts.TargetTable] if !ok { return fmt.Errorf("source table %v does not exist", ts.TargetTable) } if createDDL == createDDLAsCopyDropConstraint { strippedDDL, err := stripTableConstraints(ddl) if err != nil { return err } ddl = strippedDDL } createDDL = ddl } applyDDLs = append(applyDDLs, createDDL) } if len(applyDDLs) > 0 { sql := strings.Join(applyDDLs, ";\n") _, err = mz.wr.tmc.ApplySchema(ctx, targetTablet.Tablet, &tmutils.SchemaChange{ SQL: sql, Force: false, AllowReplication: true, SQLMode: vreplication.SQLMode, }) if err != nil { return err } } return nil }) } func stripTableConstraints(ddl string) (string, error) { ast, err := sqlparser.ParseStrictDDL(ddl) if err != nil { return "", err } stripConstraints := func(cursor *sqlparser.Cursor) bool { switch node := cursor.Node().(type) { case sqlparser.DDLStatement: if node.GetTableSpec() != nil { node.GetTableSpec().Constraints = nil } } return true } noConstraintAST := sqlparser.Rewrite(ast, stripConstraints, nil) newDDL := sqlparser.String(noConstraintAST) return newDDL, nil } func (mz *materializer) generateInserts(ctx context.Context, targetShard *topo.ShardInfo) (string, error) { ig := vreplication.NewInsertGenerator(binlogplayer.BlpStopped, "{{.dbname}}") for _, sourceShard := range mz.sourceShards { // Don't create streams from sources which won't contain data for the target shard. // We only do it for MoveTables for now since this doesn't hold for materialize flows // where the target's sharding key might differ from that of the source if mz.ms.MaterializationIntent == vtctldatapb.MaterializationIntent_MOVETABLES && !key.KeyRangesIntersect(sourceShard.KeyRange, targetShard.KeyRange) { continue } bls := &binlogdatapb.BinlogSource{ Keyspace: mz.ms.SourceKeyspace, Shard: sourceShard.ShardName(), Filter: &binlogdatapb.Filter{}, StopAfterCopy: mz.ms.StopAfterCopy, ExternalCluster: mz.ms.ExternalCluster, } for _, ts := range mz.ms.TableSettings { rule := &binlogdatapb.Rule{ Match: ts.TargetTable, } if ts.SourceExpression == "" { bls.Filter.Rules = append(bls.Filter.Rules, rule) continue } // Validate non-empty query. stmt, err := sqlparser.Parse(ts.SourceExpression) if err != nil { return "", err } sel, ok := stmt.(*sqlparser.Select) if !ok { return "", fmt.Errorf("unrecognized statement: %s", ts.SourceExpression) } filter := ts.SourceExpression if mz.targetVSchema.Keyspace.Sharded && mz.targetVSchema.Tables[ts.TargetTable].Type != vindexes.TypeReference { cv, err := vindexes.FindBestColVindex(mz.targetVSchema.Tables[ts.TargetTable]) if err != nil { return "", err } mappedCols := make([]*sqlparser.ColName, 0, len(cv.Columns)) for _, col := range cv.Columns { colName, err := matchColInSelect(col, sel) if err != nil { return "", err } mappedCols = append(mappedCols, colName) } subExprs := make(sqlparser.SelectExprs, 0, len(mappedCols)+2) for _, mappedCol := range mappedCols { subExprs = append(subExprs, &sqlparser.AliasedExpr{Expr: mappedCol}) } vindexName := fmt.Sprintf("%s.%s", mz.ms.TargetKeyspace, cv.Name) subExprs = append(subExprs, &sqlparser.AliasedExpr{Expr: sqlparser.NewStrLiteral(vindexName)}) subExprs = append(subExprs, &sqlparser.AliasedExpr{Expr: sqlparser.NewStrLiteral("{{.keyrange}}")}) inKeyRange := &sqlparser.FuncExpr{ Name: sqlparser.NewColIdent("in_keyrange"), Exprs: subExprs, } if sel.Where != nil { sel.Where = &sqlparser.Where{ Type: sqlparser.WhereClause, Expr: &sqlparser.AndExpr{ Left: inKeyRange, Right: sel.Where.Expr, }, } } else { sel.Where = &sqlparser.Where{ Type: sqlparser.WhereClause, Expr: inKeyRange, } } filter = sqlparser.String(sel) } rule.Filter = filter bls.Filter.Rules = append(bls.Filter.Rules, rule) } ig.AddRow(mz.ms.Workflow, bls, "", mz.ms.Cell, mz.ms.TabletTypes) } return ig.String(), nil } func matchColInSelect(col sqlparser.ColIdent, sel *sqlparser.Select) (*sqlparser.ColName, error) { for _, selExpr := range sel.SelectExprs { switch selExpr := selExpr.(type) { case *sqlparser.StarExpr: return &sqlparser.ColName{Name: col}, nil case *sqlparser.AliasedExpr: match := selExpr.As if match.IsEmpty() { if colExpr, ok := selExpr.Expr.(*sqlparser.ColName); ok { match = colExpr.Name } else { // Cannot match against a complex expression. continue } } if match.Equal(col) { colExpr, ok := selExpr.Expr.(*sqlparser.ColName) if !ok { return nil, fmt.Errorf("vindex column cannot be a complex expression: %v", sqlparser.String(selExpr)) } return colExpr, nil } default: return nil, fmt.Errorf("unsupported select expression: %v", sqlparser.String(selExpr)) } } return nil, fmt.Errorf("could not find vindex column %v", sqlparser.String(col)) } func (mz *materializer) createStreams(ctx context.Context, insertsMap map[string]string) error { return mz.forAllTargets(func(target *topo.ShardInfo) error { inserts := insertsMap[target.ShardName()] targetPrimary, err := mz.wr.ts.GetTablet(ctx, target.PrimaryAlias) if err != nil { return vterrors.Wrapf(err, "GetTablet(%v) failed", target.PrimaryAlias) } buf := &strings.Builder{} t := template.Must(template.New("").Parse(inserts)) input := map[string]string{ "keyrange": key.KeyRangeString(target.KeyRange), "dbname": targetPrimary.DbName(), } if err := t.Execute(buf, input); err != nil { return err } if _, err := mz.wr.TabletManagerClient().VReplicationExec(ctx, targetPrimary.Tablet, buf.String()); err != nil { return err } return nil }) } func (mz *materializer) startStreams(ctx context.Context) error { return mz.forAllTargets(func(target *topo.ShardInfo) error { targetPrimary, err := mz.wr.ts.GetTablet(ctx, target.PrimaryAlias) if err != nil { return vterrors.Wrapf(err, "GetTablet(%v) failed", target.PrimaryAlias) } query := fmt.Sprintf("update _vt.vreplication set state='Running' where db_name=%s and workflow=%s", encodeString(targetPrimary.DbName()), encodeString(mz.ms.Workflow)) if _, err := mz.wr.tmc.VReplicationExec(ctx, targetPrimary.Tablet, query); err != nil { return vterrors.Wrapf(err, "VReplicationExec(%v, %s)", targetPrimary.Tablet, query) } return nil }) } func (mz *materializer) forAllTargets(f func(*topo.ShardInfo) error) error { var wg sync.WaitGroup allErrors := &concurrency.AllErrorRecorder{} for _, target := range mz.targetShards { wg.Add(1) go func(target *topo.ShardInfo) { defer wg.Done() if err := f(target); err != nil { allErrors.RecordError(err) } }(target) } wg.Wait() return allErrors.AggrError(vterrors.Aggregate) }
vitessio/vitess
go/vt/wrangler/materializer.go
GO
apache-2.0
41,238
\section{Introduction} Introduction Section: Avadhoot \section{Client Requirements and Visualization Goals} \section{Technical Solution} \section{Visualizations} \subsection{Dashboard} \subsection{Top Agents and Trends} \subsection{Top Searches and Trends} \subsection{Top Countries and Trends} \subsection{Top URLs and Trends} \section{Key Insights} \section{Conclusion} %\end{document} % This is where a 'short' article might terminate \appendix %Appendix A %\section{Work Distribution} \begin{acks} \end{acks}
avadhoot-agasti/ivmooc-scimap-webanalytics
report/section.tex
TeX
apache-2.0
537
// // BindingPlatesViewController.h // sgSalerReport // // Created by YaoHuiQiu on 16/5/4. // Copyright © 2016年 dwolf. All rights reserved. // #import "BaseViewController.h" //解除绑定or绑定 @interface BindingPlatesViewController : BaseViewController @end
caolonghan/First
CapitaStar_IOS_1.2.4 2 11.14适配x/kaidexing/MWM/Register/BindingPlatesViewController.h
C
apache-2.0
271
# Copyright 2015 The TensorFlow 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. # ============================================================================== """Keras initializer serialization / deserialization.""" import tensorflow.compat.v2 as tf import threading from tensorflow.python import tf2 from keras.initializers import initializers_v1 from keras.initializers import initializers_v2 from keras.utils import generic_utils from keras.utils import tf_inspect as inspect from tensorflow.python.ops import init_ops from tensorflow.python.util.tf_export import keras_export # LOCAL.ALL_OBJECTS is meant to be a global mutable. Hence we need to make it # thread-local to avoid concurrent mutations. LOCAL = threading.local() def populate_deserializable_objects(): """Populates dict ALL_OBJECTS with every built-in initializer. """ global LOCAL if not hasattr(LOCAL, 'ALL_OBJECTS'): LOCAL.ALL_OBJECTS = {} LOCAL.GENERATED_WITH_V2 = None if LOCAL.ALL_OBJECTS and LOCAL.GENERATED_WITH_V2 == tf.__internal__.tf2.enabled(): # Objects dict is already generated for the proper TF version: # do nothing. return LOCAL.ALL_OBJECTS = {} LOCAL.GENERATED_WITH_V2 = tf.__internal__.tf2.enabled() # Compatibility aliases (need to exist in both V1 and V2). LOCAL.ALL_OBJECTS['ConstantV2'] = initializers_v2.Constant LOCAL.ALL_OBJECTS['GlorotNormalV2'] = initializers_v2.GlorotNormal LOCAL.ALL_OBJECTS['GlorotUniformV2'] = initializers_v2.GlorotUniform LOCAL.ALL_OBJECTS['HeNormalV2'] = initializers_v2.HeNormal LOCAL.ALL_OBJECTS['HeUniformV2'] = initializers_v2.HeUniform LOCAL.ALL_OBJECTS['IdentityV2'] = initializers_v2.Identity LOCAL.ALL_OBJECTS['LecunNormalV2'] = initializers_v2.LecunNormal LOCAL.ALL_OBJECTS['LecunUniformV2'] = initializers_v2.LecunUniform LOCAL.ALL_OBJECTS['OnesV2'] = initializers_v2.Ones LOCAL.ALL_OBJECTS['OrthogonalV2'] = initializers_v2.Orthogonal LOCAL.ALL_OBJECTS['RandomNormalV2'] = initializers_v2.RandomNormal LOCAL.ALL_OBJECTS['RandomUniformV2'] = initializers_v2.RandomUniform LOCAL.ALL_OBJECTS['TruncatedNormalV2'] = initializers_v2.TruncatedNormal LOCAL.ALL_OBJECTS['VarianceScalingV2'] = initializers_v2.VarianceScaling LOCAL.ALL_OBJECTS['ZerosV2'] = initializers_v2.Zeros # Out of an abundance of caution we also include these aliases that have # a non-zero probability of having been included in saved configs in the past. LOCAL.ALL_OBJECTS['glorot_normalV2'] = initializers_v2.GlorotNormal LOCAL.ALL_OBJECTS['glorot_uniformV2'] = initializers_v2.GlorotUniform LOCAL.ALL_OBJECTS['he_normalV2'] = initializers_v2.HeNormal LOCAL.ALL_OBJECTS['he_uniformV2'] = initializers_v2.HeUniform LOCAL.ALL_OBJECTS['lecun_normalV2'] = initializers_v2.LecunNormal LOCAL.ALL_OBJECTS['lecun_uniformV2'] = initializers_v2.LecunUniform if tf.__internal__.tf2.enabled(): # For V2, entries are generated automatically based on the content of # initializers_v2.py. v2_objs = {} base_cls = initializers_v2.Initializer generic_utils.populate_dict_with_module_objects( v2_objs, [initializers_v2], obj_filter=lambda x: inspect.isclass(x) and issubclass(x, base_cls)) for key, value in v2_objs.items(): LOCAL.ALL_OBJECTS[key] = value # Functional aliases. LOCAL.ALL_OBJECTS[generic_utils.to_snake_case(key)] = value else: # V1 initializers. v1_objs = { 'Constant': tf.compat.v1.constant_initializer, 'GlorotNormal': tf.compat.v1.glorot_normal_initializer, 'GlorotUniform': tf.compat.v1.glorot_uniform_initializer, 'Identity': tf.compat.v1.initializers.identity, 'Ones': tf.compat.v1.ones_initializer, 'Orthogonal': tf.compat.v1.orthogonal_initializer, 'VarianceScaling': tf.compat.v1.variance_scaling_initializer, 'Zeros': tf.compat.v1.zeros_initializer, 'HeNormal': initializers_v1.HeNormal, 'HeUniform': initializers_v1.HeUniform, 'LecunNormal': initializers_v1.LecunNormal, 'LecunUniform': initializers_v1.LecunUniform, 'RandomNormal': initializers_v1.RandomNormal, 'RandomUniform': initializers_v1.RandomUniform, 'TruncatedNormal': initializers_v1.TruncatedNormal, } for key, value in v1_objs.items(): LOCAL.ALL_OBJECTS[key] = value # Functional aliases. LOCAL.ALL_OBJECTS[generic_utils.to_snake_case(key)] = value # More compatibility aliases. LOCAL.ALL_OBJECTS['normal'] = LOCAL.ALL_OBJECTS['random_normal'] LOCAL.ALL_OBJECTS['uniform'] = LOCAL.ALL_OBJECTS['random_uniform'] LOCAL.ALL_OBJECTS['one'] = LOCAL.ALL_OBJECTS['ones'] LOCAL.ALL_OBJECTS['zero'] = LOCAL.ALL_OBJECTS['zeros'] # For backwards compatibility, we populate this file with the objects # from ALL_OBJECTS. We make no guarantees as to whether these objects will # using their correct version. populate_deserializable_objects() globals().update(LOCAL.ALL_OBJECTS) # Utility functions @keras_export('keras.initializers.serialize') def serialize(initializer): return generic_utils.serialize_keras_object(initializer) @keras_export('keras.initializers.deserialize') def deserialize(config, custom_objects=None): """Return an `Initializer` object from its config.""" populate_deserializable_objects() return generic_utils.deserialize_keras_object( config, module_objects=LOCAL.ALL_OBJECTS, custom_objects=custom_objects, printable_module_name='initializer') @keras_export('keras.initializers.get') def get(identifier): """Retrieve a Keras initializer by the identifier. The `identifier` may be the string name of a initializers function or class ( case-sensitively). >>> identifier = 'Ones' >>> tf.keras.initializers.deserialize(identifier) <...keras.initializers.initializers_v2.Ones...> You can also specify `config` of the initializer to this function by passing dict containing `class_name` and `config` as an identifier. Also note that the `class_name` must map to a `Initializer` class. >>> cfg = {'class_name': 'Ones', 'config': {}} >>> tf.keras.initializers.deserialize(cfg) <...keras.initializers.initializers_v2.Ones...> In the case that the `identifier` is a class, this method will return a new instance of the class by its constructor. Args: identifier: String or dict that contains the initializer name or configurations. Returns: Initializer instance base on the input identifier. Raises: ValueError: If the input identifier is not a supported type or in a bad format. """ if identifier is None: return None if isinstance(identifier, dict): return deserialize(identifier) elif isinstance(identifier, str): identifier = str(identifier) return deserialize(identifier) elif callable(identifier): if inspect.isclass(identifier): identifier = identifier() return identifier else: raise ValueError('Could not interpret initializer identifier: ' + str(identifier))
keras-team/keras
keras/initializers/__init__.py
Python
apache-2.0
7,577
# # 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 accompanying LICENSE file. # import os import sys import falcon_config as fc import subprocess cmd = sys.argv[0] prg, base_dir = fc.resolve_sym_link(os.path.abspath(cmd)) service_stop_cmd = os.path.join(base_dir, 'bin', 'service_stop.py') subprocess.call(['python', service_stop_cmd, 'prism'])
OpenPOWER-BigData/HDP-falcon
src/bin/prism_stop.py
Python
apache-2.0
848
package com.google.devrel.training.conference.domain; import static com.google.devrel.training.conference.service.OfyService.ofy; import com.google.api.server.spi.config.AnnotationBoolean; import com.google.api.server.spi.config.ApiResourceProperty; import com.google.devrel.training.conference.form.ClientForm; import com.googlecode.objectify.Key; import com.googlecode.objectify.annotation.Cache; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Index; import com.googlecode.objectify.annotation.Parent; import java.util.ArrayList; import java.util.List; /** * Client Class to store goal information */ @Entity @Cache public class Client { /** * The id for the datastore key. * * We use automatic id assignment for entities of Client class. */ @Id private String id; /** * The name of the client. */ @Index private String name; private String description; private String goalsetterid; private String location; @Index private int medicalRecordNumber; private int age; /** * Holds Goalsetter key as the parent. */ @Parent @ApiResourceProperty(ignored = AnnotationBoolean.TRUE) private Key<Goalsetter> goalsetterkey; private List<Goal> listofgoals = new ArrayList<Goal>(); //private Key<Goal> goalkey; /** * The userId of the goalsetter. */ @Index @ApiResourceProperty(ignored = AnnotationBoolean.TRUE) private String userrId; /** * Just making the default constructor private. */ private Client() { } public Client(final String id, final String goalsetterId, final ClientForm clientForm) { this.id = id; this.goalsetterkey = Key.create(Goalsetter.class, goalsetterId); setGoalsetterid(goalsetterId); this.userrId = goalsetterId; updateWithClientForm(clientForm); } public String getId() { return id; } public String getName() { return name; } @ApiResourceProperty(ignored = AnnotationBoolean.TRUE) public Key<Goalsetter> getGoalsetterKey() { return goalsetterkey; } // Get a String version of the key public String getWebsafeKey() { return Key.create(goalsetterkey, Client.class, id).getString(); } @ApiResourceProperty(ignored = AnnotationBoolean.TRUE) public String getOrganizerUserId() { return userrId; } public String getdescription(){ return description; } /** * Returns organizer's display name. * * @return organizer's display name. If there is no Profile, return his/her * userId. */ public String getOrganizerDisplayName() { Goalsetter organizer = ofy().load().key(getGoalsetterKey()).now(); if (organizer == null) { return userrId; } else { return organizer.getDisplayName(); } } public String getDisplayName() { return name; } public List<Goal> getGoals() { return listofgoals; } /** * Updates the Client with ClientForm. This method is used upon * object creation as well as updating existing Client. * * @param ClientForm * contains form data sent from the client. */ public void updateWithClientForm(ClientForm clientForm) { this.name = clientForm.getname(); this.description = clientForm.getdescription(); setAge(clientForm.getage()); setLocation(clientForm.getlocation()); setMedicalRecordNumber(clientForm.getMedicalRecordNumber()); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder("Id: " + id + "\n") .append("Name: ").append(name).append("\n"); return stringBuilder.toString(); } public String getGoalsetterid() { return goalsetterid; } public void setGoalsetterid(String goalsetterid) { this.goalsetterid = goalsetterid; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public int getAge() { return age; } public void setDescription(String description) { this.description = description; } public void setAge(int age) { this.age = age; } public void setId(String Id) { this.id = Id; } public void setname(String name) { this.name = name; } public int getMedicalRecordNumber() { return medicalRecordNumber; } public void setMedicalRecordNumber(int medicalRecordNumber) { this.medicalRecordNumber = medicalRecordNumber; } }
SudarshN/GoalScaleApplication-for-OT
src/main/java/com/google/devrel/training/conference/domain/Client.java
Java
apache-2.0
4,359
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>eRPC Generator (erpcgen): Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="customdoxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">eRPC Generator (erpcgen) &#160;<span id="projectnumber">Rev. 1.3.0</span> </div> <div id="projectbrief">NXP Semiconductors</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('class_opt_iter.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">OptIter Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="class_opt_iter.html">OptIter</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="class_opt_iter.html#a83fee36a05864e23eebc91b251ac9743">curr</a>(void)=0</td><td class="entry"><a class="el" href="class_opt_iter.html">OptIter</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="class_opt_iter.html#aa9b79aa55fa9e3cf948045ff2a59508c">next</a>(void)=0</td><td class="entry"><a class="el" href="class_opt_iter.html">OptIter</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_opt_iter.html#a039ef9ac21ffb563eedbc76cd42c5e02">operator()</a>(void)</td><td class="entry"><a class="el" href="class_opt_iter.html">OptIter</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>OptIter</b>(void) (defined in <a class="el" href="class_opt_iter.html">OptIter</a>)</td><td class="entry"><a class="el" href="class_opt_iter.html">OptIter</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>~OptIter</b>(void) (defined in <a class="el" href="class_opt_iter.html">OptIter</a>)</td><td class="entry"><a class="el" href="class_opt_iter.html">OptIter</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- HTML footer for doxygen 1.8.5--> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul class="foot"> <li class="footer">Copyright &copy; 2016 Freescale Semiconductor, Inc. </li> </ul> </div> </body> </html>
scottdarch/Noer
FRDMK66NoEr/SDK_2.1_FRDM-K66F-GCC-Full/middleware/multicore_2.1.0/erpc/doc/eRPC_infrastructure/erpcgen/class_opt_iter-members.html
HTML
apache-2.0
6,360
package org.light4j.servlet3.asyn; import java.io.IOException; import java.util.Date; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; public class MyAsyncListener implements AsyncListener { public void onComplete(AsyncEvent event) throws IOException { System.out.println("------异步调用完成------" + new Date()); } public void onError(AsyncEvent event) throws IOException { } public void onStartAsync(AsyncEvent event) throws IOException { System.out.println("------异步调用开始------" + new Date()); } public void onTimeout(AsyncEvent event) throws IOException { } }
longjiazuo/java-project
j2ee-project/java-servlet3/src/main/java/org/light4j/servlet3/asyn/MyAsyncListener.java
Java
apache-2.0
640
=head1 LICENSE Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute 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. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::IdMapping::SyntenyRegion - object representing syntenic regions =head1 SYNOPSIS # create a new SyntenyRegion from a source and a target gene my $sr = Bio::EnsEMBL::IdMapping::SyntenyRegion->new_fast( [ $source_gene->start, $source_gene->end, $source_gene->strand, $source_gene->seq_region_name, $target_gene->start, $target_gene->end, $target_gene->strand, $target_gene->seq_region_name, $entry->score, ] ); # merge with another SyntenyRegion my $merged_sr = $sr->merge($sr1); # score a gene pair against this SyntenyRegion my $score = $sr->score_location_relationship( $source_gene1, $target_gene1 ); =head1 DESCRIPTION This object represents a synteny between a source and a target location. SyntenyRegions are built from mapped genes, and the their score is defined as the score of the gene mapping. For merged SyntenyRegions, scores are combined. =head1 METHODS new_fast source_start source_end source_strand source_seq_region_name target_start target_end target_strand target_seq_region_name score merge stretch score_location_relationship to_string =cut package Bio::EnsEMBL::IdMapping::SyntenyRegion; use strict; use warnings; no warnings 'uninitialized'; use Bio::EnsEMBL::Utils::Exception qw(throw warning); =head2 new_fast Arg[1] : Arrayref $array_ref - the arrayref to bless into the SyntenyRegion object Example : my $sr = Bio::EnsEMBL::IdMapping::SyntenyRegion->new_fast([ ]); Description : Constructor. On instantiation, source and target regions are reverse complemented so that source is always on forward strand. Return type : a Bio::EnsEMBL::IdMapping::SyntenyRegion object Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub new_fast { my $class = shift; my $array_ref = shift; # reverse complement source and target so that source is always on forward # strand; this will make merging and other comparison operations easier # at later stages if ($array_ref->[2] == -1) { $array_ref->[2] = 1; $array_ref->[6] = -1 * $array_ref->[6]; } return bless $array_ref, $class; } =head2 source_start Arg[1] : (optional) Int - source location start coordinate Description : Getter/setter for source location start coordinate. Return type : Int Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub source_start { my $self = shift; $self->[0] = shift if (@_); return $self->[0]; } =head2 source_end Arg[1] : (optional) Int - source location end coordinate Description : Getter/setter for source location end coordinate. Return type : Int Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub source_end { my $self = shift; $self->[1] = shift if (@_); return $self->[1]; } =head2 source_strand Arg[1] : (optional) Int - source location strand Description : Getter/setter for source location strand. Return type : Int Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub source_strand { my $self = shift; $self->[2] = shift if (@_); return $self->[2]; } =head2 source_seq_region_name Arg[1] : (optional) String - source location seq_region name Description : Getter/setter for source location seq_region name. Return type : String Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub source_seq_region_name { my $self = shift; $self->[3] = shift if (@_); return $self->[3]; } =head2 target_start Arg[1] : (optional) Int - target location start coordinate Description : Getter/setter for target location start coordinate. Return type : Int Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub target_start { my $self = shift; $self->[4] = shift if (@_); return $self->[4]; } =head2 target_end Arg[1] : (optional) Int - target location end coordinate Description : Getter/setter for target location end coordinate. Return type : Int Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub target_end { my $self = shift; $self->[5] = shift if (@_); return $self->[5]; } =head2 target_strand Arg[1] : (optional) Int - target location strand Description : Getter/setter for target location strand. Return type : Int Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub target_strand { my $self = shift; $self->[6] = shift if (@_); return $self->[6]; } =head2 target_seq_region_name Arg[1] : (optional) String - target location seq_region name Description : Getter/setter for target location seq_region name. Return type : String Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub target_seq_region_name { my $self = shift; $self->[7] = shift if (@_); return $self->[7]; } =head2 score Arg[1] : (optional) Float - score Description : Getter/setter for the score between source and target location. Return type : Int Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub score { my $self = shift; $self->[8] = shift if (@_); return $self->[8]; } =head2 merge Arg[1] : Bio::EnsEMBL::IdMapping::SyntenyRegion $sr - another SyntenyRegion Example : $merged_sr = $sr->merge($other_sr); Description : Merges two overlapping SyntenyRegions if they meet certain criteria (see documentation in the code for details). Score is calculated as a combined distance score. If the two SyntenyRegions aren't mergeable, this method returns undef. Return type : Bio::EnsEMBL::IdMapping::SyntenyRegion or undef Exceptions : warns on bad scores Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub merge { my ($self, $sr) = @_; # must be on same seq_region if ($self->source_seq_region_name ne $sr->source_seq_region_name or $self->target_seq_region_name ne $sr->target_seq_region_name) { return 0; } # target must be on same strand return 0 unless ($self->target_strand == $sr->target_strand); # find the distance of source and target pair and compare my $source_dist = $sr->source_start - $self->source_start; my $target_dist; if ($self->target_strand == 1) { $target_dist = $sr->target_start - $self->target_start; } else { $target_dist = $self->target_end - $sr->target_end; } # prevent division by zero error if ($source_dist == 0 or $target_dist == 0) { warn("WARNING: source_dist ($source_dist) and/or target_dist ($target_dist) is zero.\n"); return 0; } # calculate a distance score my $dist = $source_dist - $target_dist; $dist = -$dist if ($dist < 0); my $d1 = $dist/$source_dist; $d1 = -$d1 if ($d1 < 0); my $d2 = $dist/$target_dist; $d2 = -$d2 if ($d2 < 0); my $dist_score = 1 - $d1 - $d2; # distance score must be more than 50% return 0 if ($dist_score < 0.5); my $new_score = $dist_score * ($sr->score + $self->score)/2; if ($new_score > 1) { warn("WARNING: Bad merge score: $new_score\n"); } # extend SyntenyRegion to cover both sources and targets, set merged score # and return if ($sr->source_start < $self->source_start) { $self->source_start($sr->source_start); } if ($sr->source_end > $self->source_end) { $self->source_end($sr->source_end); } if ($sr->target_start < $self->target_start) { $self->target_start($sr->target_start); } if ($sr->target_end > $self->target_end) { $self->target_end($sr->target_end); } $self->score($new_score); return $self; } =head2 stretch Arg[1] : Float $factor - stretching factor Example : $stretched_sr = $sr->stretch(2); Description : Extends this SyntenyRegion to span a $factor * $score more area. Return type : Bio::EnsEMBL::IdMapping::SyntenyRegion Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub stretch { my ($self, $factor) = @_; my $source_adjust = int(($self->source_end - $self->source_start + 1) * $factor * $self->score); $self->source_start($self->source_start - $source_adjust); $self->source_end($self->source_end + $source_adjust); #warn sprintf(" sss %d %d %d\n", $source_adjust, $self->source_start, # $self->source_end); my $target_adjust = int(($self->target_end - $self->target_start + 1) * $factor * $self->score); $self->target_start($self->target_start - $target_adjust); $self->target_end($self->target_end + $target_adjust); return $self; } =head2 score_location_relationship Arg[1] : Bio::EnsEMBL::IdMapping::TinyGene $source_gene - source gene Arg[2] : Bio::EnsEMBL::IdMapping::TinyGene $target_gene - target gene Example : my $score = $sr->score_location_relationship($source_gene, $target_gene); Description : This function calculates how well the given source location interpolates on given target location inside this SyntenyRegion. Scoring is done the following way: Source and target location are normalized with respect to this Regions source and target. Source range will then be somewhere close to 0.0-1.0 and target range anything around that. The extend of the covered area between source and target range is a measurement of how well they agree (smaller extend is better). The extend (actually 2*extend) is reduced by the size of the regions. This will result in 0.0 if they overlap perfectly and bigger values if they dont. This is substracted from 1.0 to give the score. The score is likely to be below zero, but is cut off at 0.0f. Finally, the score is multiplied with the score of the synteny itself. Return type : Float Exceptions : warns if score out of range Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub score_location_relationship { my ($self, $source_gene, $target_gene) = @_; # must be on same seq_region if (($self->source_seq_region_name ne $source_gene->seq_region_name) or ($self->target_seq_region_name ne $target_gene->seq_region_name)) { return 0; } # strand relationship must be the same (use logical XOR to find out) if (($self->source_strand == $source_gene->strand) xor ($self->target_strand == $target_gene->strand)) { return 0; } # normalise source location my $source_rel_start = ($source_gene->start - $self->source_start) / ($self->source_end - $self->source_start + 1); my $source_rel_end = ($source_gene->end - $self->source_start + 1) / ($self->source_end - $self->source_start + 1); #warn " aaa ".$self->to_string."\n"; #warn sprintf(" bbb %.6f %.6f\n", $source_rel_start, $source_rel_end); # cut off if the source location is completely outside return 0 if ($source_rel_start > 1.1 or $source_rel_end < -0.1); # normalise target location my ($target_rel_start, $target_rel_end); my $t_length = $self->target_end - $self->target_start + 1; if ($self->target_strand == 1) { $target_rel_start = ($target_gene->start - $self->target_start) / $t_length; $target_rel_end = ($target_gene->end - $self->target_start + 1) / $t_length; } else { $target_rel_start = ($self->target_end - $target_gene->end) / $t_length; $target_rel_end = ($self->target_end - $target_gene->start + 1) / $t_length; } my $added_range = (($target_rel_end > $source_rel_end) ? $target_rel_end : $source_rel_end) - (($target_rel_start < $source_rel_start) ? $target_rel_start : $source_rel_start); my $score = $self->score * (1 - (2 * $added_range - $target_rel_end - $source_rel_end + $target_rel_start + $source_rel_start)); #warn " ccc ".sprintf("%.6f:%.6f:%.6f:%.6f:%.6f\n", $added_range, # $source_rel_start, $source_rel_end, $target_rel_start, $target_rel_end); $score = 0 if ($score < 0); # sanity check if ($score > 1) { warn "Out of range score ($score) for ".$source_gene->id.":". $target_gene->id."\n"; } return $score; } =head2 to_string Example : print LOG $sr->to_string, "\n"; Description : Returns a string representation of the SyntenyRegion object. Useful for debugging and logging. Return type : String Exceptions : none Caller : Bio::EnsEMBL::IdMapping::SyntenyFramework Status : At Risk : under development =cut sub to_string { my $self = shift; return sprintf("%s:%s-%s:%s %s:%s-%s:%s %.6f", $self->source_seq_region_name, $self->source_start, $self->source_end, $self->source_strand, $self->target_seq_region_name, $self->target_start, $self->target_end, $self->target_strand, $self->score ); } 1;
willmclaren/ensembl
modules/Bio/EnsEMBL/IdMapping/SyntenyRegion.pm
Perl
apache-2.0
14,970
/* * Copyright 2013 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. */ package com.google.sha1coin.protocols.channels; import com.google.sha1coin.core.*; import com.google.sha1coin.crypto.TransactionSignature; import com.google.sha1coin.script.Script; import com.google.sha1coin.script.ScriptBuilder; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.Arrays; import static com.google.common.base.Preconditions.*; /** * <p>A payment channel is a method of sending money to someone such that the amount of money you send can be adjusted * after the fact, in an efficient manner that does not require broadcasting to the network. This can be used to * implement micropayments or other payment schemes in which immediate settlement is not required, but zero trust * negotiation is. Note that this class only allows the amount of money received to be incremented, not decremented.</p> * * <p>This class implements the core state machine for the server side of the protocol. The client side is implemented * by {@link PaymentChannelClientState} and {@link PaymentChannelServerListener} implements the server-side network * protocol listening for TCP/IP connections and moving this class through each state. We say that the party who is * sending funds is the <i>client</i> or <i>initiating party</i>. The party that is receiving the funds is the * <i>server</i> or <i>receiving party</i>. Although the underlying Bitcoin protocol is capable of more complex * relationships than that, this class implements only the simplest case.</p> * * <p>To protect clients from malicious servers, a channel has an expiry parameter. When this expiration is reached, the * client will broadcast the created refund transaction and take back all the money in this channel. Because this is * specified in terms of block timestamps, it is fairly fuzzy and it is possible to spend the refund transaction up to a * few hours before the actual timestamp. Thus, it is very important that the channel be closed with plenty of time left * to get the highest value payment transaction confirmed before the expire time (minimum 3-4 hours is suggested if the * payment transaction has enough fee to be confirmed in the next block or two).</p> * * <p>To begin, we must provide the client with a pubkey which we wish to use for the multi-sig contract which locks in * the channel. The client will then provide us with an incomplete refund transaction and the pubkey which they used in * the multi-sig contract. We use this pubkey to recreate the multi-sig output and then sign that to the refund * transaction. We provide that signature to the client and they then have the ability to spend the refund transaction * at the specified expire time. The client then provides us with the full, signed multi-sig contract which we verify * and broadcast, locking in their funds until we spend a payment transaction or the expire time is reached. The client * can then begin paying by providing us with signatures for the multi-sig contract which pay some amount back to the * client, and the rest is ours to do with as we wish.</p> */ public class PaymentChannelServerState { private static final Logger log = LoggerFactory.getLogger(PaymentChannelServerState.class); /** * The different logical states the channel can be in. Because the first action we need to track is the client * providing the refund transaction, we begin in WAITING_FOR_REFUND_TRANSACTION. We then step through the states * until READY, at which time the client can increase payment incrementally. */ public enum State { WAITING_FOR_REFUND_TRANSACTION, WAITING_FOR_MULTISIG_CONTRACT, WAITING_FOR_MULTISIG_ACCEPTANCE, READY, CLOSING, CLOSED, ERROR, } private State state; // The client and server keys for the multi-sig contract // We currently also use the serverKey for payouts, but this is not required private ECKey clientKey, serverKey; // Package-local for checkArguments in StoredServerChannel final Wallet wallet; // The object that will broadcast transactions for us - usually a peer group. private final TransactionBroadcaster broadcaster; // The multi-sig contract and the output script from it private Transaction multisigContract = null; private Script multisigScript; // The last signature the client provided for a payment transaction. private byte[] bestValueSignature; // The total value locked into the multi-sig output and the value to us in the last signature the client provided private Coin totalValue; private Coin bestValueToMe = Coin.ZERO; private Coin feePaidForPayment; // The refund/change transaction output that goes back to the client private TransactionOutput clientOutput; private long refundTransactionUnlockTimeSecs; private long minExpireTime; private StoredServerChannel storedServerChannel = null; PaymentChannelServerState(StoredServerChannel storedServerChannel, Wallet wallet, TransactionBroadcaster broadcaster) throws VerificationException { synchronized (storedServerChannel) { this.wallet = checkNotNull(wallet); this.broadcaster = checkNotNull(broadcaster); this.multisigContract = checkNotNull(storedServerChannel.contract); this.multisigScript = multisigContract.getOutput(0).getScriptPubKey(); this.clientKey = ECKey.fromPublicOnly(multisigScript.getChunks().get(1).data); this.clientOutput = checkNotNull(storedServerChannel.clientOutput); this.refundTransactionUnlockTimeSecs = storedServerChannel.refundTransactionUnlockTimeSecs; this.serverKey = checkNotNull(storedServerChannel.myKey); this.totalValue = multisigContract.getOutput(0).getValue(); this.bestValueToMe = checkNotNull(storedServerChannel.bestValueToMe); this.bestValueSignature = storedServerChannel.bestValueSignature; checkArgument(bestValueToMe.equals(Coin.ZERO) || bestValueSignature != null); this.storedServerChannel = storedServerChannel; storedServerChannel.state = this; this.state = State.READY; } } /** * Creates a new state object to track the server side of a payment channel. * * @param broadcaster The peer group which we will broadcast transactions to, this should have multiple peers * @param wallet The wallet which will be used to complete transactions * @param serverKey The private key which we use for our part of the multi-sig contract * (this MUST be fresh and CANNOT be used elsewhere) * @param minExpireTime The earliest time at which the client can claim the refund transaction (UNIX timestamp of block) */ public PaymentChannelServerState(TransactionBroadcaster broadcaster, Wallet wallet, ECKey serverKey, long minExpireTime) { this.state = State.WAITING_FOR_REFUND_TRANSACTION; this.serverKey = checkNotNull(serverKey); this.wallet = checkNotNull(wallet); this.broadcaster = checkNotNull(broadcaster); this.minExpireTime = minExpireTime; } /** * This object implements a state machine, and this accessor returns which state it's currently in. */ public synchronized State getState() { return state; } /** * Called when the client provides the refund transaction. * The refund transaction must have one input from the multisig contract (that we don't have yet) and one output * that the client creates to themselves. This object will later be modified when we start getting paid. * * @param refundTx The refund transaction, this object will be mutated when payment is incremented. * @param clientMultiSigPubKey The client's pubkey which is required for the multisig output * @return Our signature that makes the refund transaction valid * @throws VerificationException If the transaction isnt valid or did not meet the requirements of a refund transaction. */ public synchronized byte[] provideRefundTransaction(Transaction refundTx, byte[] clientMultiSigPubKey) throws VerificationException { checkNotNull(refundTx); checkNotNull(clientMultiSigPubKey); checkState(state == State.WAITING_FOR_REFUND_TRANSACTION); log.info("Provided with refund transaction: {}", refundTx); // Do a few very basic syntax sanity checks. refundTx.verify(); // Verify that the refund transaction has a single input (that we can fill to sign the multisig output). if (refundTx.getInputs().size() != 1) throw new VerificationException("Refund transaction does not have exactly one input"); // Verify that the refund transaction has a time lock on it and a sequence number of zero. if (refundTx.getInput(0).getSequenceNumber() != 0) throw new VerificationException("Refund transaction's input's sequence number is non-0"); if (refundTx.getLockTime() < minExpireTime) throw new VerificationException("Refund transaction has a lock time too soon"); // Verify the transaction has one output (we don't care about its contents, its up to the client) // Note that because we sign with SIGHASH_NONE|SIGHASH_ANYOENCANPAY the client can later add more outputs and // inputs, but we will need only one output later to create the paying transactions if (refundTx.getOutputs().size() != 1) throw new VerificationException("Refund transaction does not have exactly one output"); refundTransactionUnlockTimeSecs = refundTx.getLockTime(); // Sign the refund tx with the scriptPubKey and return the signature. We don't have the spending transaction // so do the steps individually. clientKey = ECKey.fromPublicOnly(clientMultiSigPubKey); Script multisigPubKey = ScriptBuilder.createMultiSigOutputScript(2, ImmutableList.of(clientKey, serverKey)); // We are really only signing the fact that the transaction has a proper lock time and don't care about anything // else, so we sign SIGHASH_NONE and SIGHASH_ANYONECANPAY. TransactionSignature sig = refundTx.calculateSignature(0, serverKey, multisigPubKey, Transaction.SigHash.NONE, true); log.info("Signed refund transaction."); this.clientOutput = refundTx.getOutput(0); state = State.WAITING_FOR_MULTISIG_CONTRACT; return sig.encodeToBitcoin(); } /** * Called when the client provides the multi-sig contract. Checks that the previously-provided refund transaction * spends this transaction (because we will use it as a base to create payment transactions) as well as output value * and form (ie it is a 2-of-2 multisig to the correct keys). * * @param multisigContract The provided multisig contract. Do not mutate this object after this call. * @return A future which completes when the provided multisig contract successfully broadcasts, or throws if the broadcast fails for some reason * Note that if the network simply rejects the transaction, this future will never complete, a timeout should be used. * @throws VerificationException If the provided multisig contract is not well-formed or does not meet previously-specified parameters */ public synchronized ListenableFuture<PaymentChannelServerState> provideMultiSigContract(final Transaction multisigContract) throws VerificationException { checkNotNull(multisigContract); checkState(state == State.WAITING_FOR_MULTISIG_CONTRACT); try { multisigContract.verify(); this.multisigContract = multisigContract; this.multisigScript = multisigContract.getOutput(0).getScriptPubKey(); // Check that multisigContract's first output is a 2-of-2 multisig to the correct pubkeys in the correct order final Script expectedScript = ScriptBuilder.createMultiSigOutputScript(2, Lists.newArrayList(clientKey, serverKey)); if (!Arrays.equals(multisigScript.getProgram(), expectedScript.getProgram())) throw new VerificationException("Multisig contract's first output was not a standard 2-of-2 multisig to client and server in that order."); this.totalValue = multisigContract.getOutput(0).getValue(); if (this.totalValue.signum() <= 0) throw new VerificationException("Not accepting an attempt to open a contract with zero value."); } catch (VerificationException e) { // We couldn't parse the multisig transaction or its output. log.error("Provided multisig contract did not verify: {}", multisigContract.toString()); throw e; } log.info("Broadcasting multisig contract: {}", multisigContract); state = State.WAITING_FOR_MULTISIG_ACCEPTANCE; final SettableFuture<PaymentChannelServerState> future = SettableFuture.create(); Futures.addCallback(broadcaster.broadcastTransaction(multisigContract), new FutureCallback<Transaction>() { @Override public void onSuccess(Transaction transaction) { log.info("Successfully broadcast multisig contract {}. Channel now open.", transaction.getHashAsString()); try { // Manually add the multisigContract to the wallet, overriding the isRelevant checks so we can track // it and check for double-spends later wallet.receivePending(multisigContract, null, true); } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen, we already called multisigContract.verify() } state = State.READY; future.set(PaymentChannelServerState.this); } @Override public void onFailure(Throwable throwable) { // Couldn't broadcast the transaction for some reason. log.error(throwable.toString()); throwable.printStackTrace(); state = State.ERROR; future.setException(throwable); } }); return future; } // Create a payment transaction with valueToMe going back to us private synchronized Wallet.SendRequest makeUnsignedChannelContract(Coin valueToMe) { Transaction tx = new Transaction(wallet.getParams()); if (!totalValue.subtract(valueToMe).equals(Coin.ZERO)) { clientOutput.setValue(totalValue.subtract(valueToMe)); tx.addOutput(clientOutput); } tx.addInput(multisigContract.getOutput(0)); return Wallet.SendRequest.forTx(tx); } /** * Called when the client provides us with a new signature and wishes to increment total payment by size. * Verifies the provided signature and only updates values if everything checks out. * If the new refundSize is not the lowest we have seen, it is simply ignored. * * @param refundSize How many satoshis of the original contract are refunded to the client (the rest are ours) * @param signatureBytes The new signature spending the multi-sig contract to a new payment transaction * @throws VerificationException If the signature does not verify or size is out of range (incl being rejected by the network as dust). * @return true if there is more value left on the channel, false if it is now fully used up. */ public synchronized boolean incrementPayment(Coin refundSize, byte[] signatureBytes) throws VerificationException, ValueOutOfRangeException, InsufficientMoneyException { checkState(state == State.READY); checkNotNull(refundSize); checkNotNull(signatureBytes); TransactionSignature signature = TransactionSignature.decodeFromBitcoin(signatureBytes, true); // We allow snapping to zero for the payment amount because it's treated specially later, but not less than // the dust level because that would prevent the transaction from being relayed/mined. final boolean fullyUsedUp = refundSize.equals(Coin.ZERO); if (refundSize.compareTo(clientOutput.getMinNonDustValue()) < 0 && !fullyUsedUp) throw new ValueOutOfRangeException("Attempt to refund negative value or value too small to be accepted by the network"); Coin newValueToMe = totalValue.subtract(refundSize); if (newValueToMe.signum() < 0) throw new ValueOutOfRangeException("Attempt to refund more than the contract allows."); if (newValueToMe.compareTo(bestValueToMe) < 0) throw new ValueOutOfRangeException("Attempt to roll back payment on the channel."); // Get the wallet's copy of the multisigContract (ie with confidence information), if this is null, the wallet // was not connected to the peergroup when the contract was broadcast (which may cause issues down the road, and // disables our double-spend check next) Transaction walletContract = wallet.getTransaction(multisigContract.getHash()); checkNotNull(walletContract, "Wallet did not contain multisig contract {} after state was marked READY", multisigContract.getHash()); // Note that we check for DEAD state here, but this test is essentially useless in production because we will // miss most double-spends due to bloom filtering right now anyway. This will eventually fixed by network-wide // double-spend notifications, so we just wait instead of attempting to add all dependant outpoints to our bloom // filters (and probably missing lots of edge-cases). if (walletContract.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.DEAD) { close(); throw new VerificationException("Multisig contract was double-spent"); } Transaction.SigHash mode; // If the client doesn't want anything back, they shouldn't sign any outputs at all. if (fullyUsedUp) mode = Transaction.SigHash.NONE; else mode = Transaction.SigHash.SINGLE; if (signature.sigHashMode() != mode || !signature.anyoneCanPay()) throw new VerificationException("New payment signature was not signed with the right SIGHASH flags."); Wallet.SendRequest req = makeUnsignedChannelContract(newValueToMe); // Now check the signature is correct. // Note that the client must sign with SIGHASH_{SINGLE/NONE} | SIGHASH_ANYONECANPAY to allow us to add additional // inputs (in case we need to add significant fee, or something...) and any outputs we want to pay to. Sha256Hash sighash = req.tx.hashForSignature(0, multisigScript, mode, true); if (!clientKey.verify(sighash, signature)) throw new VerificationException("Signature does not verify on tx\n" + req.tx); bestValueToMe = newValueToMe; bestValueSignature = signatureBytes; updateChannelInWallet(); return !fullyUsedUp; } // Signs the first input of the transaction which must spend the multisig contract. private void signMultisigInput(Transaction tx, Transaction.SigHash hashType, boolean anyoneCanPay) { TransactionSignature signature = tx.calculateSignature(0, serverKey, multisigScript, hashType, anyoneCanPay); byte[] mySig = signature.encodeToBitcoin(); Script scriptSig = ScriptBuilder.createMultiSigInputScriptBytes(ImmutableList.of(bestValueSignature, mySig)); tx.getInput(0).setScriptSig(scriptSig); } final SettableFuture<Transaction> closedFuture = SettableFuture.create(); /** * <p>Closes this channel and broadcasts the highest value payment transaction on the network.</p> * * <p>This will set the state to {@link State#CLOSED} if the transaction is successfully broadcast on the network. * If we fail to broadcast for some reason, the state is set to {@link State#ERROR}.</p> * * <p>If the current state is before {@link State#READY} (ie we have not finished initializing the channel), we * simply set the state to {@link State#CLOSED} and let the client handle getting its refund transaction confirmed. * </p> * * @return a future which completes when the provided multisig contract successfully broadcasts, or throws if the * broadcast fails for some reason. Note that if the network simply rejects the transaction, this future * will never complete, a timeout should be used. * @throws InsufficientMoneyException If the payment tx would have cost more in fees to spend than it is worth. */ public synchronized ListenableFuture<Transaction> close() throws InsufficientMoneyException { if (storedServerChannel != null) { StoredServerChannel temp = storedServerChannel; storedServerChannel = null; StoredPaymentChannelServerStates channels = (StoredPaymentChannelServerStates) wallet.getExtensions().get(StoredPaymentChannelServerStates.EXTENSION_ID); channels.closeChannel(temp); // May call this method again for us (if it wasn't the original caller) if (state.compareTo(State.CLOSING) >= 0) return closedFuture; } if (state.ordinal() < State.READY.ordinal()) { log.error("Attempt to settle channel in state " + state); state = State.CLOSED; closedFuture.set(null); return closedFuture; } if (state != State.READY) { // TODO: What is this codepath for? log.warn("Failed attempt to settle a channel in state " + state); return closedFuture; } Transaction tx = null; try { Wallet.SendRequest req = makeUnsignedChannelContract(bestValueToMe); tx = req.tx; // Provide a throwaway signature so that completeTx won't complain out about unsigned inputs it doesn't // know how to sign. Note that this signature does actually have to be valid, so we can't use a dummy // signature to save time, because otherwise completeTx will try to re-sign it to make it valid and then // die. We could probably add features to the SendRequest API to make this a bit more efficient. signMultisigInput(tx, Transaction.SigHash.NONE, true); // Let wallet handle adding additional inputs/fee as necessary. req.shuffleOutputs = false; wallet.completeTx(req); // TODO: Fix things so shuffling is usable. feePaidForPayment = req.tx.getFee(); log.info("Calculated fee is {}", feePaidForPayment); if (feePaidForPayment.compareTo(bestValueToMe) >= 0) { final String msg = String.format("Had to pay more in fees (%s) than the channel was worth (%s)", feePaidForPayment, bestValueToMe); throw new InsufficientMoneyException(feePaidForPayment.subtract(bestValueToMe), msg); } // Now really sign the multisig input. signMultisigInput(tx, Transaction.SigHash.ALL, false); // Some checks that shouldn't be necessary but it can't hurt to check. tx.verify(); // Sanity check syntax. for (TransactionInput input : tx.getInputs()) input.verify(); // Run scripts and ensure it is valid. } catch (InsufficientMoneyException e) { throw e; // Don't fall through. } catch (Exception e) { log.error("Could not verify self-built tx\nMULTISIG {}\nCLOSE {}", multisigContract, tx != null ? tx : ""); throw new RuntimeException(e); // Should never happen. } state = State.CLOSING; log.info("Closing channel, broadcasting tx {}", tx); // The act of broadcasting the transaction will add it to the wallet. ListenableFuture<Transaction> future = broadcaster.broadcastTransaction(tx); Futures.addCallback(future, new FutureCallback<Transaction>() { @Override public void onSuccess(Transaction transaction) { log.info("TX {} propagated, channel successfully closed.", transaction.getHash()); state = State.CLOSED; closedFuture.set(transaction); } @Override public void onFailure(Throwable throwable) { log.error("Failed to settle channel, could not broadcast: {}", throwable.toString()); throwable.printStackTrace(); state = State.ERROR; closedFuture.setException(throwable); } }); return closedFuture; } /** * Gets the highest payment to ourselves (which we will receive on settle(), not including fees) */ public synchronized Coin getBestValueToMe() { return bestValueToMe; } /** * Gets the fee paid in the final payment transaction (only available if settle() did not throw an exception) */ public synchronized Coin getFeePaid() { checkState(state == State.CLOSED || state == State.CLOSING); return feePaidForPayment; } /** * Gets the multisig contract which was used to initialize this channel */ public synchronized Transaction getMultisigContract() { checkState(multisigContract != null); return multisigContract; } /** * Gets the client's refund transaction which they can spend to get the entire channel value back if it reaches its * lock time. */ public synchronized long getRefundTransactionUnlockTime() { checkState(state.compareTo(State.WAITING_FOR_MULTISIG_CONTRACT) > 0 && state != State.ERROR); return refundTransactionUnlockTimeSecs; } private synchronized void updateChannelInWallet() { if (storedServerChannel != null) { storedServerChannel.updateValueToMe(bestValueToMe, bestValueSignature); StoredPaymentChannelServerStates channels = (StoredPaymentChannelServerStates) wallet.getExtensions().get(StoredPaymentChannelServerStates.EXTENSION_ID); wallet.addOrUpdateExtension(channels); } } /** * Stores this channel's state in the wallet as a part of a {@link StoredPaymentChannelServerStates} wallet * extension and keeps it up-to-date each time payment is incremented. This will be automatically removed when * a call to {@link PaymentChannelServerState#close()} completes successfully. A channel may only be stored after it * has fully opened (ie state == State.READY). * * @param connectedHandler Optional {@link PaymentChannelServer} object that manages this object. This will * set the appropriate pointer in the newly created {@link StoredServerChannel} before it is * committed to wallet. If set, closing the state object will propagate the close to the * handler which can then do a TCP disconnect. */ public synchronized void storeChannelInWallet(@Nullable PaymentChannelServer connectedHandler) { checkState(state == State.READY); if (storedServerChannel != null) return; log.info("Storing state with contract hash {}.", multisigContract.getHash()); StoredPaymentChannelServerStates channels = (StoredPaymentChannelServerStates) wallet.addOrGetExistingExtension(new StoredPaymentChannelServerStates(wallet, broadcaster)); storedServerChannel = new StoredServerChannel(this, multisigContract, clientOutput, refundTransactionUnlockTimeSecs, serverKey, bestValueToMe, bestValueSignature); if (connectedHandler != null) checkState(storedServerChannel.setConnectedHandler(connectedHandler, false) == connectedHandler); channels.putChannel(storedServerChannel); wallet.addOrUpdateExtension(channels); } }
ohac/sha1coinj
core/src/main/java/com/google/sha1coin/protocols/channels/PaymentChannelServerState.java
Java
apache-2.0
29,162
#!/usr/bin/python2.5 # # Copyright 2009 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. """Simple wave robot WSGI application and forwarding middleware.""" import webob import webob.exc from api import robot_abstract import logging class RobotMiddleware(object): """WSGI middleware that routes /_wave/ requests to a robot wsgi app.""" def __init__(self, robot_app, main_app): self._robot_app = robot_app self._main_app = main_app def __call__(self, environ, start_response): path = environ['PATH_INFO'] if path.startswith('/_wave/'): return self._robot_app(environ, start_response) return self._main_app(environ, start_response) class SimpleRobotApp(object): """WSGI application for serving an abstract robot. This is just like the Robot class in the Wave api, but it uses the plain WebOb request/response objects instead of the analogous AppEngine objects. """ def __init__(self, robot): self._robot = robot def capabilities(self): xml = self._robot.GetCapabilitiesXml() response = webob.Response(content_type='text/xml', body=xml) response.cache_control = 'Private' # XXX return response def profile(self): xml = self._robot.GetProfileJson() response = webob.Response(content_type='application/json', body=xml) response.cache_control = 'Private' # XXX return response def jsonrpc(self, req): json_body = req.body logging.info('Incoming: %s', json_body) context, events = robot_abstract.ParseJSONBody(json_body) for event in events: self._robot.HandleEvent(event, context) json_response = robot_abstract.SerializeContext( context, self._robot.version) logging.info('Outgoing: %s', json_response) return webob.Response(content_type='application/json', body=json_response) def __call__(self, environ, start_response): req = webob.Request(environ) if req.path_info == '/_wave/capabilities.xml' and req.method == 'GET': response = self.capabilities() elif req.path_info == '/_wave/robot/profile' and req.method == 'GET': response = self.profile() elif req.path_info == '/_wave/robot/jsonrpc' and req.method == 'POST': response = self.jsonrpc(req) else: response = webob.exc.HTTPNotFound() return response(environ, start_response)
alexisvincent/downy
app.py
Python
apache-2.0
2,858
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ #ifndef itkESMDemonsRegistrationFunction_h #define itkESMDemonsRegistrationFunction_h #include "itkPDEDeformableRegistrationFunction.h" #include "itkCentralDifferenceImageFunction.h" #include "itkWarpImageFilter.h" #include "itkSimpleFastMutexLock.h" namespace itk { /** * \class ESMDemonsRegistrationFunction * * \brief Fast implementation of the symmetric demons registration force * * This class provides a substantially faster implementation of the * symmetric demons registration force. Speed is improved by keeping * a deformed copy of the moving image for gradient evaluation. * * Symmetric forces simply means using the mean of the gradient * of the fixed image and the gradient of the warped moving * image. * * Note that this class also enables the use of fixed, mapped moving * and warped moving images forces by using a call to SetUseGradientType * * The moving image should not be saturated. We indeed use * NumericTraits<MovingPixelType>::Max() as a special value. * * \author Tom Vercauteren, INRIA & Mauna Kea Technologies * * This implementation was taken from the Insight Journal paper: * https://hdl.handle.net/1926/510 * * \sa SymmetricForcesDemonsRegistrationFunction * \sa SymmetricForcesDemonsRegistrationFilter * \sa DemonsRegistrationFilter * \sa DemonsRegistrationFunction * \ingroup FiniteDifferenceFunctions * * \ingroup ITKPDEDeformableRegistration */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > class ITK_TEMPLATE_EXPORT ESMDemonsRegistrationFunction: public PDEDeformableRegistrationFunction< TFixedImage, TMovingImage, TDisplacementField > { public: ITK_DISALLOW_COPY_AND_ASSIGN(ESMDemonsRegistrationFunction); /** Standard class type aliases. */ using Self = ESMDemonsRegistrationFunction; using Superclass = PDEDeformableRegistrationFunction< TFixedImage, TMovingImage, TDisplacementField >; using Pointer = SmartPointer< Self >; using ConstPointer = SmartPointer< const Self >; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(ESMDemonsRegistrationFunction, PDEDeformableRegistrationFunction); /** MovingImage image type. */ using MovingImageType = typename Superclass::MovingImageType; using MovingImagePointer = typename Superclass::MovingImagePointer; using MovingPixelType = typename MovingImageType::PixelType; /** FixedImage image type. */ using FixedImageType = typename Superclass::FixedImageType; using FixedImagePointer = typename Superclass::FixedImagePointer; using IndexType = typename FixedImageType::IndexType; using SizeType = typename FixedImageType::SizeType; using SpacingType = typename FixedImageType::SpacingType; using DirectionType = typename FixedImageType::DirectionType; /** Deformation field type. */ using DisplacementFieldType = typename Superclass::DisplacementFieldType; using DisplacementFieldTypePointer = typename Superclass::DisplacementFieldTypePointer; /** Inherit some enums from the superclass. */ static constexpr unsigned int ImageDimension = Superclass::ImageDimension; /** Inherit some enums from the superclass. */ using PixelType = typename Superclass::PixelType; using RadiusType = typename Superclass::RadiusType; using NeighborhoodType = typename Superclass::NeighborhoodType; using FloatOffsetType = typename Superclass::FloatOffsetType; using TimeStepType = typename Superclass::TimeStepType; /** Interpolator type. */ using CoordRepType = double; using InterpolatorType = InterpolateImageFunction< MovingImageType, CoordRepType >; using InterpolatorPointer = typename InterpolatorType::Pointer; using PointType = typename InterpolatorType::PointType; using DefaultInterpolatorType = LinearInterpolateImageFunction< MovingImageType, CoordRepType >; /** Warper type */ using WarperType = WarpImageFilter< MovingImageType, MovingImageType, DisplacementFieldType >; using WarperPointer = typename WarperType::Pointer; /** Covariant vector type. */ using CovariantVectorType = CovariantVector< double, Self::ImageDimension >; /** Fixed image gradient calculator type. */ using GradientCalculatorType = CentralDifferenceImageFunction< FixedImageType >; using GradientCalculatorPointer = typename GradientCalculatorType::Pointer; /** Moving image gradient (unwarped) calculator type. */ using MovingImageGradientCalculatorType = CentralDifferenceImageFunction< MovingImageType, CoordRepType >; using MovingImageGradientCalculatorPointer = typename MovingImageGradientCalculatorType::Pointer; /** Set the moving image interpolator. */ void SetMovingImageInterpolator(InterpolatorType *ptr) { m_MovingImageInterpolator = ptr; m_MovingImageWarper->SetInterpolator(ptr); } /** Get the moving image interpolator. */ InterpolatorType * GetMovingImageInterpolator() { return m_MovingImageInterpolator; } /** This class uses a constant timestep of 1. */ TimeStepType ComputeGlobalTimeStep( void *itkNotUsed(GlobalData) ) const override { return m_TimeStep; } /** Return a pointer to a global data structure that is passed to * this object from the solver at each calculation. */ void * GetGlobalDataPointer() const override { auto * global = new GlobalDataStruct(); global->m_SumOfSquaredDifference = 0.0; global->m_NumberOfPixelsProcessed = 0L; global->m_SumOfSquaredChange = 0; return global; } /** Release memory for global data structure. */ void ReleaseGlobalDataPointer(void *GlobalData) const override; /** Set the object's state before each iteration. */ void InitializeIteration() override; /** This method is called by a finite difference solver image filter at * each pixel that does not lie on a data set boundary */ PixelType ComputeUpdate( const NeighborhoodType & neighborhood, void *globalData, const FloatOffsetType & offset = FloatOffsetType(0.0) ) override; /** Get the metric value. The metric value is the mean square difference * in intensity between the fixed image and transforming moving image * computed over the the overlapping region between the two images. */ virtual double GetMetric() const { return m_Metric; } /** Get the rms change in deformation field. */ virtual const double & GetRMSChange() const { return m_RMSChange; } /** Set/Get the threshold below which the absolute difference of * intensity yields a match. When the intensities match between a * moving and fixed image pixel, the update vector (for that * iteration) will be the zero vector. Default is 0.001. */ virtual void SetIntensityDifferenceThreshold(double); virtual double GetIntensityDifferenceThreshold() const; /** Set/Get the maximum update step length. In Thirion this is 0.5. * Setting it to 0 implies no restriction (beware of numerical * instability in this case. */ virtual void SetMaximumUpdateStepLength(double sm) { this->m_MaximumUpdateStepLength = sm; } virtual double GetMaximumUpdateStepLength() const { return this->m_MaximumUpdateStepLength; } /** Type of available image forces */ enum GradientType { Symmetric = 0, Fixed = 1, WarpedMoving = 2, MappedMoving = 3 }; /** Set/Get the type of used image forces */ virtual void SetUseGradientType(GradientType gtype) { m_UseGradientType = gtype; } virtual GradientType GetUseGradientType() const { return m_UseGradientType; } protected: ESMDemonsRegistrationFunction(); ~ESMDemonsRegistrationFunction() override = default; void PrintSelf(std::ostream & os, Indent indent) const override; /** FixedImage image neighborhood iterator type. */ using FixedImageNeighborhoodIteratorType = ConstNeighborhoodIterator< FixedImageType >; /** A global data type for this class of equation. Used to store * iterators for the fixed image. */ struct GlobalDataStruct { double m_SumOfSquaredDifference; SizeValueType m_NumberOfPixelsProcessed; double m_SumOfSquaredChange; }; private: /** Cache fixed image information. */ PointType m_FixedImageOrigin; SpacingType m_FixedImageSpacing; DirectionType m_FixedImageDirection; double m_Normalizer; /** Function to compute derivatives of the fixed image. */ GradientCalculatorPointer m_FixedImageGradientCalculator; /** Function to compute derivatives of the moving image (unwarped). */ MovingImageGradientCalculatorPointer m_MappedMovingImageGradientCalculator; GradientType m_UseGradientType; /** Function to interpolate the moving image. */ InterpolatorPointer m_MovingImageInterpolator; /** Filter to warp moving image for fast gradient computation. */ WarperPointer m_MovingImageWarper; MovingImageType *m_MovingImageWarperOutput; /** The global timestep. */ TimeStepType m_TimeStep; /** Threshold below which the denominator term is considered zero. */ double m_DenominatorThreshold; /** Threshold below which two intensity value are assumed to match. */ double m_IntensityDifferenceThreshold; /** Maximum update step length in pixels (default is 0.5 as in Thirion). */ double m_MaximumUpdateStepLength; /** The metric value is the mean square difference in intensity between * the fixed image and transforming moving image computed over the * the overlapping region between the two images. */ mutable double m_Metric; mutable double m_SumOfSquaredDifference; mutable SizeValueType m_NumberOfPixelsProcessed; mutable double m_RMSChange; mutable double m_SumOfSquaredChange; /** Mutex lock to protect modification to metric. */ mutable SimpleFastMutexLock m_MetricCalculationLock; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkESMDemonsRegistrationFunction.hxx" #endif #endif
stnava/ITK
Modules/Registration/PDEDeformable/include/itkESMDemonsRegistrationFunction.h
C
apache-2.0
10,836
<html> <head> <link rel="stylesheet" href="maven-theme.css"> <title>AppSecInc. MSI Extensions</title> </head> <body> <!-- Generated by Doxygen 1.8.5 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_3911586597be601a743904149a57a02f.html">Demos</a></li><li class="navelem"><a class="el" href="dir_78ed0a1428f23748b3007eb2cf548a46.html">SystemToolsMsi</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">Win32CopyFilesUI.wxi File Reference</div> </div> </div><!--header--> <div class="contents"> </div><!-- contents --> <br><hr noshade> <table width="100%"> <tr> <td valign="top" align="left"> <font size="1">&copy; Application Security Inc. - All Rights Reserved</font> </td> <td valign="top" align="right"> <a href="http://msiext.codeplex.com" target="_blank">http://msiext.codeplex.com</a> </td> </tr> </table> </body> <head> <link href="tabs.css" rel="stylesheet" type="text/css"> </head> </html>
developmentalmadness/HelloWiX
lib/msiext-1.4/Docs/_win32_copy_files_u_i_8wxi.html
HTML
apache-2.0
1,792
package com.bjlx.QinShihuang.requestmodel; /** * 登录参数 * @author xiaozhi * */ public class LoginReq { /** * 账户 */ private String account; /** * 密码 */ private String password; /** * 个推的clientId */ private String clientId; public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } }
bujilvxing/QinShihuang
src/main/java/com/bjlx/QinShihuang/requestmodel/LoginReq.java
Java
apache-2.0
656
div#logo a { display: block; width: 100%; height: 100%; } #footer_text a { font-family: Arial,sans-serif; font-style: normal; font-size: 11px; font-weight: normal; color: #000000; text-decoration: underline; white-space: nowrap; } #key_visual { background: url(colorschemes/colorscheme1/images/dynamic/key_visual16.jpg) no-repeat; } #slogan { font-family: Arial,sans-serif; font-style: normal; font-size: 16px; font-weight: bold; text-decoration: none; color: #000000; } #main_nav_list a.main_nav_active_item { background: url(images/dynamic/buttonset1/main_nav_active.gif) no-repeat; font-family: Arial,sans-serif; font-size: 14px; font-weight: bold; text-decoration: none; color: #000000; } #main_nav_list a.main_nav_item { background: url(images/dynamic/buttonset1/main_nav.gif) no-repeat; font-family: Arial,sans-serif; font-style: normal; font-size: 14px; font-weight: bold; text-decoration: none; color: #000000; } #main_nav_list a.main_nav_item:hover { background: url(images/dynamic/buttonset1/main_nav_active.gif) no-repeat; font-family: Arial,sans-serif; font-style: normal; font-size: 14px; font-weight: bold; text-decoration: none; color: #000000; } .sub_nav_list a.sub_nav_active_item { background: url(images/dynamic/buttonset1/sub_nav_active.gif) no-repeat; font-family: Arial,sans-serif; font-style: italic; font-size: 12px; font-weight: normal; text-decoration: underline; color: #294687; } .sub_nav_list a.sub_nav_item { background: url(images/dynamic/buttonset1/sub_nav.gif) no-repeat; font-family: Arial,sans-serif; font-style: normal; font-size: 12px; font-weight: normal; text-decoration: none; color: #305774; } .sub_nav_list a.sub_nav_item:hover { background: url(images/dynamic/buttonset1/sub_nav_active.gif) no-repeat; font-family: Arial,sans-serif; font-style: normal; font-size: 12px; font-weight: normal; text-decoration: none; color: #294687; } #content_container h1 { font-family: arial, verdana, tahoma, sans-serif; font-style: normal; font-size: 29px; font-weight: bold; text-decoration: none; color: #942825; } #content_container h2 { font-family: arial, verdana, tahoma, sans-serif; font-style: normal; font-size: 23px; font-weight: bold; text-decoration: none; color: #942825; } #content_container h3 { font-family: arial, verdana, tahoma, sans-serif; font-style: normal; font-size: 18px; font-weight: bold; text-decoration: none; color: #942825; } #content_container, #content_container p { font-family: arial, verdana, tahoma, sans-serif; font-style: normal; font-size: 12px; font-weight: normal; text-decoration: none; color: #000000; } #content_container a:visited { font-family: arial, verdana, tahoma, sans-serif; font-style: normal; font-size: 100%; font-weight: normal; text-decoration: underline; color: #568db2; } #content_container a:link { font-family: arial, verdana, tahoma, sans-serif; font-style: normal; font-size: 100%; font-weight: normal; text-decoration: none; color: #366d92; } #content_container a:hover { font-family: arial, verdana, tahoma, sans-serif; font-style: normal; font-size: 100%; font-weight: normal; text-decoration: underline; color: #366d92; } #content_container a:active { font-family: arial, verdana, tahoma, sans-serif; font-style: normal; font-size: 100%; font-weight: normal; text-decoration: none; color: #942825; } #footer_text { font-family: Arial,sans-serif; font-style: normal; font-size: 11px; font-weight: normal; text-decoration: none; color: #000000; }
CGVA/cgva_asp_website
lastdigindenver/style.css
CSS
apache-2.0
3,825
# @scheduled example
arc-repos/arc-docs
en/aws/examples-scheduled.md
Markdown
apache-2.0
22
<app-main-layout [dataset]="dataset"> <mat-card> <mat-card-title><mat-icon matListIcon>contacts</mat-icon> Submitters</mat-card-title> <mat-card-content> <div class="ui-g"> <div class="ui-g-12"> <mat-card class="inner-card"> <mat-card-title> <mat-toolbar> <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter"> </mat-form-field> <span class="example-fill-remaining-space"></span> <span> <button (click)="openCreateSubmitterDialog()" mat-icon-button color="primary" matTooltip="Add submitter"><mat-icon>add_box</mat-icon></button> </span> </mat-toolbar> </mat-card-title> <mat-table #table [dataSource]="datasource" matSort> <ng-container matColumnDef="name"> <mat-header-cell *matHeaderCellDef mat-sort-header> Submitter </mat-header-cell> <mat-cell *matCellDef="let submitter" (click)="navigate(submitter.string)" style="cursor: pointer;">{{ submitter.name }}</mat-cell> </ng-container> <ng-container matColumnDef="string"> <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell> <mat-cell *matCellDef="let submitter" (click)="navigate(submitter.string)" style="cursor: pointer;">[{{ submitter.string }}]</mat-cell> </ng-container> <ng-container matColumnDef="delete"> <mat-header-cell *matHeaderCellDef mat-sort-header></mat-header-cell> <mat-cell *matCellDef="let submitter"> <span class="hidden"> <button mat-icon-button matTooltip="Delete submitter" color="warn" (click)="delete(submitter)"> <mat-icon matListIcon>delete</mat-icon></button> </span> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row class="parent" *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table> <mat-paginator #paginator [pageSize]="15" [pageSizeOptions]="pagesizeoptions()" [showFirstLastButtons]="true"> </mat-paginator> </mat-card> </div> </div> </mat-card-content> </mat-card> </app-main-layout>
dickschoeller/gedbrowser
gedbrowserng-frontend/src/app/modules/submitter-list/submitter-list.component.html
HTML
apache-2.0
2,630
//var hostname = "emobile.no-ip.org:8081" var hostname = "192.168.1.188:3000" exports.singIn = function(username, password, callback) { var credentials = '{"utf8":"✓", "authenticity_token":"fLDXlKyfXTlgnltRC3Ab23UQqGrGz/p/klJ9TZfW2r8=", "user":{"login": "' + username + '", "password": "' + password + '"}, "commit": "Sign in"}'; var client = Titanium.Network.createHTTPClient({ timeout : 15000 }); client.open("POST", "http://" + hostname + "/users/sign_in"); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(credentials); client.onload = function(e) { var current_user = JSON.parse(this.responseText); Ti.App.current_user = current_user; callback(true); } client.onerror = function(e) { alert('Invalid username or password.'); callback(false); } }; exports.singOut = function(callback) { var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("DELETE", "http://" + hostname + "/users/sign_out"); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(); client.onload = function(e) { alert('Logged out successfully'); callback(true); } client.onerror = function(e) { alert('En error has ocurred.'); callback(false); } }; exports.getBranch = function(callback) { var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("GET", "http://" + hostname + "/companies/" + Ti.App.current_user.company_id + "/branches/" + Ti.App.current_user.branch_id + ".json"); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(); client.onload = function(e) { var branch = JSON.parse(this.responseText); callback(branch); } client.onerror = function(e) { alert('An error has ocurred: ' + this.responseText + "."); callback(false); } }; exports.getCompany = function(callback) { var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("GET", "http://" + hostname + "/companies/" + Ti.App.current_user.company_id + ".json"); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(); client.onload = function(e) { var branch = JSON.parse(this.responseText); callback(branch); } client.onerror = function(e) { alert('An error has ocurred: ' + this.responseText + "."); callback(false); } }; exports.getClients = function(callback) { var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("GET", "http://" + hostname + "/clients.json"); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(); client.onload = function(e) { var clients = JSON.parse(this.responseText); callback(clients); } client.onerror = function(e) { alert('An error has ocurred: ' + this.responseText + "."); callback(false); } }; exports.getProducts = function(callback) { var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("GET", "http://" + hostname + "/companies/" + Ti.App.current_user.company_id + "/branches/" + Ti.App.current_user.branch_id + "/products.json"); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(); client.onload = function(e) { var clients = JSON.parse(this.responseText); callback(clients); } client.onerror = function(e) { alert('An error has ocurred: ' + this.responseText + "."); callback(false); } }; exports.getOrders = function(callback) { var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("GET", "http://" + hostname + "/companies/" + Ti.App.current_user.company_id + "/branches/" + Ti.App.current_user.branch_id + "/orders.json"); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(); client.onload = function(e) { var orders = JSON.parse(this.responseText); callback(orders); } client.onerror = function(e) { alert('An error has ocurred: ' + this.responseText + "."); callback(false); } }; exports.sentOrder = function(description, seller_id, client_id, latitude, longitude, products, callback) { var orderResponse = '{"utf8":"✓", "authenticity_token":"fLDXlKyfXTlgnltRC3Ab23UQqGrGz/p/klJ9TZfW2r8=", "order":{"description":"' + description + '", "seller_id":"' + seller_id + '", "client_id":"' + client_id + '", "latitude":"' + latitude + '", "longitude": "' + longitude + '", "order_details_attributes":{ ' + products + ' }}, "commit": "Crear Order"}'; var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("POST", "http://" + hostname + "/companies/" + Ti.App.current_user.company_id + "/branches/" + Ti.App.current_user.branch_id + "/orders"); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(orderResponse); client.onload = function(e) { alert('Sent'); callback(true); Ti.App.fireEvent("databaseOrdersUpdated"); } client.onerror = function(e) { alert('An error has ocurred: ' + this.responseText + ".1"); callback(false); } }; exports.updateOrder = function(description, seller_id, client_id, latitude, longitude, product_id, quantity, order_id, callback) { var orderResponse = '{"utf8":"✓", "authenticity_token":"fLDXlKyfXTlgnltRC3Ab23UQqGrGz/p/klJ9TZfW2r8=", "order":{"description":"' + description + '", "seller_id":"' + seller_id + '", "client_id":"' + client_id + '", "latitude":"' + latitude + '", "longitude": "' + longitude + '", "order_details_attributes":{"0":{"product_id":"' + product_id + '", "quantity":"' + quantity + '", "_destroy":"false"}}}, "commit": "Update"}'; var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("PUT", "http://" + hostname + "/companies/" + Ti.App.current_user.company_id + "/branches/" + Ti.App.current_user.branch_id + "/orders/" + order_id); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(orderResponse); client.onload = function(e) { alert('Sent'); callback(true); Ti.App.fireEvent("databaseOrdersUpdated"); } client.onerror = function(e) { alert('An error has ocurred: ' + this.responseText + ".1"); callback(false); } }; exports.closeOrder = function(description, seller_id, client_id, latitude, longitude, product_id, quantity, order_id, close, callback) { var orderResponse = '{"utf8":"✓", "authenticity_token":"fLDXlKyfXTlgnltRC3Ab23UQqGrGz/p/klJ9TZfW2r8=", "order":{"closed":"' + close + '", "description":"' + description + '", "seller_id":"' + seller_id + '", "client_id":"' + client_id + '", "latitude":"' + latitude + '", "longitude": "' + longitude + '", "order_details_attributes":{"0":{"product_id":"' + product_id + '", "quantity":"' + quantity + '", "_destroy":"false"}}}, "commit": "Update"}'; var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("PUT", "http://" + hostname + "/companies/" + Ti.App.current_user.company_id + "/branches/" + Ti.App.current_user.branch_id + "/orders/" + order_id); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(orderResponse); client.onload = function(e) { alert('Sent'); callback(true); Ti.App.fireEvent("databaseOrdersUpdated"); } client.onerror = function(e) { alert('An error has ocurred: ' + this.responseText + ".1"); callback(false); } }; exports.getClient = function(client_id, callback) { var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("GET", "http://" + hostname + "/clients/" + client_id + ".json"); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(); client.onload = function(e) { var client = JSON.parse(this.responseText); callback(client); } client.onerror = function(e) { alert('An error has ocurred: ' + this.responseText + "."); callback(false); } }; exports.getTasks = function(callback) { var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("GET", "http://" + hostname + "/tasks/user_tasks.json?completed=" + Ti.App.completed + "&days=" + Ti.App.days + "&priority=" + Ti.App.prioriry + "&order=" + Ti.App.order + "&user_id=" + Ti.App.current_user.id); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(); client.onload = function(e) { var tasks = JSON.parse(this.responseText); callback(tasks); } client.onerror = function(e) { alert('An error has ocurred: ' + this.responseText + "."); callback(false); } }; exports.sentTasks = function(task, completed, comments, latitude, longitude, callback) { var taskResponse = '{"utf8":"✓", "authenticity_token":"fLDXlKyfXTlgnltRC3Ab23UQqGrGz/p/klJ9TZfW2r8=", "task":{"completed":"' + completed + '", "comments":"' + comments + '", "latitude":"' + latitude + '", "longitude": "' + longitude + '" }, "commit": "Update"}'; var client = Titanium.Network.createHTTPClient({ timeout : 5000 }); client.open("PUT", "http://" + hostname + "/companies/" + task.company_id + "/branches/" + task.branch_id + "/tasks/" + task.id); client.setRequestHeader("Content-Type", "application/json", "Accept", "application/json"); client.send(taskResponse); client.onload = function(e) { alert('Sent'); callback(true); Ti.App.fireEvent("databaseUpdated"); } client.onerror = function(e) { alert('An error has ocurred: ' + this.responseText + "."); callback(false); } };
alexjabf/gestorum
Resources/lib/network.js
JavaScript
apache-2.0
9,600
# 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 kuryr.schemata import commons ENDPOINT_DELETE_SCHEMA = { u'links': [{ u'method': u'POST', u'href': u'/NetworkDriver.DeleteEndpoint', u'description': u'Delete an Endpoint', u'rel': u'self', u'title': u'Delete' }], u'title': u'Delete endpoint', u'required': [u'NetworkID', u'EndpointID'], u'definitions': {u'commons': {}}, u'$schema': u'http://json-schema.org/draft-04/hyper-schema', u'type': u'object', u'properties': { u'NetworkID': { u'description': u'Network ID', u'$ref': u'#/definitions/commons/definitions/id' }, u'EndpointID': { u'description': u'Endpoint ID', u'$ref': u'#/definitions/commons/definitions/id' } } } ENDPOINT_DELETE_SCHEMA[u'definitions'][u'commons'] = commons.COMMONS
midonet/kuryr
kuryr/schemata/endpoint_delete.py
Python
apache-2.0
1,400
// // MeeRefreshFooter.h // MeeBS // // Created by 扬帆起航 on 15/12/19. // Copyright © 2015年 Lee. All rights reserved. // #import <MJRefresh/MJRefresh.h> @interface MeeRefreshFooter : MJRefreshAutoNormalFooter @end
MeeMi/MeeBS
MeeBS/Classes/Other-其他/MeeRefreshFooter.h
C
apache-2.0
230
#!/usr/bin/env bash # resolve-run-targets.sh -- Resolves unqualified names to do into run/Makefile targets ## DEEPDIVE_APP=$(find-deepdive-app) export DEEPDIVE_APP # check if already fully compiled first app-has-been-compiled # when our make commands are nested under an outer make, e.g., our own `make # test`, some special environment variables can screw things up, so clear them unset MAKEFLAGS MFLAGS MAKEOVERRIDES MAKELEVEL # find what exactly each argument refers to if [[ $# -gt 0 ]]; then makeTargets=() for target; do resolved=false for fmt in %s %s.done {data,process,data/model,model,process/{model,grounding{,/{factor,variable}}}}/%s.done; do makeTarget=$(printf "$fmt" "$target") if [[ $(make -C "$DEEPDIVE_APP"/run -p | sed 's/:.*$//' | grep -cxF "$makeTarget") -gt 0 ]]; then makeTargets+=("$makeTarget") resolved=true break fi done $resolved || error "$target: Unknown target" done set -- "${makeTargets[@]}" else usage "$0" "No TARGET specified, which can be one of:" || make -C "$DEEPDIVE_APP"/run --silent list >&2 false fi
zifeishan/deepdive
runner/resolve-args-to-do.sh
Shell
apache-2.0
1,191
package com.Android2.controller; /** * Created by cirkus on 03.08.2017. */ public interface IHasActionBarItems { void setOnActionBarItemEnabledEnabledChanged(OnActionBarItemEnabledChangedListener listener); boolean isActionBarItemEnabled(int itemId); int[] getOwnedActionBarItemIds(); boolean onActionBarItemSelected(int itemId); interface OnActionBarItemEnabledChangedListener { void onActionBarItemEnabledChanged(); void onHasActionBarItemsDetach(); } }
j0rg3n/skattejakt
app/src/main/java/com/Android2/controller/IHasActionBarItems.java
Java
apache-2.0
501
"""Tests for greeneye_monitor sensors.""" from unittest.mock import AsyncMock, MagicMock from homeassistant.components.greeneye_monitor.sensor import ( DATA_PULSES, DATA_WATT_SECONDS, ) from homeassistant.const import STATE_UNKNOWN from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_registry import async_get as get_entity_registry from .common import ( SINGLE_MONITOR_CONFIG_POWER_SENSORS, SINGLE_MONITOR_CONFIG_PULSE_COUNTERS, SINGLE_MONITOR_CONFIG_TEMPERATURE_SENSORS, SINGLE_MONITOR_CONFIG_VOLTAGE_SENSORS, SINGLE_MONITOR_SERIAL_NUMBER, mock_monitor, setup_greeneye_monitor_component_with_config, ) from .conftest import assert_sensor_state async def test_disable_sensor_before_monitor_connected( hass: HomeAssistant, monitors: AsyncMock ) -> None: """Test that a sensor disabled before its monitor connected stops listening for new monitors.""" # The sensor base class handles connecting the monitor, so we test this with a single voltage sensor for ease await setup_greeneye_monitor_component_with_config( hass, SINGLE_MONITOR_CONFIG_VOLTAGE_SENSORS ) assert len(monitors.listeners) == 1 await disable_entity(hass, "sensor.voltage_1") assert len(monitors.listeners) == 0 # Make sure we cleaned up the listener async def test_updates_state_when_monitor_connected( hass: HomeAssistant, monitors: AsyncMock ) -> None: """Test that a sensor updates its state when its monitor first connects.""" # The sensor base class handles updating the state on connection, so we test this with a single voltage sensor for ease await setup_greeneye_monitor_component_with_config( hass, SINGLE_MONITOR_CONFIG_VOLTAGE_SENSORS ) assert_sensor_state(hass, "sensor.voltage_1", STATE_UNKNOWN) assert len(monitors.listeners) == 1 connect_monitor(monitors, SINGLE_MONITOR_SERIAL_NUMBER) assert len(monitors.listeners) == 0 # Make sure we cleaned up the listener assert_sensor_state(hass, "sensor.voltage_1", "120.0") async def test_disable_sensor_after_monitor_connected( hass: HomeAssistant, monitors: AsyncMock ) -> None: """Test that a sensor disabled after its monitor connected stops listening for sensor changes.""" # The sensor base class handles connecting the monitor, so we test this with a single voltage sensor for ease await setup_greeneye_monitor_component_with_config( hass, SINGLE_MONITOR_CONFIG_VOLTAGE_SENSORS ) monitor = connect_monitor(monitors, SINGLE_MONITOR_SERIAL_NUMBER) assert len(monitor.listeners) == 1 await disable_entity(hass, "sensor.voltage_1") assert len(monitor.listeners) == 0 async def test_updates_state_when_sensor_pushes( hass: HomeAssistant, monitors: AsyncMock ) -> None: """Test that a sensor entity updates its state when the underlying sensor pushes an update.""" # The sensor base class handles triggering state updates, so we test this with a single voltage sensor for ease await setup_greeneye_monitor_component_with_config( hass, SINGLE_MONITOR_CONFIG_VOLTAGE_SENSORS ) monitor = connect_monitor(monitors, SINGLE_MONITOR_SERIAL_NUMBER) assert_sensor_state(hass, "sensor.voltage_1", "120.0") monitor.voltage = 119.8 monitor.notify_all_listeners() assert_sensor_state(hass, "sensor.voltage_1", "119.8") async def test_power_sensor_initially_unknown( hass: HomeAssistant, monitors: AsyncMock ) -> None: """Test that the power sensor can handle its initial state being unknown (since the GEM API needs at least two packets to arrive before it can compute watts).""" await setup_greeneye_monitor_component_with_config( hass, SINGLE_MONITOR_CONFIG_POWER_SENSORS ) connect_monitor(monitors, SINGLE_MONITOR_SERIAL_NUMBER) assert_sensor_state( hass, "sensor.channel_1", STATE_UNKNOWN, {DATA_WATT_SECONDS: 1000} ) # This sensor was configured with net metering on, so we should be taking the # polarized value assert_sensor_state( hass, "sensor.channel_two", STATE_UNKNOWN, {DATA_WATT_SECONDS: -400} ) async def test_power_sensor(hass: HomeAssistant, monitors: AsyncMock) -> None: """Test that a power sensor reports its values correctly, including handling net metering.""" await setup_greeneye_monitor_component_with_config( hass, SINGLE_MONITOR_CONFIG_POWER_SENSORS ) monitor = connect_monitor(monitors, SINGLE_MONITOR_SERIAL_NUMBER) monitor.channels[0].watts = 120.0 monitor.channels[1].watts = 120.0 monitor.channels[0].notify_all_listeners() monitor.channels[1].notify_all_listeners() assert_sensor_state(hass, "sensor.channel_1", "120.0", {DATA_WATT_SECONDS: 1000}) # This sensor was configured with net metering on, so we should be taking the # polarized value assert_sensor_state(hass, "sensor.channel_two", "120.0", {DATA_WATT_SECONDS: -400}) async def test_pulse_counter(hass: HomeAssistant, monitors: AsyncMock) -> None: """Test that a pulse counter sensor reports its values properly, including calculating different units.""" await setup_greeneye_monitor_component_with_config( hass, SINGLE_MONITOR_CONFIG_PULSE_COUNTERS ) connect_monitor(monitors, SINGLE_MONITOR_SERIAL_NUMBER) assert_sensor_state(hass, "sensor.pulse_a", "10.0", {DATA_PULSES: 1000}) # This counter was configured with each pulse meaning 0.5 gallons and # wanting to show gallons per minute, so 10 pulses per second -> 300 gal/min assert_sensor_state(hass, "sensor.pulse_2", "300.0", {DATA_PULSES: 1000}) # This counter was configured with each pulse meaning 0.5 gallons and # wanting to show gallons per hour, so 10 pulses per second -> 18000 gal/hr assert_sensor_state(hass, "sensor.pulse_3", "18000.0", {DATA_PULSES: 1000}) async def test_temperature_sensor(hass: HomeAssistant, monitors: AsyncMock) -> None: """Test that a temperature sensor reports its values properly, including proper handling of when its native unit is different from that configured in hass.""" await setup_greeneye_monitor_component_with_config( hass, SINGLE_MONITOR_CONFIG_TEMPERATURE_SENSORS ) connect_monitor(monitors, SINGLE_MONITOR_SERIAL_NUMBER) # The config says that the sensor is reporting in Fahrenheit; if we set that up # properly, HA will have converted that to Celsius by default. assert_sensor_state(hass, "sensor.temp_a", "0.0") async def test_voltage_sensor(hass: HomeAssistant, monitors: AsyncMock) -> None: """Test that a voltage sensor reports its values properly.""" await setup_greeneye_monitor_component_with_config( hass, SINGLE_MONITOR_CONFIG_VOLTAGE_SENSORS ) connect_monitor(monitors, SINGLE_MONITOR_SERIAL_NUMBER) assert_sensor_state(hass, "sensor.voltage_1", "120.0") def connect_monitor(monitors: AsyncMock, serial_number: int) -> MagicMock: """Simulate a monitor connecting to Home Assistant. Returns the mock monitor API object.""" monitor = mock_monitor(serial_number) monitors.add_monitor(monitor) return monitor async def disable_entity(hass: HomeAssistant, entity_id: str) -> None: """Disable the given entity.""" entity_registry = get_entity_registry(hass) entity_registry.async_update_entity(entity_id, disabled_by="user") await hass.async_block_till_done()
jawilson/home-assistant
tests/components/greeneye_monitor/test_sensor.py
Python
apache-2.0
7,421
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_74) on Fri Apr 01 14:42:07 CDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Uses of Class org.apache.solr.rest.schema.analysis.BaseManagedTokenFilterFactory (Solr 6.0.0 API)</title> <meta name="date" content="2016-04-01"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.rest.schema.analysis.BaseManagedTokenFilterFactory (Solr 6.0.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/solr/rest/schema/analysis/BaseManagedTokenFilterFactory.html" title="class in org.apache.solr.rest.schema.analysis">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/rest/schema/analysis/class-use/BaseManagedTokenFilterFactory.html" target="_top">Frames</a></li> <li><a href="BaseManagedTokenFilterFactory.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;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.rest.schema.analysis.BaseManagedTokenFilterFactory" class="title">Uses of Class<br>org.apache.solr.rest.schema.analysis.BaseManagedTokenFilterFactory</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../org/apache/solr/rest/schema/analysis/BaseManagedTokenFilterFactory.html" title="class in org.apache.solr.rest.schema.analysis">BaseManagedTokenFilterFactory</a></span><span class="tabEnd">&nbsp;</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.rest.schema.analysis">org.apache.solr.rest.schema.analysis</a></td> <td class="colLast"> <div class="block">Analysis-related functionality for RESTful API access to the Solr Schema using Restlet.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.solr.rest.schema.analysis"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/apache/solr/rest/schema/analysis/BaseManagedTokenFilterFactory.html" title="class in org.apache.solr.rest.schema.analysis">BaseManagedTokenFilterFactory</a> in <a href="../../../../../../../org/apache/solr/rest/schema/analysis/package-summary.html">org.apache.solr.rest.schema.analysis</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/apache/solr/rest/schema/analysis/BaseManagedTokenFilterFactory.html" title="class in org.apache.solr.rest.schema.analysis">BaseManagedTokenFilterFactory</a> in <a href="../../../../../../../org/apache/solr/rest/schema/analysis/package-summary.html">org.apache.solr.rest.schema.analysis</a></span><span class="tabEnd">&nbsp;</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>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/solr/rest/schema/analysis/ManagedStopFilterFactory.html" title="class in org.apache.solr.rest.schema.analysis">ManagedStopFilterFactory</a></span></code> <div class="block">TokenFilterFactory that uses the ManagedWordSetResource implementation for managing stop words using the REST API.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/solr/rest/schema/analysis/ManagedSynonymFilterFactory.html" title="class in org.apache.solr.rest.schema.analysis">ManagedSynonymFilterFactory</a></span></code> <div class="block">TokenFilterFactory and ManagedResource implementation for doing CRUD on synonyms using the REST API.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/solr/rest/schema/analysis/BaseManagedTokenFilterFactory.html" title="class in org.apache.solr.rest.schema.analysis">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/rest/schema/analysis/class-use/BaseManagedTokenFilterFactory.html" target="_top">Frames</a></li> <li><a href="BaseManagedTokenFilterFactory.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;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 &copy; 2000-2016 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>
Velaya/gbol_solr
docs/solr-core/org/apache/solr/rest/schema/analysis/class-use/BaseManagedTokenFilterFactory.html
HTML
apache-2.0
8,322
void my_add() { } void my_del() { }
imay/palo
be/test/runtime/test_data/user_function_cache/lib/my_add.cc
C++
apache-2.0
36
# Lyonia brachytricha Urb. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ericaceae/Lyonia/Lyonia brachytricha/README.md
Markdown
apache-2.0
174
package com.thunisoft.mediax.core.vfs; import java.util.Arrays; import junit.framework.TestCase; import com.thunisoft.mediax.http.HttpRange; public class TestHttpRange extends TestCase { public void test() { // 区间在总长度里面 HttpRange r1 = HttpRange.newInstance(50, 20, 200); assertEquals(r1.startPosition(), 50); assertEquals(r1.endPosition(), 69); assertEquals(r1.length(), 20); assertEquals(r1.fullLength(), 200); // 区间不在里面 HttpRange r2 = HttpRange.newInstance(50, 20, 60); assertEquals(r2.startPosition(), 50); assertEquals(r2.endPosition(), 59); assertEquals(r2.length(), 10); // 这个一定要对! assertEquals(r2.fullLength(), 60); HttpRange r3 = HttpRange.newInstance(0, 180, 200); HttpRange r4 = HttpRange.parse(r3.toRangeHeader(), 200); assertEquals(r3, r4); HttpRange r5 = HttpRange.newInstance(0, 180, 170); HttpRange r6 = HttpRange.parse(r5.toRangeHeader(), 170); assertEquals(r5, r6); HttpRange r7 = HttpRange.parse(r6.toContentRangeHeader()); assertEquals(r7 , r6); HttpRange r8 = HttpRange.newInstance(0, 10, 20); HttpRange r9 = HttpRange.newInstance(10, 10, 20); HttpRange[] arr1 = new HttpRange[]{r9, r8}; Arrays.sort(arr1); assertEquals(arr1[0], r8); HttpRange[] r10 = HttpRange.split(1024 * 10 + 1, 1024); assertEquals(r10.length, 11); } }
chenxiuheng/httpstreams
streamserver/test/com/thunisoft/mediax/core/vfs/TestHttpRange.java
Java
apache-2.0
1,649
package view_inspector.ui.dialog.adapter; import android.content.Context; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import view_inspector.R; import view_inspector.ViewInspector; import view_inspector.dagger.qualifier.ViewSuspects; import view_inspector.util.ViewUtil; public class ViewRootAdapter extends BaseAdapter { private final LayoutInflater mLayoutInflater; private final ListView mListView; @Inject @ViewSuspects List<View> viewSuspects; private List<View> mViewGroupList = new ArrayList<>(); public ViewRootAdapter(Context context, ListView mListView) { ViewInspector.runtimeComponentMap.get(((ContextThemeWrapper) context).getBaseContext()) .inject(this); mLayoutInflater = LayoutInflater.from(context); this.mListView = mListView; for (View view : viewSuspects) { if (view instanceof ViewGroup && ViewUtil.getViewLevel(view) > 1) mViewGroupList.add(view); } } @Override public int getCount() { return mViewGroupList.size(); } @Override public Object getItem(int position) { return mViewGroupList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.view_inspector_set_view_root_listitem, parent, false); viewHolder = new ViewHolder(); viewHolder.viewClass = (TextView) convertView.findViewById(R.id.view_class); viewHolder.viewId = (TextView) convertView.findViewById(R.id.view_id); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } View view = mViewGroupList.get(position); viewHolder.viewClass.setText(ViewUtil.getClassName(view)); viewHolder.viewId.setText(ViewUtil.getSimpleViewId(view)); if (view.equals(ViewInspector.viewRoot)) mListView.setItemChecked(position, true); return convertView; } class ViewHolder { public TextView viewClass; public TextView viewId; } }
xfumihiro/ViewInspector
view-inspector-runtime/src/main/java/view_inspector/ui/dialog/adapter/ViewRootAdapter.java
Java
apache-2.0
2,391
/* * Copyright (c) 2011-2016 Pivotal Software 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. */ import React from 'react'; class Metric extends React.Component { render() { return ( <div> <div className="heading"> <strong>Metrics</strong> </div> </div> ); } } export default Metric;
reactor/reactor-pylon
src/main/app/components/metric/Metric.js
JavaScript
apache-2.0
877
package br.com.marcelogomes.exomeanalysis.managedbean.manager; import br.com.marcelogomes.exomeanalysis.managedbean.UserMB; import br.com.marcelogomes.exomeanalysis.model.Project; import br.com.marcelogomes.exomeanalysis.service.ProjectService; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.faces.view.ViewScoped; import javax.inject.Named; import javax.inject.Inject; /** * * @author marcelo */ @Named(value = "proccessedMB") //@RequestScoped @ViewScoped public class ProccessedMB implements Serializable { private static final long serialVersionUID = 1L; @Inject private ProjectService projectService; @Inject private UserMB userMB; private List<Project> listProject = new ArrayList<Project>(); public List<Project> getListProject() { return listProject; } public void setListProject(List<Project> listProject) { this.listProject = listProject; } public void updateList(){ listProject = projectService.findAllProccessed(userMB.getUser()); } public ProccessedMB() { } }
marcelogomesrp/ExomeAnalysis
ExomeAnalysis/src/main/java/br/com/marcelogomes/exomeanalysis/managedbean/manager/ProccessedMB.java
Java
apache-2.0
1,161
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.worker.block; import alluxio.Configuration; import alluxio.PropertyKey; import alluxio.StorageTierAssoc; import alluxio.WorkerStorageTierAssoc; import alluxio.collections.Pair; import alluxio.exception.BlockAlreadyExistsException; import alluxio.exception.BlockDoesNotExistException; import alluxio.exception.ExceptionMessage; import alluxio.exception.InvalidWorkerStateException; import alluxio.exception.WorkerOutOfSpaceException; import alluxio.resource.LockResource; import alluxio.util.io.FileUtils; import alluxio.worker.block.allocator.Allocator; import alluxio.worker.block.evictor.BlockTransferInfo; import alluxio.worker.block.evictor.EvictionPlan; import alluxio.worker.block.evictor.Evictor; import alluxio.worker.block.io.BlockReader; import alluxio.worker.block.io.BlockWriter; import alluxio.worker.block.io.LocalFileBlockReader; import alluxio.worker.block.io.LocalFileBlockWriter; import alluxio.worker.block.meta.BlockMeta; import alluxio.worker.block.meta.StorageDirView; import alluxio.worker.block.meta.TempBlockMeta; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.concurrent.NotThreadSafe; /** * This class represents an object store that manages all the blocks in the local tiered storage. * This store exposes simple public APIs to operate blocks. Inside this store, it creates an * Allocator to decide where to put a new block, an Evictor to decide where to evict a stale block, * a BlockMetadataManager to maintain the status of the tiered storage, and a LockManager to * coordinate read/write on the same block. * <p> * This class is thread-safe, using the following lock hierarchy to ensure thread-safety: * <ul> * <li>Any block-level operation (e.g., read, move or remove) on an existing block must acquire a * block lock for this block via {@link TieredBlockStore#mLockManager}. This block lock is a * read/write lock, guarding both the metadata operations and the following I/O on this block. It * coordinates different threads (clients) when accessing the same block concurrently.</li> * <li>Any metadata operation (read or write) must go through {@link TieredBlockStore#mMetaManager} * and guarded by {@link TieredBlockStore#mMetadataLock}. This is also a read/write lock and * coordinates different threads (clients) when accessing the shared data structure for metadata. * </li> * <li>Method {@link #createBlock} does not acquire the block lock, because it only creates a * temp block which is only visible to its writer before committed (thus no concurrent access).</li> * <li>Method {@link #abortBlock(long, long)} does not acquire the block lock, because only * temporary blocks can be aborted, and they are only visible to their writers (thus no concurrent * access). * <li>Eviction is done in {@link #freeSpaceInternal} and it is on the basis of best effort. For * operations that may trigger this eviction (e.g., move, create, requestSpace), retry is used</li> * </ul> */ @NotThreadSafe // TODO(jiri): make thread-safe (c.f. ALLUXIO-1624) public class TieredBlockStore implements BlockStore { private static final Logger LOG = LoggerFactory.getLogger(TieredBlockStore.class); private static final int MAX_RETRIES = Configuration.getInt(PropertyKey.WORKER_TIERED_STORE_RETRY); private final BlockMetadataManager mMetaManager; private final BlockLockManager mLockManager; private final Allocator mAllocator; private final Evictor mEvictor; private final List<BlockStoreEventListener> mBlockStoreEventListeners = new ArrayList<>(); /** A set of pinned inodes fetched from the master. */ private final Set<Long> mPinnedInodes = new HashSet<>(); /** Lock to guard metadata operations. */ private final ReentrantReadWriteLock mMetadataLock = new ReentrantReadWriteLock(); /** ReadLock provided by {@link #mMetadataLock} to guard metadata read operations. */ private final Lock mMetadataReadLock = mMetadataLock.readLock(); /** WriteLock provided by {@link #mMetadataLock} to guard metadata write operations. */ private final Lock mMetadataWriteLock = mMetadataLock.writeLock(); /** Association between storage tier aliases and ordinals. */ private final StorageTierAssoc mStorageTierAssoc; /** * Creates a new instance of {@link TieredBlockStore}. */ public TieredBlockStore() { mMetaManager = BlockMetadataManager.createBlockMetadataManager(); mLockManager = new BlockLockManager(); BlockMetadataManagerView initManagerView = new BlockMetadataManagerView(mMetaManager, Collections.<Long>emptySet(), Collections.<Long>emptySet()); mAllocator = Allocator.Factory.create(initManagerView); if (mAllocator instanceof BlockStoreEventListener) { registerBlockStoreEventListener((BlockStoreEventListener) mAllocator); } initManagerView = new BlockMetadataManagerView(mMetaManager, Collections.<Long>emptySet(), Collections.<Long>emptySet()); mEvictor = Evictor.Factory.create(initManagerView, mAllocator); if (mEvictor instanceof BlockStoreEventListener) { registerBlockStoreEventListener((BlockStoreEventListener) mEvictor); } mStorageTierAssoc = new WorkerStorageTierAssoc(); } @Override public long lockBlock(long sessionId, long blockId) throws BlockDoesNotExistException { long lockId = mLockManager.lockBlock(sessionId, blockId, BlockLockType.READ); boolean hasBlock; try (LockResource r = new LockResource(mMetadataReadLock)) { hasBlock = mMetaManager.hasBlockMeta(blockId); } if (hasBlock) { return lockId; } mLockManager.unlockBlock(lockId); throw new BlockDoesNotExistException(ExceptionMessage.NO_BLOCK_ID_FOUND, blockId); } @Override public long lockBlockNoException(long sessionId, long blockId) { long lockId = mLockManager.lockBlock(sessionId, blockId, BlockLockType.READ); boolean hasBlock; try (LockResource r = new LockResource(mMetadataReadLock)) { hasBlock = mMetaManager.hasBlockMeta(blockId); } if (hasBlock) { return lockId; } mLockManager.unlockBlockNoException(lockId); return BlockLockManager.INVALID_LOCK_ID; } @Override public void unlockBlock(long lockId) throws BlockDoesNotExistException { mLockManager.unlockBlock(lockId); } @Override public boolean unlockBlock(long sessionId, long blockId) { return mLockManager.unlockBlock(sessionId, blockId); } @Override public BlockWriter getBlockWriter(long sessionId, long blockId) throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException, IOException { // NOTE: a temp block is supposed to only be visible by its own writer, unnecessary to acquire // block lock here since no sharing // TODO(bin): Handle the case where multiple writers compete for the same block. try (LockResource r = new LockResource(mMetadataReadLock)) { checkTempBlockOwnedBySession(sessionId, blockId); TempBlockMeta tempBlockMeta = mMetaManager.getTempBlockMeta(blockId); return new LocalFileBlockWriter(tempBlockMeta.getPath()); } } @Override public BlockReader getBlockReader(long sessionId, long blockId, long lockId) throws BlockDoesNotExistException, InvalidWorkerStateException, IOException { mLockManager.validateLock(sessionId, blockId, lockId); try (LockResource r = new LockResource(mMetadataReadLock)) { BlockMeta blockMeta = mMetaManager.getBlockMeta(blockId); return new LocalFileBlockReader(blockMeta.getPath()); } } @Override public TempBlockMeta createBlock(long sessionId, long blockId, BlockStoreLocation location, long initialBlockSize) throws BlockAlreadyExistsException, WorkerOutOfSpaceException, IOException { for (int i = 0; i < MAX_RETRIES + 1; i++) { TempBlockMeta tempBlockMeta = createBlockMetaInternal(sessionId, blockId, location, initialBlockSize, true); if (tempBlockMeta != null) { createBlockFile(tempBlockMeta.getPath()); return tempBlockMeta; } if (i < MAX_RETRIES) { // Failed to create a temp block, so trigger Evictor to make some space. // NOTE: a successful {@link freeSpaceInternal} here does not ensure the subsequent // allocation also successful, because these two operations are not atomic. freeSpaceInternal(sessionId, initialBlockSize, location); } } // TODO(bin): We are probably seeing a rare transient failure, maybe define and throw some // other types of exception to indicate this case. throw new WorkerOutOfSpaceException(ExceptionMessage.NO_SPACE_FOR_BLOCK_ALLOCATION, initialBlockSize, MAX_RETRIES, blockId); } // TODO(bin): Make this method to return a snapshot. @Override public BlockMeta getVolatileBlockMeta(long blockId) throws BlockDoesNotExistException { try (LockResource r = new LockResource(mMetadataReadLock)) { return mMetaManager.getBlockMeta(blockId); } } @Override public BlockMeta getBlockMeta(long sessionId, long blockId, long lockId) throws BlockDoesNotExistException, InvalidWorkerStateException { mLockManager.validateLock(sessionId, blockId, lockId); try (LockResource r = new LockResource(mMetadataReadLock)) { return mMetaManager.getBlockMeta(blockId); } } @Override public TempBlockMeta getTempBlockMeta(long sessionId, long blockId) { try (LockResource r = new LockResource(mMetadataReadLock)) { return mMetaManager.getTempBlockMetaOrNull(blockId); } } @Override public void commitBlock(long sessionId, long blockId) throws BlockAlreadyExistsException, InvalidWorkerStateException, BlockDoesNotExistException, IOException { BlockStoreLocation loc = commitBlockInternal(sessionId, blockId); synchronized (mBlockStoreEventListeners) { for (BlockStoreEventListener listener : mBlockStoreEventListeners) { listener.onCommitBlock(sessionId, blockId, loc); } } } @Override public void abortBlock(long sessionId, long blockId) throws BlockAlreadyExistsException, BlockDoesNotExistException, InvalidWorkerStateException, IOException { abortBlockInternal(sessionId, blockId); synchronized (mBlockStoreEventListeners) { for (BlockStoreEventListener listener : mBlockStoreEventListeners) { listener.onAbortBlock(sessionId, blockId); } } } @Override public void requestSpace(long sessionId, long blockId, long additionalBytes) throws BlockDoesNotExistException, WorkerOutOfSpaceException, IOException { for (int i = 0; i < MAX_RETRIES + 1; i++) { Pair<Boolean, BlockStoreLocation> requestResult = requestSpaceInternal(blockId, additionalBytes); if (requestResult.getFirst()) { return; } if (i < MAX_RETRIES) { freeSpaceInternal(sessionId, additionalBytes, requestResult.getSecond()); } } throw new WorkerOutOfSpaceException(ExceptionMessage.NO_SPACE_FOR_BLOCK_ALLOCATION, additionalBytes, MAX_RETRIES, blockId); } @Override public void moveBlock(long sessionId, long blockId, BlockStoreLocation newLocation) throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException, WorkerOutOfSpaceException, IOException { moveBlock(sessionId, blockId, BlockStoreLocation.anyTier(), newLocation); } @Override public void moveBlock(long sessionId, long blockId, BlockStoreLocation oldLocation, BlockStoreLocation newLocation) throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException, WorkerOutOfSpaceException, IOException { for (int i = 0; i < MAX_RETRIES + 1; i++) { MoveBlockResult moveResult = moveBlockInternal(sessionId, blockId, oldLocation, newLocation); if (moveResult.getSuccess()) { synchronized (mBlockStoreEventListeners) { for (BlockStoreEventListener listener : mBlockStoreEventListeners) { listener.onMoveBlockByClient(sessionId, blockId, moveResult.getSrcLocation(), moveResult.getDstLocation()); } } return; } if (i < MAX_RETRIES) { freeSpaceInternal(sessionId, moveResult.getBlockSize(), newLocation); } } throw new WorkerOutOfSpaceException(ExceptionMessage.NO_SPACE_FOR_BLOCK_MOVE, newLocation, blockId, MAX_RETRIES); } @Override public void removeBlock(long sessionId, long blockId) throws InvalidWorkerStateException, BlockDoesNotExistException, IOException { removeBlock(sessionId, blockId, BlockStoreLocation.anyTier()); } @Override public void removeBlock(long sessionId, long blockId, BlockStoreLocation location) throws InvalidWorkerStateException, BlockDoesNotExistException, IOException { removeBlockInternal(sessionId, blockId, location); synchronized (mBlockStoreEventListeners) { for (BlockStoreEventListener listener : mBlockStoreEventListeners) { listener.onRemoveBlockByClient(sessionId, blockId); } } } @Override public void accessBlock(long sessionId, long blockId) throws BlockDoesNotExistException { boolean hasBlock; try (LockResource r = new LockResource(mMetadataReadLock)) { hasBlock = mMetaManager.hasBlockMeta(blockId); } if (!hasBlock) { throw new BlockDoesNotExistException(ExceptionMessage.NO_BLOCK_ID_FOUND, blockId); } synchronized (mBlockStoreEventListeners) { for (BlockStoreEventListener listener : mBlockStoreEventListeners) { listener.onAccessBlock(sessionId, blockId); } } } @Override public void freeSpace(long sessionId, long availableBytes, BlockStoreLocation location) throws BlockDoesNotExistException, WorkerOutOfSpaceException, IOException { // TODO(bin): Consider whether to retry here. freeSpaceInternal(sessionId, availableBytes, location); } @Override public void cleanupSession(long sessionId) { // Release all locks the session is holding. mLockManager.cleanupSession(sessionId); // Collect a list of temp blocks the given session owns and abort all of them with best effort List<TempBlockMeta> tempBlocksToRemove; try (LockResource r = new LockResource(mMetadataReadLock)) { tempBlocksToRemove = mMetaManager.getSessionTempBlocks(sessionId); } for (TempBlockMeta tempBlockMeta : tempBlocksToRemove) { try { LOG.warn("Clean up expired temporary block {} from session {}.", tempBlockMeta.getBlockId(), sessionId); abortBlockInternal(sessionId, tempBlockMeta.getBlockId()); } catch (Exception e) { LOG.error("Failed to cleanup tempBlock {} due to {}", tempBlockMeta.getBlockId(), e.getMessage()); } } } @Override public boolean hasBlockMeta(long blockId) { try (LockResource r = new LockResource(mMetadataReadLock)) { return mMetaManager.hasBlockMeta(blockId); } } @Override public BlockStoreMeta getBlockStoreMeta() { BlockStoreMeta storeMeta; try (LockResource r = new LockResource(mMetadataReadLock)) { storeMeta = mMetaManager.getBlockStoreMeta(); } return storeMeta; } @Override public BlockStoreMeta getBlockStoreMetaFull() { BlockStoreMeta storeMeta; try (LockResource r = new LockResource(mMetadataReadLock)) { storeMeta = mMetaManager.getBlockStoreMetaFull(); } return storeMeta; } @Override public void registerBlockStoreEventListener(BlockStoreEventListener listener) { synchronized (mBlockStoreEventListeners) { mBlockStoreEventListeners.add(listener); } } /** * Checks if a block id is available for a new temp block. This method must be enclosed by * {@link #mMetadataLock}. * * @param blockId the id of block * @throws BlockAlreadyExistsException if block id already exists */ private void checkTempBlockIdAvailable(long blockId) throws BlockAlreadyExistsException { if (mMetaManager.hasTempBlockMeta(blockId)) { throw new BlockAlreadyExistsException(ExceptionMessage.TEMP_BLOCK_ID_EXISTS, blockId); } if (mMetaManager.hasBlockMeta(blockId)) { throw new BlockAlreadyExistsException(ExceptionMessage.TEMP_BLOCK_ID_COMMITTED, blockId); } } /** * Checks if block id is a temporary block and owned by session id. This method must be enclosed * by {@link #mMetadataLock}. * * @param sessionId the id of session * @param blockId the id of block * @throws BlockDoesNotExistException if block id can not be found in temporary blocks * @throws BlockAlreadyExistsException if block id already exists in committed blocks * @throws InvalidWorkerStateException if block id is not owned by session id */ private void checkTempBlockOwnedBySession(long sessionId, long blockId) throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException { if (mMetaManager.hasBlockMeta(blockId)) { throw new BlockAlreadyExistsException(ExceptionMessage.TEMP_BLOCK_ID_COMMITTED, blockId); } TempBlockMeta tempBlockMeta = mMetaManager.getTempBlockMeta(blockId); long ownerSessionId = tempBlockMeta.getSessionId(); if (ownerSessionId != sessionId) { throw new InvalidWorkerStateException(ExceptionMessage.BLOCK_ID_FOR_DIFFERENT_SESSION, blockId, ownerSessionId, sessionId); } } /** * Aborts a temp block. * * @param sessionId the id of session * @param blockId the id of block * @throws BlockDoesNotExistException if block id can not be found in temporary blocks * @throws BlockAlreadyExistsException if block id already exists in committed blocks * @throws InvalidWorkerStateException if block id is not owned by session id */ private void abortBlockInternal(long sessionId, long blockId) throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException, IOException { String path; TempBlockMeta tempBlockMeta; try (LockResource r = new LockResource(mMetadataReadLock)) { checkTempBlockOwnedBySession(sessionId, blockId); tempBlockMeta = mMetaManager.getTempBlockMeta(blockId); path = tempBlockMeta.getPath(); } // The metadata lock is released during heavy IO. The temp block is private to one session, so // we do not lock it. Files.delete(Paths.get(path)); try (LockResource r = new LockResource(mMetadataWriteLock)) { mMetaManager.abortTempBlockMeta(tempBlockMeta); } catch (BlockDoesNotExistException e) { throw Throwables.propagate(e); // We shall never reach here } } /** * Commits a temp block. * * @param sessionId the id of session * @param blockId the id of block * @return destination location to move the block * @throws BlockDoesNotExistException if block id can not be found in temporary blocks * @throws BlockAlreadyExistsException if block id already exists in committed blocks * @throws InvalidWorkerStateException if block id is not owned by session id */ private BlockStoreLocation commitBlockInternal(long sessionId, long blockId) throws BlockAlreadyExistsException, InvalidWorkerStateException, BlockDoesNotExistException, IOException { long lockId = mLockManager.lockBlock(sessionId, blockId, BlockLockType.WRITE); try { // When committing TempBlockMeta, the final BlockMeta calculates the block size according to // the actual file size of this TempBlockMeta. Therefore, commitTempBlockMeta must happen // after moving actual block file to its committed path. BlockStoreLocation loc; String srcPath; String dstPath; TempBlockMeta tempBlockMeta; try (LockResource r = new LockResource(mMetadataReadLock)) { checkTempBlockOwnedBySession(sessionId, blockId); tempBlockMeta = mMetaManager.getTempBlockMeta(blockId); srcPath = tempBlockMeta.getPath(); dstPath = tempBlockMeta.getCommitPath(); loc = tempBlockMeta.getBlockLocation(); } // Heavy IO is guarded by block lock but not metadata lock. This may throw IOException. FileUtils.move(srcPath, dstPath); try (LockResource r = new LockResource(mMetadataWriteLock)) { mMetaManager.commitTempBlockMeta(tempBlockMeta); } catch (BlockAlreadyExistsException | BlockDoesNotExistException | WorkerOutOfSpaceException e) { throw Throwables.propagate(e); // we shall never reach here } return loc; } finally { mLockManager.unlockBlock(lockId); } } /** * Creates a temp block meta only if allocator finds available space. This method will not trigger * any eviction. * * @param sessionId session id * @param blockId block id * @param location location to create the block * @param initialBlockSize initial block size in bytes * @param newBlock true if this temp block is created for a new block * @return a temp block created if successful, or null if allocation failed (instead of throwing * {@link WorkerOutOfSpaceException} because allocation failure could be an expected case) * @throws BlockAlreadyExistsException if there is already a block with the same block id */ private TempBlockMeta createBlockMetaInternal(long sessionId, long blockId, BlockStoreLocation location, long initialBlockSize, boolean newBlock) throws BlockAlreadyExistsException { // NOTE: a temp block is supposed to be visible for its own writer, unnecessary to acquire // block lock here since no sharing try (LockResource r = new LockResource(mMetadataWriteLock)) { if (newBlock) { checkTempBlockIdAvailable(blockId); } StorageDirView dirView = mAllocator.allocateBlockWithView(sessionId, initialBlockSize, location, getUpdatedView()); if (dirView == null) { // Allocator fails to find a proper place for this new block. return null; } // TODO(carson): Add tempBlock to corresponding storageDir and remove the use of // StorageDirView.createTempBlockMeta. TempBlockMeta tempBlock = dirView.createTempBlockMeta(sessionId, blockId, initialBlockSize); try { // Add allocated temp block to metadata manager. This should never fail if allocator // correctly assigns a StorageDir. mMetaManager.addTempBlockMeta(tempBlock); } catch (WorkerOutOfSpaceException | BlockAlreadyExistsException e) { // If we reach here, allocator is not working properly LOG.error("Unexpected failure: {} bytes allocated at {} by allocator, " + "but addTempBlockMeta failed", initialBlockSize, location); throw Throwables.propagate(e); } return tempBlock; } } /** * Increases the temp block size only if this temp block's parent dir has enough available space. * * @param blockId block id * @param additionalBytes additional bytes to request for this block * @return a pair of boolean and {@link BlockStoreLocation}. The boolean indicates if the * operation succeeds and the {@link BlockStoreLocation} denotes where to free more space * if it fails. * @throws BlockDoesNotExistException if this block is not found */ private Pair<Boolean, BlockStoreLocation> requestSpaceInternal(long blockId, long additionalBytes) throws BlockDoesNotExistException { // NOTE: a temp block is supposed to be visible for its own writer, unnecessary to acquire // block lock here since no sharing try (LockResource r = new LockResource(mMetadataWriteLock)) { TempBlockMeta tempBlockMeta = mMetaManager.getTempBlockMeta(blockId); if (tempBlockMeta.getParentDir().getAvailableBytes() < additionalBytes) { return new Pair<>(false, tempBlockMeta.getBlockLocation()); } // Increase the size of this temp block try { mMetaManager.resizeTempBlockMeta(tempBlockMeta, tempBlockMeta.getBlockSize() + additionalBytes); } catch (InvalidWorkerStateException e) { throw Throwables.propagate(e); // we shall never reach here } return new Pair<>(true, null); } } /** * Tries to get an eviction plan to free a certain amount of space in the given location, and * carries out this plan with the best effort. * * @param sessionId the session id * @param availableBytes amount of space in bytes to free * @param location location of space * @throws WorkerOutOfSpaceException if it is impossible to achieve the free requirement */ private void freeSpaceInternal(long sessionId, long availableBytes, BlockStoreLocation location) throws WorkerOutOfSpaceException, IOException { EvictionPlan plan; try (LockResource r = new LockResource(mMetadataReadLock)) { plan = mEvictor.freeSpaceWithView(availableBytes, location, getUpdatedView()); // Absent plan means failed to evict enough space. if (plan == null) { throw new WorkerOutOfSpaceException(ExceptionMessage.NO_EVICTION_PLAN_TO_FREE_SPACE); } } // 1. remove blocks to make room. for (Pair<Long, BlockStoreLocation> blockInfo : plan.toEvict()) { try { removeBlockInternal(sessionId, blockInfo.getFirst(), blockInfo.getSecond()); } catch (InvalidWorkerStateException e) { // Evictor is not working properly LOG.error("Failed to evict blockId {}, this is temp block", blockInfo.getFirst()); continue; } catch (BlockDoesNotExistException e) { LOG.info("Failed to evict blockId {}, it could be already deleted", blockInfo.getFirst()); continue; } synchronized (mBlockStoreEventListeners) { for (BlockStoreEventListener listener : mBlockStoreEventListeners) { listener.onRemoveBlockByWorker(sessionId, blockInfo.getFirst()); } } } // 2. transfer blocks among tiers. // 2.1. group blocks move plan by the destination tier. Map<String, Set<BlockTransferInfo>> blocksGroupedByDestTier = new HashMap<>(); for (BlockTransferInfo entry : plan.toMove()) { String alias = entry.getDstLocation().tierAlias(); if (!blocksGroupedByDestTier.containsKey(alias)) { blocksGroupedByDestTier.put(alias, new HashSet<BlockTransferInfo>()); } blocksGroupedByDestTier.get(alias).add(entry); } // 2.2. move blocks in the order of their dst tiers, from bottom to top for (int tierOrdinal = mStorageTierAssoc.size() - 1; tierOrdinal >= 0; --tierOrdinal) { Set<BlockTransferInfo> toMove = blocksGroupedByDestTier.get(mStorageTierAssoc.getAlias(tierOrdinal)); if (toMove == null) { toMove = new HashSet<>(); } for (BlockTransferInfo entry : toMove) { long blockId = entry.getBlockId(); BlockStoreLocation oldLocation = entry.getSrcLocation(); BlockStoreLocation newLocation = entry.getDstLocation(); MoveBlockResult moveResult; try { moveResult = moveBlockInternal(sessionId, blockId, oldLocation, newLocation); } catch (InvalidWorkerStateException e) { // Evictor is not working properly LOG.error("Failed to evict blockId {}, this is temp block", blockId); continue; } catch (BlockAlreadyExistsException e) { continue; } catch (BlockDoesNotExistException e) { LOG.info("Failed to move blockId {}, it could be already deleted", blockId); continue; } if (moveResult.getSuccess()) { synchronized (mBlockStoreEventListeners) { for (BlockStoreEventListener listener : mBlockStoreEventListeners) { listener.onMoveBlockByWorker(sessionId, blockId, moveResult.getSrcLocation(), newLocation); } } } } } } /** * Gets the most updated view with most recent information on pinned inodes, and currently locked * blocks. * * @return {@link BlockMetadataManagerView}, an updated view with most recent information */ private BlockMetadataManagerView getUpdatedView() { // TODO(calvin): Update the view object instead of creating new one every time. synchronized (mPinnedInodes) { return new BlockMetadataManagerView(mMetaManager, mPinnedInodes, mLockManager.getLockedBlocks()); } } /** * Moves a block to new location only if allocator finds available space in newLocation. This * method will not trigger any eviction. Returns {@link MoveBlockResult}. * * @param sessionId session id * @param blockId block id * @param oldLocation the source location of the block * @param newLocation new location to move this block * @return the resulting information about the move operation * @throws BlockDoesNotExistException if block is not found * @throws BlockAlreadyExistsException if a block with same id already exists in new location * @throws InvalidWorkerStateException if the block to move is a temp block */ private MoveBlockResult moveBlockInternal(long sessionId, long blockId, BlockStoreLocation oldLocation, BlockStoreLocation newLocation) throws BlockDoesNotExistException, BlockAlreadyExistsException, InvalidWorkerStateException, IOException { long lockId = mLockManager.lockBlock(sessionId, blockId, BlockLockType.WRITE); try { long blockSize; String srcFilePath; String dstFilePath; BlockMeta srcBlockMeta; BlockStoreLocation srcLocation; BlockStoreLocation dstLocation; try (LockResource r = new LockResource(mMetadataReadLock)) { if (mMetaManager.hasTempBlockMeta(blockId)) { throw new InvalidWorkerStateException(ExceptionMessage.MOVE_UNCOMMITTED_BLOCK, blockId); } srcBlockMeta = mMetaManager.getBlockMeta(blockId); srcLocation = srcBlockMeta.getBlockLocation(); srcFilePath = srcBlockMeta.getPath(); blockSize = srcBlockMeta.getBlockSize(); } if (!srcLocation.belongsTo(oldLocation)) { throw new BlockDoesNotExistException(ExceptionMessage.BLOCK_NOT_FOUND_AT_LOCATION, blockId, oldLocation); } TempBlockMeta dstTempBlock = createBlockMetaInternal(sessionId, blockId, newLocation, blockSize, false); if (dstTempBlock == null) { return new MoveBlockResult(false, blockSize, null, null); } // When `newLocation` is some specific location, the `newLocation` and the `dstLocation` are // just the same; while for `newLocation` with a wildcard significance, the `dstLocation` // is a specific one with specific tier and dir which belongs to newLocation. dstLocation = dstTempBlock.getBlockLocation(); // When the dstLocation belongs to srcLocation, simply abort the tempBlockMeta just created // internally from the newLocation and return success with specific block location. if (dstLocation.belongsTo(srcLocation)) { mMetaManager.abortTempBlockMeta(dstTempBlock); return new MoveBlockResult(true, blockSize, srcLocation, dstLocation); } dstFilePath = dstTempBlock.getCommitPath(); // Heavy IO is guarded by block lock but not metadata lock. This may throw IOException. FileUtils.move(srcFilePath, dstFilePath); try (LockResource r = new LockResource(mMetadataWriteLock)) { // If this metadata update fails, we panic for now. // TODO(bin): Implement rollback scheme to recover from IO failures. mMetaManager.moveBlockMeta(srcBlockMeta, dstTempBlock); } catch (BlockAlreadyExistsException | BlockDoesNotExistException | WorkerOutOfSpaceException e) { // WorkerOutOfSpaceException is only possible if session id gets cleaned between // createBlockMetaInternal and moveBlockMeta. throw Throwables.propagate(e); // we shall never reach here } return new MoveBlockResult(true, blockSize, srcLocation, dstLocation); } finally { mLockManager.unlockBlock(lockId); } } /** * Removes a block. * * @param sessionId session id * @param blockId block id * @param location the source location of the block * @throws InvalidWorkerStateException if the block to remove is a temp block * @throws BlockDoesNotExistException if this block can not be found */ private void removeBlockInternal(long sessionId, long blockId, BlockStoreLocation location) throws InvalidWorkerStateException, BlockDoesNotExistException, IOException { long lockId = mLockManager.lockBlock(sessionId, blockId, BlockLockType.WRITE); try { String filePath; BlockMeta blockMeta; try (LockResource r = new LockResource(mMetadataReadLock)) { if (mMetaManager.hasTempBlockMeta(blockId)) { throw new InvalidWorkerStateException(ExceptionMessage.REMOVE_UNCOMMITTED_BLOCK, blockId); } blockMeta = mMetaManager.getBlockMeta(blockId); filePath = blockMeta.getPath(); } if (!blockMeta.getBlockLocation().belongsTo(location)) { throw new BlockDoesNotExistException(ExceptionMessage.BLOCK_NOT_FOUND_AT_LOCATION, blockId, location); } // Heavy IO is guarded by block lock but not metadata lock. This may throw IOException. Files.delete(Paths.get(filePath)); try (LockResource r = new LockResource(mMetadataWriteLock)) { mMetaManager.removeBlockMeta(blockMeta); } catch (BlockDoesNotExistException e) { throw Throwables.propagate(e); // we shall never reach here } } finally { mLockManager.unlockBlock(lockId); } } /** * Creates a file to represent a block denoted by the given block path. This file will be owned * by the Alluxio worker but have 777 permissions so processes under users different from the * user that launched the Alluxio worker can read and write to the file. The tiered storage * directory has the sticky bit so only the worker user can delete or rename files it creates. * * @param blockPath the block path to create */ // TODO(peis): Consider using domain socket to avoid setting the permission to 777. private static void createBlockFile(String blockPath) throws IOException { FileUtils.createBlockPath(blockPath); FileUtils.createFile(blockPath); FileUtils.changeLocalFileToFullPermission(blockPath); LOG.debug("Created new file block, block path: {}", blockPath); } /** * Updates the pinned blocks. * * @param inodes a set of ids inodes that are pinned */ @Override public void updatePinnedInodes(Set<Long> inodes) { synchronized (mPinnedInodes) { mPinnedInodes.clear(); mPinnedInodes.addAll(Preconditions.checkNotNull(inodes)); } } /** * A wrapper on necessary info after a move block operation. */ private static class MoveBlockResult { /** Whether this move operation succeeds. */ private final boolean mSuccess; /** Size of this block in bytes. */ private final long mBlockSize; /** Source location of this block to move. */ private final BlockStoreLocation mSrcLocation; /** Destination location of this block to move. */ private final BlockStoreLocation mDstLocation; /** * Creates a new instance of {@link MoveBlockResult}. * * @param success success indication * @param blockSize block size * @param srcLocation source location * @param dstLocation destination location */ MoveBlockResult(boolean success, long blockSize, BlockStoreLocation srcLocation, BlockStoreLocation dstLocation) { mSuccess = success; mBlockSize = blockSize; mSrcLocation = srcLocation; mDstLocation = dstLocation; } /** * @return the success indicator */ boolean getSuccess() { return mSuccess; } /** * @return the block size */ long getBlockSize() { return mBlockSize; } /** * @return the source location */ BlockStoreLocation getSrcLocation() { return mSrcLocation; } /** * @return the destination location */ BlockStoreLocation getDstLocation() { return mDstLocation; } } }
ChangerYoung/alluxio
core/server/worker/src/main/java/alluxio/worker/block/TieredBlockStore.java
Java
apache-2.0
37,444
<!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) on Thu Aug 09 18:46:45 EDT 2012 --> <title>Period</title> <meta name="date" content="2012-08-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="Period"; } //--> </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 class="navBarCell1Rev">Class</li> <li><a href="class-use/Period.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/drip/analytics/period/LossPeriodCurveFactors.html" title="class in org.drip.analytics.period"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/drip/analytics/period/Period.html" target="_top">Frames</a></li> <li><a href="Period.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_org.drip.service.stream.Serializer">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.drip.analytics.period</div> <h2 title="Class Period" class="title">Class Period</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../org/drip/service/stream/Serializer.html" title="class in org.drip.service.stream">org.drip.service.stream.Serializer</a></li> <li> <ul class="inheritance"> <li>org.drip.analytics.period.Period</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Direct Known Subclasses:</dt> <dd><a href="../../../../org/drip/analytics/period/CouponPeriod.html" title="class in org.drip.analytics.period">CouponPeriod</a>, <a href="../../../../org/drip/analytics/period/CouponPeriodCurveFactors.html" title="class in org.drip.analytics.period">CouponPeriodCurveFactors</a>, <a href="../../../../org/drip/analytics/period/LossPeriodCurveFactors.html" title="class in org.drip.analytics.period">LossPeriodCurveFactors</a></dd> </dl> <hr> <br> <pre>public class <span class="strong">Period</span> extends <a href="../../../../org/drip/service/stream/Serializer.html" title="class in org.drip.service.stream">Serializer</a></pre> <div class="block">This class serves as a holder for the period dates: period start/end, period accrual start/end, pay, and full period day count fraction.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <ul class="blockList"> <li class="blockList"><a name="fields_inherited_from_class_org.drip.service.stream.Serializer"> <!-- --> </a> <h3>Fields inherited from class&nbsp;org.drip.service.stream.<a href="../../../../org/drip/service/stream/Serializer.html" title="class in org.drip.service.stream">Serializer</a></h3> <code><a href="../../../../org/drip/service/stream/Serializer.html#NULL_SER_STRING">NULL_SER_STRING</a>, <a href="../../../../org/drip/service/stream/Serializer.html#VERSION">VERSION</a></code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#Period(byte[])">Period</a></strong>(byte[]&nbsp;ab)</code> <div class="block">De-serialization of Period from byte stream</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#Period(double, double, double, double, double, double)">Period</a></strong>(double&nbsp;dblStart, double&nbsp;dblEnd, double&nbsp;dblAccrualStart, double&nbsp;dblAccrualEnd, double&nbsp;dblPay, double&nbsp;dblDCF)</code> <div class="block">Constructs a period object instance from the corresponding date parameters</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#contains(double)">contains</a></strong>(double&nbsp;dblDate)</code> <div class="block">Checks whether the supplied date is inside the period specified</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/drip/service/stream/Serializer.html" title="class in org.drip.service.stream">Serializer</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#deserialize(byte[])">deserialize</a></strong>(byte[]&nbsp;ab)</code> <div class="block">De-serialize from a byte array.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#getAccrualDCF(double)">getAccrualDCF</a></strong>(double&nbsp;dblAccrualEnd)</code> <div class="block">Get the period Accrual Day Count Fraction to an accrual end date</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#getAccrualEndDate()">getAccrualEndDate</a></strong>()</code> <div class="block">Returns the period Accrual End Date</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#getAccrualStartDate()">getAccrualStartDate</a></strong>()</code> <div class="block">Returns the period Accrual Start Date</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#getCouponDCF()">getCouponDCF</a></strong>()</code> <div class="block">Gets the coupon DCF</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#getEndDate()">getEndDate</a></strong>()</code> <div class="block">Returns the period End Date</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#getFieldDelimiter()">getFieldDelimiter</a></strong>()</code> <div class="block">Returns the Field Delimiter String</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#getObjectTrailer()">getObjectTrailer</a></strong>()</code> <div class="block">Returns the Object Trailer String</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#getPayDate()">getPayDate</a></strong>()</code> <div class="block">Returns the period Pay Date</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#getResetDate()">getResetDate</a></strong>()</code> <div class="block">Returns the period Reset Date</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#getStartDate()">getStartDate</a></strong>()</code> <div class="block">Returns the period Start Date</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#main(java.lang.String[])">main</a></strong>(java.lang.String[]&nbsp;astrArgs)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>byte[]</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#serialize()">serialize</a></strong>()</code> <div class="block">Serialize into a byte array.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#setAccrualStartDate(double)">setAccrualStartDate</a></strong>(double&nbsp;dblAccrualStart)</code> <div class="block">Set the period Accrual Start Date</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/drip/analytics/period/Period.html#setPayDate(double)">setPayDate</a></strong>(double&nbsp;dblPay)</code> <div class="block">Set the period Pay Date</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.drip.service.stream.Serializer"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.drip.service.stream.<a href="../../../../org/drip/service/stream/Serializer.html" title="class in org.drip.service.stream">Serializer</a></h3> <code><a href="../../../../org/drip/service/stream/Serializer.html#getCollectionKeyValueDelimiter()">getCollectionKeyValueDelimiter</a>, <a href="../../../../org/drip/service/stream/Serializer.html#getCollectionMultiLevelKeyDelimiter()">getCollectionMultiLevelKeyDelimiter</a>, <a href="../../../../org/drip/service/stream/Serializer.html#getCollectionRecordDelimiter()">getCollectionRecordDelimiter</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Period(double, double, double, double, double, double)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>Period</h4> <pre>public&nbsp;Period(double&nbsp;dblStart, double&nbsp;dblEnd, double&nbsp;dblAccrualStart, double&nbsp;dblAccrualEnd, double&nbsp;dblPay, double&nbsp;dblDCF) throws java.lang.Exception</pre> <div class="block">Constructs a period object instance from the corresponding date parameters</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>dblStart</code> - Period Start Date</dd><dd><code>dblEnd</code> - Period End Date</dd><dd><code>dblAccrualStart</code> - Period Accrual Start Date</dd><dd><code>dblAccrualEnd</code> - Period Accrual End Date</dd><dd><code>dblPay</code> - Period Pay Date</dd><dd><code>dblDCF</code> - Period Day count fraction</dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.lang.Exception</code> - Thrown if the inputs are invalid</dd></dl> </li> </ul> <a name="Period(byte[])"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Period</h4> <pre>public&nbsp;Period(byte[]&nbsp;ab) throws java.lang.Exception</pre> <div class="block">De-serialization of Period from byte stream</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>ab</code> - Byte stream</dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.lang.Exception</code> - Thrown if cannot properly de-serialize</dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getStartDate()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getStartDate</h4> <pre>public&nbsp;double&nbsp;getStartDate()</pre> <div class="block">Returns the period Start Date</div> <dl><dt><span class="strong">Returns:</span></dt><dd>Period Start Date</dd></dl> </li> </ul> <a name="getEndDate()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getEndDate</h4> <pre>public&nbsp;double&nbsp;getEndDate()</pre> <div class="block">Returns the period End Date</div> <dl><dt><span class="strong">Returns:</span></dt><dd>Period End Date</dd></dl> </li> </ul> <a name="getAccrualStartDate()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getAccrualStartDate</h4> <pre>public&nbsp;double&nbsp;getAccrualStartDate()</pre> <div class="block">Returns the period Accrual Start Date</div> <dl><dt><span class="strong">Returns:</span></dt><dd>Period Accrual Start Date</dd></dl> </li> </ul> <a name="setAccrualStartDate(double)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setAccrualStartDate</h4> <pre>public&nbsp;boolean&nbsp;setAccrualStartDate(double&nbsp;dblAccrualStart)</pre> <div class="block">Set the period Accrual Start Date</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>dblAccrualStart</code> - Period Accrual Start Date</dd></dl> </li> </ul> <a name="getAccrualEndDate()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getAccrualEndDate</h4> <pre>public&nbsp;double&nbsp;getAccrualEndDate()</pre> <div class="block">Returns the period Accrual End Date</div> <dl><dt><span class="strong">Returns:</span></dt><dd>Period Accrual End Date</dd></dl> </li> </ul> <a name="getResetDate()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getResetDate</h4> <pre>public&nbsp;double&nbsp;getResetDate()</pre> <div class="block">Returns the period Reset Date</div> <dl><dt><span class="strong">Returns:</span></dt><dd>Period Reset Date</dd></dl> </li> </ul> <a name="getPayDate()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getPayDate</h4> <pre>public&nbsp;double&nbsp;getPayDate()</pre> <div class="block">Returns the period Pay Date</div> <dl><dt><span class="strong">Returns:</span></dt><dd>Period Pay Date</dd></dl> </li> </ul> <a name="setPayDate(double)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setPayDate</h4> <pre>public&nbsp;boolean&nbsp;setPayDate(double&nbsp;dblPay)</pre> <div class="block">Set the period Pay Date</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>dblPay</code> - Period Pay Date</dd></dl> </li> </ul> <a name="getAccrualDCF(double)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getAccrualDCF</h4> <pre>public&nbsp;double&nbsp;getAccrualDCF(double&nbsp;dblAccrualEnd) throws java.lang.Exception</pre> <div class="block">Get the period Accrual Day Count Fraction to an accrual end date</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>dblAccrualEnd</code> - Accrual End Date</dd> <dt><span class="strong">Throws:</span></dt> <dd><code>Throws</code> - if inputs are invalid, or if the date does not lie within the period</dd> <dd><code>java.lang.Exception</code></dd></dl> </li> </ul> <a name="getCouponDCF()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getCouponDCF</h4> <pre>public&nbsp;double&nbsp;getCouponDCF()</pre> <div class="block">Gets the coupon DCF</div> <dl><dt><span class="strong">Returns:</span></dt><dd>The coupon DCF</dd></dl> </li> </ul> <a name="contains(double)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>contains</h4> <pre>public&nbsp;boolean&nbsp;contains(double&nbsp;dblDate) throws java.lang.Exception</pre> <div class="block">Checks whether the supplied date is inside the period specified</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>dblDate</code> - Date input</dd> <dt><span class="strong">Returns:</span></dt><dd>True indicates the specified date is inside the period</dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.lang.Exception</code> - Thrown if input is invalid</dd></dl> </li> </ul> <a name="getFieldDelimiter()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getFieldDelimiter</h4> <pre>public&nbsp;java.lang.String&nbsp;getFieldDelimiter()</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../org/drip/service/stream/Serializer.html#getFieldDelimiter()">Serializer</a></code></strong></div> <div class="block">Returns the Field Delimiter String</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../org/drip/service/stream/Serializer.html#getFieldDelimiter()">getFieldDelimiter</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/drip/service/stream/Serializer.html" title="class in org.drip.service.stream">Serializer</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd>Field Delimiter String</dd></dl> </li> </ul> <a name="getObjectTrailer()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getObjectTrailer</h4> <pre>public&nbsp;java.lang.String&nbsp;getObjectTrailer()</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../org/drip/service/stream/Serializer.html#getObjectTrailer()">Serializer</a></code></strong></div> <div class="block">Returns the Object Trailer String</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../org/drip/service/stream/Serializer.html#getObjectTrailer()">getObjectTrailer</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/drip/service/stream/Serializer.html" title="class in org.drip.service.stream">Serializer</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd>Object Trailer String</dd></dl> </li> </ul> <a name="serialize()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>serialize</h4> <pre>public&nbsp;byte[]&nbsp;serialize()</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../org/drip/service/stream/Serializer.html#serialize()">Serializer</a></code></strong></div> <div class="block">Serialize into a byte array.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../org/drip/service/stream/Serializer.html#serialize()">serialize</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/drip/service/stream/Serializer.html" title="class in org.drip.service.stream">Serializer</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd>Byte Array</dd></dl> </li> </ul> <a name="deserialize(byte[])"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>deserialize</h4> <pre>public&nbsp;<a href="../../../../org/drip/service/stream/Serializer.html" title="class in org.drip.service.stream">Serializer</a>&nbsp;deserialize(byte[]&nbsp;ab)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../org/drip/service/stream/Serializer.html#deserialize(byte[])">Serializer</a></code></strong></div> <div class="block">De-serialize from a byte array.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../org/drip/service/stream/Serializer.html#deserialize(byte[])">deserialize</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/drip/service/stream/Serializer.html" title="class in org.drip.service.stream">Serializer</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd>De-serialized object instance represented by Serializer</dd></dl> </li> </ul> <a name="main(java.lang.String[])"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>main</h4> <pre>public static&nbsp;void&nbsp;main(java.lang.String[]&nbsp;astrArgs) throws java.lang.Exception</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>java.lang.Exception</code></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= 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 class="navBarCell1Rev">Class</li> <li><a href="class-use/Period.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/drip/analytics/period/LossPeriodCurveFactors.html" title="class in org.drip.analytics.period"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/drip/analytics/period/Period.html" target="_top">Frames</a></li> <li><a href="Period.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_org.drip.service.stream.Serializer">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
tectronics/creditsuite
1.6/docs/Javadoc/org/drip/analytics/period/Period.html
HTML
apache-2.0
25,326
from migrate.changeset import UniqueConstraint from migrate import ForeignKeyConstraint from sqlalchemy import Boolean, BigInteger, Column, DateTime, Enum, Float from sqlalchemy import dialects from sqlalchemy import ForeignKey, Index, Integer, MetaData, String, Table from sqlalchemy import Text from sqlalchemy.types import NullType from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging LOG = logging.getLogger(__name__) def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine node_info = Table('node_info',meta, Column('created_at', DateTime), Column('updated_at', DateTime), Column('deleted_at', DateTime), Column('deleted', Integer), Column('id', Integer, primary_key=True, nullable=False), Column('node_id',Integer,nullable=False), Column('name',String(length=30),nullable=False), Column('ip_addr',String(length=20)), Column('hostname',String(length=255)), mysql_engine='InnoDB', mysql_charset='utf8' ) edge_info = Table('edge_info',meta, Column('created_at', DateTime), Column('updated_at', DateTime), Column('deleted_at', DateTime), Column('deleted', Integer), Column('id', Integer, primary_key=True, nullable=False), Column('start',Integer,nullable=False), Column('end',Integer,nullable=False), mysql_engine='InnoDB', mysql_charset='utf8' ) try: node_info.create() except Exception: LOG.info(repr(node_info)) LOG.exception(_('Exception while creating table node_info.')) raise try: edge_info.create() except Exception: LOG.info(repr(edge_info)) LOG.exception(_('Exception while creating table edge_info.')) raise # TO DO # Create indicies def downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine node_info = Table('node_info',meta) try: node_info.drop() except Exception: LOG.info("Table node_info doesn't exist") #LOG.info(repr(node_info)) #LOG.exception(_('Exception while deleting table node_info.')) edge_info = Table('edge_info',meta) try: edge_info.drop() except Exception: LOG.info("Table edge_info doesn't exist") #LOG.info(repr(edge_info)) #LOG.exception(_('Exception while deleting table edge_info.'))
ashepelev/TopologyWeigher
source/migrate_versions/243_topology_tables.py
Python
apache-2.0
2,616
/* * 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.geode.internal.cache; import static org.apache.geode.cache.RegionShortcut.PARTITION; import static org.apache.geode.cache.RegionShortcut.PARTITION_PERSISTENT; import static org.assertj.core.api.Assertions.assertThat; import java.io.Serializable; import java.util.concurrent.TimeUnit; import org.awaitility.Awaitility; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.apache.geode.cache.PartitionAttributesFactory; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionShortcut; import org.apache.geode.test.dunit.AsyncInvocation; import org.apache.geode.test.dunit.rules.ClusterStartupRule; import org.apache.geode.test.dunit.rules.MemberVM; import org.apache.geode.test.junit.rules.serializable.SerializableTestName; public class PartitionedRegionLowBucketRedundancyDistributedTest implements Serializable { public String regionName; @Rule public ClusterStartupRule startupRule = new ClusterStartupRule(); @Rule public SerializableTestName testName = new SerializableTestName(); @Before public void setUp() { regionName = testName.getMethodName() + "_region"; } @Test public void testTwoServersWithOneRedundantCopy() throws Exception { // Start locator MemberVM locator = startupRule.startLocatorVM(0); int locatorPort = locator.getPort(); // Start server1 and create region MemberVM server1 = startServerAndCreateRegion(1, locatorPort, PARTITION, 1); // Verify lowBucketRedundancyCount == 0 in server1 server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); // Do puts in server1 server1.getVM().invoke(() -> doPuts(500)); // Verify lowBucketRedundancyCount == 113 in server1 server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(113)); // Start server2 and create region MemberVM server2 = startServerAndCreateRegion(2, locatorPort, PARTITION, 1); // Verify lowBucketRedundancyCount == 0 in both servers server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); // Stop server2 server2.stop(false); // Verify lowBucketRedundancyCount == 113 in server1 server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(113)); } @Test public void testThreeServersWithTwoRedundantCopies() throws Exception { // Start locator MemberVM locator = startupRule.startLocatorVM(0); int locatorPort = locator.getPort(); // Start server1 and create region MemberVM server1 = startServerAndCreateRegion(1, locatorPort, PARTITION, 2); // Verify lowBucketRedundancyCount == 0 in server1 server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); // Do puts in server1 server1.getVM().invoke(() -> doPuts(500)); // Verify lowBucketRedundancyCount == 113 in server1 server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(113)); // Start server2 and create region MemberVM server2 = startServerAndCreateRegion(2, locatorPort, PARTITION, 2); // Verify lowBucketRedundancyCount == 113 in both servers server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(113)); server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(113)); // Start server2 and create region MemberVM server3 = startServerAndCreateRegion(3, locatorPort, PARTITION, 2); // Verify lowBucketRedundancyCount == 113 in server1 server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server3.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); } @Test public void testFourServersWithPersistentRegionAndOneRedundantCopy() throws Exception { // Start locator MemberVM locator = startupRule.startLocatorVM(0); int locatorPort = locator.getPort(); // Start servers and create regions MemberVM server1 = startServerAndCreateRegion(1, locatorPort, PARTITION_PERSISTENT, 1); MemberVM server2 = startServerAndCreateRegion(2, locatorPort, PARTITION_PERSISTENT, 1); MemberVM server3 = startServerAndCreateRegion(3, locatorPort, PARTITION_PERSISTENT, 1); MemberVM server4 = startServerAndCreateRegion(4, locatorPort, PARTITION_PERSISTENT, 1); // Verify lowBucketRedundancyCount == 0 in all servers server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server3.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server4.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); // Do puts in server1 server1.getVM().invoke(() -> doPuts(500)); // Verify lowBucketRedundancyCount == 0 in all servers server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server3.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server4.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); // Stop servers 1 and 2 server1.stop(false); server2.stop(false); server3.getVM().invoke(() -> waitForMembers(1)); server4.getVM().invoke(() -> waitForMembers(1)); // Restart servers 1 and 2 server1 = startupRule.startServerVM(1, locatorPort); server2 = startupRule.startServerVM(2, locatorPort); // Asynchronously recreate the regions in servers 1 and 2 (since they are recovering persistent // data) AsyncInvocation recreateRegionInServer1 = server1.getVM().invokeAsync(() -> createRegion(PARTITION_PERSISTENT, 1)); AsyncInvocation recreateRegionInServer2 = server2.getVM().invokeAsync(() -> createRegion(PARTITION_PERSISTENT, 1)); recreateRegionInServer1.await(); recreateRegionInServer2.await(); // Verify lowBucketRedundancyCount == 0 in all servers server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server3.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); server4.getVM().invoke(() -> waitForLowBucketRedundancyCount(0)); } private MemberVM startServerAndCreateRegion(int vmId, int locatorPort, RegionShortcut shortcut, int redundantCopies) { // Start server MemberVM server = startupRule.startServerVM(vmId, locatorPort); // Create region server.getVM().invoke(() -> createRegion(shortcut, redundantCopies)); return server; } private void createRegion(RegionShortcut shortcut, int redundantCopies) { PartitionAttributesFactory<?, ?> paf = new PartitionAttributesFactory(); paf.setRedundantCopies(redundantCopies); ClusterStartupRule.getCache().createRegionFactory(shortcut) .setPartitionAttributes(paf.create()).create(regionName); } private void doPuts(int numPuts) { Region region = ClusterStartupRule.getCache().getRegion(regionName); for (int i = 0; i < numPuts; i++) { region.put("key" + i, "value" + i); } } private void waitForLowBucketRedundancyCount(int count) { PartitionedRegion region = (PartitionedRegion) ClusterStartupRule.getCache().getRegion(regionName); Awaitility.await().atMost(30, TimeUnit.SECONDS).untilAsserted( () -> assertThat(region.getPrStats().getLowRedundancyBucketCount()).isEqualTo(count)); } private void waitForMembers(int count) { Awaitility.await().atMost(30, TimeUnit.SECONDS).untilAsserted( () -> assertThat(ClusterStartupRule.getCache().getMembers().size()).isEqualTo(count)); } }
deepakddixit/incubator-geode
geode-core/src/distributedTest/java/org/apache/geode/internal/cache/PartitionedRegionLowBucketRedundancyDistributedTest.java
Java
apache-2.0
8,394
/* * Copyright 2013-2021 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 example.springdata.jpa.custom; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.NamedQuery; import org.springframework.data.jpa.domain.AbstractPersistable; /** * Sample user class. * * @author Oliver Gierke * @author Thomas Darimont */ @Entity @NamedQuery(name = "User.findByTheUsersName", query = "from User u where u.username = ?1") public class User extends AbstractPersistable<Long> { private static final long serialVersionUID = -2952735933715107252L; @Column(unique = true) private String username; private String firstname; private String lastname; public User() { this(null); } /** * Creates a new user instance. */ public User(Long id) { this.setId(id); } /** * Returns the username. * * @return */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the firstname */ public String getFirstname() { return firstname; } /** * @param firstname the firstname to set */ public void setFirstname(String firstname) { this.firstname = firstname; } /** * @return the lastname */ public String getLastname() { return lastname; } /** * @param lastname the lastname to set */ public void setLastname(String lastname) { this.lastname = lastname; } }
spring-projects/spring-data-examples
jpa/example/src/main/java/example/springdata/jpa/custom/User.java
Java
apache-2.0
2,041
# Kobresia curvula (All.) N.A.Ivanova 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/Liliopsida/Poales/Cyperaceae/Carex/Carex curvula/ Syn. Kobresia curvula/README.md
Markdown
apache-2.0
192
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.svek.image; import java.awt.geom.Dimension2D; import net.sourceforge.plantuml.ColorParam; import net.sourceforge.plantuml.Dimension2DDouble; import net.sourceforge.plantuml.ISkinParam; import net.sourceforge.plantuml.SkinParamUtils; import net.sourceforge.plantuml.UseStyle; import net.sourceforge.plantuml.cucadiagram.ILeaf; import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.style.PName; import net.sourceforge.plantuml.style.SName; import net.sourceforge.plantuml.style.Style; import net.sourceforge.plantuml.style.StyleSignature; import net.sourceforge.plantuml.svek.AbstractEntityImage; import net.sourceforge.plantuml.svek.ShapeType; import net.sourceforge.plantuml.ugraphic.UGraphic; import net.sourceforge.plantuml.ugraphic.UGroupType; import net.sourceforge.plantuml.ugraphic.UPolygon; import net.sourceforge.plantuml.ugraphic.UStroke; import net.sourceforge.plantuml.ugraphic.color.HColor; public class EntityImageBranch extends AbstractEntityImage { final private static int SIZE = 12; public EntityImageBranch(ILeaf entity, ISkinParam skinParam) { super(entity, skinParam); } public StyleSignature getDefaultStyleDefinition() { return StyleSignature.of(SName.root, SName.element, SName.activityDiagram, SName.activity, SName.diamond); } public Dimension2D calculateDimension(StringBounder stringBounder) { return new Dimension2DDouble(SIZE * 2, SIZE * 2); } final public void drawU(UGraphic ug) { final UPolygon diams = new UPolygon(); double shadowing = 0; diams.addPoint(SIZE, 0); diams.addPoint(SIZE * 2, SIZE); diams.addPoint(SIZE, SIZE * 2); diams.addPoint(0, SIZE); diams.addPoint(SIZE, 0); HColor border = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.activityDiamondBorder, ColorParam.activityBorder); HColor back = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.activityDiamondBackground, ColorParam.activityBackground); UStroke stroke = new UStroke(1.5); if (UseStyle.useBetaStyle()) { final Style style = getDefaultStyleDefinition().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); border = style.value(PName.LineColor).asColor(getSkinParam().getThemeStyle(), getSkinParam().getIHtmlColorSet()); back = style.value(PName.BackGroundColor).asColor(getSkinParam().getThemeStyle(), getSkinParam().getIHtmlColorSet()); stroke = style.getStroke(); shadowing = style.value(PName.Shadowing).asDouble(); } else { if (getSkinParam().shadowing(getEntity().getStereotype())) { shadowing = 5; } } diams.setDeltaShadow(shadowing); ug.startGroup(UGroupType.CLASS, "elem " + getEntity().getCode() + " selected"); ug.apply(border).apply(back.bg()).apply(stroke).draw(diams); ug.closeGroup(); } public ShapeType getShapeType() { return ShapeType.DIAMOND; } }
talsma-ict/umldoclet
src/plantuml-asl/src/net/sourceforge/plantuml/svek/image/EntityImageBranch.java
Java
apache-2.0
3,975
/* * Copyright 2011 Shou Takenaka * * 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. */ using System; using System.Linq.Expressions; using System.Reflection; using Fidely.Framework.Compilation.Operators; namespace Fidely.Framework.Compilation.Objects.Operators { /// <summary> /// Represents the divide operator. /// </summary> public class Divide : BaseBuiltInCalculatingOperator { /// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="symbol">The symbol of this operator.</param> /// <param name="priority">The priority of this operator.</param> public Divide(string symbol, int priority) : this(symbol, priority, OperatorIndependency.Strong, null) { } /// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="symbol">The symbol of this operator.</param> /// <param name="priority">The priority of this operator.</param> /// <param name="independency">The independency of this operator.</param> /// <param name="description">The description of this operator.</param> public Divide(string symbol, int priority, OperatorIndependency independency, string description) : base(symbol, priority, independency, description) { } /// <summary> /// Builds up an expression to divide the left operand by the right operand. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns>The operand that consists of the expression to divide the left operand by the right operand.</returns> public override Operand Calculate(Operand left, Operand right) { Logger.Info("Dividing operands (left = '{0}', right = '{1}').", left.OperandType.FullName, right.OperandType.FullName); Operand result = null; var operands = new OperandPair(left, right); if (operands.Are(typeof(decimal))) { result = new Operand(Expression.Divide(left.Expression, right.Expression), typeof(decimal)); } else { Warn("'{0}' doesn't support to divide '{1}' and '{2}'.", GetType().FullName, left.OperandType.FullName, right.OperandType.FullName); var l = Expression.Call(null, typeof(Convert).GetMethod("ToString", new Type[] { typeof(object) }), Expression.Convert(left.Expression, typeof(object))); var r = Expression.Call(null, typeof(Convert).GetMethod("ToString", new Type[] { typeof(object) }), Expression.Convert(right.Expression, typeof(object))); var method = typeof(string).GetMethod("Concat", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(string), typeof(string), typeof(string) }, null); result = new Operand(Expression.Call(null, method, l, Expression.Constant(Symbol), r), typeof(string)); } Logger.Info("Divided operands (result = '{0}').", result.OperandType.FullName); return result; } /// <summary> /// Creates the clone instance. /// </summary> /// <returns>The cloned instance.</returns> public override FidelyOperator Clone() { return new Divide(Symbol, Priority, Independency, Description); } } }
angelovstanton/AutomateThePlanet
dotnet/Development-Series/FidelyOpenSourceDotNetSearchQueryCompiler/Operators/Divide.cs
C#
apache-2.0
3,994
package water.rapids.ast.prims.advmath; import water.MRTask; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.Vec; import water.rapids.Env; import water.rapids.vals.ValFrame; import water.rapids.ast.AstPrimitive; import water.rapids.ast.AstRoot; import water.util.VecUtils; import java.util.Random; import static water.util.RandomUtils.getRNG; public class AstKFold extends AstPrimitive { @Override public String[] args() { return new String[]{"ary", "nfolds", "seed"}; } @Override public int nargs() { return 1 + 3; } // (kfold_column x nfolds seed) @Override public String str() { return "kfold_column"; } public static Vec kfoldColumn(Vec v, final int nfolds, final long seed) { new MRTask() { @Override public void map(Chunk c) { long start = c.start(); for (int i = 0; i < c._len; ++i) { int fold = Math.abs(getRNG(start + seed + i).nextInt()) % nfolds; c.set(i, fold); } } }.doAll(v); return v; } public static Vec moduloKfoldColumn(Vec v, final int nfolds) { new MRTask() { @Override public void map(Chunk c) { long start = c.start(); for (int i = 0; i < c._len; ++i) c.set(i, (int) ((start + i) % nfolds)); } }.doAll(v); return v; } public static Vec stratifiedKFoldColumn(Vec y, final int nfolds, final long seed) { // for each class, generate a fold column (never materialized) // therefore, have a seed per class to be used by the map call if (!(y.isCategorical() || (y.isNumeric() && y.isInt()))) throw new IllegalArgumentException("stratification only applies to integer and categorical columns. Got: " + y.get_type_str()); final long[] classes = new VecUtils.CollectDomain().doAll(y).domain(); final int nClass = y.isNumeric() ? classes.length : y.domain().length; final long[] seeds = new long[nClass]; // seed for each regular fold column (one per class) for (int i = 0; i < nClass; ++i) seeds[i] = getRNG(seed + i).nextLong(); return new MRTask() { private int getFoldId(long absoluteRow, long seed) { return Math.abs(getRNG(absoluteRow + seed).nextInt()) % nfolds; } // dress up the foldColumn (y[1]) as follows: // 1. For each testFold and each classLabel loop over the response column (y[0]) // 2. If the classLabel is the current response and the testFold is the foldId // for the current row and classLabel, then set the foldColumn to testFold // // How this balances labels per fold: // Imagine that a KFold column was generated for each class. Observe that this // makes the outer loop a way of selecting only the test rows from each fold // (i.e., the holdout rows). Each fold is balanced sequentially in this way // since y[1] is only updated if the current row happens to be a holdout row // for the given classLabel. // // Next observe that looping over each classLabel filters down each KFold // so that it contains labels for just THAT class. This is how the balancing // can be made so that it is independent of the chunk distribution and the // per chunk class distribution. // // Downside is this performs nfolds*nClass passes over each Chunk. For // "reasonable" classification problems, this could be 100 passes per Chunk. @Override public void map(Chunk[] y) { long start = y[0].start(); for (int testFold = 0; testFold < nfolds; ++testFold) { for (int classLabel = 0; classLabel < nClass; ++classLabel) { for (int row = 0; row < y[0]._len; ++row) { // missing response gets spread around if (y[0].isNA(row)) { if ((start + row) % nfolds == testFold) y[1].set(row, testFold); } else { if (y[0].at8(row) == (classes == null ? classLabel : classes[classLabel])) { if (testFold == getFoldId(start + row, seeds[classLabel])) y[1].set(row, testFold); } } } } } } }.doAll(new Frame(y, y.makeZero()))._fr.vec(1); } @Override public ValFrame apply(Env env, Env.StackHelp stk, AstRoot asts[]) { Vec foldVec = stk.track(asts[1].exec(env)).getFrame().anyVec().makeZero(); int nfolds = (int) asts[2].exec(env).getNum(); long seed = (long) asts[3].exec(env).getNum(); return new ValFrame(new Frame(kfoldColumn(foldVec, nfolds, seed == -1 ? new Random().nextLong() : seed))); } }
jangorecki/h2o-3
h2o-core/src/main/java/water/rapids/ast/prims/advmath/AstKFold.java
Java
apache-2.0
4,723
<div class="form-group" ng-class="{'has-error': invalid }"> <label class="control-label">{{label}}</label> <span ng-transclude></span> </div>
aweiland/grails3-angular-bootstrap
grails-app/assets/vendor/grails/templates/directives/fields/field-container.tpl.html
HTML
apache-2.0
154
package com.tenforwardconsulting.cordova.bgloc.data; import java.util.Date; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.os.SystemClock; import android.util.Log; import com.tenforwardconsulting.cordova.bgloc.data.CardDAO; import com.tenforwardconsulting.cordova.bgloc.data.sqlite.SQLiteCardDAO; public class Card { private static final String TAG = "LocationUpdateService"; private long created; private String info; private String location; private String latitude; private String longitude; private String sharing_level; private String location_level; private String user_id; private String confirm; private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public long getCreated() { return created; } public void setCreated(long created) { this.created = created; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getSharing_level() { return sharing_level; } public void setSharing_level(String sharing_level) { this.sharing_level = sharing_level; } public String getLocation_level() { return location_level; } public void setLocation_level(String location_level) { this.location_level = location_level; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getConfirm() { return confirm; } public void setConfirm(String confirm) { this.confirm = confirm; } public static Card createCard(android.location.Location originalLocation, Context context, String userId, int cardId) { Card card = new Card(); SharedPreferences pref = context.getSharedPreferences("lifesharePreferences", Context.MODE_MULTI_PROCESS); card.setId(cardId); card.setCreated(new Date().getTime()); card.setInfo(""); card.setLocation(""); card.setLongitude(String.valueOf(originalLocation.getLongitude())); card.setLatitude(String.valueOf(originalLocation.getLatitude())); card.setSharing_level(pref.getString("sharing_setting", "")); Log.i(TAG, "Sha Set: " + pref.getString("sharing_setting", "")); card.setLocation_level(pref.getString("location_setting", "")); Log.i(TAG, "Loc Set: " + pref.getString("location_setting", "")); card.setUser_id(userId); String confirmationDlg = "false"; if (!pref.getString("sharing_setting", "").equals("automatic")) confirmationDlg = "true"; card.setConfirm(confirmationDlg); Log.i(TAG, "Conf Set: " + confirmationDlg); return card; } }
Juanjojara/cordova-plugin-background-geolocation
src/android/data/Card.java
Java
apache-2.0
3,080
package org.hl7.v3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for COCT_MT290000UV06.PatientEncounter complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="COCT_MT290000UV06.PatientEncounter"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{urn:hl7-org:v3}InfrastructureRootElements"/> * &lt;element name="id" type="{urn:hl7-org:v3}II" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="code" type="{urn:hl7-org:v3}CD" minOccurs="0"/> * &lt;element name="effectiveTime" type="{urn:hl7-org:v3}IVL_TS" minOccurs="0"/> * &lt;element name="activityTime" type="{urn:hl7-org:v3}IVL_TS" minOccurs="0"/> * &lt;element name="priorityCode" type="{urn:hl7-org:v3}CE" minOccurs="0"/> * &lt;element name="admissionReferralSourceCode" type="{urn:hl7-org:v3}CE" minOccurs="0"/> * &lt;element name="dischargeDispositionCode" type="{urn:hl7-org:v3}CE" minOccurs="0"/> * &lt;element name="reason" type="{urn:hl7-org:v3}COCT_MT290000UV06.Reason5" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/> * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" /> * &lt;attribute name="classCode" use="required" type="{urn:hl7-org:v3}ActClass" fixed="ENC" /> * &lt;attribute name="moodCode" use="required" type="{urn:hl7-org:v3}ActMood" fixed="EVN" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "COCT_MT290000UV06.PatientEncounter", propOrder = { "realmCode", "typeId", "templateId", "id", "code", "effectiveTime", "activityTime", "priorityCode", "admissionReferralSourceCode", "dischargeDispositionCode", "reason" }) public class COCTMT290000UV06PatientEncounter { protected List<CS> realmCode; protected II typeId; protected List<II> templateId; protected List<II> id; protected CD code; protected IVLTS effectiveTime; protected IVLTS activityTime; protected CE priorityCode; protected CE admissionReferralSourceCode; protected CE dischargeDispositionCode; @XmlElement(nillable = true) protected List<COCTMT290000UV06Reason5> reason; @XmlAttribute(name = "nullFlavor") protected List<String> nullFlavor; @XmlAttribute(name = "classCode", required = true) protected List<String> classCode; @XmlAttribute(name = "moodCode", required = true) protected List<String> moodCode; /** * Gets the value of the realmCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the realmCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CS } * * */ public List<CS> getRealmCode() { if (realmCode == null) { realmCode = new ArrayList<CS>(); } return this.realmCode; } /** * Gets the value of the typeId property. * * @return * possible object is * {@link II } * */ public II getTypeId() { return typeId; } /** * Sets the value of the typeId property. * * @param value * allowed object is * {@link II } * */ public void setTypeId(II value) { this.typeId = value; } /** * Gets the value of the templateId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the templateId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getTemplateId() { if (templateId == null) { templateId = new ArrayList<II>(); } return this.templateId; } /** * Gets the value of the id property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the id property. * * <p> * For example, to add a new item, do as follows: * <pre> * getId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getId() { if (id == null) { id = new ArrayList<II>(); } return this.id; } /** * Gets the value of the code property. * * @return * possible object is * {@link CD } * */ public CD getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is * {@link CD } * */ public void setCode(CD value) { this.code = value; } /** * Gets the value of the effectiveTime property. * * @return * possible object is * {@link IVLTS } * */ public IVLTS getEffectiveTime() { return effectiveTime; } /** * Sets the value of the effectiveTime property. * * @param value * allowed object is * {@link IVLTS } * */ public void setEffectiveTime(IVLTS value) { this.effectiveTime = value; } /** * Gets the value of the activityTime property. * * @return * possible object is * {@link IVLTS } * */ public IVLTS getActivityTime() { return activityTime; } /** * Sets the value of the activityTime property. * * @param value * allowed object is * {@link IVLTS } * */ public void setActivityTime(IVLTS value) { this.activityTime = value; } /** * Gets the value of the priorityCode property. * * @return * possible object is * {@link CE } * */ public CE getPriorityCode() { return priorityCode; } /** * Sets the value of the priorityCode property. * * @param value * allowed object is * {@link CE } * */ public void setPriorityCode(CE value) { this.priorityCode = value; } /** * Gets the value of the admissionReferralSourceCode property. * * @return * possible object is * {@link CE } * */ public CE getAdmissionReferralSourceCode() { return admissionReferralSourceCode; } /** * Sets the value of the admissionReferralSourceCode property. * * @param value * allowed object is * {@link CE } * */ public void setAdmissionReferralSourceCode(CE value) { this.admissionReferralSourceCode = value; } /** * Gets the value of the dischargeDispositionCode property. * * @return * possible object is * {@link CE } * */ public CE getDischargeDispositionCode() { return dischargeDispositionCode; } /** * Sets the value of the dischargeDispositionCode property. * * @param value * allowed object is * {@link CE } * */ public void setDischargeDispositionCode(CE value) { this.dischargeDispositionCode = value; } /** * Gets the value of the reason property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the reason property. * * <p> * For example, to add a new item, do as follows: * <pre> * getReason().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link COCTMT290000UV06Reason5 } * * */ public List<COCTMT290000UV06Reason5> getReason() { if (reason == null) { reason = new ArrayList<COCTMT290000UV06Reason5>(); } return this.reason; } /** * Gets the value of the nullFlavor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nullFlavor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNullFlavor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNullFlavor() { if (nullFlavor == null) { nullFlavor = new ArrayList<String>(); } return this.nullFlavor; } /** * Gets the value of the classCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the classCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getClassCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getClassCode() { if (classCode == null) { classCode = new ArrayList<String>(); } return this.classCode; } /** * Gets the value of the moodCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the moodCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMoodCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getMoodCode() { if (moodCode == null) { moodCode = new ArrayList<String>(); } return this.moodCode; } }
KRMAssociatesInc/eHMP
lib/mvi/org/hl7/v3/COCTMT290000UV06PatientEncounter.java
Java
apache-2.0
12,469
/* * Copyright 2016 Igor Maznitsa. * * 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.igormaznitsa.mvngolang; import com.igormaznitsa.meta.annotation.LazyInited; import com.igormaznitsa.meta.annotation.MayContainNull; import com.igormaznitsa.meta.annotation.MustNotContainNull; import com.igormaznitsa.meta.annotation.ReturnsOriginal; import com.igormaznitsa.meta.common.utils.ArrayUtils; import com.igormaznitsa.meta.common.utils.GetUtils; import com.igormaznitsa.meta.common.utils.StrUtils; import com.igormaznitsa.mvngolang.utils.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.commons.lang3.SystemUtils; import org.apache.http.*; import org.apache.http.auth.AuthScope; import org.apache.http.auth.NTCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.impl.conn.DefaultProxyRoutePlanner; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.settings.Proxy; import org.apache.maven.settings.Settings; import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolver; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.zeroturnaround.exec.ProcessExecutor; import org.zeroturnaround.exec.ProcessResult; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.net.InetAddress; import java.net.URLEncoder; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.*; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Pattern; import static com.igormaznitsa.meta.common.utils.Assertions.assertNotNull; import static com.igormaznitsa.mvngolang.utils.MavenUtils.findProperty; public abstract class AbstractGolangMojo extends AbstractMojo { public static final String GOARTIFACT_PACKAGING = "mvn-golang"; public static final String GO_MOD_FILE_NAME = "go.mod"; public static final String GO_SUM_FILE_NAME = "go.sum"; public static final String ENV_GO111MODULE = "GO111MODULE"; /** * VERSION, OS, PLATFORM,-OSXVERSION */ public static final String NAME_PATTERN = "go%s.%s-%s%s"; private static final List<String> ALLOWED_SDKARCHIVE_CONTENT_TYPE = Collections.unmodifiableList( Arrays.asList("application/octet-stream", "application/zip", "application/x-tar", "application/x-gzip")); private static final ReentrantLock LOCKER = new ReentrantLock(); private static final String[] BANNER = new String[]{"______ ___ _________ ______", "___ |/ /__ __________ ____/________ / ______ ______________ _", "__ /|_/ /__ | / /_ __ \\ / __ _ __ \\_ / _ __ `/_ __ \\_ __ `/", "_ / / / __ |/ /_ / / / /_/ / / /_/ / /___/ /_/ /_ / / / /_/ / ", "/_/ /_/ _____/ /_/ /_/\\____/ \\____//_____/\\__,_/ /_/ /_/_\\__, /", " /____/", " https://github.com/raydac/mvn-golang", "" }; private static final Pattern GOBINFOLDER_PATTERN = Pattern .compile("(?:\\\\|/)go[0-9\\-\\+.]*(?:\\\\|/)bin(?:\\\\|/)?$", Pattern.CASE_INSENSITIVE); /** * set of flags to be ignored among build and extra build flags, for inside * use */ protected final Set<String> buildFlagsToIgnore = new HashSet<>(); protected final List<String> tempBuildFlags = new ArrayList<>(); @Parameter(defaultValue = "${settings}", readonly = true) protected Settings settings; @Component private ArtifactResolver artifactResolver; @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true) private List<ArtifactRepository> remoteRepositories; @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession session; @Parameter(defaultValue = "${mojoExecution}", readonly = true, required = true) private MojoExecution execution; /** * Flag to turn on support for module mode. Dependencies will not be added * into GOPATH, go.mod files will be preprocessed to have replace links to * each other locally. After processing all go.mod files are restored from * backup. Can be overridden by property "mvn.golang.module.mode" * * @since 2.3.3 */ @Parameter(name = "moduleMode", defaultValue = "false") private boolean moduleMode; /** * Path to be used as working directory for executing process, by default it * is unset and working directory depends on mode and command. * * @since 2.3.3 */ @Parameter(name = "workingDir") private String workingDir; /** * Flag shows that environment PATH variable should be filtered for footsteps * of other go/bin folders to prevent conflicts. * * @since 2.3.0 */ @Parameter(defaultValue = "true", name = "filterEnvPath") private boolean filterEnvPath = true; /** * Check hash for downloaded SDK archive. * * @since 2.3.0 */ @Parameter(name = "checkSdkHash", defaultValue = "true") private boolean checkSdkHash = true; /** * Use proxy server defined for maven. * * @since 2.3.0 */ @Parameter(name = "useMavenProxy", defaultValue = "true") private boolean useMavenProxy; /** * Disable check of SSL certificate during HTTPS request. Also can be changed * by system property 'mvn.golang.disable.ssl.check' * * @since 2.1.7 */ @Parameter(name = "disableSSLcheck", defaultValue = "false") private boolean disableSSLcheck; /** * Suppose SDK archive file name if it is not presented in the list loaded * from server. * * @since 2.1.6 */ @Parameter(name = "supposeSdkArchiveFileName", defaultValue = "true") private boolean supposeSdkArchiveFileName; /** * Parameters of proxy server to be used to make connection to SDK server. * * @since 2.1.1 */ @Parameter(name = "proxy") private ProxySettings proxy; /** * Skip execution of the mojo. Also can be disabled through system property * `mvn.golang.skip' * * @since 2.1.2 */ @Parameter(name = "skip", defaultValue = "false") private boolean skip; /** * Ignore error exit code returned by GoLang tool and don't generate any * failure. * * @since 2.1.1 */ @Parameter(name = "ignoreErrorExitCode", defaultValue = "false") private boolean ignoreErrorExitCode; /** * Folder to place console logs. * * @since 2.1.1 */ @Parameter(name = "reportsFolder", defaultValue = "${project.build.directory}${file.separator}reports") private String reportsFolder; /** * File to save console out log. If empty then will not be saved. * * @since 2.1.1 */ @Parameter(name = "outLogFile") private String outLogFile; /** * File to save console error log. If empty then will not be saved * * @since 2.1.1 */ @Parameter(name = "errLogFile") private String errLogFile; /** * Base site for SDK download. By default it uses * <a href="https://storage.googleapis.com/golang/">https://storage.googleapis.com/golang/</a> */ @Parameter(name = "sdkSite", defaultValue = "https://storage.googleapis.com/golang/") private String sdkSite; /** * Hide ASC banner. */ @Parameter(defaultValue = "true", name = "hideBanner") private boolean hideBanner; /** * Folder to be used to save and unpack loaded SDKs and also keep different * info. By default it has value "${user.home}${file.separator}.mvnGoLang" */ @Parameter(defaultValue = "${user.home}${file.separator}.mvnGoLang", name = "storeFolder") private String storeFolder; /** * Folder to be used as $GOPATH. NB! By default it has value * "${user.home}${file.separator}.mvnGoLang${file.separator}.go_path" */ @Parameter(defaultValue = "${user.home}${file.separator}.mvnGoLang${file.separator}.go_path", name = "goPath") private String goPath; /** * Value to be provided as $GO386. This controls the code generated by gc to * use either the 387 floating-point unit (set to 387) or SSE2 instructions * (set to sse2) for floating point computations. * * @since 2.1.7 */ private String target386; /** * Value to be provided as $GOARM. This sets the ARM floating point * co-processor architecture version the run-time should target. If you are * compiling on the target system, its value will be auto-detected. * * @since 2.1.1 */ @Parameter(name = "targetArm") private String targetArm; /** * Folder to be used as $GOBIN. NB! By default it has value * "${project.build.directory}". It is possible to disable usage of GOBIN in * process through value <b>NONE</b> */ @Parameter(defaultValue = "${project.build.directory}", name = "goBin") private String goBin; /** * The Go SDK version. It plays role if goRoot is undefined. Can be defined * through system property 'mvn.golang.go.version' */ @Parameter(name = "goVersion", defaultValue = "1.17.7") private String goVersion; /** * Cache directory to keep build data. It affects GOCACHE environment * variable. By default it is turned off by value `off` * * @since 2.3.1 */ @Parameter(name = "goCache", defaultValue = "${project.build.directory}${file.separator}.goBuildCache") private String goCache; /** * The Go home folder. It can be undefined and in the case the plug-in will * make automatic business to find SDK in its cache or download it. */ @Parameter(name = "goRoot") private String goRoot; /** * The Go bootstrap home folder. */ @Parameter(name = "goRootBootstrap") private String goRootBootstrap; /** * Make GOPATH value as the last one in new generated GOPATH chain. * * @since 2.1.3 */ @Parameter(name = "enforceGoPathToEnd", defaultValue = "false") private boolean enforceGoPathToEnd; /** * Sub-path to executing go tool in SDK folder. * * @since 1.1.0 */ @Parameter(name = "execSubpath", defaultValue = "bin") private String execSubpath; /** * Go tool to be executed. NB! An Extension for OS will be automatically * added. * * @since 1.1.0 */ @Parameter(name = "exec", defaultValue = "go") private String exec; /** * Allows defined text to be printed before execution as warning in to log. */ @Parameter(name = "echoWarn") private String[] echoWarn; /** * Allows defined text to be printed before execution as info into log. */ @Parameter(name = "echo") private String[] echo; /** * Disable loading GoLang SDK through network if it is not found at cache. */ @Parameter(name = "disableSdkLoad", defaultValue = "false") private boolean disableSdkLoad; /** * GoLang source directory. By default <b>${project.build.sourceDirectory}</b> */ @Parameter(defaultValue = "${project.build.sourceDirectory}", name = "sources") private String sources; /** * The Target OS. */ @Parameter(name = "targetOs") private String targetOs; /** * The OS. If it is not defined then plug-in will try figure out the current * one. */ @Parameter(name = "os") private String os; /** * The Target architecture. */ @Parameter(name = "targetArch") private String targetArch; /** * The Architecture. If it is not defined then plug-in will try figure out the * current one. */ @Parameter(name = "arch") private String arch; /** * Version of OSX to be used during distributive name synthesis. */ @Parameter(name = "osxVersion") private String osxVersion; /** * List of optional build flags. */ @Parameter(name = "buildFlags") private String[] buildFlags; /** * Be verbose in logging. */ @Parameter(name = "verbose", defaultValue = "false") private boolean verbose; /** * Do not delete SDK archive after unpacking. */ @Parameter(name = "keepSdkArchive", defaultValue = "false") private boolean keepSdkArchive; /** * Name of tool to be called instead of standard 'go' tool. */ @Parameter(name = "useGoTool") private String useGoTool; /** * Flag to override all provided configuration variables by their environment * values if such value is detected * <ul> * <li>goRoot by $GOROOT</li> * <li>goRootBootstrap by $GOROOT_BOOTSTRAP</li> * <li>targetOs by $GOOS</li> * <li>targetArch by $GOARCH</li> * <li>targetArm by $GOARM</li> * <li>goPath by $GOPATH</li> * </ul> * <b>NB! Your configuration values will be ignored if you define the flag * because it has higher priority!</b> */ @Parameter(name = "useEnvVars", defaultValue = "false") private boolean useEnvVars; /** * It allows to define key value pairs which will be used as environment * variables for started GoLang process. */ @Parameter(name = "env") private Map<?, ?> env; /** * Allows directly define name of SDK archive. If it is not defined then * plug-in will try to generate name and find such one in downloaded SDK * list.. */ @Parameter(name = "sdkArchiveName") private String sdkArchiveName; /** * Directly defined URL to download GoSDK. In the case SDK list will not be * downloaded and plug-in will try download archive through the link. */ @Parameter(name = "sdkDownloadUrl") private String sdkDownloadUrl; /** * Timeout for HTTP connection in milliseconds. * * @since 2.3.0 */ @Parameter(name = "connectionTimeout", defaultValue = "60000") private int connectionTimeout = 60000; /** * Keep unpacked wrongly SDK folder. */ @Parameter(name = "keepUnarchFolderIfError", defaultValue = "false") private boolean keepUnarchFolderIfError; /** * Allows to define folders which will be added into $GOPATH * * @since 2.0.0 */ @Parameter(name = "addToGoPath") private String[] addToGoPath; @LazyInited private CloseableHttpClient httpClient; @LazyInited private ByteArrayOutputStream consoleErrBuffer; @LazyInited private ByteArrayOutputStream consoleOutBuffer; @Nonnull private static String ensureNoSurroundingSlashes(@Nonnull final String str) { String result = str; if (!result.isEmpty() && (result.charAt(0) == '/' || result.charAt(0) == '\\')) { result = result.substring(1); } if (!result.isEmpty() && (result.charAt(result.length() - 1) == '/' || result.charAt(result.length() - 1) == '\\')) { result = result.substring(0, result.length() - 1); } return result; } private static void deleteFileIfExists(@Nonnull final File file) throws IOException { if (file.isFile() && !file.delete()) { throw new IOException("Can't delete file : " + file); } } private static boolean isSafeEmpty(@Nullable final String value) { return value == null || value.isEmpty(); } @Nonnull private static String extractExtensionOfArchive(@Nonnull final String archiveName) { final String lcName = archiveName.toLowerCase(Locale.ENGLISH); final String result; if (lcName.endsWith(".tar.gz")) { result = archiveName.substring(archiveName.length() - "tar.gz".length()); } else { result = FilenameUtils.getExtension(archiveName); } return result; } @Nonnull protected static String adaptExecNameForOS(@Nonnull final String execName) { return execName + (SystemUtils.IS_OS_WINDOWS ? ".exe" : ""); } @Nonnull private static String getPathToFolder(@Nonnull final String path) { String text = path; if (!text.endsWith("/") && !text.endsWith("\\")) { text = text + File.separatorChar; } return text; } @Nonnull private static String getPathToFolder(@Nonnull final File path) { return getPathToFolder(path.getAbsolutePath()); } @Nullable protected static File findExisting(@Nonnull @MayContainNull final File... files) { File result = null; for (final File f : files) { if (f != null && f.isFile()) { result = f; break; } } return result; } @Nonnull private static String removeSrcFolderAtEndIfPresented(@Nonnull final String text) { String result = text; if (text.endsWith("/src") || text.endsWith("\\src")) { result = text.substring(0, text.length() - 4); } return result; } @Nonnull private static String extractComputerName() { String result = System.getenv("COMPUTERNAME"); if (result == null) { result = System.getenv("HOSTNAME"); } if (result == null) { try { result = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ex) { // do nothing, let be null } } return GetUtils.ensureNonNull(result, "<Unknown computer>"); } @Nonnull private static String extractDomainName() { final String result = System.getenv("USERDOMAIN"); return GetUtils.ensureNonNull(result, ""); } @Nullable public final String getWorkingDir() { return this.workingDir; } public final void setWorkingDir(@Nullable final String path) { this.workingDir = path; } public boolean isModuleMode() { return Boolean .parseBoolean(findMvnProperty("mvn.golang.module.mode", Boolean.toString(this.moduleMode))); } public void setModuleMode(final boolean value) { this.moduleMode = value; } @Nonnull public ArtifactResolver getArtifactResolver() { return assertNotNull("Artifact resolver component is not provided by Maven", this.artifactResolver); } @Nonnull @MustNotContainNull public List<ArtifactRepository> getRemoteRepositories() { return this.remoteRepositories; } protected boolean doesNeedSessionLock() { return false; } /** * Generate unique file name in bounds current maven session. * * @return file name, must not be null * @since 2.3.3 */ @Nonnull private String makeSessionLockFileName() { final String id = Long.toHexString(this.getSession().getStartTime().getTime()).toUpperCase(Locale.ENGLISH); return ".#mvn.go.session.lock." + id; } @Nonnull protected File getTempFileFolder() { return new File(System.getProperty("java.io.tmpdir")); } /** * Internal method to generate session locking file for mvn-golang mojo. If * file exists then it will be waiting for its removing to create new one. * * @throws MojoExecutionException it will be thrown if any error in process * @since 2.3.3 */ private void lockMvnGolangSession() throws MojoExecutionException { final File lockFile = new File(this.getTempFileFolder(), makeSessionLockFileName()); this.getLog().debug("Locking project for mvn-golang sync processing, locker file: " + lockFile); while (!Thread.currentThread().isInterrupted()) { final boolean locked; try { locked = lockFile.createNewFile(); } catch (IOException ex) { throw new MojoExecutionException( "Detected error during attempt to make locker file: " + lockFile, ex); } if (locked) { lockFile.deleteOnExit(); this.getLog().debug("Locking file created: " + lockFile); return; } else { try { Thread.sleep(100); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); break; } } } } /** * Internal method to unlock current mvn-golang session through removing of * the locking file. If file can't be found then it warns and continue work as * if it would be removed. * * @throws MojoExecutionException it is thrown if any error * @since 2.3.3 */ private void unlockMvnGolangSession() throws MojoExecutionException { final File locker = new File(this.getTempFileFolder(), makeSessionLockFileName()); this.getLog().debug("Unlocking project for mvn-golang sync processing, locker file: " + locker); if (locker.isFile()) { if (!locker.delete()) { throw new MojoExecutionException("Can't delete locker file: " + locker); } } else { this.getLog().warn("Can't detect locker file, may be it was removed externally: " + locker); } } @Nonnull private File loadSDKAndUnpackIntoCache( @Nullable final ProxySettings proxySettings, @Nonnull final File cacheFolder, @Nonnull final String baseSdkName, final boolean notLoadIfNotInCache ) throws IOException, MojoExecutionException { synchronized (AbstractGolangMojo.class) { final File sdkFolder = new File(cacheFolder, baseSdkName); if (sdkFolder.isDirectory()) { return sdkFolder; } final File lockFile = new File(cacheFolder, ".lck" + baseSdkName); lockFile.deleteOnExit(); try { if (!lockFile.createNewFile()) { this.getLog().info("Detected SDK loading, waiting for the process end"); while (lockFile.exists()) { try { Thread.sleep(100L); } catch (InterruptedException ex) { throw new IOException("Wait of SDK loading is interrupted", ex); } } this.getLog().info("Loading process has been completed"); return sdkFolder; } if (sdkFolder.isDirectory()) { if (this.isVerbose() || this.getLog().isDebugEnabled()) { this.getLog().info("SDK cache folder : " + sdkFolder); } return sdkFolder; } else if (notLoadIfNotInCache || this.session.isOffline()) { this.getLog().error( "Can't find cached Golang SDK and downloading is disabled or Maven in offline mode"); throw new IOException( "Can't find " + baseSdkName + " in the cache but loading is directly disabled"); } final String predefinedLink = this.getSdkDownloadUrl(); final File archiveFile; final String linkForDownloading; if (isSafeEmpty(predefinedLink)) { this.logOptionally("There is not any predefined SDK URL"); final String sdkFileName = this.findSdkArchiveFileName(proxySettings, baseSdkName); archiveFile = new File(cacheFolder, sdkFileName); linkForDownloading = this.getSdkSite() + sdkFileName; } else { final String extension = extractExtensionOfArchive(assertNotNull(predefinedLink)); archiveFile = new File(cacheFolder, baseSdkName + '.' + extension); linkForDownloading = predefinedLink; this.logOptionally("Using predefined URL to download SDK : " + linkForDownloading); this.logOptionally("Detected extension of archive : " + extension); } if (archiveFile.exists()) { this.logOptionally( "Detected existing archive " + archiveFile + ", deleting it and reload"); if (!archiveFile.delete()) { throw new IOException("Can't delete archive file: " + archiveFile); } } final HttpGet methodGet = new HttpGet(linkForDownloading); final RequestConfig config = this.processRequestConfig(proxySettings, this.getConnectionTimeout(), RequestConfig.custom()).build(); methodGet.setConfig(config); boolean errorsDuringLoading = true; boolean showProgressBar; try { if (!archiveFile.isFile()) { this.getLog().warn("Loading SDK archive with URL : " + linkForDownloading); final HttpResponse response = this.getHttpClient(proxySettings).execute(methodGet); final StatusLine statusLine = response.getStatusLine(); this.getLog().debug("HttpResponse: " + response); if (statusLine.getStatusCode() != HttpStatus.SC_OK) { throw new IOException(String .format("Can't load SDK archive from %s : %d %s", linkForDownloading, statusLine.getStatusCode(), statusLine.getReasonPhrase())); } final XGoogHashHeader xGoogHash = new XGoogHashHeader(response.getHeaders("x-goog-hash")); this.getLog().debug("XGoogHashHeader: " + xGoogHash); final HttpEntity entity = response.getEntity(); final Header contentType = entity.getContentType(); if (!ALLOWED_SDKARCHIVE_CONTENT_TYPE.contains(contentType.getValue())) { throw new IOException("Unsupported content type : " + contentType.getValue()); } final long size = entity.getContentLength(); try (final InputStream inStream = entity.getContent()) { showProgressBar = size > 0L && !this.session.isParallel(); this.getLog().info("Downloading SDK archive into file : " + archiveFile); long loadedCounter = 0L; final byte[] buffer = new byte[1024 * 1024]; int lastRenderedValue = -1; final int PROGRESSBAR_WIDTH = 10; final String LOADING_TITLE = "Loading " + size / (1024L * 1024L) + " Mb "; if (showProgressBar) { lastRenderedValue = IOUtils .printTextProgressBar(LOADING_TITLE, 0, size, PROGRESSBAR_WIDTH, lastRenderedValue); } final OutputStream fileOutStream = new BufferedOutputStream(new FileOutputStream(archiveFile), 128 * 16384); try { while (!Thread.currentThread().isInterrupted()) { final int readCounter = inStream.read(buffer); if (readCounter < 0) { break; } fileOutStream.write(buffer, 0, readCounter); loadedCounter += readCounter; if (showProgressBar) { lastRenderedValue = IOUtils .printTextProgressBar(LOADING_TITLE, loadedCounter, size, PROGRESSBAR_WIDTH, lastRenderedValue); } } } finally { if (showProgressBar) { System.out.println(); } IOUtils.closeSilently(fileOutStream); } if (Thread.currentThread().isInterrupted()) { throw new MojoExecutionException("Interrupted"); } this.getLog().info("Archived SDK has been succesfully downloaded, its size is " + (archiveFile.length() / 1024L) + " Kb"); } if (this.isCheckSdkHash()) { if (xGoogHash.isValid() && xGoogHash.hasData()) { this.getLog().debug("Checking hash of file"); final boolean fileHashOk = xGoogHash.isFileOk(this.getLog(), archiveFile); if (fileHashOk) { this.getLog().info("Downloaded archive file hash is OK"); } else { this.getLog().error("Downloaded archive file hash is BAD"); throw new MojoExecutionException("Downloaded SDK archive has wrong hash"); } } else { if (!xGoogHash.isValid()) { throw new MojoExecutionException( "Couldn't parse x-goog-hash from response: " + response); } else { throw new MojoExecutionException( "Parsed x-goog-hash doesn't contain data but marked as valid one: " + xGoogHash); } } } } else { this.getLog().info("Archive file of SDK has been found in the cache : " + archiveFile); } errorsDuringLoading = false; final File interFolder = this.unpackArchToFolder(archiveFile, "go", new File(cacheFolder, ".#" + baseSdkName)); this.getLog().info("Renaming " + interFolder.getName() + " to " + sdkFolder.getName()); if (interFolder.renameTo(sdkFolder)) { this.logOptionally("Renamed successfully: " + interFolder + " -> " + sdkFolder); } else { throw new IOException( "Can't rename temp GoSDK folder: " + interFolder + " -> " + sdkFolder); } return sdkFolder; } finally { methodGet.releaseConnection(); if (errorsDuringLoading || !this.isKeepSdkArchive()) { this.logOptionally("Deleting archive : " + archiveFile + (errorsDuringLoading ? " (because error during loading)" : "")); deleteFileIfExists(archiveFile); } else { this.logOptionally("Archive file is kept for special flag : " + archiveFile); } } } finally { final boolean deleted = FileUtils.deleteQuietly(lockFile); this.getLog().debug("Lock file " + lockFile + " deleted : " + deleted); } } } public boolean isFilterEnvPath() { return this.filterEnvPath; } @Nullable protected String findMvnProperty(@Nonnull final String key, @Nullable final String dflt) { if (this.session == null || this.project == null) { return null; } return findProperty(this.session, this.project, key, dflt); } public boolean isSkip() { final boolean result = Boolean.parseBoolean(findMvnProperty("mvn.golang.skip", Boolean.toString(this.skip))); final String skipMojoSuffix = this.getSkipMojoPropertySuffix(); return skipMojoSuffix == null ? result : result || Boolean.parseBoolean( findMvnProperty(String.format("mvn.golang.%s.skip", skipMojoSuffix), "false")); } public boolean isEnforceGoPathToEnd() { return this.enforceGoPathToEnd; } @Nonnull public MavenProject getProject() { return this.project; } @Nonnull public MojoExecution getExecution() { return this.execution; } @Nonnull public MavenSession getSession() { return this.session; } public boolean isIgnoreErrorExitCode() { return this.ignoreErrorExitCode; } @Nonnull public Map<?, ?> getEnv() { return GetUtils.ensureNonNull(this.env, Collections.EMPTY_MAP); } @Nullable public String getSdkDownloadUrl() { return this.sdkDownloadUrl; } @Nonnull public String getExecSubpath() { return ensureNoSurroundingSlashes(assertNotNull(this.execSubpath)); } public int getConnectionTimeout() { return this.connectionTimeout; } @Nonnull public String getExec() { return ensureNoSurroundingSlashes(assertNotNull(this.exec)); } public boolean isUseEnvVars() { return this.useEnvVars; } public boolean isKeepSdkArchive() { return this.keepSdkArchive; } public boolean isKeepUnarchFolderIfError() { return this.keepUnarchFolderIfError; } @Nullable public String getSdkArchiveName() { return this.sdkArchiveName; } @Nonnull public String getReportsFolder() { return this.reportsFolder; } @Nullable public String getOutLogFile() { return this.outLogFile; } @Nullable public String getErrLogFile() { return this.errLogFile; } public boolean isCheckSdkHash() { return this.checkSdkHash; } @Nonnull public String getStoreFolder() { return this.storeFolder; } @Nullable public String getUseGoTool() { return this.useGoTool; } public boolean isVerbose() { return Boolean .parseBoolean(findMvnProperty("mvn.golang.verbose", Boolean.toString(this.verbose))); } public boolean isDisableSdkLoad() { return this.disableSdkLoad; } @Nonnull public String getSdkSite() { return assertNotNull(this.sdkSite); } @Nonnull @MustNotContainNull public String[] getBuildFlags() { final List<String> result = new ArrayList<>(); for (final String s : ArrayUtils .joinArrays(GetUtils.ensureNonNull(this.buildFlags, ArrayUtils.EMPTY_STRING_ARRAY), getExtraBuildFlags())) { if (!this.buildFlagsToIgnore.contains(s)) { result.add(s); } } result.addAll(this.tempBuildFlags); return result.toArray(new String[0]); } @Nonnull @MustNotContainNull protected String[] getExtraBuildFlags() { return ArrayUtils.EMPTY_STRING_ARRAY; } @Nonnull @MustNotContainNull public File[] findGoPath(final boolean ensureExist) throws IOException { LOCKER.lock(); try { final String foundGoPath = getGoPath(); if (getLog().isDebugEnabled()) { getLog().debug("findGoPath(" + ensureExist + "), getGoPath() returns " + foundGoPath); } final List<File> result = new ArrayList<>(); for (final String p : foundGoPath.split(String.format("\\%s", File.pathSeparator))) { final File folder = new File(p); result.add(folder); if (ensureExist && !folder.isDirectory() && !folder.mkdirs()) { throw new IOException("Can't create folder for GOPATH : " + folder.getAbsolutePath()); } } return result.toArray(new File[0]); } finally { LOCKER.unlock(); } } @Nullable public File findGoRootBootstrap(final boolean ensureExist) throws IOException { LOCKER.lock(); try { final String value = getGoRootBootstrap(); File result = null; if (value != null) { result = new File(value); if (ensureExist && !result.isDirectory()) { throw new IOException("Can't find folder for GOROOT_BOOTSTRAP: " + result); } } return result; } finally { LOCKER.unlock(); } } @Nonnull public String getOs() { String result = this.os; if (isSafeEmpty(result)) { if (isSafeEmpty(result)) { result = assertNotNull(String.format("Can't recognize OS: %s", SystemUtils.OS_NAME), SysUtils.findGoSdkOsType()); } } return result; } @Nullable public String getArch() { String result = this.arch; if (isSafeEmpty(result)) { result = assertNotNull(String.format("Can't recognize ARCH: %s", SystemUtils.OS_ARCH), SysUtils.decodeGoSdkArchType(SystemUtils.OS_ARCH)); } return result; } @Nullable private String getValueOrEnv(@Nonnull final String varName, @Nullable final String configValue) { final String foundInEnvironment = System.getenv(varName); String result = configValue; if (foundInEnvironment != null && isUseEnvVars()) { if (!isSafeEmpty(configValue)) { getLog().warn(String.format("Value %s is replaced by environment value.", varName)); } result = foundInEnvironment; } return result; } @Nullable public String getGoRoot() { return getValueOrEnv("GOROOT", this.goRoot); } @Nullable public String getGoCache() { return getValueOrEnv("GOCACHE", this.goCache); } @Nullable public String getGoRootBootstrap() { return getValueOrEnv("GOROOT_BOOTSTRAP", this.goRootBootstrap); } @Nullable public String getGoBin() { String result = getValueOrEnv("GOBIN", this.goBin); return "NONE".equals(result) ? null : result; } @Nonnull public String getGoPath() { return assertNotNull(getValueOrEnv("GOPATH", this.goPath)); } @Nullable public String getTargetArm() { return getValueOrEnv("GOARM", this.targetArm); } @Nullable public String getTarget386() { return getValueOrEnv("GO386", this.target386); } @Nullable public String getTargetOS() { return getValueOrEnv("GOOS", this.targetOs); } @Nullable public String getTargetArch() { return getValueOrEnv("GOARCH", this.targetArch); } public boolean isUseMavenProxy() { return this.useMavenProxy; } public boolean getSupposeSdkArchiveFileName() { return this.supposeSdkArchiveFileName; } public boolean isDisableSslCheck() { return this.disableSSLcheck || Boolean.parseBoolean( findProperty(this.getSession(), this.getProject(), "mvn.golang.disable.ssl.check", "false")); } public void setDisableSslCheck(final boolean flag) { this.disableSSLcheck = flag; } @Nullable public ProxySettings getProxy() { return this.proxy; } @Nullable public String getOSXVersion() { return this.osxVersion; } @Nonnull public String getGoVersion() { return findProperty(this.session, this.project, "mvn.golang.go.version", this.goVersion); } @Nonnull public File getSources(final boolean ensureExist) throws IOException { final File result = new File(this.sources); if (ensureExist && !result.isDirectory()) { throw new IOException("Can't find GoLang project sources : " + result); } return result; } protected void addTmpBuildFlagIfNotPresented(@Nonnull @MustNotContainNull final String... flags) { for (final String s : flags) { if (this.tempBuildFlags.contains(s)) { continue; } boolean found = false; if (this.buildFlags != null) { for (final String b : this.buildFlags) { if (s.equals(b)) { found = true; break; } } } if (!found) { this.tempBuildFlags.add(s); } } } @Nullable private static String nullIfBlank(@Nullable final String text) { return text == null || text.trim().isEmpty() ? null : text; } @Nullable private ProxySettings extractProxySettings() { final ProxySettings result; if (this.isUseMavenProxy()) { final Proxy activeMavenProxy = this.settings == null ? null : this.settings.getActiveProxy(); result = activeMavenProxy == null ? null : new ProxySettings(activeMavenProxy); getLog().debug("Detected maven proxy : " + result); } else { result = this.proxy; if (result != null) { getLog().debug("Defined proxy : " + result); } } return result; } @ReturnsOriginal @Nonnull private RequestConfig.Builder processRequestConfig(@Nullable final ProxySettings proxySettings, final int timeout, @Nonnull final RequestConfig.Builder config) { this.getLog() .debug("Connection(timeout=" + timeout + "ms, proxySettings=" + proxySettings + ')'); if (proxySettings != null) { final HttpHost proxyHost = new HttpHost(proxySettings.host, proxySettings.port, proxySettings.protocol); config.setProxy(proxyHost); } return config.setConnectTimeout(timeout).setSocketTimeout(timeout); } @Nonnull private String loadGoLangSdkList(@Nullable final ProxySettings proxySettings, @Nullable final String keyPrefix) throws IOException, MojoExecutionException { final String sdksite = getSdkSite() + (keyPrefix == null ? "" : "?prefix=" + keyPrefix); getLog().warn("Loading list of available GoLang SDKs from " + sdksite); final HttpGet get = new HttpGet(sdksite); final RequestConfig config = processRequestConfig(proxySettings, this.getConnectionTimeout(), RequestConfig.custom()) .build(); get.setConfig(config); get.addHeader("Accept", "application/xml"); try { final HttpResponse response = getHttpClient(proxySettings).execute(get); final StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { final String content = EntityUtils.toString(response.getEntity()); getLog().info("GoLang SDK list has been loaded successfuly"); getLog().debug(content); return content; } else { throw new IOException(String .format("Can't load list of SDKs from %s : %d %s", sdksite, statusLine.getStatusCode(), statusLine.getReasonPhrase())); } } finally { get.releaseConnection(); } } @Nonnull private Document convertSdkListToDocument(@Nonnull final String sdkListAsString) throws IOException { try { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(new StringReader(sdkListAsString))); } catch (ParserConfigurationException ex) { getLog().error("Can't configure XML parser", ex); throw new IOException("Can't configure XML parser", ex); } catch (SAXException ex) { getLog().error("Can't parse document", ex); throw new IOException("Can't parse document", ex); } catch (IOException ex) { getLog().error("Unexpected IOException", ex); throw new IOException("Unexpected IOException", ex); } } private void printEcho() { if (this.echoWarn != null) { for (final String s : this.echoWarn) { getLog().warn(s); } } if (this.echo != null) { for (final String s : this.echo) { getLog().info(s); } } } protected void logOptionally(@Nonnull final String message) { if (getLog().isDebugEnabled() || this.verbose) { getLog().info(message); } } protected void initConsoleBuffers() { getLog().debug("Initing console out and console err buffers"); this.consoleErrBuffer = new ByteArrayOutputStream(); this.consoleOutBuffer = new ByteArrayOutputStream(); } @ReturnsOriginal @Nonnull private File unpackArchToFolder(@Nonnull final File archiveFile, @Nonnull final String folderInArchive, @Nonnull final File destinationFolder) throws IOException { getLog().info(String.format("Unpacking archive %s to folder %s", archiveFile.getName(), destinationFolder.getName())); boolean detectedError = true; try { final int unpackedFileCounter = UnpackUtils .unpackFileToFolder(getLog(), folderInArchive, archiveFile, destinationFolder, true); if (unpackedFileCounter == 0) { throw new IOException( "Couldn't find folder '" + folderInArchive + "' in archive or the archive is empty"); } else { getLog().info("Unpacked " + unpackedFileCounter + " file(s)"); } detectedError = false; } finally { if (detectedError && !isKeepUnarchFolderIfError()) { logOptionally("Deleting folder because error during unpack : " + destinationFolder); FileUtils.deleteQuietly(destinationFolder); } } return destinationFolder; } @Nonnull private String extractSDKFileName(@Nonnull final String listUrl, @Nonnull final Document doc, @Nonnull final String sdkBaseName, @Nonnull @MustNotContainNull final String[] allowedExtensions) throws IOException { getLog().debug("Looking for SDK started with base name : " + sdkBaseName); final Set<String> variants = new HashSet<>(); for (final String ext : allowedExtensions) { variants.add(sdkBaseName + '.' + ext); } final List<String> listedSdk = new ArrayList<>(); final Element root = doc.getDocumentElement(); if ("ListBucketResult".equals(root.getTagName())) { final NodeList list = root.getElementsByTagName("Contents"); for (int i = 0; i < list.getLength(); i++) { final Element element = (Element) list.item(i); final NodeList keys = element.getElementsByTagName("Key"); if (keys.getLength() > 0) { final String text = keys.item(0).getTextContent(); if (variants.contains(text)) { logOptionally("Detected compatible SDK in the SDK list : " + text); return text; } else { listedSdk.add(text); } } } if (this.supposeSdkArchiveFileName) { final String supposedSdkName = sdkBaseName + '.' + (SystemUtils.IS_OS_WINDOWS ? "zip" : "tar.gz"); getLog().warn("Can't find SDK file in the loaded list"); getLog().debug(".................................................."); for (final String s : listedSdk) { getLog().debug(s); } getLog().debug(".................................................."); getLog().warn("Supposed name of SDK archive is " + supposedSdkName + ", trying to load it directly! It can be disabled with <supposeSdkArchiveFileName>false</supposeSdkArchiveFileName>)"); return supposedSdkName; } getLog().error("Can't find any SDK to be used as " + sdkBaseName); getLog().error("GoLang list contains listed SDKs (" + listUrl + ")"); getLog().error( "It is possible directly define link to SDK through configuration parameter <sdkDownloadUrl>..</sdkDownloadUrl>"); getLog().error(".................................................."); for (final String s : listedSdk) { getLog().error(s); } throw new IOException("Can't find SDK : " + sdkBaseName); } else { throw new IOException("It is not a ListBucket file [" + root.getTagName() + ']'); } } @Nonnull private String findSdkArchiveFileName(@Nullable final ProxySettings proxySettings, @Nonnull final String sdkBaseName) throws IOException, MojoExecutionException { String result = getSdkArchiveName(); if (isSafeEmpty(result)) { final Document parsed = convertSdkListToDocument( loadGoLangSdkList(proxySettings, URLEncoder.encode(sdkBaseName, "UTF-8"))); result = extractSDKFileName(getSdkSite(), parsed, sdkBaseName, new String[]{"tar.gz", "zip"}); } else { getLog().info("SDK archive name is predefined : " + result); } return GetUtils.ensureNonNullStr(result); } private void warnIfContainsUC(@Nonnull final String message, @Nonnull final String str) { boolean detected = false; for (final char c : str.toCharArray()) { if (Character.isUpperCase(c)) { detected = true; break; } } if (detected) { getLog().warn(message + " : " + str); } } @Nonnull protected File findGoRoot(@Nullable final ProxySettings proxySettings) throws IOException, MojoFailureException, MojoExecutionException { final File result; LOCKER.lock(); try { final String predefinedGoRoot = this.getGoRoot(); if (isSafeEmpty(predefinedGoRoot)) { final File cacheFolder = new File(this.storeFolder); if (!cacheFolder.isDirectory()) { if (cacheFolder.isFile()) { throw new IOException("Can't create folder '" + cacheFolder + "' because there is presented a file with such name!"); } logOptionally("Making SDK cache folder : " + cacheFolder); FileUtils.forceMkdir(cacheFolder); } final String definedOsxVersion = this.getOSXVersion(); final String sdkVersion = this.getGoVersion(); this.getLog().debug( String.format("SdkVersion = %s, osxVersion = %s", sdkVersion, definedOsxVersion)); if (isSafeEmpty(sdkVersion)) { throw new MojoFailureException("GoLang SDK version is not defined!"); } final String sdkBaseName = String .format(NAME_PATTERN, sdkVersion, this.getOs(), this.getArch(), isSafeEmpty(definedOsxVersion) ? "" : "-" + definedOsxVersion); warnIfContainsUC("Prefer usage of lower case chars only for SDK base name", sdkBaseName); result = loadSDKAndUnpackIntoCache(proxySettings, cacheFolder, sdkBaseName, isDisableSdkLoad()); } else { logOptionally("Detected predefined SDK root folder : " + predefinedGoRoot); result = new File(predefinedGoRoot); if (!result.isDirectory()) { throw new MojoFailureException("Predefined SDK root is not a directory : " + result); } } } finally { LOCKER.unlock(); } return result; } private void printBanner() { for (final String s : BANNER) { getLog().info(s); } } public boolean isHideBanner() { return this.hideBanner; } protected boolean doesNeedOneMoreAttempt(@Nonnull final ProcessResult result, @Nonnull final String consoleOut, @Nonnull final String consoleErr) throws IOException, MojoExecutionException { return false; } protected void doLogging( final int resultCode, final boolean error, @Nonnull final String outLog, @Nonnull final String errLog ) throws MojoExecutionException { if (getLog().isDebugEnabled()) { getLog().debug("OUT_LOG: " + outLog); getLog().debug("ERR_LOG: " + errLog); } this.processLogFiles(outLog, errLog); this.printLogs( error || isEnforcePrintOutput() || (this.isVerbose() && this.isCommandSupportVerbose()), error, outLog, errLog); } protected boolean doMainBusiness(@Nullable final ProxySettings proxySettings, final int maxAttempts) throws InterruptedException, MojoFailureException, MojoExecutionException, IOException { int iterations = 0; boolean error = false; while (!Thread.currentThread().isInterrupted()) { final ProcessExecutor executor = prepareExecutor(proxySettings); if (executor == null) { logOptionally("The Mojo should not be executed"); break; } final ProcessResult result = executor.executeNoTimeout(); final int resultCode = result.getExitValue(); error = resultCode != 0 && !isIgnoreErrorExitCode(); iterations++; final String outLog = extractOutAsString(); final String errLog = extractErrorOutAsString(); this.doLogging(resultCode, error, outLog, errLog); if (doesNeedOneMoreAttempt(result, outLog, errLog)) { if (iterations > maxAttempts) { throw new MojoExecutionException( "Too many iterations detected, may be some loop and bug at mojo " + this.getClass().getName()); } getLog().warn("Make one more attempt..."); } else { if (!isIgnoreErrorExitCode()) { assertProcessResult(result); } break; } } return error; } @Override public final void execute() throws MojoExecutionException, MojoFailureException { if (this.isSkip()) { getLog().info("Skipping mvn-golang execution"); } else { if (this.doesNeedSessionLock()) { lockMvnGolangSession(); if (Thread.currentThread().isInterrupted()) { throw new MojoFailureException("Current thread is interrupted"); } } try { if (!isHideBanner()) { printBanner(); } doInit(); printEcho(); final ProxySettings proxySettings = extractProxySettings(); beforeExecution(proxySettings); Exception exception = null; boolean errorDuringMainBusiness = false; try { errorDuringMainBusiness = doMainBusiness(proxySettings, 10); } catch (final IOException | InterruptedException | MojoExecutionException | MojoFailureException ex) { if (ex instanceof InterruptedException) { Thread.currentThread().interrupt(); } exception = ex; } finally { afterExecution(null, errorDuringMainBusiness || exception != null); } if (exception != null) { throw new MojoExecutionException(exception.getMessage(), exception); } else if (errorDuringMainBusiness) { throw new MojoFailureException("Mojo execution failed, see log"); } } finally { if (this.doesNeedSessionLock()) { unlockMvnGolangSession(); } } } } public void doInit() throws MojoFailureException, MojoExecutionException { } public void beforeExecution(@Nullable final ProxySettings proxySettings) throws MojoFailureException, MojoExecutionException { } public void afterExecution(@Nullable final ProxySettings proxySettings, final boolean error) throws MojoFailureException, MojoExecutionException { } public boolean isEnforcePrintOutput() { return false; } @Nonnull private String extractOutAsString() { return new String(this.consoleOutBuffer.toByteArray(), Charset.defaultCharset()); } @Nonnull private String extractErrorOutAsString() { return new String(this.consoleErrBuffer.toByteArray(), Charset.defaultCharset()); } protected void printLogs(final boolean forcePrint, final boolean errorDetected, @Nonnull final String outLog, @Nonnull final String errLog) { final boolean outLogNotEmpty = !outLog.isEmpty(); final boolean errLogNotEmpty = !errLog.isEmpty(); if (outLogNotEmpty) { if (forcePrint || getLog().isDebugEnabled()) { getLog().info(""); getLog().info("---------Exec.Out---------"); for (final String str : outLog.split("\n")) { getLog().info(StrUtils.trimRight(str)); } getLog().info(""); } else { getLog().debug("There is not any log out from the process"); } } if (errLogNotEmpty) { if (forcePrint) { if (errorDetected) { getLog().error(""); getLog().error("---------Exec.Err---------"); for (final String str : errLog.split("\n")) { getLog().error(StrUtils.trimRight(str)); } getLog().error(""); } else { getLog().warn(""); getLog().warn("---------Exec.Err---------"); for (final String str : errLog.split("\n")) { getLog().warn(StrUtils.trimRight(str)); } getLog().warn(""); } } else { getLog().debug("---------Exec.Err---------"); for (final String str : errLog.split("\n")) { getLog().debug(StrUtils.trimRight(str)); } } } else { getLog().debug("Error log buffer is empty"); } } private void assertProcessResult(@Nonnull final ProcessResult result) throws MojoFailureException { final int code = result.getExitValue(); if (code != 0) { throw new MojoFailureException("Process exit code : " + code); } } public boolean isSourceFolderRequired() { return false; } public boolean isMojoMustNotBeExecuted() throws MojoFailureException { try { return isSourceFolderRequired() && !this.getSources(false).isDirectory(); } catch (IOException ex) { throw new MojoFailureException("Can't check source folder", ex); } } @Nonnull @MustNotContainNull public abstract String[] getTailArguments(); @Nonnull @MustNotContainNull public String[] getOptionalExtraTailArguments() { return ArrayUtils.EMPTY_STRING_ARRAY; } @Nonnull public String makeExecutableFileSubpath() { return getExecSubpath() + File.separatorChar + getExec(); } @Nonnull public abstract String getGoCommand(); @Nonnull @MustNotContainNull public abstract String[] getCommandFlags(); @Nullable private String getEnvPath() { String path = System.getenv("PATH"); if (path == null) { this.getLog().warn("Can't find any defined PATH in environment"); } else { this.getLog().debug("Found env.PATH: " + path); } final boolean filter = this.isFilterEnvPath(); if (path != null) { final StringBuilder buffer = new StringBuilder(); for (final String s : path.split(Pattern.quote(File.pathSeparator))) { if (filter && GOBINFOLDER_PATTERN.matcher(s).find()) { getLog().debug("Removing item '" + s + "' from PATH because it looks like go/bin"); continue; } if (buffer.length() > 0) { buffer.append(File.pathSeparator); } buffer.append(s); getLog().debug("Add item '" + s + "' to PATH"); } path = buffer.toString(); } this.getLog().debug("Prepared PATH var content:" + path); return path; } private void addEnvVar(@Nonnull final ProcessExecutor executor, @Nonnull final String name, @Nonnull final String value) { logOptionally(" $" + name + " = " + value); executor.environment(name, value); } @Nonnull private synchronized HttpClient getHttpClient(@Nullable final ProxySettings proxy) throws MojoExecutionException { if (this.httpClient == null) { final HttpClientBuilder builder = HttpClients.custom(); if (proxy != null) { if (proxy.hasCredentials()) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxy.host, proxy.port), new NTCredentials(GetUtils.ensureNonNull(proxy.username, ""), proxy.password, extractComputerName(), extractDomainName())); builder.setDefaultCredentialsProvider(credentialsProvider); getLog().debug(String .format("Credentials provider has been created for proxy (username : %s): %s", proxy.username, proxy)); } final String[] ignoreForAddresses = proxy.nonProxyHosts == null ? new String[0] : proxy.nonProxyHosts.split("\\|"); final WildCardMatcher[] matchers; if (ignoreForAddresses.length > 0) { matchers = new WildCardMatcher[ignoreForAddresses.length]; for (int i = 0; i < ignoreForAddresses.length; i++) { matchers[i] = new WildCardMatcher(ignoreForAddresses[i]); } } else { matchers = new WildCardMatcher[0]; } getLog().debug("Regular routing mode"); final HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(new HttpHost(proxy.host, proxy.port, proxy.protocol)) { @Override @Nonnull public HttpRoute determineRoute(@Nonnull final HttpHost host, @Nonnull final HttpRequest request, @Nonnull final HttpContext context) throws HttpException { HttpRoute result = null; final String hostName = host.getHostName(); for (final WildCardMatcher m : matchers) { if (m.match(hostName)) { getLog().debug("Ignoring proxy for host : " + hostName); result = new HttpRoute(host); break; } } if (result == null) { result = super.determineRoute(host, request, context); } getLog().debug("Made connection route : " + result); return result; } }; builder.setRoutePlanner(routePlanner); getLog().debug("Proxy will ignore: " + Arrays.toString(matchers)); } builder.setUserAgent("mvn-golang-wrapper-agent/1.0"); builder.disableCookieManagement(); if (this.isDisableSslCheck()) { this.getLog().warn("SSL certificate check is disabled"); try { final SSLContext sslcontext = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override @Nullable @MustNotContainNull public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted( @Nonnull @MustNotContainNull final X509Certificate[] arg0, @Nonnull final String arg1) throws CertificateException { } @Override public void checkServerTrusted( @Nonnull @MustNotContainNull final X509Certificate[] arg0, @Nonnull String arg1) throws CertificateException { } }; sslcontext.init(null, new TrustManager[]{tm}, null); final SSLConnectionSocketFactory sslfactory = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE); final Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslfactory) .register("http", new PlainConnectionSocketFactory()).build(); builder.setConnectionManager(new BasicHttpClientConnectionManager(r)); builder.setSSLSocketFactory(sslfactory); builder.setSSLContext(sslcontext); } catch (final KeyManagementException | NoSuchAlgorithmException ex) { throw new MojoExecutionException("Can't disable SSL certificate check", ex); } } else { this.getLog().debug("SSL check is enabled"); } this.httpClient = builder.build(); } return this.httpClient; } protected void registerOutputBuffers(@Nonnull final ProcessExecutor executor) { executor.redirectOutput(this.consoleOutBuffer); executor.redirectError(this.consoleErrBuffer); } protected void registerEnvVars( @Nonnull final ProcessExecutor result, @Nonnull final File theGoRoot, @Nullable final String theGoBin, @Nullable final String theGoCache, @Nonnull final File sourcesFile, @MustNotContainNull @Nonnull final File[] goPathParts ) throws IOException { logOptionally("....Environment vars...."); addEnvVar(result, "GOROOT", theGoRoot.getAbsolutePath()); this.project.getProperties().setProperty("mvn.golang.last.goroot", theGoRoot.getAbsolutePath()); String preparedGoPath = IOUtils.makeOsFilePathWithoutDuplications(goPathParts); if (isEnforceGoPathToEnd()) { preparedGoPath = IOUtils.makeOsFilePathWithoutDuplications(makePathFromExtraGoPathElements(), removeSrcFolderAtEndIfPresented(sourcesFile.getAbsolutePath()), getSpecialPartOfGoPath(), preparedGoPath); } else { preparedGoPath = IOUtils .makeOsFilePathWithoutDuplications(preparedGoPath, makePathFromExtraGoPathElements(), removeSrcFolderAtEndIfPresented(sourcesFile.getAbsolutePath()), getSpecialPartOfGoPath()); } addEnvVar(result, "GOPATH", preparedGoPath); this.project.getProperties().setProperty("mvn.golang.last.gopath", preparedGoPath); if (theGoBin == null) { getLog().warn("GOBIN is disabled by direct order"); } else { addEnvVar(result, "GOBIN", theGoBin); this.project.getProperties().setProperty("mvn.golang.last.gobin", theGoBin); } if (theGoBin == null) { getLog().warn("GOCACHE is not provided by direct order"); } else { addEnvVar(result, "GOCACHE", theGoCache); this.project.getProperties().setProperty("mvn.golang.last.gocache", theGoCache); } final String trgtOs = this.getTargetOS(); final String trgtArch = this.getTargetArch(); final String trgtArm = this.getTargetArm(); final String trgt386 = this.getTarget386(); if (trgt386 != null) { addEnvVar(result, "GO386", trgt386); this.project.getProperties().setProperty("mvn.golang.last.go386", trgt386); } if (trgtOs != null) { addEnvVar(result, "GOOS", trgtOs); this.project.getProperties().setProperty("mvn.golang.last.goos", trgtOs); } if (trgtArm != null) { addEnvVar(result, "GOARM", trgtArm); this.project.getProperties().setProperty("mvn.golang.last.goarm", trgtArm); } if (trgtArch != null) { addEnvVar(result, "GOARCH", trgtArch); this.project.getProperties().setProperty("mvn.golang.last.goarch", trgtArch); } final File gorootbootstrap = findGoRootBootstrap(true); if (gorootbootstrap != null) { addEnvVar(result, "GOROOT_BOOTSTRAP", gorootbootstrap.getAbsolutePath()); this.project.getProperties() .setProperty("mvn.golang.last.goroot_bootstrap", gorootbootstrap.getAbsolutePath()); } String thePath = GetUtils.ensureNonNull(getEnvPath(), ""); thePath = IOUtils .makeOsFilePathWithoutDuplications((theGoRoot + File.separator + getExecSubpath()), thePath, theGoBin); addEnvVar(result, "PATH", thePath); this.project.getProperties().setProperty("mvn.golang.last.path", thePath); boolean go111moduleDetected = false; for (final Map.Entry<?, ?> record : getEnv().entrySet()) { if (ENV_GO111MODULE.equals(record.getKey().toString())) { go111moduleDetected = true; } addEnvVar(result, record.getKey().toString(), GetUtils.ensureNonNull(record.getValue(),"").toString()); } if (this.isModuleMode()) { if (go111moduleDetected) { this.getLog().warn(String .format("Module mode is true but %s detected among custom environment parameters", ENV_GO111MODULE)); } else { this.getLog().warn( String.format("Forcing '%s = on' because module mode is activated", ENV_GO111MODULE)); addEnvVar(result, ENV_GO111MODULE, "on"); } } } @Nonnull @MustNotContainNull protected List<File> findAllGoModsInFolder(@Nonnull @MustNotContainNull final File folder) throws IOException { return new ArrayList<>(FileUtils .listFiles(folder, FileFilterUtils.nameFileFilter(GO_MOD_FILE_NAME), TrueFileFilter.INSTANCE)); } @Nonnull protected File getWorkingDirectoryForExecutor() throws IOException { final String forcedWorkingDirdir = this.getWorkingDir(); if (forcedWorkingDirdir != null) { final File result = new File(forcedWorkingDirdir); if (!result.isDirectory()) { throw new IOException("Working directory doesn't exist: " + result); } return result; } if (this.isModuleMode()) { final File srcFolder = this.getSources(false); if (srcFolder.isDirectory()) { final List<File> foundGoMods = this.findAllGoModsInFolder(srcFolder); this.getLog().debug(String .format("Detected %d go.mod files in source folder %s", foundGoMods.size(), srcFolder)); foundGoMods.sort(Comparator.comparing(File::toString)); if (foundGoMods.isEmpty()) { this.getLog().error( "Module mode is activated but there is no any go.mod file in the source folder: " + srcFolder); throw new IOException("Can't find any go.mod folder in the source folder: " + srcFolder); } else { final File gomodFolder = foundGoMods.get(0).getParentFile(); this.getLog().info(String .format("Detected module folder '%s' in use as working folder", gomodFolder)); return gomodFolder; } } else { this.getLog().debug("Source folder is not found: " + srcFolder); } } return this.getSources(isSourceFolderRequired()); } /** * Internal method which returns special part of GOPATH which can be formed by * mojos. Must be either empty or contain folders divided by file path * separator. * * @return special part of GOPATH, must not be null, by default must be empty */ @Nonnull protected String getSpecialPartOfGoPath() { return ""; } @Nonnull protected String makePathFromExtraGoPathElements() { String result = ""; if (this.addToGoPath != null) { result = IOUtils.makeOsFilePathWithoutDuplications(this.addToGoPath); } return result; } public boolean isCommandSupportVerbose() { return false; } @Nullable protected String getSkipMojoPropertySuffix() { return null; } @Nullable protected ProcessExecutor prepareExecutor(@Nullable final ProxySettings proxySettings) throws IOException, MojoFailureException, MojoExecutionException { initConsoleBuffers(); final String execNameAdaptedForOs = adaptExecNameForOS(makeExecutableFileSubpath()); final File detectedRoot = findGoRoot(proxySettings); final String gobin = getGoBin(); final String gocache = getGoCache(); final File[] gopathParts = findGoPath(true); if (isMojoMustNotBeExecuted()) { return null; } final String toolName = FilenameUtils.normalize(GetUtils.ensureNonNull(getUseGoTool(), execNameAdaptedForOs)); final File executableFileInPathOrRoot = new File(getPathToFolder(detectedRoot) + toolName); final File executableFileInBin = gobin == null ? null : new File(getPathToFolder(gobin) + adaptExecNameForOS(getExec())); final File[] exeVariants = new File[]{executableFileInBin, executableFileInPathOrRoot}; final File foundExecutableTool = findExisting(exeVariants); if (foundExecutableTool == null) { throw new MojoFailureException( "Can't find executable file : " + Arrays.toString(exeVariants)); } else { logOptionally("Executable file detected : " + foundExecutableTool); } final List<String> commandLine = new ArrayList<>(); commandLine.add(foundExecutableTool.getAbsolutePath()); final String gocommand = getGoCommand(); if (!gocommand.isEmpty()) { commandLine.add(getGoCommand()); } boolean verboseAdded = false; for (final String s : getCommandFlags()) { if (s.equals("-v")) { verboseAdded = true; } commandLine.add(s); } if (this.isVerbose() && !verboseAdded && isCommandSupportVerbose()) { commandLine.add("-v"); } commandLine.addAll(Arrays.asList(getBuildFlags())); commandLine.addAll(Arrays.asList(getTailArguments())); commandLine.addAll(Arrays.asList(getOptionalExtraTailArguments())); final StringBuilder cli = new StringBuilder(); int index = 0; for (final String s : commandLine) { if (cli.length() > 0) { cli.append(' '); } if (index == 0) { cli.append(execNameAdaptedForOs); } else { cli.append(s); } index++; } getLog().info(String.format("Prepared command line : %s", cli)); final ProcessExecutor result = new ProcessExecutor(commandLine); final File workingDirectory = this.getWorkingDirectoryForExecutor(); if (workingDirectory.isDirectory()) { logOptionally("Working directory: " + workingDirectory); result.directory(workingDirectory); } else { logOptionally("Working directory is not set because provided folder doesn't exist: " + workingDirectory); } logOptionally(""); registerEnvVars(result, detectedRoot, gobin, gocache, this.getSources(this.isSourceFolderRequired()), gopathParts); logOptionally("........................"); registerOutputBuffers(result); return result; } private void processLogFiles(@Nonnull final String logOut, @Nonnull final String logErr) throws MojoExecutionException { final File reportsFolderFile = new File(this.getReportsFolder()); final String targetOutFileName = nullIfBlank(this.getOutLogFile()); final String targetErrFileName = nullIfBlank(this.getErrLogFile()); if (targetErrFileName != null ^ targetOutFileName != null) { if (targetOutFileName == null && !logOut.isEmpty()) { this.getLog().warn("File logging for ERR stream is ON but also detected text in output stream!"); } if (targetErrFileName == null && !logErr.isEmpty()) { this.getLog().warn("File logging for OUT stream is ON but also detected text in error stream!"); } } this.getLog().debug("log.file.out: " + targetOutFileName); this.getLog().debug("log.file.err: " + targetErrFileName); final File targetOutFile = targetOutFileName == null ? null : new File(reportsFolderFile, targetOutFileName); final File targetErrFile = targetErrFileName == null ? null : new File(reportsFolderFile, targetErrFileName); if (targetOutFile == null) { this.getLog().debug("Log file to write output stream is not set"); } else { getLog().debug("Reports folder : " + reportsFolderFile); if (!reportsFolderFile.isDirectory() && !reportsFolderFile.mkdirs()) { throw new MojoExecutionException( "Can't create folder for console logs : " + reportsFolderFile); } try { getLog().debug("Writing " + logOut.length() + " chars as output console log : " + targetOutFile); FileUtils.write(targetOutFile, logOut, "UTF-8"); } catch (IOException ex) { throw new MojoExecutionException( "Can't save console output log into file : " + targetOutFile, ex); } } if (targetErrFile == null) { this.getLog().debug("Log file to write error stream is not set"); } else { getLog().debug("Reports folder : " + reportsFolderFile); if (!reportsFolderFile.isDirectory() && !reportsFolderFile.mkdirs()) { throw new MojoExecutionException( "Can't create folder for console logs : " + reportsFolderFile); } try { getLog().debug("Writing " + logErr.length() + " chars as error console log : " + targetErrFile); FileUtils.write(targetErrFile, logErr, "UTF-8"); } catch (IOException ex) { throw new MojoExecutionException( "Can't save console error log into file : " + targetErrFile, ex); } } } }
raydac/mvn-golang
mvn-golang-wrapper/src/main/java/com/igormaznitsa/mvngolang/AbstractGolangMojo.java
Java
apache-2.0
76,810