code
stringlengths
4
1.01M
language
stringclasses
2 values
/* * Kendo UI Web v2014.1.318 (http://kendoui.com) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI Web commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-web * If you do not own a commercial license, this file shall be governed by the * GNU General Public License (GPL) version 3. * For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["nn"] = { name: "nn", numberFormat: { pattern: ["-n"], decimals: 2, ",": " ", ".": ",", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "%" }, currency: { pattern: ["$ -n","$ n"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "kr" } }, calendars: { standard: { days: { names: ["søndag","måndag","tysdag","onsdag","torsdag","fredag","laurdag"], namesAbbr: ["sø","må","ty","on","to","fr","la"], namesShort: ["sø","må","ty","on","to","fr","la"] }, months: { names: ["januar","februar","mars","april","mai","juni","juli","august","september","oktober","november","desember",""], namesAbbr: ["jan","feb","mar","apr","mai","jun","jul","aug","sep","okt","nov","des",""] }, AM: [""], PM: [""], patterns: { d: "dd.MM.yyyy", D: "d. MMMM yyyy", F: "d. MMMM yyyy HH:mm:ss", g: "dd.MM.yyyy HH:mm", G: "dd.MM.yyyy HH:mm:ss", m: "d. MMMM", M: "d. MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": ".", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
Java
using System; using System.Text; using System.Threading.Tasks; using Foundatio.Extensions; namespace Foundatio.Serializer { public interface ISerializer { Task<object> DeserializeAsync(byte[] data, Type objectType); Task<byte[]> SerializeAsync(object value); } public static class SerializerExtensions { public static Task<object> DeserializeAsync(this ISerializer serializer, string data, Type objectType) { return serializer.DeserializeAsync(Encoding.UTF8.GetBytes(data ?? String.Empty), objectType); } public static async Task<T> DeserializeAsync<T>(this ISerializer serializer, byte[] data) { return (T)await serializer.DeserializeAsync(data, typeof(T)).AnyContext(); } public static Task<T> DeserializeAsync<T>(this ISerializer serializer, string data) { return DeserializeAsync<T>(serializer, Encoding.UTF8.GetBytes(data ?? String.Empty)); } public static async Task<string> SerializeToStringAsync(this ISerializer serializer, object value) { if (value == null) return null; return Encoding.UTF8.GetString(await serializer.SerializeAsync(value).AnyContext()); } } }
Java
package ec2 import ( "github.com/crowdmob/goamz/aws" "time" ) func Sign(auth aws.Auth, method, path string, params map[string]string, host string) { sign(auth, method, path, params, host) } func fixedTime() time.Time { return time.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC) } func FakeTime(fakeIt bool) { if fakeIt { timeNow = fixedTime } else { timeNow = time.Now } }
Java
\section{File List} Here is a list of all files with brief descriptions\-:\begin{DoxyCompactList} \item\contentsline{section}{build/catkin\-\_\-generated/\hyperlink{generate__cached__setup_8py}{generate\-\_\-cached\-\_\-setup.\-py} }{\pageref{generate__cached__setup_8py}}{} \item\contentsline{section}{build/catkin\-\_\-generated/\hyperlink{order__packages_8py}{order\-\_\-packages.\-py} }{\pageref{order__packages_8py}}{} \item\contentsline{section}{build/catkin\-\_\-generated/installspace/\hyperlink{build_2catkin__generated_2installspace_2__setup__util_8py}{\-\_\-setup\-\_\-util.\-py} }{\pageref{build_2catkin__generated_2installspace_2__setup__util_8py}}{} \item\contentsline{section}{build/\-C\-Make\-Files/2.\-8.\-12.\-2/\-Compiler\-Id\-C/\hyperlink{CMakeCCompilerId_8c}{C\-Make\-C\-Compiler\-Id.\-c} }{\pageref{CMakeCCompilerId_8c}}{} \item\contentsline{section}{build/\-C\-Make\-Files/2.\-8.\-12.\-2/\-Compiler\-Id\-C\-X\-X/\hyperlink{CMakeCXXCompilerId_8cpp}{C\-Make\-C\-X\-X\-Compiler\-Id.\-cpp} }{\pageref{CMakeCXXCompilerId_8cpp}}{} \item\contentsline{section}{build/nubot\-\_\-common/catkin\-\_\-generated/\hyperlink{nubot__common_2catkin__generated_2pkg_8develspace_8context_8pc_8py}{pkg.\-develspace.\-context.\-pc.\-py} }{\pageref{nubot__common_2catkin__generated_2pkg_8develspace_8context_8pc_8py}}{} \item\contentsline{section}{build/nubot\-\_\-common/catkin\-\_\-generated/\hyperlink{nubot__common_2catkin__generated_2pkg_8installspace_8context_8pc_8py}{pkg.\-installspace.\-context.\-pc.\-py} }{\pageref{nubot__common_2catkin__generated_2pkg_8installspace_8context_8pc_8py}}{} \item\contentsline{section}{build/nubot\-\_\-common/cmake/\hyperlink{nubot__common-genmsg-context_8py}{nubot\-\_\-common-\/genmsg-\/context.\-py} }{\pageref{nubot__common-genmsg-context_8py}}{} \item\contentsline{section}{build/nubot\-\_\-simulation/nubot\-\_\-description/catkin\-\_\-generated/\hyperlink{nubot__simulation_2nubot__description_2catkin__generated_2pkg_8develspace_8context_8pc_8py}{pkg.\-develspace.\-context.\-pc.\-py} }{\pageref{nubot__simulation_2nubot__description_2catkin__generated_2pkg_8develspace_8context_8pc_8py}}{} \item\contentsline{section}{build/nubot\-\_\-simulation/nubot\-\_\-description/catkin\-\_\-generated/\hyperlink{nubot__simulation_2nubot__description_2catkin__generated_2pkg_8installspace_8context_8pc_8py}{pkg.\-installspace.\-context.\-pc.\-py} }{\pageref{nubot__simulation_2nubot__description_2catkin__generated_2pkg_8installspace_8context_8pc_8py}}{} \item\contentsline{section}{build/nubot\-\_\-simulation/nubot\-\_\-gazebo/catkin\-\_\-generated/\hyperlink{nubot__simulation_2nubot__gazebo_2catkin__generated_2pkg_8develspace_8context_8pc_8py}{pkg.\-develspace.\-context.\-pc.\-py} }{\pageref{nubot__simulation_2nubot__gazebo_2catkin__generated_2pkg_8develspace_8context_8pc_8py}}{} \item\contentsline{section}{build/nubot\-\_\-simulation/nubot\-\_\-gazebo/catkin\-\_\-generated/\hyperlink{nubot__simulation_2nubot__gazebo_2catkin__generated_2pkg_8installspace_8context_8pc_8py}{pkg.\-installspace.\-context.\-pc.\-py} }{\pageref{nubot__simulation_2nubot__gazebo_2catkin__generated_2pkg_8installspace_8context_8pc_8py}}{} \item\contentsline{section}{devel/\hyperlink{devel_2__setup__util_8py}{\-\_\-setup\-\_\-util.\-py} }{\pageref{devel_2__setup__util_8py}}{} \item\contentsline{section}{devel/include/nubot\-\_\-common/\hyperlink{BallHandle_8h}{Ball\-Handle.\-h} }{\pageref{BallHandle_8h}}{} \item\contentsline{section}{devel/include/nubot\-\_\-common/\hyperlink{BallHandleRequest_8h}{Ball\-Handle\-Request.\-h} }{\pageref{BallHandleRequest_8h}}{} \item\contentsline{section}{devel/include/nubot\-\_\-common/\hyperlink{BallHandleResponse_8h}{Ball\-Handle\-Response.\-h} }{\pageref{BallHandleResponse_8h}}{} \item\contentsline{section}{devel/include/nubot\-\_\-common/\hyperlink{Shoot_8h}{Shoot.\-h} }{\pageref{Shoot_8h}}{} \item\contentsline{section}{devel/include/nubot\-\_\-common/\hyperlink{ShootRequest_8h}{Shoot\-Request.\-h} }{\pageref{ShootRequest_8h}}{} \item\contentsline{section}{devel/include/nubot\-\_\-common/\hyperlink{ShootResponse_8h}{Shoot\-Response.\-h} }{\pageref{ShootResponse_8h}}{} \item\contentsline{section}{devel/include/nubot\-\_\-common/\hyperlink{VelCmd_8h}{Vel\-Cmd.\-h} }{\pageref{VelCmd_8h}}{} \item\contentsline{section}{devel/include/nubot\-\_\-gazebo/\hyperlink{NubotGazeboConfig_8h}{Nubot\-Gazebo\-Config.\-h} }{\pageref{NubotGazeboConfig_8h}}{} \item\contentsline{section}{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-common/\hyperlink{nubot__common_2____init_____8py}{\-\_\-\-\_\-init\-\_\-\-\_\-.\-py} }{\pageref{nubot__common_2____init_____8py}}{} \item\contentsline{section}{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-common/msg/\hyperlink{nubot__common_2msg_2____init_____8py}{\-\_\-\-\_\-init\-\_\-\-\_\-.\-py} }{\pageref{nubot__common_2msg_2____init_____8py}}{} \item\contentsline{section}{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-common/msg/\hyperlink{__VelCmd_8py}{\-\_\-\-Vel\-Cmd.\-py} }{\pageref{__VelCmd_8py}}{} \item\contentsline{section}{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-common/srv/\hyperlink{nubot__common_2srv_2____init_____8py}{\-\_\-\-\_\-init\-\_\-\-\_\-.\-py} }{\pageref{nubot__common_2srv_2____init_____8py}}{} \item\contentsline{section}{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-common/srv/\hyperlink{__BallHandle_8py}{\-\_\-\-Ball\-Handle.\-py} }{\pageref{__BallHandle_8py}}{} \item\contentsline{section}{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-common/srv/\hyperlink{__Shoot_8py}{\-\_\-\-Shoot.\-py} }{\pageref{__Shoot_8py}}{} \item\contentsline{section}{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-gazebo/\hyperlink{nubot__gazebo_2____init_____8py}{\-\_\-\-\_\-init\-\_\-\-\_\-.\-py} }{\pageref{nubot__gazebo_2____init_____8py}}{} \item\contentsline{section}{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-gazebo/cfg/\hyperlink{nubot__gazebo_2cfg_2____init_____8py}{\-\_\-\-\_\-init\-\_\-\-\_\-.\-py} }{\pageref{nubot__gazebo_2cfg_2____init_____8py}}{} \item\contentsline{section}{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-gazebo/cfg/\hyperlink{NubotGazeboConfig_8py}{Nubot\-Gazebo\-Config.\-py} }{\pageref{NubotGazeboConfig_8py}}{} \item\contentsline{section}{src/nubot\-\_\-common/core/include/nubot/core/\hyperlink{Angle_8hpp}{Angle.\-hpp} }{\pageref{Angle_8hpp}}{} \item\contentsline{section}{src/nubot\-\_\-common/core/include/nubot/core/\hyperlink{Circle_8hpp}{Circle.\-hpp} }{\pageref{Circle_8hpp}}{} \item\contentsline{section}{src/nubot\-\_\-common/core/include/nubot/core/\hyperlink{core_8hpp}{core.\-hpp} }{\pageref{core_8hpp}}{} \item\contentsline{section}{src/nubot\-\_\-common/core/include/nubot/core/\hyperlink{DPoint_8hpp}{D\-Point.\-hpp} }{\pageref{DPoint_8hpp}}{} \item\contentsline{section}{src/nubot\-\_\-common/core/include/nubot/core/\hyperlink{Line_8hpp}{Line.\-hpp} }{\pageref{Line_8hpp}}{} \item\contentsline{section}{src/nubot\-\_\-common/core/include/nubot/core/\hyperlink{PPoint_8hpp}{P\-Point.\-hpp} }{\pageref{PPoint_8hpp}}{} \item\contentsline{section}{src/nubot\-\_\-common/core/include/nubot/core/\hyperlink{time_8hpp}{time.\-hpp} }{\pageref{time_8hpp}}{} \item\contentsline{section}{src/nubot\-\_\-simulation/nubot\-\_\-gazebo/plugins/\hyperlink{nubot__gazebo_8cc}{nubot\-\_\-gazebo.\-cc} }{\pageref{nubot__gazebo_8cc}}{} \item\contentsline{section}{src/nubot\-\_\-simulation/nubot\-\_\-gazebo/plugins/\hyperlink{nubot__gazebo_8hh}{nubot\-\_\-gazebo.\-hh} }{\pageref{nubot__gazebo_8hh}}{} \item\contentsline{section}{src/nubot\-\_\-simulation/nubot\-\_\-gazebo/plugins/\hyperlink{nubot__PID_8cc}{nubot\-\_\-\-P\-I\-D.\-cc} }{\pageref{nubot__PID_8cc}}{} \item\contentsline{section}{src/nubot\-\_\-simulation/nubot\-\_\-gazebo/plugins/\hyperlink{nubot__PID_8hh}{nubot\-\_\-\-P\-I\-D.\-hh} }{\pageref{nubot__PID_8hh}}{} \item\contentsline{section}{src/nubot\-\_\-simulation/nubot\-\_\-gazebo/plugins/\hyperlink{nubot__teleop__keyboard_8cc}{nubot\-\_\-teleop\-\_\-keyboard.\-cc} }{\pageref{nubot__teleop__keyboard_8cc}}{} \item\contentsline{section}{src/nubot\-\_\-simulation/nubot\-\_\-gazebo/plugins/\hyperlink{nubot__teleop__keyboard_8hh}{nubot\-\_\-teleop\-\_\-keyboard.\-hh} }{\pageref{nubot__teleop__keyboard_8hh}}{} \item\contentsline{section}{src/nubot\-\_\-simulation/nubot\-\_\-gazebo/plugins/\hyperlink{parabolic__transition__planning_8cc}{parabolic\-\_\-transition\-\_\-planning.\-cc} }{\pageref{parabolic__transition__planning_8cc}}{} \item\contentsline{section}{src/nubot\-\_\-simulation/nubot\-\_\-gazebo/plugins/\hyperlink{parabolic__transition__planning_8hh}{parabolic\-\_\-transition\-\_\-planning.\-hh} }{\pageref{parabolic__transition__planning_8hh}}{} \item\contentsline{section}{src/nubot\-\_\-simulation/nubot\-\_\-gazebo/plugins/\hyperlink{vector__angle_8hh}{vector\-\_\-angle.\-hh} }{\pageref{vector__angle_8hh}}{} \end{DoxyCompactList}
Java
// Copyright 2017, Dell EMC, Inc. /* jshint node:true */ 'use strict'; describe(require('path').basename(__filename), function () { var base = require('./base-task-data-spec'); base.before(function (context) { context.taskdefinition = helper.require( '/lib/task-data/base-tasks/dell-wsman-reset-components.js' ); }); describe('task-data', function () { base.examples(); }); });
Java
/* * Copyright (C) FuseSource, Inc. * http://fusesource.com * * 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.fusesource.fabric.monitor.internal import scala.collection.mutable.HashMap import org.rrd4j.ConsolFun._ import org.rrd4j.core._ import org.rrd4j.DsType._ import java.util.concurrent.atomic.AtomicBoolean import org.rrd4j.core.Util import org.linkedin.util.clock.Timespan import java.io.File import java.{util => ju} import FileSupport._ import collection.JavaConversions._ import org.fusesource.scalate.util.Log import org.fusesource.fabric.monitor.api._ import scala.Some object DefaultMonitor { val log = Log(classOf[DefaultMonitor]) } import DefaultMonitor._ /** * <p> * </p> * * @author <a href="http://hiramchirino.com">Hiram Chirino</a> */ class DefaultMonitor ( val rrd_file_prefix:String="", val rrd_backend:RrdBackendFactory = new RrdNioBackendFactory() ) extends Monitor { var step_duration = 1000L def path_to_rrd_file(name:String) = rrd_file_prefix + name +".rrd" case class MonitoredSet(dto:MonitoredSetDTO) { import dto._ import collection.JavaConversions._ val sample_span = Timespan.parse(dto.step) val sources = { var source_counter = 0 ; (dto.data_sources.map { source => // rrd ids are limitied to 20 chars... lets do the best we can: var rrd_id = "%x:".format(source_counter) // Use the right most part of the id as it's usually the most specific rrd_id += source.id.takeRight(20-rrd_id.length) source_counter += 1 (rrd_id, source) }).toMap } def file_base_name: String = { rrd_file_prefix + name } val rrd_file_name = path_to_rrd_file(name) val rrd_archive_funcs = dto.archives.map(_.consolidation toUpperCase match { case "AVERAGE" => AVERAGE case "MIN" => MIN case "MAX" => MAX case "LAST" => LAST case "FIRST" => FIRST case "TOTAL" => TOTAL }).toSet val rrd_def = { log.info("Creating RRD file to: " + rrd_file_name) val rc = new RrdDef(rrd_file_name, sample_span.getDurationInSeconds) sources.foreach { case (rrd_id, source) => import source._ val steps = Option(heartbeat).map( x => Timespan.parse(x).getDuration(Timespan.TimeUnit.SECOND) ).getOrElse(2 * sample_span.getDuration(Timespan.TimeUnit.SECOND)) rc.addDatasource(rrd_id, kind.toUpperCase match { case "GAUGE" => GAUGE case "COUNTER" => COUNTER case "DERIVE" => DERIVE case "ABSOLUTE" => ABSOLUTE }, steps, min, max); } archives.foreach { archive => import archive._ val archive_span = Option(step).map(Timespan.parse(_)).getOrElse(sample_span) val steps = (archive_span.getDurationInMilliseconds / sample_span.getDurationInMilliseconds).toInt val total_span = Timespan.parse(window) val rows = (total_span.getDurationInMilliseconds / archive_span.getDurationInMilliseconds).toInt val consolFun = consolidation.toUpperCase match { case "AVERAGE" => AVERAGE case "MIN" => MIN case "MAX" => MAX case "LAST" => LAST case "FIRST" => FIRST case "TOTAL" => TOTAL } rc.addArchive(consolFun, xff, steps, rows); } rc } var pollers = List[(String, Poller)]() var thread:Thread = _ var active = new AtomicBoolean() def start = { if( active.compareAndSet(false, true) ) { new File(file_base_name+".json").write_bytes(JsonCodec.encode(dto)) thread = new Thread("Monitoring: "+name) { setDaemon(true) override def run: Unit = { val sources_by_factory = HashMap[PollerFactory, List[(String, DataSourceDTO)]]() sources.foreach { case (rrd_id, source) => poller_factories.find(_.accepts(source)).foreach { factory => val sources = sources_by_factory.getOrElseUpdate(factory, Nil) sources_by_factory.put(factory, (rrd_id, source)::sources) } } pollers = { sources_by_factory.flatMap{ case (factory, sources)=> sources.map{ case (rrd_id, source) => (rrd_id, factory.create(source)) } } }.toList val rrd_db = new RrdDb(rrd_def, rrd_backend); try { while(active.get) { val sample = rrd_db.createSample() sample.setTime(Util.getTime()) val start = System.currentTimeMillis() // log.info("Collecting samples from %d pollers.".format(pollers.size)) pollers.foreach { case (rrd_id, poller) => val result = poller.poll sample.setValue(rrd_id, result) } // log.info("Collected sample: "+sample.dump) sample.update(); // Sleep until we need to poll again. def remaining = (start + (step_duration * sample_span.getDurationInSeconds)) - System.currentTimeMillis() var r = remaining while( r > 0 ) { Thread.sleep( r ) r = remaining } } } finally { rrd_db.close } } } thread.start() } } def stop = { if( active.compareAndSet(true, false) ) { thread.join thread = null } } } val current_monitored_sets = HashMap [String, MonitoredSet]() // TODO: if the poller_factories gets changed, we should // recreate the current_monitored_sets as there may be more or less // data sources that we can gather data for. var poller_factories:Seq[PollerFactory] = Nil def configure(value: Traversable[MonitoredSetDTO]): Unit = this.synchronized { val next_services = Map[String, MonitoredSet]( value.map { dto=> dto.name -> MonitoredSet(dto) }.toSeq : _*) // Figure out which services are being added, removed, or updated. val existing_keys = current_monitored_sets.keys.toSet val next_service_keys = next_services.keys.toSet val updating = existing_keys.intersect(next_service_keys) val adding = next_service_keys -- updating val removing = existing_keys -- next_service_keys adding.foreach { id => val next = next_services.get(id).get next.start current_monitored_sets += id -> next } updating.foreach { id => val next = next_services.get(id).get val prev = current_monitored_sets.get(id).get // did the service configuration change? if( next != prev ) { prev.stop next.start current_monitored_sets.put(id, next) } } removing.foreach{ id => val prev = current_monitored_sets.remove(id).get prev.stop } } def close: Unit = { } def fetch(fetch: FetchMonitoredViewDTO):Option[MonitoredViewDTO] = this.synchronized { val monitored_set_id = fetch.monitored_set val ids = fetch.data_sources val consolidations = fetch.consolidations val start = fetch.start val end = fetch.end val step = fetch.step val monitored_set = current_monitored_sets.get(monitored_set_id) match { case Some(x) => x case None => return None } val rrd_db = new RrdDb(monitored_set.rrd_file_name, true, rrd_backend); try { val rc = new MonitoredViewDTO rc.start = start rc.end = end rc.step = step if( rc.step == 0 ) { rc.step = 1 } if( rc.end == 0 ) { rc.end = Util.getTime-1 } if( rc.start == 0 ) { rc.start = rc.end - (rc.step*60*5) } monitored_set.rrd_archive_funcs.foreach { consol_fun => if( consolidations == null || consolidations.size == 0 || consolidations.contains(consol_fun) ) { val request = rrd_db.createFetchRequest(consol_fun, rc.start, rc.end, rc.step) if ( ids !=null && !ids.isEmpty ) { // Map DS ids to rrd_ids so that we only fetch the requested data... val filter: ju.Set[String] = setAsJavaSet(monitored_set.sources.flatMap { case (rrd_id, source) => if (ids.contains(source.id)) { Some(rrd_id) } else { None } }.toSet) request.setFilter(filter) } val data = request.fetchData(); for( rrd_id <- data.getDsNames ) { val t = new DataSourceViewDTO t.id = rrd_id t.label = rrd_id t.description = "" // we can probably get better values from // the data source dto for( dto <- monitored_set.sources.get(rrd_id) ) { t.id = dto.id t.label = Option(dto.name)getOrElse(t.id) t.description = Option(dto.description).getOrElse("") } rc.data_sources.add(t) t.consolidation = consol_fun.toString t.data = data.getValues(rrd_id) } // lets reorder the data so it matches the order it was // requested in.. if ( ids !=null && !ids.isEmpty ) { val sources = rc.data_sources.map( x=> (x.id, x) ).toMap rc.data_sources = ids.flatMap(id => sources.get(id)) } } } Some(rc) } finally { rrd_db.close() } } def list: Array[MonitoredSetDTO] = this.synchronized { current_monitored_sets.values.map(_.dto).toArray } }
Java
/* Copyright 2017 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. ==============================================================================*/ #ifndef TENSORFLOW_COMPILER_XLA_SERVICE_GPU_COPY_THUNK_H_ #define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_COPY_THUNK_H_ #include "tensorflow/compiler/xla/service/buffer_assignment.h" #include "tensorflow/compiler/xla/service/gpu/buffer_allocations.h" #include "tensorflow/compiler/xla/service/gpu/thunk.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/core/platform/stream_executor_no_cuda.h" #include "tensorflow/core/platform/types.h" namespace xla { namespace gpu { // A thunk that copies data from a host buffer to a device buffer. class HostToDeviceCopyThunk : public Thunk { public: // Constructs a CopyThunk that copies host data from `source_address` to the // device buffer `destination_buffer`. `mem_size` is the size of the data in // bytes. HostToDeviceCopyThunk(ThunkInfo thunk_info, const void* source_address, const BufferAllocation::Slice& destination_buffer, uint64 mem_size); HostToDeviceCopyThunk(const HostToDeviceCopyThunk&) = delete; HostToDeviceCopyThunk& operator=(const HostToDeviceCopyThunk&) = delete; Status ExecuteOnStream(const ExecuteParams& params) override; private: const void* source_address_; const BufferAllocation::Slice destination_buffer_; const uint64 mem_size_; }; // A thunk that copies data from a device buffer to another device buffer. class DeviceToDeviceCopyThunk : public Thunk { public: // Constructs a CopyThunk that copies host data from `source_buffer` to the // device buffer `destination_buffer`. `mem_size` is the size of the data in // bytes. DeviceToDeviceCopyThunk(ThunkInfo thunk_info, const BufferAllocation::Slice& source_buffer, const BufferAllocation::Slice& destination_buffer, uint64 mem_size); DeviceToDeviceCopyThunk(const DeviceToDeviceCopyThunk&) = delete; DeviceToDeviceCopyThunk& operator=(const DeviceToDeviceCopyThunk&) = delete; Status ExecuteOnStream(const ExecuteParams& params) override; private: const BufferAllocation::Slice source_buffer_; const BufferAllocation::Slice destination_buffer_; const uint64 mem_size_; }; } // namespace gpu } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_SERVICE_GPU_COPY_THUNK_H_
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using RestSharp.Deserializers; namespace Twilio { public class IpAddress : TwilioBase { public string Sid { get; set; } public string FriendlyName { get; set; } [DeserializeAs(Name="IpAddress")] public string Address { get; set; } } }
Java
package provision import ( "bytes" "fmt" "io/ioutil" "net/url" "path" "path/filepath" "strconv" "strings" log "github.com/Sirupsen/logrus" "github.com/docker/machine/libmachine/auth" "github.com/docker/machine/libmachine/provision/pkgaction" "github.com/docker/machine/libmachine/swarm" "github.com/docker/machine/utils" ) type DockerOptions struct { EngineOptions string EngineOptionsPath string } func installDockerGeneric(p Provisioner) error { // install docker - until cloudinit we use ubuntu everywhere so we // just install it using the docker repos if output, err := p.SSHCommand("if ! type docker; then curl -sSL https://get.docker.com | sh -; fi"); err != nil { var buf bytes.Buffer if _, err := buf.ReadFrom(output.Stderr); err != nil { return err } return fmt.Errorf("error installing docker: %s\n", buf.String()) } return nil } func ConfigureAuth(p Provisioner, authOptions auth.AuthOptions) error { var ( err error ) machineName := p.GetDriver().GetMachineName() org := machineName bits := 2048 ip, err := p.GetDriver().GetIP() if err != nil { return err } // copy certs to client dir for docker client machineDir := filepath.Join(utils.GetMachineDir(), machineName) if err := utils.CopyFile(authOptions.CaCertPath, filepath.Join(machineDir, "ca.pem")); err != nil { log.Fatalf("Error copying ca.pem to machine dir: %s", err) } if err := utils.CopyFile(authOptions.ClientCertPath, filepath.Join(machineDir, "cert.pem")); err != nil { log.Fatalf("Error copying cert.pem to machine dir: %s", err) } if err := utils.CopyFile(authOptions.ClientKeyPath, filepath.Join(machineDir, "key.pem")); err != nil { log.Fatalf("Error copying key.pem to machine dir: %s", err) } log.Debugf("generating server cert: %s ca-key=%s private-key=%s org=%s", authOptions.ServerCertPath, authOptions.CaCertPath, authOptions.PrivateKeyPath, org, ) // TODO: Switch to passing just authOptions to this func // instead of all these individual fields err = utils.GenerateCert( []string{ip}, authOptions.ServerCertPath, authOptions.ServerKeyPath, authOptions.CaCertPath, authOptions.PrivateKeyPath, org, bits, ) if err != nil { return fmt.Errorf("error generating server cert: %s", err) } if err := p.Service("docker", pkgaction.Stop); err != nil { return err } dockerDir := p.GetDockerOptionsDir() if _, err := p.SSHCommand(fmt.Sprintf("sudo mkdir -p %s", dockerDir)); err != nil { return err } // upload certs and configure TLS auth caCert, err := ioutil.ReadFile(authOptions.CaCertPath) if err != nil { return err } // due to windows clients, we cannot use filepath.Join as the paths // will be mucked on the linux hosts machineCaCertPath := path.Join(dockerDir, "ca.pem") authOptions.CaCertRemotePath = machineCaCertPath serverCert, err := ioutil.ReadFile(authOptions.ServerCertPath) if err != nil { return err } machineServerCertPath := path.Join(dockerDir, "server.pem") authOptions.ServerCertRemotePath = machineServerCertPath serverKey, err := ioutil.ReadFile(authOptions.ServerKeyPath) if err != nil { return err } machineServerKeyPath := path.Join(dockerDir, "server-key.pem") authOptions.ServerKeyRemotePath = machineServerKeyPath if _, err = p.SSHCommand(fmt.Sprintf("echo \"%s\" | sudo tee %s", string(caCert), machineCaCertPath)); err != nil { return err } if _, err = p.SSHCommand(fmt.Sprintf("echo \"%s\" | sudo tee %s", string(serverKey), machineServerKeyPath)); err != nil { return err } if _, err = p.SSHCommand(fmt.Sprintf("echo \"%s\" | sudo tee %s", string(serverCert), machineServerCertPath)); err != nil { return err } dockerUrl, err := p.GetDriver().GetURL() if err != nil { return err } u, err := url.Parse(dockerUrl) if err != nil { return err } dockerPort := 2376 parts := strings.Split(u.Host, ":") if len(parts) == 2 { dPort, err := strconv.Atoi(parts[1]) if err != nil { return err } dockerPort = dPort } dkrcfg, err := p.GenerateDockerOptions(dockerPort, authOptions) if err != nil { return err } if _, err = p.SSHCommand(fmt.Sprintf("echo \"%s\" | sudo tee -a %s", dkrcfg.EngineOptions, dkrcfg.EngineOptionsPath)); err != nil { return err } if err := p.Service("docker", pkgaction.Start); err != nil { return err } return nil } func getDefaultDaemonOpts(driverName string, authOptions auth.AuthOptions) string { return fmt.Sprintf(`--tlsverify --tlscacert=%s --tlskey=%s --tlscert=%s %s`, authOptions.CaCertRemotePath, authOptions.ServerKeyRemotePath, authOptions.ServerCertRemotePath, fmt.Sprintf("--label=provider=%s", driverName), ) } func configureSwarm(p Provisioner, swarmOptions swarm.SwarmOptions) error { if !swarmOptions.IsSwarm { return nil } basePath := p.GetDockerOptionsDir() ip, err := p.GetDriver().GetIP() if err != nil { return err } tlsCaCert := path.Join(basePath, "ca.pem") tlsCert := path.Join(basePath, "server.pem") tlsKey := path.Join(basePath, "server-key.pem") masterArgs := fmt.Sprintf("--tlsverify --tlscacert=%s --tlscert=%s --tlskey=%s -H %s %s", tlsCaCert, tlsCert, tlsKey, swarmOptions.Host, swarmOptions.Discovery) nodeArgs := fmt.Sprintf("--addr %s:2376 %s", ip, swarmOptions.Discovery) u, err := url.Parse(swarmOptions.Host) if err != nil { return err } parts := strings.Split(u.Host, ":") port := parts[1] // TODO: Do not hardcode daemon port, ask the driver if err := utils.WaitForDocker(ip, 2376); err != nil { return err } if _, err := p.SSHCommand(fmt.Sprintf("sudo docker pull %s", swarm.DockerImage)); err != nil { return err } dockerDir := p.GetDockerOptionsDir() // if master start master agent if swarmOptions.Master { log.Debug("launching swarm master") log.Debugf("master args: %s", masterArgs) if _, err = p.SSHCommand(fmt.Sprintf("sudo docker run -d -p %s:%s --restart=always --name swarm-agent-master -v %s:%s %s manage %s", port, port, dockerDir, dockerDir, swarm.DockerImage, masterArgs)); err != nil { return err } } // start node agent log.Debug("launching swarm node") log.Debugf("node args: %s", nodeArgs) if _, err = p.SSHCommand(fmt.Sprintf("sudo docker run -d --restart=always --name swarm-agent -v %s:%s %s join %s", dockerDir, dockerDir, swarm.DockerImage, nodeArgs)); err != nil { return err } return nil }
Java
/* * Copyright (c) 2018 Makaio GmbH * * SPDX-License-Identifier: Apache-2.0 */ #include <shell/shell_rtt.h> #include <init.h> #include <SEGGER_RTT.h> #include <logging/log.h> BUILD_ASSERT_MSG(!(IS_ENABLED(CONFIG_LOG_BACKEND_RTT) && COND_CODE_0(CONFIG_LOG_BACKEND_RTT_BUFFER, (1), (0))), "Conflicting log RTT backend enabled on the same channel"); SHELL_RTT_DEFINE(shell_transport_rtt); SHELL_DEFINE(shell_rtt, CONFIG_SHELL_PROMPT_RTT, &shell_transport_rtt, CONFIG_SHELL_BACKEND_RTT_LOG_MESSAGE_QUEUE_SIZE, CONFIG_SHELL_BACKEND_RTT_LOG_MESSAGE_QUEUE_TIMEOUT, SHELL_FLAG_OLF_CRLF); LOG_MODULE_REGISTER(shell_rtt, CONFIG_SHELL_RTT_LOG_LEVEL); static bool rtt_blocking; static void timer_handler(struct k_timer *timer) { const struct shell_rtt *sh_rtt = k_timer_user_data_get(timer); if (SEGGER_RTT_HasData(0)) { sh_rtt->handler(SHELL_TRANSPORT_EVT_RX_RDY, sh_rtt->context); } } static int init(const struct shell_transport *transport, const void *config, shell_transport_handler_t evt_handler, void *context) { struct shell_rtt *sh_rtt = (struct shell_rtt *)transport->ctx; sh_rtt->handler = evt_handler; sh_rtt->context = context; k_timer_init(&sh_rtt->timer, timer_handler, NULL); k_timer_user_data_set(&sh_rtt->timer, (void *)sh_rtt); k_timer_start(&sh_rtt->timer, CONFIG_SHELL_RTT_RX_POLL_PERIOD, CONFIG_SHELL_RTT_RX_POLL_PERIOD); return 0; } static int uninit(const struct shell_transport *transport) { return 0; } static int enable(const struct shell_transport *transport, bool blocking) { struct shell_rtt *sh_rtt = (struct shell_rtt *)transport->ctx; if (blocking) { rtt_blocking = true; k_timer_stop(&sh_rtt->timer); } return 0; } static int write(const struct shell_transport *transport, const void *data, size_t length, size_t *cnt) { struct shell_rtt *sh_rtt = (struct shell_rtt *)transport->ctx; const u8_t *data8 = (const u8_t *)data; if (rtt_blocking) { *cnt = SEGGER_RTT_WriteNoLock(0, data8, length); while (SEGGER_RTT_HasDataUp(0)) { /* empty */ } } else { *cnt = SEGGER_RTT_Write(0, data8, length); } sh_rtt->handler(SHELL_TRANSPORT_EVT_TX_RDY, sh_rtt->context); return 0; } static int read(const struct shell_transport *transport, void *data, size_t length, size_t *cnt) { *cnt = SEGGER_RTT_Read(0, data, length); return 0; } const struct shell_transport_api shell_rtt_transport_api = { .init = init, .uninit = uninit, .enable = enable, .write = write, .read = read }; static int enable_shell_rtt(struct device *arg) { ARG_UNUSED(arg); bool log_backend = CONFIG_SHELL_RTT_INIT_LOG_LEVEL > 0; u32_t level = (CONFIG_SHELL_RTT_INIT_LOG_LEVEL > LOG_LEVEL_DBG) ? CONFIG_LOG_MAX_LEVEL : CONFIG_SHELL_RTT_INIT_LOG_LEVEL; shell_init(&shell_rtt, NULL, true, log_backend, level); return 0; } /* Function is used for testing purposes */ const struct shell *shell_backend_rtt_get_ptr(void) { return &shell_rtt; } SYS_INIT(enable_shell_rtt, POST_KERNEL, 0);
Java
/* Copyright (c) 2020 PaddlePaddle 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 "paddle/fluid/operators/inverse_op.h" #include <string> #include <unordered_map> namespace paddle { namespace operators { class InverseOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { OP_INOUT_CHECK(ctx->HasInput("Input"), "Input", "Input", "Inverse"); OP_INOUT_CHECK(ctx->HasOutput("Output"), "Output", "Output", "Inverse"); auto input_dims = ctx->GetInputDim("Input"); int64_t input_rank = input_dims.size(); PADDLE_ENFORCE_GE( input_rank, 2, platform::errors::InvalidArgument( "The dimension of Input(Input) is expected to be no less than 2. " "But recieved: Input(Input)'s dimension = %d, shape = [%s].", input_rank, input_dims)); for (int64_t i = 0; i < input_rank; ++i) { PADDLE_ENFORCE_EQ( (input_dims[i] == -1) || (input_dims[i] > 0), true, platform::errors::InvalidArgument( "Each dimension of input tensor is expected to be -1 or a " "positive number, but recieved %d. Input's shape is [%s].", input_dims[i], input_dims)); } if (input_dims[input_rank - 2] > 0 && input_dims[input_rank - 1] > 0) { PADDLE_ENFORCE_EQ(input_dims[input_rank - 2], input_dims[input_rank - 1], platform::errors::InvalidArgument( "The last two dimensions are expected to be equal. " "But recieved: %d and %d; " "Input(Input)'s shape = [%s].", input_dims[input_rank - 2], input_dims[input_rank - 1], input_dims)); } ctx->SetOutputDim("Output", input_dims); ctx->ShareLoD("Input", /*->*/ "Output"); } }; class InverseOpInferVarType : public framework::PassInDtypeAndVarTypeToOutput { protected: std::unordered_map<std::string, std::string>& GetInputOutputWithSameType() const override { static std::unordered_map<std::string, std::string> m{ {"Input", /*->*/ "Output"}}; return m; } }; class InverseGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { auto input_grad = framework::GradVarName("Input"); auto output_grad = framework::GradVarName("Output"); OP_INOUT_CHECK(ctx->HasInput("Output"), "Input", "Output", "InverseGrad"); OP_INOUT_CHECK(ctx->HasInput(output_grad), "Input", output_grad, "InverseGrad"); if (ctx->HasOutput(input_grad)) { ctx->SetOutputDim(input_grad, ctx->GetInputDim(output_grad)); } } }; class InverseOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput( "Input", "(Tensor) A square matrix (2-D Tensor) or batches of square matrices" " to inverse."); AddOutput("Output", "(Tensor) The inverse of input matrix."); AddComment(R"DOC( Inverse Operator Takes the inverse of the square matrix. )DOC"); } }; template <typename T> class InverseGradOpMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> grad) const override { grad->SetType(this->ForwardOpType() + "_grad"); grad->SetInput("Output", this->Output("Output")); grad->SetInput(framework::GradVarName("Output"), this->OutputGrad("Output")); grad->SetOutput(framework::GradVarName("Input"), this->InputGrad("Input")); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(inverse, ops::InverseOp, ops::InverseOpMaker, ops::InverseOpInferVarType, ops::InverseGradOpMaker<paddle::framework::OpDesc>, ops::InverseGradOpMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(inverse_grad, ops::InverseGradOp); REGISTER_OP_CPU_KERNEL( inverse, ops::InverseKernel<paddle::platform::CPUDeviceContext, float>, ops::InverseKernel<paddle::platform::CPUDeviceContext, double>); REGISTER_OP_CPU_KERNEL( inverse_grad, ops::InverseGradKernel<paddle::platform::CPUDeviceContext, float>, ops::InverseGradKernel<paddle::platform::CPUDeviceContext, double>);
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_45) on Fri Sep 05 23:35:02 UTC 2014 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.hadoop.fs.http.server.HttpFSParametersProvider.LenParam (Apache Hadoop HttpFS 2.5.1 API) </TITLE> <META NAME="date" CONTENT="2014-09-05"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.fs.http.server.HttpFSParametersProvider.LenParam (Apache Hadoop HttpFS 2.5.1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/fs/http/server/HttpFSParametersProvider.LenParam.html" title="class in org.apache.hadoop.fs.http.server"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/fs/http/server//class-useHttpFSParametersProvider.LenParam.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="HttpFSParametersProvider.LenParam.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.fs.http.server.HttpFSParametersProvider.LenParam</B></H2> </CENTER> No usage of org.apache.hadoop.fs.http.server.HttpFSParametersProvider.LenParam <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/fs/http/server/HttpFSParametersProvider.LenParam.html" title="class in org.apache.hadoop.fs.http.server"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/fs/http/server//class-useHttpFSParametersProvider.LenParam.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="HttpFSParametersProvider.LenParam.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2014 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
Java
<?php /** * @package php-font-lib * @link https://github.com/PhenX/php-font-lib * @author Fabien Ménager <[email protected]> * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License */ namespace FontLib\WOFF; use FontLib\Table\DirectoryEntry; /** * WOFF font file. * * @package php-font-lib * * @property TableDirectoryEntry[] $directory */ class File extends \FontLib\TrueType\File { function parseHeader() { if (!empty($this->header)) { return; } $this->header = new Header($this); $this->header->parse(); } public function load($file) { parent::load($file); $this->parseTableEntries(); $dataOffset = $this->pos() + count($this->directory) * 20; $fw = $this->getTempFile(false); $fr = $this->f; $this->f = $fw; $offset = $this->header->encode(); foreach ($this->directory as $entry) { // Read ... $this->f = $fr; $this->seek($entry->offset); $data = $this->read($entry->length); if ($entry->length < $entry->origLength) { $data = gzuncompress($data); } // Prepare data ... $length = strlen($data); $entry->length = $entry->origLength = $length; $entry->offset = $dataOffset; // Write ... $this->f = $fw; // Woff Entry $this->seek($offset); $offset += $this->write($entry->tag, 4); // tag $offset += $this->writeUInt32($dataOffset); // offset $offset += $this->writeUInt32($length); // length $offset += $this->writeUInt32($length); // origLength $offset += $this->writeUInt32(DirectoryEntry::computeChecksum($data)); // checksum // Data $this->seek($dataOffset); $dataOffset += $this->write($data, $length); } $this->f = $fw; $this->seek(0); // Need to re-parse this, don't know why $this->header = null; $this->directory = array(); $this->parseTableEntries(); } }
Java
using Newtonsoft.Json; namespace Nest { [JsonObject] public interface ILoggingAction : IAction { [JsonProperty("text")] string Text { get; set; } [JsonProperty("category")] string Category { get; set; } [JsonProperty("level")] LogLevel? Level { get; set; } } public class LoggingAction : ActionBase, ILoggingAction { public override ActionType ActionType => ActionType.Logging; public string Text { get; set; } public string Category { get; set; } public LogLevel? Level { get; set; } public LoggingAction(string name) : base(name) {} } public class LoggingActionDescriptor : ActionsDescriptorBase<LoggingActionDescriptor, ILoggingAction>, ILoggingAction { protected override ActionType ActionType => ActionType.Logging; LogLevel? ILoggingAction.Level { get; set; } string ILoggingAction.Text { get; set; } string ILoggingAction.Category { get; set; } public LoggingActionDescriptor(string name) : base(name) {} public LoggingActionDescriptor Level(LogLevel level) => Assign(a => a.Level = level); public LoggingActionDescriptor Text(string text) => Assign(a => a.Text = text); public LoggingActionDescriptor Category(string category) => Assign(a => a.Category = category); } }
Java
/* (c) British Telecommunications plc, 2009, All Rights Reserved */ package com.bt.pi.sss; import com.bt.pi.app.common.entities.User; public interface UserManager { boolean userExists(String accessKey); User getUserByAccessKey(String accessKey); }
Java
#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import DBMS from lib.core.settings import MAXDB_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.maxdb.enumeration import Enumeration from plugins.dbms.maxdb.filesystem import Filesystem from plugins.dbms.maxdb.fingerprint import Fingerprint from plugins.dbms.maxdb.syntax import Syntax from plugins.dbms.maxdb.takeover import Takeover from plugins.generic.misc import Miscellaneous class MaxDBMap(Syntax, Fingerprint, Enumeration, Filesystem, Miscellaneous, Takeover): """ This class defines SAP MaxDB methods """ def __init__(self): self.excludeDbsList = MAXDB_SYSTEM_DBS Syntax.__init__(self) Fingerprint.__init__(self) Enumeration.__init__(self) Filesystem.__init__(self) Miscellaneous.__init__(self) Takeover.__init__(self) unescaper[DBMS.MAXDB] = Syntax.escape
Java
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pl.allegro.foggerexample.config; import android.app.Application; import android.app.Instrumentation; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import pl.allegro.foggerexample.config.application.ApplicationRunConfiguration; import pl.allegro.foggerexample.config.dagger.Injector; import pl.allegro.foggerexample.config.dagger.module.RootModule; public class FoggerExampleApplication extends Application { private static FoggerExampleApplication instance; private ApplicationRunConfiguration applicationRunConfiguration; public FoggerExampleApplication() { } public FoggerExampleApplication(final Context context) { super(); attachBaseContext(context); setInstance(this); } @Override public void onCreate() { super.onCreate(); initDaggerOnApplicationCreationStep(); Injector.inject(this); } private void initDaggerOnApplicationCreationStep() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); applicationRunConfiguration = ApplicationRunConfiguration.create(sharedPreferences); Object[] modules = new Object[]{new RootModule()}; Injector.init(modules); Injector.injectStatics(); } private static void setInstance(FoggerExampleApplication foggerExampleApplication) { instance = foggerExampleApplication; } public FoggerExampleApplication(final Instrumentation instrumentation) { super(); attachBaseContext(instrumentation.getTargetContext()); } public static FoggerExampleApplication getInstance() { return instance; } }
Java
/* * Copyright 2015 Alexey Andreev. * * 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.teavm.jso.impl; import java.io.IOException; /** * * @author Alexey Andreev */ interface NameEmitter { void emit(int precedence) throws IOException; }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <boost/lexical_cast.hpp> #include "errmsgs.hpp" namespace Drill{ static Drill::ErrorMessages errorMessages[]={ {ERR_NONE, 0, 0, "No Error."}, {ERR_CONN_FAILURE, ERR_CATEGORY_CONN, 0, "Connection failure. Host:%s port:%s. Error: %s."}, {ERR_CONN_EXCEPT, ERR_CATEGORY_CONN, 0, "Socket connection failure with the following exception: %s."}, {ERR_CONN_UNKPROTO, ERR_CATEGORY_CONN, 0, "Unknown protocol: %s."}, {ERR_CONN_RDFAIL, ERR_CATEGORY_CONN, 0, "Connection failed with error: %s."}, {ERR_CONN_WFAIL, ERR_CATEGORY_CONN, 0, "Synchronous socket write failed with error: %s."}, {ERR_CONN_ZOOKEEPER, ERR_CATEGORY_CONN, 0, "Zookeeper error. %s"}, {ERR_CONN_NOHSHAKE, ERR_CATEGORY_CONN, 0, "Handshake failed because the server killed the connection. " "Expected RPC version %d."}, {ERR_CONN_ZKFAIL, ERR_CATEGORY_CONN, 0, "Failed to connect to Zookeeper."}, {ERR_CONN_ZKTIMOUT, ERR_CATEGORY_CONN, 0, "Timed out while waiting to connect."}, {ERR_CONN_ZKERR, ERR_CATEGORY_CONN, 0, "Error in reading from Zookeeper (error code: %d)."}, {ERR_CONN_ZKDBITERR, ERR_CATEGORY_CONN, 0, "Error in reading drillbit endpoint from Zookeeper (error code: %d)."}, {ERR_CONN_ZKNODBIT, ERR_CATEGORY_CONN, 0, "No drillbit found with this Zookeeper."}, {ERR_CONN_ZKNOAUTH, ERR_CATEGORY_CONN, 0, "Authentication failed."}, {ERR_CONN_ZKEXP, ERR_CATEGORY_CONN, 0, "Session expired."}, {ERR_CONN_HSHAKETIMOUT, ERR_CATEGORY_CONN, 0, "Handshake Timeout."}, {ERR_CONN_BAD_RPC_VER, ERR_CATEGORY_CONN, 0, "Handshake failed because of a RPC version mismatch. " "Expected RPC version %d, got %d. [Server message was: (%s) %s]"}, {ERR_CONN_AUTHFAIL, ERR_CATEGORY_CONN, 0, "User authentication failed (please check the username and password)." "[Server message was: (%s) %s]"}, {ERR_CONN_UNKNOWN_ERR, ERR_CATEGORY_CONN, 0, "Handshake Failed due to an error on the server. [Server message was: (%s) %s]"}, {ERR_CONN_NOCONN, ERR_CATEGORY_CONN, 0, "There is no connection to the server."}, {ERR_CONN_ALREADYCONN, ERR_CATEGORY_CONN, 0, "This client is already connected to a server."}, {ERR_CONN_NOCONNSTR, ERR_CATEGORY_CONN, 0, "Cannot connect if either host name or port number are empty."}, {ERR_CONN_SSLCERTFAIL, ERR_CATEGORY_CONN, 0, "SSL certificate file %s could not be loaded (exception message: %s)."}, {ERR_CONN_NOSOCKET, ERR_CATEGORY_CONN, 0, "Failed to open socket connection."}, {ERR_CONN_NOSERVERAUTH, ERR_CATEGORY_CONN, 0, "Client needs a secure connection but server does not" " support any security mechanisms. Please contact an administrator. [Warn: This" " could be due to a bad configuration or a security attack is in progress.]"}, {ERR_CONN_NOSERVERENC, ERR_CATEGORY_CONN, 0, "Client needs encryption but encryption is disabled on the server." " Please check connection parameters or contact administrator. [Warn: This" " could be due to a bad configuration or a security attack is in progress.]"}, {ERR_QRY_OUTOFMEM, ERR_CATEGORY_QRY, 0, "Out of memory."}, {ERR_QRY_COMMERR, ERR_CATEGORY_QRY, 0, "Communication error. %s"}, {ERR_QRY_INVREADLEN, ERR_CATEGORY_QRY, 0, "Internal Error: Received a message with an invalid read length."}, {ERR_QRY_INVQUERYID, ERR_CATEGORY_QRY, 0, "Internal Error: Cannot find query Id in internal structure."}, {ERR_QRY_INVRPCTYPE, ERR_CATEGORY_QRY, 0, "Unknown rpc type received from server:%d."}, {ERR_QRY_OUTOFORDER, ERR_CATEGORY_QRY, 0, "Internal Error: Query result received before query id. Aborting ..."}, {ERR_QRY_INVRPC, ERR_CATEGORY_QRY, 0, "Rpc Error: %s."}, {ERR_QRY_TIMOUT, ERR_CATEGORY_QRY, 0, "Timed out waiting for server to respond."}, {ERR_QRY_FAILURE, ERR_CATEGORY_QRY, 0, "Query execution error. Details:[ \n%s\n]"}, {ERR_QRY_SELVEC2, ERR_CATEGORY_QRY, 0, "Receiving a selection_vector_2 from the server came as a complete surprise at this point"}, {ERR_QRY_RESPFAIL, ERR_CATEGORY_QRY, 0, "Received a RESPONSE_FAILURE from the server."}, {ERR_QRY_UNKQRYSTATE, ERR_CATEGORY_QRY, 0, "Got an unknown query state message from the server."}, {ERR_QRY_UNKQRY, ERR_CATEGORY_QRY, 0, "Query not found on server. It might have been terminated already."}, {ERR_QRY_CANCELED, ERR_CATEGORY_QRY, 0, "Query has been cancelled"}, {ERR_QRY_COMPLETED, ERR_CATEGORY_QRY, 0, "Query completed."}, {ERR_QRY_16, ERR_CATEGORY_QRY, 0, "Query Failed."}, {ERR_QRY_17, ERR_CATEGORY_QRY, 0, "Query Failed."}, {ERR_QRY_18, ERR_CATEGORY_QRY, 0, "Query Failed."}, {ERR_QRY_19, ERR_CATEGORY_QRY, 0, "Query Failed."}, {ERR_QRY_20, ERR_CATEGORY_QRY, 0, "Query Failed."}, }; std::string getMessage(uint32_t msgId, ...){ char str[10240]; std::string s; assert((ERR_NONE <= msgId) && (msgId < ERR_QRY_MAX)); va_list args; va_start (args, msgId); vsnprintf (str, sizeof(str), errorMessages[msgId-DRILL_ERR_START].msgFormatStr, args); va_end (args); s=std::string("[")+boost::lexical_cast<std::string>(msgId)+std::string("]")+str; return s; } }// namespace Drill
Java
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package adwords.axis.v201502.advancedoperations; import com.google.api.ads.adwords.axis.factory.AdWordsServices; import com.google.api.ads.adwords.axis.v201502.cm.AdvertisingChannelType; import com.google.api.ads.adwords.axis.v201502.cm.ApiException; import com.google.api.ads.adwords.axis.v201502.cm.BiddingStrategyConfiguration; import com.google.api.ads.adwords.axis.v201502.cm.BiddingStrategyOperation; import com.google.api.ads.adwords.axis.v201502.cm.BiddingStrategyReturnValue; import com.google.api.ads.adwords.axis.v201502.cm.BiddingStrategyServiceInterface; import com.google.api.ads.adwords.axis.v201502.cm.Budget; import com.google.api.ads.adwords.axis.v201502.cm.BudgetBudgetDeliveryMethod; import com.google.api.ads.adwords.axis.v201502.cm.BudgetBudgetPeriod; import com.google.api.ads.adwords.axis.v201502.cm.BudgetOperation; import com.google.api.ads.adwords.axis.v201502.cm.BudgetReturnValue; import com.google.api.ads.adwords.axis.v201502.cm.BudgetServiceInterface; import com.google.api.ads.adwords.axis.v201502.cm.Campaign; import com.google.api.ads.adwords.axis.v201502.cm.CampaignOperation; import com.google.api.ads.adwords.axis.v201502.cm.CampaignReturnValue; import com.google.api.ads.adwords.axis.v201502.cm.CampaignServiceInterface; import com.google.api.ads.adwords.axis.v201502.cm.Money; import com.google.api.ads.adwords.axis.v201502.cm.NetworkSetting; import com.google.api.ads.adwords.axis.v201502.cm.Operator; import com.google.api.ads.adwords.axis.v201502.cm.SharedBiddingStrategy; import com.google.api.ads.adwords.axis.v201502.cm.TargetSpendBiddingScheme; import com.google.api.ads.adwords.lib.client.AdWordsSession; import com.google.api.ads.common.lib.auth.OfflineCredentials; import com.google.api.ads.common.lib.auth.OfflineCredentials.Api; import com.google.api.client.auth.oauth2.Credential; import java.rmi.RemoteException; import javax.xml.rpc.ServiceException; /** * This example adds a Shared Bidding Strategy and uses it to construct a campaign. */ public class UseSharedBiddingStrategy { // Optional: If you'd like to use an existing shared budget, assign a // shared budget ID here. private static final Long SHARED_BUDGET_ID = null; public static void main(String[] args) throws Exception { Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.ADWORDS) .fromFile() .build() .generateCredential(); // Construct an AdWordsSession. AdWordsSession session = new AdWordsSession.Builder() .fromFile() .withOAuth2Credential(oAuth2Credential) .build(); AdWordsServices adWordsServices = new AdWordsServices(); runExample(adWordsServices, session, SHARED_BUDGET_ID); } public static void runExample(AdWordsServices adWordsServices, AdWordsSession session, Long sharedBudgetId) throws Exception { SharedBiddingStrategy sharedBiddingStrategy = createBiddingStrategy(adWordsServices, session); if (sharedBudgetId == null) { Budget budget = createSharedBudget(adWordsServices, session); sharedBudgetId = budget.getBudgetId(); } createCampaignWithBiddingStrategy(adWordsServices, session, sharedBiddingStrategy.getId(), sharedBudgetId); } /** * Creates the bidding strategy object. * * @param adWordsServices the user to run the example with * @param session the AdWordsSession * @throws RemoteException * @throws ApiException * @throws ServiceException */ private static SharedBiddingStrategy createBiddingStrategy(AdWordsServices adWordsServices, AdWordsSession session) throws ApiException, RemoteException, ServiceException { // Get the BiddingStrategyService, which loads the required classes. BiddingStrategyServiceInterface biddingStrategyService = adWordsServices.get(session, BiddingStrategyServiceInterface.class); // Create a shared bidding strategy. SharedBiddingStrategy sharedBiddingStrategy = new SharedBiddingStrategy(); sharedBiddingStrategy.setName("Maximize Clicks" + System.currentTimeMillis()); TargetSpendBiddingScheme biddingScheme = new TargetSpendBiddingScheme(); // Optionally set additional bidding scheme parameters. biddingScheme.setBidCeiling(new Money(null, 2000000L)); biddingScheme.setSpendTarget(new Money(null, 20000000L)); sharedBiddingStrategy.setBiddingScheme(biddingScheme); // Create operation. BiddingStrategyOperation operation = new BiddingStrategyOperation(); operation.setOperand(sharedBiddingStrategy); operation.setOperator(Operator.ADD); BiddingStrategyOperation[] operations = new BiddingStrategyOperation[] {operation}; BiddingStrategyReturnValue result = biddingStrategyService.mutate(operations); SharedBiddingStrategy newBiddingStrategy = result.getValue(0); System.out.printf( "Shared bidding strategy with name '%s' and ID %d of type %s was created.\n", newBiddingStrategy.getName(), newBiddingStrategy.getId(), newBiddingStrategy.getBiddingScheme().getBiddingSchemeType()); return newBiddingStrategy; } /** * Creates an explicit budget to be used only to create the Campaign. * * @param adWordsServices the user to run the example with * @param session the AdWordsSession * @throws ServiceException * @throws RemoteException * @throws ApiException */ private static Budget createSharedBudget(AdWordsServices adWordsServices, AdWordsSession session) throws ServiceException, ApiException, RemoteException { // Get the BudgetService, which loads the required classes. BudgetServiceInterface budgetService = adWordsServices.get(session, BudgetServiceInterface.class); // Create a shared budget. Budget budget = new Budget(); budget.setName("Shared Interplanetary Budget #" + System.currentTimeMillis()); budget.setPeriod(BudgetBudgetPeriod.DAILY); budget.setAmount(new Money(null, 50000000L)); budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD); budget.setIsExplicitlyShared(true); BudgetOperation operation = new BudgetOperation(); operation.setOperand(budget); operation.setOperator(Operator.ADD); BudgetOperation[] operations = new BudgetOperation[] {operation}; // Make the mutate request. BudgetReturnValue result = budgetService.mutate(operations); Budget newBudget = result.getValue(0); System.out.printf("Budget with name '%s', ID %d was created.\n", newBudget.getName(), newBudget.getBudgetId()); return newBudget; } /** * Create a Campaign with a Shared Bidding Strategy. * * @param adWordsServices the user to run the example with * @param session the AdWordsSession * @param biddingStrategyId the bidding strategy id to use * @param sharedBudgetId the shared budget id to use * @throws RemoteException * @throws ApiException * @throws ServiceException */ private static Campaign createCampaignWithBiddingStrategy( AdWordsServices adWordsServices, AdWordsSession session, Long biddingStrategyId, Long sharedBudgetId) throws ApiException, RemoteException, ServiceException { // Get the CampaignService, which loads the required classes. CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class); // Create campaign. Campaign campaign = new Campaign(); campaign.setName("Interplanetary Cruise #" + System.currentTimeMillis()); // Set the budget. Budget budget = new Budget(); budget.setBudgetId(sharedBudgetId); campaign.setBudget(budget); // Set bidding strategy (required). BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration(); biddingStrategyConfiguration.setBiddingStrategyId(biddingStrategyId); campaign.setBiddingStrategyConfiguration(biddingStrategyConfiguration); // Set advertising channel type (required). campaign.setAdvertisingChannelType(AdvertisingChannelType.SEARCH); // Set network targeting (recommended). NetworkSetting networkSetting = new NetworkSetting(); networkSetting.setTargetGoogleSearch(true); networkSetting.setTargetSearchNetwork(true); networkSetting.setTargetContentNetwork(true); campaign.setNetworkSetting(networkSetting); // Create operation. CampaignOperation operation = new CampaignOperation(); operation.setOperand(campaign); operation.setOperator(Operator.ADD); CampaignReturnValue result = campaignService.mutate(new CampaignOperation[] {operation}); Campaign newCampaign = result.getValue(0); System.out.printf("Campaign with name '%s', ID %d and bidding scheme ID %d was created.\n", newCampaign.getName(), newCampaign.getId(), newCampaign.getBiddingStrategyConfiguration().getBiddingStrategyId()); return newCampaign; } }
Java
<?php /** * Copyright 2012-2015 ContactLab, Italy * * 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. */ class createCampaignResponse { /** * @var Campaign $return * @access public */ public $return = null; }
Java
/* * Copyright 2014 Space Dynamics Laboratory - Utah State University Research Foundation. * * 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.usu.sdl.openstorefront.web.init; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** * * @author dshurtleff */ @WebListener public class ApplicationInit implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { } @Override public void contextDestroyed(ServletContextEvent sce) { } }
Java
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.kie.scanner; import java.util.Collection; import java.util.HashMap; import org.drools.compiler.kie.builder.impl.MessageImpl; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.conf.EqualityBehaviorOption; import org.kie.api.conf.EventProcessingOption; import org.kie.internal.builder.IncrementalResults; import org.kie.internal.builder.InternalKieBuilder; import static org.junit.Assert.*; public class KieModuleIncrementalCompilationTest extends AbstractKieCiTest { @Test public void testCheckMetaDataAfterIncrementalDelete() throws Exception { String drl1 = "package org.kie.scanner\n" + "rule R1 when\n" + " String()\n" + "then\n" + "end\n"; String drl2 = "package org.kie.scanner\n" + "rule R2_2 when\n" + " String( )\n" + "then\n" + "end\n"; KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem() .write( "src/main/resources/r1.drl", drl1 ) .write( "src/main/resources/r2.drl", drl2 ); KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll(); assertEquals( 2, getRuleNames( kieBuilder ).get( "org.kie.scanner" ).size() ); kfs.delete( "src/main/resources/r2.drl" ); IncrementalResults addResults = ( (InternalKieBuilder) kieBuilder ).createFileSet( "src/main/resources/r2.drl" ).build(); assertEquals( 1, getRuleNames( kieBuilder ).get( "org.kie.scanner" ).size() ); } private HashMap<String, Collection<String>> getRuleNames( KieBuilder kieBuilder ) { KieModuleMetaData kieModuleMetaData = getKieModuleMetaData( kieBuilder ); HashMap<String, Collection<String>> ruleNames = new HashMap<String, Collection<String>>(); for ( String packageName : kieModuleMetaData.getPackages() ) { ruleNames.put( packageName, kieModuleMetaData.getRuleNamesInPackage( packageName ) ); } return ruleNames; } private KieModuleMetaData getKieModuleMetaData( KieBuilder kieBuilder ) { return KieModuleMetaData.Factory.newKieModuleMetaData( ( (InternalKieBuilder) kieBuilder ).getKieModuleIgnoringErrors() ); } @Test public void testIncrementalCompilationFirstBuildHasErrors() throws Exception { KieServices ks = KieServices.Factory.get(); //Malformed POM - No Version information ReleaseId releaseId = ks.newReleaseId( "org.kie", "incremental-test-with-invalid pom", "" ); KieFileSystem kfs = createKieFileSystemWithKProject( ks ); kfs.writePomXML( getPom( releaseId ) ); //Valid String drl1 = "rule R1 when\n" + " $s : String()\n" + "then\n" + "end\n"; //Invalid String drl2 = "rule R2 when\n" + " $s : Strin( )\n" + "then\n" + "end\n"; //Write Rule 1 - No DRL errors, but POM is in error kfs.write( "src/main/resources/KBase1/r1.drl", drl1 ); KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll(); assertEquals( 1, kieBuilder.getResults().getMessages( org.kie.api.builder.Message.Level.ERROR ).size() ); //Add file with error - expect 1 "added" error message kfs.write( "src/main/resources/KBase1/r2.drl", drl2 ); IncrementalResults addResults = ( (InternalKieBuilder) kieBuilder ).createFileSet( "src/main/resources/KBase1/r2.drl" ).build(); assertEquals( 1, addResults.getAddedMessages().size() ); assertEquals( 0, addResults.getRemovedMessages().size() ); } @Test public void checkIncrementalCompilationWithRuleFunctionRule() throws Exception { String rule_1 = "package org.kie.scanner\n" + "rule R1 when\n" + " String()\n" + "then\n" + "end\n"; String rule_2 = "package org.kie.scanner\n" + "rule R1 when\n" + " String()\n" + "then\n" + " System.out.println(MyFunction());\n" + "end\n"; String function = "package org.kie.scanner\n" + "function int MyFunction() {\n" + " return 1;\n" + "}\n"; KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write( "src/main/resources/org/kie/scanner/rule.drl", rule_1 ); KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll(); assertEquals( 0, kieBuilder.getResults().getMessages( org.kie.api.builder.Message.Level.ERROR ).size() ); kfs.write( "src/main/resources/org/kie/scanner/function.drl", function ); IncrementalResults addResults1 = ( (InternalKieBuilder) kieBuilder ).createFileSet( "src/main/resources/org/kie/scanner/function.drl" ).build(); assertEquals( 0, addResults1.getAddedMessages().size() ); assertEquals( 0, addResults1.getRemovedMessages().size() ); kfs.write( "src/main/resources/org/kie/scanner/rule.drl", rule_2 ); IncrementalResults addResults2 = ( (InternalKieBuilder) kieBuilder ).createFileSet( "src/main/resources/org/kie/scanner/rule.drl" ).build(); assertEquals( 0, addResults2.getAddedMessages().size() ); assertEquals( 0, addResults2.getRemovedMessages().size() ); } @Test public void checkIncrementalCompilationWithRuleThenFunction() throws Exception { String rule = "package org.kie.scanner\n" + "rule R1 when\n" + " String()\n" + "then\n" + " System.out.println(MyFunction());\n" + "end\n"; String function = "package org.kie.scanner\n" + "function int MyFunction() {\n" + " return 1;\n" + "}\n"; KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write( "src/main/resources/org/kie/scanner/rule.drl", rule ); KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll(); assertEquals( 1, kieBuilder.getResults().getMessages( org.kie.api.builder.Message.Level.ERROR ).size() ); kfs.write( "src/main/resources/org/kie/scanner/function.drl", function ); IncrementalResults addResults1 = ( (InternalKieBuilder) kieBuilder ).createFileSet( "src/main/resources/org/kie/scanner/function.drl" ).build(); assertEquals( 0, addResults1.getAddedMessages().size() ); assertEquals( 1, addResults1.getRemovedMessages().size() ); } @Test public void checkIncrementalCompilationWithFunctionThenRule() throws Exception { String rule = "package org.kie.scanner\n" + "rule R1 when\n" + " String()\n" + "then\n" + " System.out.println(MyFunction());\n" + "end\n"; String function = "package org.kie.scanner\n" + "function int MyFunction() {\n" + " return 1;\n" + "}\n"; KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write( "src/main/resources/org/kie/scanner/function.drl", function ); KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll(); assertEquals( 0, kieBuilder.getResults().getMessages( org.kie.api.builder.Message.Level.ERROR ).size() ); kfs.write( "src/main/resources/org/kie/scanner/rule.drl", rule ); IncrementalResults addResults = ( (InternalKieBuilder) kieBuilder ).createFileSet( "src/main/resources/org/kie/scanner/rule.drl" ).build(); assertEquals( 0, addResults.getAddedMessages().size() ); assertEquals( 0, addResults.getRemovedMessages().size() ); } @Test public void checkIncrementalCompilationWithMultipleKieBases() throws Exception { String rule = "package org.kie.scanner\n" + "rule R1 when\n" + "then\n" + "end\n"; String invalidRule = "package org.kie.scanner\n" + "rule R2 when\n" + " Cheese()\n" + // missing import "then\n" + "end\n"; KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = createKieFileSystemWithTwoKBases(ks); kfs.write("src/main/resources/org/kie/scanner/rule.drl", rule); KieBuilder kieBuilder = ks.newKieBuilder(kfs).buildAll(); assertEquals(0, kieBuilder.getResults().getMessages().size()); kfs.write("src/main/resources/org/kie/scanner/invalidRule.drl", invalidRule); IncrementalResults addResults = ((InternalKieBuilder) kieBuilder).createFileSet("src/main/resources/org/kie/scanner/invalidRule.drl").build(); assertEquals(2, addResults.getAddedMessages().size()); addResults .getAddedMessages() .stream() .map(m -> (MessageImpl) m ) .forEach(m -> assertNotNull(m.getKieBaseName())); } private KieFileSystem createKieFileSystemWithTwoKBases(final KieServices ks) { final KieModuleModel kproj = ks.newKieModuleModel(); kproj.newKieBaseModel("default").setDefault(true) .setEqualsBehavior( EqualityBehaviorOption.EQUALITY ) .setEventProcessingMode( EventProcessingOption.STREAM ); kproj.newKieBaseModel("kbase1").setDefault(false) .setEqualsBehavior(EqualityBehaviorOption.EQUALITY) .setEventProcessingMode(EventProcessingOption.STREAM); final KieFileSystem kfs = ks.newKieFileSystem(); kfs.writeKModuleXML(kproj.toXML()); return kfs; } }
Java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/events/CloudWatchEvents_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/events/model/ConnectionState.h> #include <aws/core/utils/DateTime.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace CloudWatchEvents { namespace Model { class AWS_CLOUDWATCHEVENTS_API UpdateConnectionResult { public: UpdateConnectionResult(); UpdateConnectionResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); UpdateConnectionResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The ARN of the connection that was updated.</p> */ inline const Aws::String& GetConnectionArn() const{ return m_connectionArn; } /** * <p>The ARN of the connection that was updated.</p> */ inline void SetConnectionArn(const Aws::String& value) { m_connectionArn = value; } /** * <p>The ARN of the connection that was updated.</p> */ inline void SetConnectionArn(Aws::String&& value) { m_connectionArn = std::move(value); } /** * <p>The ARN of the connection that was updated.</p> */ inline void SetConnectionArn(const char* value) { m_connectionArn.assign(value); } /** * <p>The ARN of the connection that was updated.</p> */ inline UpdateConnectionResult& WithConnectionArn(const Aws::String& value) { SetConnectionArn(value); return *this;} /** * <p>The ARN of the connection that was updated.</p> */ inline UpdateConnectionResult& WithConnectionArn(Aws::String&& value) { SetConnectionArn(std::move(value)); return *this;} /** * <p>The ARN of the connection that was updated.</p> */ inline UpdateConnectionResult& WithConnectionArn(const char* value) { SetConnectionArn(value); return *this;} /** * <p>The state of the connection that was updated.</p> */ inline const ConnectionState& GetConnectionState() const{ return m_connectionState; } /** * <p>The state of the connection that was updated.</p> */ inline void SetConnectionState(const ConnectionState& value) { m_connectionState = value; } /** * <p>The state of the connection that was updated.</p> */ inline void SetConnectionState(ConnectionState&& value) { m_connectionState = std::move(value); } /** * <p>The state of the connection that was updated.</p> */ inline UpdateConnectionResult& WithConnectionState(const ConnectionState& value) { SetConnectionState(value); return *this;} /** * <p>The state of the connection that was updated.</p> */ inline UpdateConnectionResult& WithConnectionState(ConnectionState&& value) { SetConnectionState(std::move(value)); return *this;} /** * <p>A time stamp for the time that the connection was created.</p> */ inline const Aws::Utils::DateTime& GetCreationTime() const{ return m_creationTime; } /** * <p>A time stamp for the time that the connection was created.</p> */ inline void SetCreationTime(const Aws::Utils::DateTime& value) { m_creationTime = value; } /** * <p>A time stamp for the time that the connection was created.</p> */ inline void SetCreationTime(Aws::Utils::DateTime&& value) { m_creationTime = std::move(value); } /** * <p>A time stamp for the time that the connection was created.</p> */ inline UpdateConnectionResult& WithCreationTime(const Aws::Utils::DateTime& value) { SetCreationTime(value); return *this;} /** * <p>A time stamp for the time that the connection was created.</p> */ inline UpdateConnectionResult& WithCreationTime(Aws::Utils::DateTime&& value) { SetCreationTime(std::move(value)); return *this;} /** * <p>A time stamp for the time that the connection was last modified.</p> */ inline const Aws::Utils::DateTime& GetLastModifiedTime() const{ return m_lastModifiedTime; } /** * <p>A time stamp for the time that the connection was last modified.</p> */ inline void SetLastModifiedTime(const Aws::Utils::DateTime& value) { m_lastModifiedTime = value; } /** * <p>A time stamp for the time that the connection was last modified.</p> */ inline void SetLastModifiedTime(Aws::Utils::DateTime&& value) { m_lastModifiedTime = std::move(value); } /** * <p>A time stamp for the time that the connection was last modified.</p> */ inline UpdateConnectionResult& WithLastModifiedTime(const Aws::Utils::DateTime& value) { SetLastModifiedTime(value); return *this;} /** * <p>A time stamp for the time that the connection was last modified.</p> */ inline UpdateConnectionResult& WithLastModifiedTime(Aws::Utils::DateTime&& value) { SetLastModifiedTime(std::move(value)); return *this;} /** * <p>A time stamp for the time that the connection was last authorized.</p> */ inline const Aws::Utils::DateTime& GetLastAuthorizedTime() const{ return m_lastAuthorizedTime; } /** * <p>A time stamp for the time that the connection was last authorized.</p> */ inline void SetLastAuthorizedTime(const Aws::Utils::DateTime& value) { m_lastAuthorizedTime = value; } /** * <p>A time stamp for the time that the connection was last authorized.</p> */ inline void SetLastAuthorizedTime(Aws::Utils::DateTime&& value) { m_lastAuthorizedTime = std::move(value); } /** * <p>A time stamp for the time that the connection was last authorized.</p> */ inline UpdateConnectionResult& WithLastAuthorizedTime(const Aws::Utils::DateTime& value) { SetLastAuthorizedTime(value); return *this;} /** * <p>A time stamp for the time that the connection was last authorized.</p> */ inline UpdateConnectionResult& WithLastAuthorizedTime(Aws::Utils::DateTime&& value) { SetLastAuthorizedTime(std::move(value)); return *this;} private: Aws::String m_connectionArn; ConnectionState m_connectionState; Aws::Utils::DateTime m_creationTime; Aws::Utils::DateTime m_lastModifiedTime; Aws::Utils::DateTime m_lastAuthorizedTime; }; } // namespace Model } // namespace CloudWatchEvents } // namespace Aws
Java
using System; using BEPUphysics.BroadPhaseEntries; using BEPUphysics.BroadPhaseSystems; using BEPUphysics.BroadPhaseEntries.MobileCollidables; using BEPUphysics.CollisionTests; using BEPUphysics.CollisionTests.CollisionAlgorithms.GJK; using BEPUphysics.CollisionTests.Manifolds; using BEPUphysics.Constraints.Collision; using BEPUphysics.PositionUpdating; using BEPUphysics.Settings; namespace BEPUphysics.NarrowPhaseSystems.Pairs { ///<summary> /// Handles a convex-convex collision pair. ///</summary> public class GeneralConvexPairHandler : ConvexConstraintPairHandler { ConvexCollidable convexA; ConvexCollidable convexB; GeneralConvexContactManifold contactManifold = new GeneralConvexContactManifold(); public override Collidable CollidableA { get { return convexA; } } public override Collidable CollidableB { get { return convexB; } } /// <summary> /// Gets the contact manifold used by the pair handler. /// </summary> public override ContactManifold ContactManifold { get { return contactManifold; } } public override Entities.Entity EntityA { get { return convexA.entity; } } public override Entities.Entity EntityB { get { return convexB.entity; } } ///<summary> /// Initializes the pair handler. ///</summary> ///<param name="entryA">First entry in the pair.</param> ///<param name="entryB">Second entry in the pair.</param> public override void Initialize(BroadPhaseEntry entryA, BroadPhaseEntry entryB) { convexA = entryA as ConvexCollidable; convexB = entryB as ConvexCollidable; if (convexA == null || convexB == null) { throw new ArgumentException("Inappropriate types used to initialize pair."); } base.Initialize(entryA, entryB); } ///<summary> /// Cleans up the pair handler. ///</summary> public override void CleanUp() { base.CleanUp(); convexA = null; convexB = null; } } }
Java
# # Author:: Seth Chisamore <[email protected]> # Cookbook Name:: python # Recipe:: source # # Copyright 2011, Opscode, 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. # configure_options = node['python']['configure_options'].join(" ") packages = value_for_platform_family( "rhel" => ["openssl-devel","bzip2-devel","zlib-devel","expat-devel","db4-devel","sqlite-devel","ncurses-devel","readline-devel"], "default" => ["libssl-dev","libbz2-dev","zlib1g-dev","libexpat1-dev","libdb-dev","libsqlite3-dev","libncursesw5-dev","libncurses5-dev","libreadline-dev","libsasl2-dev", "libgdbm-dev"] ) # packages.each do |dev_pkg| package dev_pkg end version = node['python']['version'] install_path = "#{node['python']['prefix_dir']}/bin/python#{version.split(/(^\d+\.\d+)/)[1]}" remote_file "#{Chef::Config[:file_cache_path]}/Python-#{version}.tar.bz2" do source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2" checksum node['python']['checksum'] mode "0644" not_if { ::File.exists?(install_path) } end bash "build-and-install-python" do cwd Chef::Config[:file_cache_path] code <<-EOF tar -jxvf Python-#{version}.tar.bz2 (cd Python-#{version} && ./configure #{configure_options}) (cd Python-#{version} && make && make install) EOF environment({ "LDFLAGS" => "-L#{node['python']['prefix_dir']} -L/usr/lib", "CPPFLAGS" => "-I#{node['python']['prefix_dir']} -I/usr/lib", "CXXFLAGS" => "-I#{node['python']['prefix_dir']} -I/usr/lib", "CFLAGS" => "-I#{node['python']['prefix_dir']} -I/usr/lib" }) if platform?("ubuntu") && node['platform_version'].to_f >= 12.04 not_if { ::File.exists?(install_path) } end
Java
<?php final class PhabricatorDifferentialApplication extends PhabricatorApplication { public function getBaseURI() { return '/differential/'; } public function getName() { return pht('Differential'); } public function getMenuName() { return pht('Code Review'); } public function getShortDescription() { return pht('Pre-Commit Review'); } public function getIcon() { return 'fa-cog'; } public function isPinnedByDefault(PhabricatorUser $viewer) { return true; } public function getHelpDocumentationArticles(PhabricatorUser $viewer) { return array( array( 'name' => pht('Differential User Guide'), 'href' => PhabricatorEnv::getDoclink('Differential User Guide'), ), ); } public function getFactObjectsForAnalysis() { return array( new DifferentialRevision(), ); } public function getTitleGlyph() { return "\xE2\x9A\x99"; } public function getOverview() { return pht( 'Differential is a **code review application** which allows '. 'engineers to review, discuss and approve changes to software.'); } public function getRoutes() { return array( '/D(?P<id>[1-9]\d*)' => 'DifferentialRevisionViewController', '/differential/' => array( '(?:query/(?P<queryKey>[^/]+)/)?' => 'DifferentialRevisionListController', 'diff/' => array( '(?P<id>[1-9]\d*)/' => 'DifferentialDiffViewController', 'create/' => 'DifferentialDiffCreateController', ), 'changeset/' => 'DifferentialChangesetViewController', 'revision/' => array( $this->getEditRoutePattern('edit/') => 'DifferentialRevisionEditController', $this->getEditRoutePattern('attach/(?P<diffID>[^/]+)/to/') => 'DifferentialRevisionEditController', 'closedetails/(?P<phid>[^/]+)/' => 'DifferentialRevisionCloseDetailsController', 'update/(?P<revisionID>[1-9]\d*)/' => 'DifferentialDiffCreateController', 'operation/(?P<id>[1-9]\d*)/' => 'DifferentialRevisionOperationController', 'inlines/(?P<id>[1-9]\d*)/' => 'DifferentialRevisionInlinesController', ), 'comment/' => array( 'preview/(?P<id>[1-9]\d*)/' => 'DifferentialCommentPreviewController', 'save/(?P<id>[1-9]\d*)/' => 'DifferentialCommentSaveController', 'inline/' => array( 'preview/(?P<id>[1-9]\d*)/' => 'DifferentialInlineCommentPreviewController', 'edit/(?P<id>[1-9]\d*)/' => 'DifferentialInlineCommentEditController', ), ), 'preview/' => 'PhabricatorMarkupPreviewController', ), ); } public function getApplicationOrder() { return 0.100; } public function getRemarkupRules() { return array( new DifferentialRemarkupRule(), ); } public function supportsEmailIntegration() { return true; } public function getAppEmailBlurb() { return pht( 'Send email to these addresses to create revisions. The body of the '. 'message and / or one or more attachments should be the output of a '. '"diff" command. %s', phutil_tag( 'a', array( 'href' => $this->getInboundEmailSupportLink(), ), pht('Learn More'))); } protected function getCustomCapabilities() { return array( DifferentialDefaultViewCapability::CAPABILITY => array( 'caption' => pht('Default view policy for newly created revisions.'), 'template' => DifferentialRevisionPHIDType::TYPECONST, 'capability' => PhabricatorPolicyCapability::CAN_VIEW, ), ); } public function getMailCommandObjects() { return array( 'revision' => array( 'name' => pht('Email Commands: Revisions'), 'header' => pht('Interacting with Differential Revisions'), 'object' => new DifferentialRevision(), 'summary' => pht( 'This page documents the commands you can use to interact with '. 'revisions in Differential.'), ), ); } public function getApplicationSearchDocumentTypes() { return array( DifferentialRevisionPHIDType::TYPECONST, ); } }
Java
/* * Copyright 2019 NAVER Corp. * * 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.navercorp.pinpoint.profiler.sender.grpc; import com.navercorp.pinpoint.common.util.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * @author Woonduk Kang(emeroad) */ public class ReconnectExecutor { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private volatile boolean shutdown; private final ScheduledExecutorService scheduledExecutorService; private final AtomicLong rejectedCounter = new AtomicLong(); public ReconnectExecutor(ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = Assert.requireNonNull(scheduledExecutorService, "scheduledExecutorService"); } private void execute0(Runnable command) { Assert.requireNonNull(command, "command"); if (shutdown) { logger.debug("already shutdown"); return; } if (command instanceof ReconnectJob) { ReconnectJob reconnectJob = (ReconnectJob) command; try { scheduledExecutorService.schedule(reconnectJob, reconnectJob.nextBackoffNanos(), TimeUnit.NANOSECONDS); } catch (RejectedExecutionException e) { final long failCount = rejectedCounter.incrementAndGet(); logger.info("{} reconnectJob scheduled fail {}", command, failCount); } } else { throw new IllegalArgumentException("unknown command type " + command); } } public void close() { shutdown = true; } public Reconnector newReconnector(Runnable reconnectJob) { Assert.requireNonNull(reconnectJob, "reconnectJob"); if (logger.isInfoEnabled()) { logger.info("newReconnector(reconnectJob = [{}])", reconnectJob); } final Executor dispatch = new Executor() { @Override public void execute(Runnable command) { ReconnectExecutor.this.execute0(command); } }; final ReconnectJob reconnectJobWrap = wrapReconnectJob(reconnectJob); return new ReconnectAdaptor(dispatch, reconnectJobWrap); } private ReconnectJob wrapReconnectJob(Runnable runnable) { return new ExponentialBackoffReconnectJob(runnable); } }
Java
/* * 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.solr.internal.csv; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; /** Utility methods for dealing with CSV files */ public class CSVUtils { private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final String[][] EMPTY_DOUBLE_STRING_ARRAY = new String[0][0]; /** * <code>CSVUtils</code> instances should NOT be constructed in standard programming. * * <p>This constructor is public to permit tools that require a JavaBean instance to operate. */ public CSVUtils() {} /** * Converts an array of string values into a single CSV line. All <code>null</code> values are * converted to the string <code>"null"</code>, all strings equal to <code>"null"</code> will * additionally get quotes around. * * @param values the value array * @return the CSV string, will be an empty string if the length of the value array is 0 */ public static String printLine(String[] values, CSVStrategy strategy) { // set up a CSVUtils StringWriter stringWriter = new StringWriter(); CSVPrinter csvPrinter = new CSVPrinter(stringWriter, strategy); // check for null values an "null" as strings and convert them // into the strings "null" and "\"null\"" for (int i = 0; i < values.length; i++) { if (values[i] == null) { values[i] = "null"; } else if (values[i].equals("null")) { values[i] = "\"null\""; } } // convert to CSV try { csvPrinter.println(values); } catch (IOException e) { // should not happen with StringWriter } // as the resulting string has \r\n at the end, we will trim that away return stringWriter.toString().trim(); } // ====================================================== // static parsers // ====================================================== /** * Parses the given String according to the default {@link CSVStrategy}. * * @param s CSV String to be parsed. * @return parsed String matrix (which is never null) * @throws IOException in case of error */ public static String[][] parse(String s) throws IOException { if (s == null) { throw new IllegalArgumentException("Null argument not allowed."); } String[][] result = (new CSVParser(new StringReader(s))).getAllValues(); if (result == null) { // since CSVStrategy ignores empty lines an empty array is returned // (i.e. not "result = new String[][] {{""}};") result = EMPTY_DOUBLE_STRING_ARRAY; } return result; } /** * Parses the first line only according to the default {@link CSVStrategy}. * * <p>Parsing empty string will be handled as valid records containing zero elements, so the * following property holds: parseLine("").length == 0. * * @param s CSV String to be parsed. * @return parsed String vector (which is never null) * @throws IOException in case of error */ public static String[] parseLine(String s) throws IOException { if (s == null) { throw new IllegalArgumentException("Null argument not allowed."); } // uh,jh: make sure that parseLine("").length == 0 if (s.length() == 0) { return EMPTY_STRING_ARRAY; } return (new CSVParser(new StringReader(s))).getLine(); } }
Java
/* * Autosleep * Copyright (C) 2016 Orange * Authors: Benjamin Einaudi [email protected] * Arnaud Ruffin [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.autosleep.ui.proxy; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.net.HttpURLConnection; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; @Configuration public class HttpClientConfiguration { @Value("${autowakeup.skip.ssl.validation:false}") private boolean skipSslValidation; private SSLContext buildSslContext(TrustManager trustManager) { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{trustManager}, null); return sslContext; } catch (KeyManagementException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } } private TrustManager buildTrustAllCerts() { return new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] certificates, String client) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] certificates, String client) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; } private HostnameVerifier buildVerifyNoHostname() { return (hostname, session) -> true; } @Bean public RestTemplate restTemplate() { if (!skipSslValidation) { return new RestTemplate(); } else { final HostnameVerifier hostnameVerifier = buildVerifyNoHostname(); final SSLContext sslContext = buildSslContext(buildTrustAllCerts()); return new RestTemplate(new SimpleClientHttpRequestFactory() { @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if (connection instanceof HttpsURLConnection) { HttpsURLConnection secureConnection = (HttpsURLConnection) connection; secureConnection.setHostnameVerifier(hostnameVerifier); secureConnection.setSSLSocketFactory(sslContext.getSocketFactory()); } super.prepareConnection(connection, httpMethod); } }); } } }
Java
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Web.Mvc { public abstract class MvcFilter : IMvcFilter { protected MvcFilter() { } protected MvcFilter(bool allowMultiple, int order) { AllowMultiple = allowMultiple; Order = order; } public bool AllowMultiple { get; private set; } public int Order { get; private set; } } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.weld.tests.event.observer.transactional; import static javax.ejb.TransactionManagementType.BEAN; import static javax.enterprise.event.TransactionPhase.AFTER_COMPLETION; import static javax.enterprise.event.TransactionPhase.AFTER_FAILURE; import static javax.enterprise.event.TransactionPhase.AFTER_SUCCESS; import static javax.enterprise.event.TransactionPhase.BEFORE_COMPLETION; import static javax.enterprise.event.TransactionPhase.IN_PROGRESS; import java.io.Serializable; import javax.annotation.Priority; import javax.ejb.Stateful; import javax.ejb.TransactionManagement; import javax.enterprise.context.SessionScoped; import javax.enterprise.event.Observes; @Stateful @TransactionManagement(BEAN) @Tame @SessionScoped @SuppressWarnings("serial") public class Pomeranian implements PomeranianInterface, Serializable { @Override public void observeInProgress(@Observes(during = IN_PROGRESS) Bark event) { Actions.add(IN_PROGRESS); } @Override public void observeAfterCompletion(@Observes(during = AFTER_COMPLETION) Bark someEvent) { Actions.add(AFTER_COMPLETION); } @Override public void observeAfterSuccess(@Observes(during = AFTER_SUCCESS) Bark event) { Actions.add(AFTER_SUCCESS); } @Override public void observeAfterSuccessWithHighPriority(@Priority(1) @Observes(during = AFTER_SUCCESS) Bark event) { Actions.add(AFTER_SUCCESS + "1"); } @Override public void observeAfterSuccessWithLowPriority(@Priority(100) @Observes(during = AFTER_SUCCESS) Bark event) { Actions.add(AFTER_SUCCESS + "100"); } @Override public void observeAfterFailure(@Observes(during = AFTER_FAILURE) Bark event) { Actions.add(AFTER_FAILURE); } @Override public void observeBeforeCompletion(@Observes(during = BEFORE_COMPLETION) Bark event) { Actions.add(BEFORE_COMPLETION); } @Override public void observeAndFail(@Observes(during=BEFORE_COMPLETION) @Gnarly Bark event) throws FooException { Actions.add(BEFORE_COMPLETION); throw new FooException(); } }
Java
// 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. * using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Apache Software Foundation")] [assembly: AssemblyProduct("Apache Etch")] [assembly: AssemblyCopyright("Copyright © Apache Software Foundation 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")]
Java
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/appstream/AppStream_EXPORTS.h> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace AppStream { namespace Model { class AWS_APPSTREAM_API DisassociateFleetResult { public: DisassociateFleetResult(); DisassociateFleetResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); DisassociateFleetResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); }; } // namespace Model } // namespace AppStream } // namespace Aws
Java
/* * Kendo UI Web v2014.1.318 (http://kendoui.com) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI Web commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-web * If you do not own a commercial license, this file shall be governed by the * GNU General Public License (GPL) version 3. * For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["he"] = { name: "he", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$-n","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "₪" } }, calendars: { standard: { days: { names: ["יום ראשון","יום שני","יום שלישי","יום רביעי","יום חמישי","יום שישי","שבת"], namesAbbr: ["יום א","יום ב","יום ג","יום ד","יום ה","יום ו","שבת"], namesShort: ["א","ב","ג","ד","ה","ו","ש"] }, months: { names: ["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר",""], namesAbbr: ["ינו","פבר","מרץ","אפר","מאי","יונ","יול","אוג","ספט","אוק","נוב","דצמ",""] }, AM: ["AM","am","AM"], PM: ["PM","pm","PM"], patterns: { d: "dd/MM/yyyy", D: "dddd dd MMMM yyyy", F: "dddd dd MMMM yyyy HH:mm:ss", g: "dd/MM/yyyy HH:mm", G: "dd/MM/yyyy HH:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": "/", ":": ":", firstDay: 0 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
Java
/** * Copyright (c) Microsoft Corporation * * 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. * * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, * MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ package com.interopbridges.scx.webservices; /** * * <p> * Concrete representation of an Endpoint to match what is described in the web * service's WSDL. * </p> * * <p> * * <pre> * &lt;service name="CalculatorService"&gt; * &lt;port name="CalculatorPort" binding="tns:CalculatorPortBinding"&gt; * &lt;soap:address location="http://scxom64-ws7-02:9080/WebServiceProject/CalculatorService" /&gt; * &lt;/port&gt; * &lt;/service&gt; * </pre> * * </p> * * <p> * Typically this might look like: * <ol> * <li><b>http://scxom64-ws7-02:9080/WebServiceProject/CalculatorService</b></li> * <li><b>http://scxom-ws7-02:8080/axis2/services/DinnerFinderService</li> * DinnerFinderServiceHttpSoap11Endpoint/</b> * </ol>> * </p> * * @author Christopher Crammond */ public class Endpoint implements EndpointMBean { /** * Key for describing for the (interopbridges) JMX type of MBean */ private String _jmxType = "endpoint"; /** * String representing the full URL of the endpoint address. This should * match the soap:address's location attribute from the WSDL. <br> * */ private String _url; /** * Empty Constructor. It is considered to be a best practice to create this * default constructor rather than relying on the compiler to auto-generate * it. */ public Endpoint() { this._url = ""; } /** * Preferred Constructor * * @param url * String representing the full URL of the endpoint address. */ public Endpoint(String url) { this._url = url; } /* * (non-Javadoc) * * @see com.interopbridges.scx.webservices.EndpointMBean#getUrl() */ public String getUrl() { return this._url; } /* * (non-Javadoc) * * @see com.interopbridges.scx.webservices.IMBean#getJmxType() */ public String getJmxType() { return this._jmxType; } }
Java
/* * 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.cache.snapshot; import java.io.Serializable; import org.apache.geode.internal.cache.snapshot.SnapshotFileMapper; /** * Provides a way to configure the behavior of snapshot operations. The default options are: * <dl> * <dt>filter</dt> * <dd>null</dd> * </dl> * * @param <K> the cache entry key type * @param <V> the cache entry value type * * @since GemFire 7.0 */ public interface SnapshotOptions<K, V> extends Serializable { /** * Defines the available snapshot file formats. * * @since GemFire 7.0 */ enum SnapshotFormat { /** an optimized binary format specific to GemFire */ GEMFIRE } /** * Sets a filter to apply to snapshot entries. Entries that are accepted by the filter will be * included in import and export operations. * * @param filter the filter to apply, or null to remove the filter * @return the snapshot options */ SnapshotOptions<K, V> setFilter(SnapshotFilter<K, V> filter); /** * Returns the filter to be applied to snapshot entries. Entries that are accepted by the filter * will be included in import and export operations. * * @return the filter, or null if the filter is not set */ SnapshotFilter<K, V> getFilter(); /** * Sets whether to invoke callbacks when loading a snapshot. The default is false. * * @param invokeCallbacks * * @return the snapshot options */ SnapshotOptions<K, V> invokeCallbacks(boolean invokeCallbacks); /** * Returns whether loading a snapshot causes callbacks to be invoked * * @return whether loading a snapshot causes callbacks to be invoked */ boolean shouldInvokeCallbacks(); /** * Returns true if the snapshot operation will proceed in parallel. * * @return true if the parallel mode has been enabled * * @since Geode 1.3 */ boolean isParallelMode(); /** * Enables parallel mode for snapshot export, which will cause each member of a partitioned region * to save its local data set (ignoring redundant copies) to a separate snapshot file. * * <p> * Parallelizing snapshot operations may yield significant performance improvements for large data * sets. This is particularly true when each member is writing to separate physical disks. * <p> * This flag is ignored for replicated regions. * * @param parallel true if the snapshot operations will be performed in parallel * @return the snapshot options * * @see SnapshotFileMapper * * @since Geode 1.3 */ SnapshotOptions<K, V> setParallelMode(boolean parallel); }
Java
# Copyright (c) 2021 PaddlePaddle 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. from __future__ import print_function import unittest import numpy as np import paddle import paddle.fluid.core as core from op_test import OpTest class ApiFMaxTest(unittest.TestCase): """ApiFMaxTest""" def setUp(self): """setUp""" if core.is_compiled_with_cuda(): self.place = core.CUDAPlace(0) else: self.place = core.CPUPlace() self.input_x = np.random.rand(10, 15).astype("float32") self.input_y = np.random.rand(10, 15).astype("float32") self.input_z = np.random.rand(15).astype("float32") self.input_a = np.array([0, np.nan, np.nan]).astype('int64') self.input_b = np.array([2, np.inf, -np.inf]).astype('int64') self.input_c = np.array([4, 1, 3]).astype('int64') self.np_expected1 = np.fmax(self.input_x, self.input_y) self.np_expected2 = np.fmax(self.input_x, self.input_z) self.np_expected3 = np.fmax(self.input_a, self.input_c) self.np_expected4 = np.fmax(self.input_b, self.input_c) def test_static_api(self): """test_static_api""" paddle.enable_static() with paddle.static.program_guard(paddle.static.Program(), paddle.static.Program()): data_x = paddle.static.data("x", shape=[10, 15], dtype="float32") data_y = paddle.static.data("y", shape=[10, 15], dtype="float32") result_fmax = paddle.fmax(data_x, data_y) exe = paddle.static.Executor(self.place) res, = exe.run(feed={"x": self.input_x, "y": self.input_y}, fetch_list=[result_fmax]) self.assertTrue(np.allclose(res, self.np_expected1)) with paddle.static.program_guard(paddle.static.Program(), paddle.static.Program()): data_x = paddle.static.data("x", shape=[10, 15], dtype="float32") data_z = paddle.static.data("z", shape=[15], dtype="float32") result_fmax = paddle.fmax(data_x, data_z) exe = paddle.static.Executor(self.place) res, = exe.run(feed={"x": self.input_x, "z": self.input_z}, fetch_list=[result_fmax]) self.assertTrue(np.allclose(res, self.np_expected2)) with paddle.static.program_guard(paddle.static.Program(), paddle.static.Program()): data_a = paddle.static.data("a", shape=[3], dtype="int64") data_c = paddle.static.data("c", shape=[3], dtype="int64") result_fmax = paddle.fmax(data_a, data_c) exe = paddle.static.Executor(self.place) res, = exe.run(feed={"a": self.input_a, "c": self.input_c}, fetch_list=[result_fmax]) self.assertTrue(np.allclose(res, self.np_expected3)) with paddle.static.program_guard(paddle.static.Program(), paddle.static.Program()): data_b = paddle.static.data("b", shape=[3], dtype="int64") data_c = paddle.static.data("c", shape=[3], dtype="int64") result_fmax = paddle.fmax(data_b, data_c) exe = paddle.static.Executor(self.place) res, = exe.run(feed={"b": self.input_b, "c": self.input_c}, fetch_list=[result_fmax]) self.assertTrue(np.allclose(res, self.np_expected4)) def test_dynamic_api(self): """test_dynamic_api""" paddle.disable_static() x = paddle.to_tensor(self.input_x) y = paddle.to_tensor(self.input_y) z = paddle.to_tensor(self.input_z) a = paddle.to_tensor(self.input_a) b = paddle.to_tensor(self.input_b) c = paddle.to_tensor(self.input_c) res = paddle.fmax(x, y) res = res.numpy() self.assertTrue(np.allclose(res, self.np_expected1)) # test broadcast res = paddle.fmax(x, z) res = res.numpy() self.assertTrue(np.allclose(res, self.np_expected2)) res = paddle.fmax(a, c) res = res.numpy() self.assertTrue(np.allclose(res, self.np_expected3)) res = paddle.fmax(b, c) res = res.numpy() self.assertTrue(np.allclose(res, self.np_expected4)) class TestElementwiseFmaxOp(OpTest): """TestElementwiseFmaxOp""" def setUp(self): """setUp""" self.op_type = "elementwise_fmax" # If x and y have the same value, the max() is not differentiable. # So we generate test data by the following method # to avoid them being too close to each other. x = np.random.uniform(0.1, 1, [13, 17]).astype("float64") sgn = np.random.choice([-1, 1], [13, 17]).astype("float64") y = x + sgn * np.random.uniform(0.1, 1, [13, 17]).astype("float64") self.inputs = {'X': x, 'Y': y} self.outputs = {'Out': np.fmax(self.inputs['X'], self.inputs['Y'])} def test_check_output(self): """test_check_output""" self.check_output() def test_check_grad_normal(self): """test_check_grad_normal""" self.check_grad(['X', 'Y'], 'Out') def test_check_grad_ingore_x(self): """test_check_grad_ingore_x""" self.check_grad( ['Y'], 'Out', max_relative_error=0.005, no_grad_set=set("X")) def test_check_grad_ingore_y(self): """test_check_grad_ingore_y""" self.check_grad( ['X'], 'Out', max_relative_error=0.005, no_grad_set=set('Y')) class TestElementwiseFmax2Op(OpTest): """TestElementwiseFmax2Op""" def setUp(self): """setUp""" self.op_type = "elementwise_fmax" # If x and y have the same value, the max() is not differentiable. # So we generate test data by the following method # to avoid them being too close to each other. x = np.random.uniform(0.1, 1, [13, 17]).astype("float64") sgn = np.random.choice([-1, 1], [13, 17]).astype("float64") y = x + sgn * np.random.uniform(0.1, 1, [13, 17]).astype("float64") y[2, 10:] = np.nan self.inputs = {'X': x, 'Y': y} self.outputs = {'Out': np.fmax(self.inputs['X'], self.inputs['Y'])} def test_check_output(self): """test_check_output""" self.check_output() def test_check_grad_normal(self): """test_check_grad_normal""" self.check_grad(['X', 'Y'], 'Out') def test_check_grad_ingore_x(self): """test_check_grad_ingore_x""" self.check_grad( ['Y'], 'Out', max_relative_error=0.005, no_grad_set=set("X")) def test_check_grad_ingore_y(self): """test_check_grad_ingore_y""" self.check_grad( ['X'], 'Out', max_relative_error=0.005, no_grad_set=set('Y'))
Java
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.weld.util.bean; import java.io.Serializable; import javax.enterprise.inject.spi.InjectionPoint; import org.jboss.weld.injection.ForwardingInjectionPoint; import org.jboss.weld.serialization.InjectionPointHolder; public class SerializableForwardingInjectionPoint extends ForwardingInjectionPoint implements Serializable { private static final long serialVersionUID = 7803445899943317029L; private final InjectionPointHolder ip; public SerializableForwardingInjectionPoint(String contextId, InjectionPoint ip) { this.ip = new InjectionPointHolder(contextId, ip); } @Override protected InjectionPoint delegate() { return ip.get(); } }
Java
/* * 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.logging.log4j.flume.appender; import java.util.Properties; import org.apache.flume.Event; import org.apache.flume.api.RpcClient; import org.apache.flume.api.RpcClientFactory; import org.apache.logging.log4j.core.appender.AppenderLoggingException; import org.apache.logging.log4j.core.appender.ManagerFactory; /** * Manager for FlumeAvroAppenders. */ public class FlumeAvroManager extends AbstractFlumeManager { private static final int MAX_RECONNECTS = 3; private static final int MINIMUM_TIMEOUT = 1000; private static AvroManagerFactory factory = new AvroManagerFactory(); private final Agent[] agents; private final int batchSize; private final int retries; private final int connectTimeout; private final int requestTimeout; private final int current = 0; private RpcClient rpcClient = null; /** * Constructor * @param name The unique name of this manager. * @param agents An array of Agents. * @param batchSize The number of events to include in a batch. * @param retries The number of times to retry connecting before giving up. * @param connectTimeout The connection timeout in ms. * @param requestTimeout The request timeout in ms. * */ protected FlumeAvroManager(final String name, final String shortName, final Agent[] agents, final int batchSize, final int retries, final int connectTimeout, final int requestTimeout) { super(name); this.agents = agents; this.batchSize = batchSize; this.retries = retries; this.connectTimeout = connectTimeout; this.requestTimeout = requestTimeout; this.rpcClient = connect(agents, retries, connectTimeout, requestTimeout); } /** * Returns a FlumeAvroManager. * @param name The name of the manager. * @param agents The agents to use. * @param batchSize The number of events to include in a batch. * @param retries The number of times to retry connecting before giving up. * @param connectTimeout The connection timeout in ms. * @param requestTimeout The request timeout in ms. * @return A FlumeAvroManager. */ public static FlumeAvroManager getManager(final String name, final Agent[] agents, int batchSize, final int retries, final int connectTimeout, final int requestTimeout) { if (agents == null || agents.length == 0) { throw new IllegalArgumentException("At least one agent is required"); } if (batchSize <= 0) { batchSize = 1; } final StringBuilder sb = new StringBuilder("FlumeAvro["); boolean first = true; for (final Agent agent : agents) { if (!first) { sb.append(","); } sb.append(agent.getHost()).append(":").append(agent.getPort()); first = false; } sb.append("]"); return getManager(sb.toString(), factory, new FactoryData(name, agents, batchSize, retries, connectTimeout, requestTimeout)); } /** * Returns the agents. * @return The agent array. */ public Agent[] getAgents() { return agents; } /** * Returns the index of the current agent. * @return The index for the current agent. */ public int getCurrent() { return current; } public int getRetries() { return retries; } public int getConnectTimeout() { return connectTimeout; } public int getRequestTimeout() { return requestTimeout; } public int getBatchSize() { return batchSize; } public synchronized void send(final BatchEvent events) { if (rpcClient == null) { rpcClient = connect(agents, retries, connectTimeout, requestTimeout); } if (rpcClient != null) { try { LOGGER.trace("Sending batch of {} events", events.getEvents().size()); rpcClient.appendBatch(events.getEvents()); } catch (final Exception ex) { rpcClient.close(); rpcClient = null; final String msg = "Unable to write to " + getName() + " at " + agents[current].getHost() + ":" + agents[current].getPort(); LOGGER.warn(msg, ex); throw new AppenderLoggingException("No Flume agents are available"); } } else { final String msg = "Unable to write to " + getName() + " at " + agents[current].getHost() + ":" + agents[current].getPort(); LOGGER.warn(msg); throw new AppenderLoggingException("No Flume agents are available"); } } @Override public synchronized void send(final Event event) { if (rpcClient == null) { rpcClient = connect(agents, retries, connectTimeout, requestTimeout); } if (rpcClient != null) { try { rpcClient.append(event); } catch (final Exception ex) { rpcClient.close(); rpcClient = null; final String msg = "Unable to write to " + getName() + " at " + agents[current].getHost() + ":" + agents[current].getPort(); LOGGER.warn(msg, ex); throw new AppenderLoggingException("No Flume agents are available"); } } else { final String msg = "Unable to write to " + getName() + " at " + agents[current].getHost() + ":" + agents[current].getPort(); LOGGER.warn(msg); throw new AppenderLoggingException("No Flume agents are available"); } } /** * There is a very good chance that this will always return the first agent even if it isn't available. * @param agents The list of agents to choose from * @return The FlumeEventAvroServer. */ private RpcClient connect(final Agent[] agents, int retries, final int connectTimeout, final int requestTimeout) { try { final Properties props = new Properties(); props.put("client.type", agents.length > 1 ? "default_failover" : "default"); int count = 1; final StringBuilder sb = new StringBuilder(); for (final Agent agent : agents) { if (sb.length() > 0) { sb.append(" "); } final String hostName = "host" + count++; props.put("hosts." + hostName, agent.getHost() + ":" + agent.getPort()); sb.append(hostName); } props.put("hosts", sb.toString()); if (batchSize > 0) { props.put("batch-size", Integer.toString(batchSize)); } if (retries > 1) { if (retries > MAX_RECONNECTS) { retries = MAX_RECONNECTS; } props.put("max-attempts", Integer.toString(retries * agents.length)); } if (requestTimeout >= MINIMUM_TIMEOUT) { props.put("request-timeout", Integer.toString(requestTimeout)); } if (connectTimeout >= MINIMUM_TIMEOUT) { props.put("connect-timeout", Integer.toString(connectTimeout)); } return RpcClientFactory.getInstance(props); } catch (final Exception ex) { LOGGER.error("Unable to create Flume RPCClient: {}", ex.getMessage()); return null; } } @Override protected void releaseSub() { if (rpcClient != null) { try { rpcClient.close(); } catch (final Exception ex) { LOGGER.error("Attempt to close RPC client failed", ex); } } rpcClient = null; } /** * Factory data. */ private static class FactoryData { private final String name; private final Agent[] agents; private final int batchSize; private final int retries; private final int conntectTimeout; private final int requestTimeout; /** * Constructor. * @param name The name of the Appender. * @param agents The agents. * @param batchSize The number of events to include in a batch. */ public FactoryData(final String name, final Agent[] agents, final int batchSize, final int retries, final int connectTimeout, final int requestTimeout) { this.name = name; this.agents = agents; this.batchSize = batchSize; this.retries = retries; this.conntectTimeout = connectTimeout; this.requestTimeout = requestTimeout; } } /** * Avro Manager Factory. */ private static class AvroManagerFactory implements ManagerFactory<FlumeAvroManager, FactoryData> { /** * Create the FlumeAvroManager. * @param name The name of the entity to manage. * @param data The data required to create the entity. * @return The FlumeAvroManager. */ @Override public FlumeAvroManager createManager(final String name, final FactoryData data) { try { return new FlumeAvroManager(name, data.name, data.agents, data.batchSize, data.retries, data.conntectTimeout, data.requestTimeout); } catch (final Exception ex) { LOGGER.error("Could not create FlumeAvroManager", ex); } return null; } } }
Java
package net.stickycode.configuration.value; import net.stickycode.configuration.ConfigurationValue; public class SystemValue implements ConfigurationValue { private String value; public SystemValue(String value) { this.value = value; } @Override public String get() { return value; } @Override public boolean hasPrecedence(ConfigurationValue v) { if (ApplicationValue.class.isAssignableFrom(v.getClass())) return false; if (SystemValue.class.isAssignableFrom(v.getClass())) return false; return true; } @Override public String toString() { return getClass().getSimpleName() + "{" + value + "}"; } }
Java
// Generated by xsd compiler for android/java // DO NOT CHANGE! package com.ebay.marketplace.search.v1.services; import com.leansoft.nano.annotation.*; /** * * Reserved for future use. * */ @RootElement(name = "findItemsForFavoriteSearchResponse", namespace = "http://www.ebay.com/marketplace/search/v1/services") public class FindItemsForFavoriteSearchResponse extends BaseFindingServiceResponse { @Element private CategoryHistogramContainer categoryHistogramContainer; @Element private AspectHistogramContainer aspectHistogramContainer; @Element private ConditionHistogramContainer conditionHistogramContainer; /** * public getter * * * Reserved for future use. * * * @returns com.ebay.marketplace.search.v1.services.CategoryHistogramContainer */ public CategoryHistogramContainer getCategoryHistogramContainer() { return this.categoryHistogramContainer; } /** * public setter * * * Reserved for future use. * * * @param com.ebay.marketplace.search.v1.services.CategoryHistogramContainer */ public void setCategoryHistogramContainer(CategoryHistogramContainer categoryHistogramContainer) { this.categoryHistogramContainer = categoryHistogramContainer; } /** * public getter * * * Reserved for future use. * * * @returns com.ebay.marketplace.search.v1.services.AspectHistogramContainer */ public AspectHistogramContainer getAspectHistogramContainer() { return this.aspectHistogramContainer; } /** * public setter * * * Reserved for future use. * * * @param com.ebay.marketplace.search.v1.services.AspectHistogramContainer */ public void setAspectHistogramContainer(AspectHistogramContainer aspectHistogramContainer) { this.aspectHistogramContainer = aspectHistogramContainer; } /** * public getter * * * Reserved for future use. * * * @returns com.ebay.marketplace.search.v1.services.ConditionHistogramContainer */ public ConditionHistogramContainer getConditionHistogramContainer() { return this.conditionHistogramContainer; } /** * public setter * * * Reserved for future use. * * * @param com.ebay.marketplace.search.v1.services.ConditionHistogramContainer */ public void setConditionHistogramContainer(ConditionHistogramContainer conditionHistogramContainer) { this.conditionHistogramContainer = conditionHistogramContainer; } }
Java
package transaction import ( . "DNA/common" "DNA/common/serialization" "DNA/core/contract" "DNA/core/contract/program" sig "DNA/core/signature" "DNA/core/transaction/payload" . "DNA/errors" "crypto/sha256" "errors" "fmt" "io" "sort" ) //for different transaction types with different payload format //and transaction process methods type TransactionType byte const ( BookKeeping TransactionType = 0x00 IssueAsset TransactionType = 0x01 BookKeeper TransactionType = 0x02 PrivacyPayload TransactionType = 0x20 RegisterAsset TransactionType = 0x40 TransferAsset TransactionType = 0x80 Record TransactionType = 0x81 DeployCode TransactionType = 0xd0 DataFile TransactionType = 0x12 ) //Payload define the func for loading the payload data //base on payload type which have different struture type Payload interface { // Get payload data Data(version byte) []byte //Serialize payload data Serialize(w io.Writer, version byte) error Deserialize(r io.Reader, version byte) error } //Transaction is used for carry information or action to Ledger //validated transaction will be added to block and updates state correspondingly var TxStore ILedgerStore type Transaction struct { TxType TransactionType PayloadVersion byte Payload Payload Attributes []*TxAttribute UTXOInputs []*UTXOTxInput BalanceInputs []*BalanceTxInput Outputs []*TxOutput Programs []*program.Program //Inputs/Outputs map base on Asset (needn't serialize) AssetOutputs map[Uint256][]*TxOutput AssetInputAmount map[Uint256]Fixed64 AssetOutputAmount map[Uint256]Fixed64 hash *Uint256 } //Serialize the Transaction func (tx *Transaction) Serialize(w io.Writer) error { err := tx.SerializeUnsigned(w) if err != nil { return NewDetailErr(err, ErrNoCode, "Transaction txSerializeUnsigned Serialize failed.") } //Serialize Transaction's programs lens := uint64(len(tx.Programs)) err = serialization.WriteVarUint(w, lens) if err != nil { return NewDetailErr(err, ErrNoCode, "Transaction WriteVarUint failed.") } if lens > 0 { for _, p := range tx.Programs { err = p.Serialize(w) if err != nil { return NewDetailErr(err, ErrNoCode, "Transaction Programs Serialize failed.") } } } return nil } //Serialize the Transaction data without contracts func (tx *Transaction) SerializeUnsigned(w io.Writer) error { //txType w.Write([]byte{byte(tx.TxType)}) //PayloadVersion w.Write([]byte{tx.PayloadVersion}) //Payload if tx.Payload == nil { return errors.New("Transaction Payload is nil.") } tx.Payload.Serialize(w, tx.PayloadVersion) //[]*txAttribute err := serialization.WriteVarUint(w, uint64(len(tx.Attributes))) if err != nil { return NewDetailErr(err, ErrNoCode, "Transaction item txAttribute length serialization failed.") } if len(tx.Attributes) > 0 { for _, attr := range tx.Attributes { attr.Serialize(w) } } //[]*UTXOInputs err = serialization.WriteVarUint(w, uint64(len(tx.UTXOInputs))) if err != nil { return NewDetailErr(err, ErrNoCode, "Transaction item UTXOInputs length serialization failed.") } if len(tx.UTXOInputs) > 0 { for _, utxo := range tx.UTXOInputs { utxo.Serialize(w) } } // TODO BalanceInputs //[]*Outputs err = serialization.WriteVarUint(w, uint64(len(tx.Outputs))) if err != nil { return NewDetailErr(err, ErrNoCode, "Transaction item Outputs length serialization failed.") } if len(tx.Outputs) > 0 { for _, output := range tx.Outputs { output.Serialize(w) } } return nil } //deserialize the Transaction func (tx *Transaction) Deserialize(r io.Reader) error { // tx deserialize err := tx.DeserializeUnsigned(r) if err != nil { return NewDetailErr(err, ErrNoCode, "transaction Deserialize error") } // tx program lens, err := serialization.ReadVarUint(r, 0) if err != nil { return NewDetailErr(err, ErrNoCode, "transaction tx program Deserialize error") } programHashes := []*program.Program{} if lens > 0 { for i := 0; i < int(lens); i++ { outputHashes := new(program.Program) outputHashes.Deserialize(r) programHashes = append(programHashes, outputHashes) } tx.Programs = programHashes } return nil } func (tx *Transaction) DeserializeUnsigned(r io.Reader) error { var txType [1]byte _, err := io.ReadFull(r, txType[:]) if err != nil { return err } tx.TxType = TransactionType(txType[0]) return tx.DeserializeUnsignedWithoutType(r) } func (tx *Transaction) DeserializeUnsignedWithoutType(r io.Reader) error { var payloadVersion [1]byte _, err := io.ReadFull(r, payloadVersion[:]) tx.PayloadVersion = payloadVersion[0] if err != nil { return err } //payload //tx.Payload.Deserialize(r) switch tx.TxType { case RegisterAsset: tx.Payload = new(payload.RegisterAsset) case IssueAsset: tx.Payload = new(payload.IssueAsset) case TransferAsset: tx.Payload = new(payload.TransferAsset) case BookKeeping: tx.Payload = new(payload.BookKeeping) case Record: tx.Payload = new(payload.Record) case BookKeeper: tx.Payload = new(payload.BookKeeper) case PrivacyPayload: tx.Payload = new(payload.PrivacyPayload) case DataFile: tx.Payload = new(payload.DataFile) default: return errors.New("[Transaction],invalide transaction type.") } err = tx.Payload.Deserialize(r, tx.PayloadVersion) if err != nil { return NewDetailErr(err, ErrNoCode, "Payload Parse error") } //attributes Len, err := serialization.ReadVarUint(r, 0) if err != nil { return err } if Len > uint64(0) { for i := uint64(0); i < Len; i++ { attr := new(TxAttribute) err = attr.Deserialize(r) if err != nil { return err } tx.Attributes = append(tx.Attributes, attr) } } //UTXOInputs Len, err = serialization.ReadVarUint(r, 0) if err != nil { return err } if Len > uint64(0) { for i := uint64(0); i < Len; i++ { utxo := new(UTXOTxInput) err = utxo.Deserialize(r) if err != nil { return err } tx.UTXOInputs = append(tx.UTXOInputs, utxo) } } //TODO balanceInputs //Outputs Len, err = serialization.ReadVarUint(r, 0) if err != nil { return err } if Len > uint64(0) { for i := uint64(0); i < Len; i++ { output := new(TxOutput) output.Deserialize(r) tx.Outputs = append(tx.Outputs, output) } } return nil } func (tx *Transaction) GetProgramHashes() ([]Uint160, error) { if tx == nil { return []Uint160{}, errors.New("[Transaction],GetProgramHashes transaction is nil.") } hashs := []Uint160{} uniqHashes := []Uint160{} // add inputUTXO's transaction referenceWithUTXO_Output, err := tx.GetReference() if err != nil { return nil, NewDetailErr(err, ErrNoCode, "[Transaction], GetProgramHashes failed.") } for _, output := range referenceWithUTXO_Output { programHash := output.ProgramHash hashs = append(hashs, programHash) } for _, attribute := range tx.Attributes { if attribute.Usage == Script { dataHash, err := Uint160ParseFromBytes(attribute.Data) if err != nil { return nil, NewDetailErr(errors.New("[Transaction], GetProgramHashes err."), ErrNoCode, "") } hashs = append(hashs, Uint160(dataHash)) } } switch tx.TxType { case RegisterAsset: issuer := tx.Payload.(*payload.RegisterAsset).Issuer signatureRedeemScript, err := contract.CreateSignatureRedeemScript(issuer) if err != nil { return nil, NewDetailErr(err, ErrNoCode, "[Transaction], GetProgramHashes CreateSignatureRedeemScript failed.") } astHash, err := ToCodeHash(signatureRedeemScript) if err != nil { return nil, NewDetailErr(err, ErrNoCode, "[Transaction], GetProgramHashes ToCodeHash failed.") } hashs = append(hashs, astHash) case IssueAsset: result := tx.GetMergedAssetIDValueFromOutputs() if err != nil { return nil, NewDetailErr(err, ErrNoCode, "[Transaction], GetTransactionResults failed.") } for k := range result { tx, err := TxStore.GetTransaction(k) if err != nil { return nil, NewDetailErr(err, ErrNoCode, fmt.Sprintf("[Transaction], GetTransaction failed With AssetID:=%x", k)) } if tx.TxType != RegisterAsset { return nil, NewDetailErr(errors.New("[Transaction] error"), ErrNoCode, fmt.Sprintf("[Transaction], Transaction Type ileage With AssetID:=%x", k)) } switch v1 := tx.Payload.(type) { case *payload.RegisterAsset: hashs = append(hashs, v1.Controller) default: return nil, NewDetailErr(errors.New("[Transaction] error"), ErrNoCode, fmt.Sprintf("[Transaction], payload is illegal", k)) } } case DataFile: issuer := tx.Payload.(*payload.DataFile).Issuer signatureRedeemScript, err := contract.CreateSignatureRedeemScript(issuer) if err != nil { return nil, NewDetailErr(err, ErrNoCode, "[Transaction], GetProgramHashes CreateSignatureRedeemScript failed.") } astHash, err := ToCodeHash(signatureRedeemScript) if err != nil { return nil, NewDetailErr(err, ErrNoCode, "[Transaction], GetProgramHashes ToCodeHash failed.") } hashs = append(hashs, astHash) case TransferAsset: case Record: case BookKeeper: issuer := tx.Payload.(*payload.BookKeeper).Issuer signatureRedeemScript, err := contract.CreateSignatureRedeemScript(issuer) if err != nil { return nil, NewDetailErr(err, ErrNoCode, "[Transaction - BookKeeper], GetProgramHashes CreateSignatureRedeemScript failed.") } astHash, err := ToCodeHash(signatureRedeemScript) if err != nil { return nil, NewDetailErr(err, ErrNoCode, "[Transaction - BookKeeper], GetProgramHashes ToCodeHash failed.") } hashs = append(hashs, astHash) case PrivacyPayload: issuer := tx.Payload.(*payload.PrivacyPayload).EncryptAttr.(*payload.EcdhAes256).FromPubkey signatureRedeemScript, err := contract.CreateSignatureRedeemScript(issuer) if err != nil { return nil, NewDetailErr(err, ErrNoCode, "[Transaction], GetProgramHashes CreateSignatureRedeemScript failed.") } astHash, err := ToCodeHash(signatureRedeemScript) if err != nil { return nil, NewDetailErr(err, ErrNoCode, "[Transaction], GetProgramHashes ToCodeHash failed.") } hashs = append(hashs, astHash) default: } //remove dupilicated hashes uniq := make(map[Uint160]bool) for _, v := range hashs { uniq[v] = true } for k := range uniq { uniqHashes = append(uniqHashes, k) } sort.Sort(byProgramHashes(uniqHashes)) return uniqHashes, nil } func (tx *Transaction) SetPrograms(programs []*program.Program) { tx.Programs = programs } func (tx *Transaction) GetPrograms() []*program.Program { return tx.Programs } func (tx *Transaction) GetOutputHashes() ([]Uint160, error) { //TODO: implement Transaction.GetOutputHashes() return []Uint160{}, nil } func (tx *Transaction) GenerateAssetMaps() { //TODO: implement Transaction.GenerateAssetMaps() } func (tx *Transaction) GetMessage() []byte { return sig.GetHashData(tx) } func (tx *Transaction) Hash() Uint256 { if tx.hash == nil { d := sig.GetHashData(tx) temp := sha256.Sum256([]byte(d)) f := Uint256(sha256.Sum256(temp[:])) tx.hash = &f } return *tx.hash } func (tx *Transaction) SetHash(hash Uint256) { tx.hash = &hash } func (tx *Transaction) Type() InventoryType { return TRANSACTION } func (tx *Transaction) Verify() error { //TODO: Verify() return nil } func (tx *Transaction) GetReference() (map[*UTXOTxInput]*TxOutput, error) { if tx.TxType == RegisterAsset { return nil, nil } //UTXO input / Outputs reference := make(map[*UTXOTxInput]*TxOutput) // Key index,v UTXOInput for _, utxo := range tx.UTXOInputs { transaction, err := TxStore.GetTransaction(utxo.ReferTxID) if err != nil { return nil, NewDetailErr(err, ErrNoCode, "[Transaction], GetReference failed.") } index := utxo.ReferTxOutputIndex reference[utxo] = transaction.Outputs[index] } return reference, nil } func (tx *Transaction) GetTransactionResults() (TransactionResult, error) { result := make(map[Uint256]Fixed64) outputResult := tx.GetMergedAssetIDValueFromOutputs() InputResult, err := tx.GetMergedAssetIDValueFromReference() if err != nil { return nil, err } //calc the balance of input vs output for outputAssetid, outputValue := range outputResult { if inputValue, ok := InputResult[outputAssetid]; ok { result[outputAssetid] = inputValue - outputValue } else { result[outputAssetid] -= outputValue } } for inputAssetid, inputValue := range InputResult { if _, exist := result[inputAssetid]; !exist { result[inputAssetid] += inputValue } } return result, nil } func (tx *Transaction) GetMergedAssetIDValueFromOutputs() TransactionResult { var result = make(map[Uint256]Fixed64) for _, v := range tx.Outputs { amout, ok := result[v.AssetID] if ok { result[v.AssetID] = amout + v.Value } else { result[v.AssetID] = v.Value } } return result } func (tx *Transaction) GetMergedAssetIDValueFromReference() (TransactionResult, error) { reference, err := tx.GetReference() if err != nil { return nil, err } var result = make(map[Uint256]Fixed64) for _, v := range reference { amout, ok := result[v.AssetID] if ok { result[v.AssetID] = amout + v.Value } else { result[v.AssetID] = v.Value } } return result, nil } type byProgramHashes []Uint160 func (a byProgramHashes) Len() int { return len(a) } func (a byProgramHashes) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byProgramHashes) Less(i, j int) bool { if a[i].CompareTo(a[j]) > 0 { return false } else { return true } }
Java
/* * Copyright 2010 JBoss 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 org.optaplanner.benchmark.impl.statistic.bestscore; import java.util.List; import org.optaplanner.benchmark.config.statistic.ProblemStatisticType; import org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult; import org.optaplanner.benchmark.impl.statistic.ProblemBasedSubSingleStatistic; import org.optaplanner.core.api.domain.solution.Solution; import org.optaplanner.core.api.solver.Solver; import org.optaplanner.core.api.solver.event.BestSolutionChangedEvent; import org.optaplanner.core.api.solver.event.SolverEventListener; import org.optaplanner.core.impl.score.definition.ScoreDefinition; public class BestScoreSubSingleStatistic extends ProblemBasedSubSingleStatistic<BestScoreStatisticPoint> { private final BestScoreSubSingleStatisticListener listener; public BestScoreSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) { super(subSingleBenchmarkResult, ProblemStatisticType.BEST_SCORE); listener = new BestScoreSubSingleStatisticListener(); } // ************************************************************************ // Lifecycle methods // ************************************************************************ public void open(Solver solver) { solver.addEventListener(listener); } public void close(Solver solver) { solver.removeEventListener(listener); } private class BestScoreSubSingleStatisticListener implements SolverEventListener<Solution> { public void bestSolutionChanged(BestSolutionChangedEvent<Solution> event) { pointList.add(new BestScoreStatisticPoint( event.getTimeMillisSpent(), event.getNewBestSolution().getScore())); } } // ************************************************************************ // CSV methods // ************************************************************************ @Override protected String getCsvHeader() { return BestScoreStatisticPoint.buildCsvLine("timeMillisSpent", "score"); } @Override protected BestScoreStatisticPoint createPointFromCsvLine(ScoreDefinition scoreDefinition, List<String> csvLine) { return new BestScoreStatisticPoint(Long.valueOf(csvLine.get(0)), scoreDefinition.parseScore(csvLine.get(1))); } }
Java
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # # 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 base64 import struct import socket import logging import netaddr from ryu.ofproto import ether from ryu.ofproto import inet from ryu.ofproto import ofproto_v1_2 from ryu.ofproto import ofproto_v1_2_parser from ryu.lib import hub from ryu.lib import mac LOG = logging.getLogger('ryu.lib.ofctl_v1_2') DEFAULT_TIMEOUT = 1.0 def str_to_int(src): if isinstance(src, str): if src.startswith("0x") or src.startswith("0X"): dst = int(src, 16) else: dst = int(src) else: dst = src return dst def to_action(dp, dic): ofp = dp.ofproto parser = dp.ofproto_parser action_type = dic.get('type') if action_type == 'OUTPUT': out_port = int(dic.get('port', ofp.OFPP_ANY)) max_len = int(dic.get('max_len', ofp.OFPCML_MAX)) result = parser.OFPActionOutput(out_port, max_len) elif action_type == 'COPY_TTL_OUT': result = parser.OFPActionCopyTtlOut() elif action_type == 'COPY_TTL_IN': result = parser.OFPActionCopyTtlIn() elif action_type == 'SET_MPLS_TTL': mpls_ttl = int(dic.get('mpls_ttl')) result = parser.OFPActionSetMplsTtl(mpls_ttl) elif action_type == 'DEC_MPLS_TTL': result = parser.OFPActionDecMplsTtl() elif action_type == 'PUSH_VLAN': ethertype = int(dic.get('ethertype')) result = parser.OFPActionPushVlan(ethertype) elif action_type == 'POP_VLAN': result = parser.OFPActionPopVlan() elif action_type == 'PUSH_MPLS': ethertype = int(dic.get('ethertype')) result = parser.OFPActionPushMpls(ethertype) elif action_type == 'POP_MPLS': ethertype = int(dic.get('ethertype')) result = parser.OFPActionPopMpls(ethertype) elif action_type == 'SET_QUEUE': queue_id = int(dic.get('queue_id')) result = parser.OFPActionSetQueue(queue_id) elif action_type == 'GROUP': group_id = int(dic.get('group_id')) result = parser.OFPActionGroup(group_id) elif action_type == 'SET_NW_TTL': nw_ttl = int(dic.get('nw_ttl')) result = parser.OFPActionSetNwTtl(nw_ttl) elif action_type == 'DEC_NW_TTL': result = parser.OFPActionDecNwTtl() elif action_type == 'SET_FIELD': field = dic.get('field') value = dic.get('value') result = parser.OFPActionSetField(**{field: value}) else: result = None return result def to_actions(dp, acts): inst = [] actions = [] ofp = dp.ofproto parser = dp.ofproto_parser for a in acts: action = to_action(dp, a) if action is not None: actions.append(action) else: action_type = a.get('type') if action_type == 'GOTO_TABLE': table_id = int(a.get('table_id')) inst.append(parser.OFPInstructionGotoTable(table_id)) elif action_type == 'WRITE_METADATA': metadata = str_to_int(a.get('metadata')) metadata_mask = (str_to_int(a['metadata_mask']) if 'metadata_mask' in a else parser.UINT64_MAX) inst.append( parser.OFPInstructionWriteMetadata( metadata, metadata_mask)) else: LOG.debug('Unknown action type: %s' % action_type) inst.append(parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS, actions)) return inst def action_to_str(act): action_type = act.cls_action_type if action_type == ofproto_v1_2.OFPAT_OUTPUT: buf = 'OUTPUT:' + str(act.port) elif action_type == ofproto_v1_2.OFPAT_COPY_TTL_OUT: buf = 'COPY_TTL_OUT' elif action_type == ofproto_v1_2.OFPAT_COPY_TTL_IN: buf = 'COPY_TTL_IN' elif action_type == ofproto_v1_2.OFPAT_SET_MPLS_TTL: buf = 'SET_MPLS_TTL:' + str(act.mpls_ttl) elif action_type == ofproto_v1_2.OFPAT_DEC_MPLS_TTL: buf = 'DEC_MPLS_TTL' elif action_type == ofproto_v1_2.OFPAT_PUSH_VLAN: buf = 'PUSH_VLAN:' + str(act.ethertype) elif action_type == ofproto_v1_2.OFPAT_POP_VLAN: buf = 'POP_VLAN' elif action_type == ofproto_v1_2.OFPAT_PUSH_MPLS: buf = 'PUSH_MPLS:' + str(act.ethertype) elif action_type == ofproto_v1_2.OFPAT_POP_MPLS: buf = 'POP_MPLS:' + str(act.ethertype) elif action_type == ofproto_v1_2.OFPAT_SET_QUEUE: buf = 'SET_QUEUE:' + str(act.queue_id) elif action_type == ofproto_v1_2.OFPAT_GROUP: buf = 'GROUP:' + str(act.group_id) elif action_type == ofproto_v1_2.OFPAT_SET_NW_TTL: buf = 'SET_NW_TTL:' + str(act.nw_ttl) elif action_type == ofproto_v1_2.OFPAT_DEC_NW_TTL: buf = 'DEC_NW_TTL' elif action_type == ofproto_v1_2.OFPAT_SET_FIELD: buf = 'SET_FIELD: {%s:%s}' % (act.key, act.value) else: buf = 'UNKNOWN' return buf def actions_to_str(instructions): actions = [] for instruction in instructions: if isinstance(instruction, ofproto_v1_2_parser.OFPInstructionActions): for a in instruction.actions: actions.append(action_to_str(a)) elif isinstance(instruction, ofproto_v1_2_parser.OFPInstructionGotoTable): buf = 'GOTO_TABLE:' + str(instruction.table_id) actions.append(buf) elif isinstance(instruction, ofproto_v1_2_parser.OFPInstructionWriteMetadata): buf = ('WRITE_METADATA:0x%x/0x%x' % (instruction.metadata, instruction.metadata_mask) if instruction.metadata_mask else 'WRITE_METADATA:0x%x' % instruction.metadata) actions.append(buf) else: continue return actions def to_match(dp, attrs): convert = {'in_port': int, 'in_phy_port': int, 'metadata': to_match_metadata, 'dl_dst': to_match_eth, 'dl_src': to_match_eth, 'eth_dst': to_match_eth, 'eth_src': to_match_eth, 'dl_type': int, 'eth_type': int, 'dl_vlan': to_match_vid, 'vlan_vid': to_match_vid, 'vlan_pcp': int, 'ip_dscp': int, 'ip_ecn': int, 'nw_proto': int, 'ip_proto': int, 'nw_src': to_match_ip, 'nw_dst': to_match_ip, 'ipv4_src': to_match_ip, 'ipv4_dst': to_match_ip, 'tp_src': int, 'tp_dst': int, 'tcp_src': int, 'tcp_dst': int, 'udp_src': int, 'udp_dst': int, 'sctp_src': int, 'sctp_dst': int, 'icmpv4_type': int, 'icmpv4_code': int, 'arp_op': int, 'arp_spa': to_match_ip, 'arp_tpa': to_match_ip, 'arp_sha': to_match_eth, 'arp_tha': to_match_eth, 'ipv6_src': to_match_ip, 'ipv6_dst': to_match_ip, 'ipv6_flabel': int, 'icmpv6_type': int, 'icmpv6_code': int, 'ipv6_nd_target': to_match_ip, 'ipv6_nd_sll': to_match_eth, 'ipv6_nd_tll': to_match_eth, 'mpls_label': int, 'mpls_tc': int} keys = {'dl_dst': 'eth_dst', 'dl_src': 'eth_src', 'dl_type': 'eth_type', 'dl_vlan': 'vlan_vid', 'nw_src': 'ipv4_src', 'nw_dst': 'ipv4_dst', 'nw_proto': 'ip_proto'} if attrs.get('dl_type') == ether.ETH_TYPE_ARP or \ attrs.get('eth_type') == ether.ETH_TYPE_ARP: if 'nw_src' in attrs and 'arp_spa' not in attrs: attrs['arp_spa'] = attrs['nw_src'] del attrs['nw_src'] if 'nw_dst' in attrs and 'arp_tpa' not in attrs: attrs['arp_tpa'] = attrs['nw_dst'] del attrs['nw_dst'] kwargs = {} for key, value in attrs.items(): if key in convert: value = convert[key](value) if key in keys: # For old field name key = keys[key] if key == 'tp_src' or key == 'tp_dst': # TCP/UDP port conv = {inet.IPPROTO_TCP: {'tp_src': 'tcp_src', 'tp_dst': 'tcp_dst'}, inet.IPPROTO_UDP: {'tp_src': 'udp_src', 'tp_dst': 'udp_dst'}} ip_proto = attrs.get('nw_proto', attrs.get('ip_proto', 0)) key = conv[ip_proto][key] kwargs[key] = value else: # others kwargs[key] = value return dp.ofproto_parser.OFPMatch(**kwargs) def to_match_eth(value): if '/' in value: value = value.split('/') return value[0], value[1] else: return value def to_match_ip(value): if '/' in value: ip = netaddr.ip.IPNetwork(value) ip_addr = str(ip.ip) ip_mask = str(ip.netmask) return ip_addr, ip_mask else: return value def to_match_vid(value): # NOTE: If "vlan_id/dl_vlan" field is described as decimal int value # (and decimal string value), it is treated as values of # VLAN tag, and OFPVID_PRESENT(0x1000) bit is automatically # applied. OTOH, If it is described as hexadecimal string, # treated as values of oxm_value (including OFPVID_PRESENT # bit), and OFPVID_PRESENT bit is NOT automatically applied. if isinstance(value, int): # described as decimal int value return value | ofproto_v1_2.OFPVID_PRESENT else: if '/' in value: val = value.split('/') return int(val[0], 0), int(val[1], 0) else: if value.isdigit(): # described as decimal string value return int(value, 10) | ofproto_v1_2.OFPVID_PRESENT else: return int(value, 0) def to_match_metadata(value): if '/' in value: value = value.split('/') return str_to_int(value[0]), str_to_int(value[1]) else: return str_to_int(value) def match_to_str(ofmatch): keys = {'eth_src': 'dl_src', 'eth_dst': 'dl_dst', 'eth_type': 'dl_type', 'vlan_vid': 'dl_vlan', 'ipv4_src': 'nw_src', 'ipv4_dst': 'nw_dst', 'ip_proto': 'nw_proto', 'tcp_src': 'tp_src', 'tcp_dst': 'tp_dst', 'udp_src': 'tp_src', 'udp_dst': 'tp_dst' } match = {} ofmatch = ofmatch.to_jsondict()['OFPMatch'] ofmatch = ofmatch['oxm_fields'] for match_field in ofmatch: key = match_field['OXMTlv']['field'] if key in keys: key = keys[key] mask = match_field['OXMTlv']['mask'] value = match_field['OXMTlv']['value'] if key == 'dl_vlan': value = match_vid_to_str(value, mask) elif key == 'metadata': value = match_metadata_to_str(value, mask) else: if mask is not None: value = value + '/' + mask else: value = value match.setdefault(key, value) return match def match_metadata_to_str(value, mask): return ('%d/%d' % (value, mask) if mask else '%d' % value) def match_vid_to_str(value, mask): if mask is not None: value = '0x%04x/0x%04x' % (value, mask) else: if value & ofproto_v1_2.OFPVID_PRESENT: value = str(value & ~ofproto_v1_2.OFPVID_PRESENT) else: value = '0x%04x' % value return value def send_stats_request(dp, stats, waiters, msgs): dp.set_xid(stats) waiters_per_dp = waiters.setdefault(dp.id, {}) lock = hub.Event() waiters_per_dp[stats.xid] = (lock, msgs) dp.send_msg(stats) lock.wait(timeout=DEFAULT_TIMEOUT) if not lock.is_set(): del waiters_per_dp[stats.xid] def get_desc_stats(dp, waiters): stats = dp.ofproto_parser.OFPDescStatsRequest(dp) msgs = [] send_stats_request(dp, stats, waiters, msgs) s = {} for msg in msgs: stats = msg.body s = {'mfr_desc': stats.mfr_desc, 'hw_desc': stats.hw_desc, 'sw_desc': stats.sw_desc, 'serial_num': stats.serial_num, 'dp_desc': stats.dp_desc} desc = {str(dp.id): s} return desc def get_queue_stats(dp, waiters): ofp = dp.ofproto stats = dp.ofproto_parser.OFPQueueStatsRequest(dp, 0, ofp.OFPP_ANY, ofp.OFPQ_ALL) msgs = [] send_stats_request(dp, stats, waiters, msgs) s = [] for msg in msgs: stats = msg.body for stat in stats: s.append({'port_no': stat.port_no, 'queue_id': stat.queue_id, 'tx_bytes': stat.tx_bytes, 'tx_errors': stat.tx_errors, 'tx_packets': stat.tx_packets}) desc = {str(dp.id): s} return desc def get_flow_stats(dp, waiters, flow={}): table_id = int(flow.get('table_id', dp.ofproto.OFPTT_ALL)) out_port = int(flow.get('out_port', dp.ofproto.OFPP_ANY)) out_group = int(flow.get('out_group', dp.ofproto.OFPG_ANY)) cookie = int(flow.get('cookie', 0)) cookie_mask = int(flow.get('cookie_mask', 0)) match = to_match(dp, flow.get('match', {})) stats = dp.ofproto_parser.OFPFlowStatsRequest( dp, table_id, out_port, out_group, cookie, cookie_mask, match) msgs = [] send_stats_request(dp, stats, waiters, msgs) flows = [] for msg in msgs: for stats in msg.body: actions = actions_to_str(stats.instructions) match = match_to_str(stats.match) s = {'priority': stats.priority, 'cookie': stats.cookie, 'idle_timeout': stats.idle_timeout, 'hard_timeout': stats.hard_timeout, 'actions': actions, 'match': match, 'byte_count': stats.byte_count, 'duration_sec': stats.duration_sec, 'duration_nsec': stats.duration_nsec, 'packet_count': stats.packet_count, 'table_id': stats.table_id, 'length': stats.length} flows.append(s) flows = {str(dp.id): flows} return flows def get_port_stats(dp, waiters): stats = dp.ofproto_parser.OFPPortStatsRequest( dp, dp.ofproto.OFPP_ANY, 0) msgs = [] send_stats_request(dp, stats, waiters, msgs) ports = [] for msg in msgs: for stats in msg.body: s = {'port_no': stats.port_no, 'rx_packets': stats.rx_packets, 'tx_packets': stats.tx_packets, 'rx_bytes': stats.rx_bytes, 'tx_bytes': stats.tx_bytes, 'rx_dropped': stats.rx_dropped, 'tx_dropped': stats.tx_dropped, 'rx_errors': stats.rx_errors, 'tx_errors': stats.tx_errors, 'rx_frame_err': stats.rx_frame_err, 'rx_over_err': stats.rx_over_err, 'rx_crc_err': stats.rx_crc_err, 'collisions': stats.collisions} ports.append(s) ports = {str(dp.id): ports} return ports def get_group_stats(dp, waiters): stats = dp.ofproto_parser.OFPGroupStatsRequest( dp, dp.ofproto.OFPG_ALL, 0) msgs = [] send_stats_request(dp, stats, waiters, msgs) groups = [] for msg in msgs: for stats in msg.body: bucket_counters = [] for bucket_counter in stats.bucket_counters: c = {'packet_count': bucket_counter.packet_count, 'byte_count': bucket_counter.byte_count} bucket_counters.append(c) g = {'length': stats.length, 'group_id': stats.group_id, 'ref_count': stats.ref_count, 'packet_count': stats.packet_count, 'byte_count': stats.byte_count, 'bucket_stats': bucket_counters} groups.append(g) groups = {str(dp.id): groups} return groups def get_group_features(dp, waiters): ofp = dp.ofproto type_convert = {ofp.OFPGT_ALL: 'ALL', ofp.OFPGT_SELECT: 'SELECT', ofp.OFPGT_INDIRECT: 'INDIRECT', ofp.OFPGT_FF: 'FF'} cap_convert = {ofp.OFPGFC_SELECT_WEIGHT: 'SELECT_WEIGHT', ofp.OFPGFC_SELECT_LIVENESS: 'SELECT_LIVENESS', ofp.OFPGFC_CHAINING: 'CHAINING', ofp.OFPGFC_CHAINING_CHECKS: 'CHAINING_CHECKS'} act_convert = {ofp.OFPAT_OUTPUT: 'OUTPUT', ofp.OFPAT_COPY_TTL_OUT: 'COPY_TTL_OUT', ofp.OFPAT_COPY_TTL_IN: 'COPY_TTL_IN', ofp.OFPAT_SET_MPLS_TTL: 'SET_MPLS_TTL', ofp.OFPAT_DEC_MPLS_TTL: 'DEC_MPLS_TTL', ofp.OFPAT_PUSH_VLAN: 'PUSH_VLAN', ofp.OFPAT_POP_VLAN: 'POP_VLAN', ofp.OFPAT_PUSH_MPLS: 'PUSH_MPLS', ofp.OFPAT_POP_MPLS: 'POP_MPLS', ofp.OFPAT_SET_QUEUE: 'SET_QUEUE', ofp.OFPAT_GROUP: 'GROUP', ofp.OFPAT_SET_NW_TTL: 'SET_NW_TTL', ofp.OFPAT_DEC_NW_TTL: 'DEC_NW_TTL', ofp.OFPAT_SET_FIELD: 'SET_FIELD'} stats = dp.ofproto_parser.OFPGroupFeaturesStatsRequest(dp, 0) msgs = [] send_stats_request(dp, stats, waiters, msgs) features = [] for msg in msgs: feature = msg.body types = [] for k, v in type_convert.items(): if (1 << k) & feature.types: types.append(v) capabilities = [] for k, v in cap_convert.items(): if k & feature.capabilities: capabilities.append(v) max_groups = [] for k, v in type_convert.items(): max_groups.append({v: feature.max_groups[k]}) actions = [] for k1, v1 in type_convert.items(): acts = [] for k2, v2 in act_convert.items(): if (1 << k2) & feature.actions[k1]: acts.append(v2) actions.append({v1: acts}) f = {'types': types, 'capabilities': capabilities, 'max_groups': max_groups, 'actions': actions} features.append(f) features = {str(dp.id): features} return features def get_group_desc(dp, waiters): type_convert = {dp.ofproto.OFPGT_ALL: 'ALL', dp.ofproto.OFPGT_SELECT: 'SELECT', dp.ofproto.OFPGT_INDIRECT: 'INDIRECT', dp.ofproto.OFPGT_FF: 'FF'} stats = dp.ofproto_parser.OFPGroupDescStatsRequest(dp, 0) msgs = [] send_stats_request(dp, stats, waiters, msgs) descs = [] for msg in msgs: for stats in msg.body: buckets = [] for bucket in stats.buckets: actions = [] for action in bucket.actions: actions.append(action_to_str(action)) b = {'weight': bucket.weight, 'watch_port': bucket.watch_port, 'watch_group': bucket.watch_group, 'actions': actions} buckets.append(b) d = {'type': type_convert.get(stats.type), 'group_id': stats.group_id, 'buckets': buckets} descs.append(d) descs = {str(dp.id): descs} return descs def get_port_desc(dp, waiters): stats = dp.ofproto_parser.OFPFeaturesRequest(dp) msgs = [] send_stats_request(dp, stats, waiters, msgs) descs = [] for msg in msgs: stats = msg.ports for stat in stats.values(): d = {'port_no': stat.port_no, 'hw_addr': stat.hw_addr, 'name': stat.name, 'config': stat.config, 'state': stat.state, 'curr': stat.curr, 'advertised': stat.advertised, 'supported': stat.supported, 'peer': stat.peer, 'curr_speed': stat.curr_speed, 'max_speed': stat.max_speed} descs.append(d) descs = {str(dp.id): descs} return descs def mod_flow_entry(dp, flow, cmd): cookie = int(flow.get('cookie', 0)) cookie_mask = int(flow.get('cookie_mask', 0)) table_id = int(flow.get('table_id', 0)) idle_timeout = int(flow.get('idle_timeout', 0)) hard_timeout = int(flow.get('hard_timeout', 0)) priority = int(flow.get('priority', 0)) buffer_id = int(flow.get('buffer_id', dp.ofproto.OFP_NO_BUFFER)) out_port = int(flow.get('out_port', dp.ofproto.OFPP_ANY)) out_group = int(flow.get('out_group', dp.ofproto.OFPG_ANY)) flags = int(flow.get('flags', 0)) match = to_match(dp, flow.get('match', {})) inst = to_actions(dp, flow.get('actions', [])) flow_mod = dp.ofproto_parser.OFPFlowMod( dp, cookie, cookie_mask, table_id, cmd, idle_timeout, hard_timeout, priority, buffer_id, out_port, out_group, flags, match, inst) dp.send_msg(flow_mod) def mod_group_entry(dp, group, cmd): type_convert = {'ALL': dp.ofproto.OFPGT_ALL, 'SELECT': dp.ofproto.OFPGT_SELECT, 'INDIRECT': dp.ofproto.OFPGT_INDIRECT, 'FF': dp.ofproto.OFPGT_FF} type_ = type_convert.get(group.get('type', 'ALL')) if type_ is None: LOG.debug('Unknown type: %s', group.get('type')) group_id = int(group.get('group_id', 0)) buckets = [] for bucket in group.get('buckets', []): weight = int(bucket.get('weight', 0)) watch_port = int(bucket.get('watch_port', dp.ofproto.OFPP_ANY)) watch_group = int(bucket.get('watch_group', dp.ofproto.OFPG_ANY)) actions = [] for dic in bucket.get('actions', []): action = to_action(dp, dic) if action is not None: actions.append(action) buckets.append(dp.ofproto_parser.OFPBucket( weight, watch_port, watch_group, actions)) group_mod = dp.ofproto_parser.OFPGroupMod( dp, cmd, type_, group_id, buckets) dp.send_msg(group_mod) def mod_port_behavior(dp, port_config): port_no = int(port_config.get('port_no', 0)) hw_addr = port_config.get('hw_addr') config = int(port_config.get('config', 0)) mask = int(port_config.get('mask', 0)) advertise = int(port_config.get('advertise')) port_mod = dp.ofproto_parser.OFPPortMod( dp, port_no, hw_addr, config, mask, advertise) dp.send_msg(port_mod) def send_experimenter(dp, exp): experimenter = exp.get('experimenter', 0) exp_type = exp.get('exp_type', 0) data_type = exp.get('data_type', 'ascii') if data_type != 'ascii' and data_type != 'base64': LOG.debug('Unknown data type: %s', data_type) data = exp.get('data', '') if data_type == 'base64': data = base64.b64decode(data) expmsg = dp.ofproto_parser.OFPExperimenter( dp, experimenter, exp_type, data) dp.send_msg(expmsg)
Java
// Copyright (c) 2006-7 John Maddock // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_MATH_TOOLS_CONFIG_HPP #define BOOST_MATH_TOOLS_CONFIG_HPP #ifdef _MSC_VER #pragma once #endif #include <boost/config.hpp> #include <boost/cstdint.hpp> // for geofeatures_boost::uintmax_t #include <boost/detail/workaround.hpp> #include <boost/type_traits/is_integral.hpp> #include <algorithm> // for min and max #include <boost/config/no_tr1/cmath.hpp> #include <climits> #include <cfloat> #if (defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)) # include <math.h> #endif #ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS # include <limits> #endif #include <boost/math/tools/user.hpp> #if (defined(__CYGWIN__) || defined(__FreeBSD__) || defined(__NetBSD__) \ || (defined(__hppa) && !defined(__OpenBSD__)) || (defined(__NO_LONG_DOUBLE_MATH) && (DBL_MANT_DIG != LDBL_MANT_DIG))) \ && !defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS) # define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #endif #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) // // Borland post 5.8.2 uses Dinkumware's std C lib which // doesn't have true long double precision. Earlier // versions are problematic too: // # define BOOST_MATH_NO_REAL_CONCEPT_TESTS # define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS # define BOOST_MATH_CONTROL_FP _control87(MCW_EM,MCW_EM) # include <float.h> #endif #ifdef __IBMCPP__ // // For reasons I don't unserstand, the tests with IMB's compiler all // pass at long double precision, but fail with real_concept, those tests // are disabled for now. (JM 2012). # define BOOST_MATH_NO_REAL_CONCEPT_TESTS #endif #ifdef sun // Any use of __float128 in program startup code causes a segfault (tested JM 2015, Solaris 11). # define BOOST_MATH_DISABLE_FLOAT128 #endif #ifdef __HAIKU__ // // Not sure what's up with the math detection on Haiku, but linking fails with // float128 code enabled, and we don't have an implementation of __expl, so // disabling long double functions for now as well. # define BOOST_MATH_DISABLE_FLOAT128 # define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #endif #if (defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)) && ((LDBL_MANT_DIG == 106) || (__LDBL_MANT_DIG__ == 106)) && !defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS) // // Darwin's rather strange "double double" is rather hard to // support, it should be possible given enough effort though... // # define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #endif #if defined(unix) && defined(__INTEL_COMPILER) && (__INTEL_COMPILER <= 1000) && !defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS) // // Intel compiler prior to version 10 has sporadic problems // calling the long double overloads of the std lib math functions: // calling ::powl is OK, but std::pow(long double, long double) // may segfault depending upon the value of the arguments passed // and the specific Linux distribution. // // We'll be conservative and disable long double support for this compiler. // // Comment out this #define and try building the tests to determine whether // your Intel compiler version has this issue or not. // # define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #endif #if defined(unix) && defined(__INTEL_COMPILER) // // Intel compiler has sporadic issues compiling std::fpclassify depending on // the exact OS version used. Use our own code for this as we know it works // well on Intel processors: // #define BOOST_MATH_DISABLE_STD_FPCLASSIFY #endif #if defined(BOOST_MSVC) && !defined(_WIN32_WCE) // Better safe than sorry, our tests don't support hardware exceptions: # define BOOST_MATH_CONTROL_FP _control87(MCW_EM,MCW_EM) #endif #ifdef __IBMCPP__ # define BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS #endif #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901)) # define BOOST_MATH_USE_C99 #endif #if (defined(__hpux) && !defined(__hppa)) # define BOOST_MATH_USE_C99 #endif #if defined(__GNUC__) && defined(_GLIBCXX_USE_C99) # define BOOST_MATH_USE_C99 #endif #if defined(_LIBCPP_VERSION) && !defined(_MSC_VER) # define BOOST_MATH_USE_C99 #endif #if defined(__CYGWIN__) || defined(__HP_aCC) || defined(BOOST_INTEL) \ || defined(BOOST_NO_NATIVE_LONG_DOUBLE_FP_CLASSIFY) \ || (defined(__GNUC__) && !defined(BOOST_MATH_USE_C99))\ || defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS) # define BOOST_MATH_NO_NATIVE_LONG_DOUBLE_FP_CLASSIFY #endif #if BOOST_WORKAROUND(__SUNPRO_CC, <= 0x590) # include "boost/type.hpp" # include "boost/non_type.hpp" # define BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(t) geofeatures_boost::type<t>* = 0 # define BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(t) geofeatures_boost::type<t>* # define BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE(t, v) geofeatures_boost::non_type<t, v>* = 0 # define BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) geofeatures_boost::non_type<t, v>* # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(t) \ , BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(t) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE_SPEC(t) \ , BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(t) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_NON_TYPE(t, v) \ , BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE(t, v) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) \ , BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) #else // no workaround needed: expand to nothing # define BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(t) # define BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(t) # define BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE(t, v) # define BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(t) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE_SPEC(t) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_NON_TYPE(t, v) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) #endif // __SUNPRO_CC #if (defined(__SUNPRO_CC) || defined(__hppa) || defined(__GNUC__)) && !defined(BOOST_MATH_SMALL_CONSTANT) // Sun's compiler emits a hard error if a constant underflows, // as does aCC on PA-RISC, while gcc issues a large number of warnings: # define BOOST_MATH_SMALL_CONSTANT(x) 0.0 #else # define BOOST_MATH_SMALL_CONSTANT(x) x #endif #if BOOST_WORKAROUND(BOOST_MSVC, < 1400) // // Define if constants too large for a float cause "bad" // values to be stored in the data, rather than infinity // or a suitably large value. // # define BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS #endif // // Tune performance options for specific compilers: // #ifdef BOOST_MSVC # define BOOST_MATH_POLY_METHOD 2 #elif defined(BOOST_INTEL) # define BOOST_MATH_POLY_METHOD 2 # define BOOST_MATH_RATIONAL_METHOD 2 #elif defined(__GNUC__) # define BOOST_MATH_POLY_METHOD 3 # define BOOST_MATH_RATIONAL_METHOD 3 # define BOOST_MATH_INT_TABLE_TYPE(RT, IT) RT # define BOOST_MATH_INT_VALUE_SUFFIX(RV, SUF) RV##.0L #endif #if defined(BOOST_NO_LONG_LONG) && !defined(BOOST_MATH_INT_TABLE_TYPE) # define BOOST_MATH_INT_TABLE_TYPE(RT, IT) RT # define BOOST_MATH_INT_VALUE_SUFFIX(RV, SUF) RV##.0L #endif // // The maximum order of polynomial that will be evaluated // via an unrolled specialisation: // #ifndef BOOST_MATH_MAX_POLY_ORDER # define BOOST_MATH_MAX_POLY_ORDER 17 #endif // // Set the method used to evaluate polynomials and rationals: // #ifndef BOOST_MATH_POLY_METHOD # define BOOST_MATH_POLY_METHOD 1 #endif #ifndef BOOST_MATH_RATIONAL_METHOD # define BOOST_MATH_RATIONAL_METHOD 0 #endif // // decide whether to store constants as integers or reals: // #ifndef BOOST_MATH_INT_TABLE_TYPE # define BOOST_MATH_INT_TABLE_TYPE(RT, IT) IT #endif #ifndef BOOST_MATH_INT_VALUE_SUFFIX # define BOOST_MATH_INT_VALUE_SUFFIX(RV, SUF) RV##SUF #endif // // Test whether to support __float128: // #if defined(_GLIBCXX_USE_FLOAT128) && defined(BOOST_GCC) && !defined(__STRICT_ANSI__) \ && !defined(BOOST_MATH_DISABLE_FLOAT128) || defined(BOOST_MATH_USE_FLOAT128) // // Only enable this when the compiler really is GCC as clang and probably // intel too don't support __float128 yet :-( // #ifndef BOOST_MATH_USE_FLOAT128 # define BOOST_MATH_USE_FLOAT128 #endif # if defined(BOOST_INTEL) && defined(BOOST_INTEL_CXX_VERSION) && (BOOST_INTEL_CXX_VERSION >= 1310) && defined(__GNUC__) # if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) # define BOOST_MATH_FLOAT128_TYPE __float128 # endif # elif defined(__GNUC__) # define BOOST_MATH_FLOAT128_TYPE __float128 # endif # ifndef BOOST_MATH_FLOAT128_TYPE # define BOOST_MATH_FLOAT128_TYPE _Quad # endif #endif // // Check for WinCE with no iostream support: // #if defined(_WIN32_WCE) && !defined(__SGI_STL_PORT) # define BOOST_MATH_NO_LEXICAL_CAST #endif // // Helper macro for controlling the FP behaviour: // #ifndef BOOST_MATH_CONTROL_FP # define BOOST_MATH_CONTROL_FP #endif // // Helper macro for using statements: // #define BOOST_MATH_STD_USING_CORE \ using std::abs;\ using std::acos;\ using std::cos;\ using std::fmod;\ using std::modf;\ using std::tan;\ using std::asin;\ using std::cosh;\ using std::frexp;\ using std::pow;\ using std::tanh;\ using std::atan;\ using std::exp;\ using std::ldexp;\ using std::sin;\ using std::atan2;\ using std::fabs;\ using std::log;\ using std::sinh;\ using std::ceil;\ using std::floor;\ using std::log10;\ using std::sqrt; #define BOOST_MATH_STD_USING BOOST_MATH_STD_USING_CORE namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost{ namespace math{ namespace tools { template <class T> inline T max BOOST_PREVENT_MACRO_SUBSTITUTION(T a, T b, T c) { return (std::max)((std::max)(a, b), c); } template <class T> inline T max BOOST_PREVENT_MACRO_SUBSTITUTION(T a, T b, T c, T d) { return (std::max)((std::max)(a, b), (std::max)(c, d)); } } // namespace tools template <class T> void suppress_unused_variable_warning(const T&) { } namespace detail{ template <class T> struct is_integer_for_rounding { static const bool value = geofeatures_boost::is_integral<T>::value #ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS || (std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer) #endif ; }; } }} // namespace geofeatures_boost namespace math #ifdef __GLIBC_PREREQ # if __GLIBC_PREREQ(2,14) # define BOOST_MATH_HAVE_FIXED_GLIBC # endif #endif #if ((defined(__linux__) && !defined(__UCLIBC__) && !defined(BOOST_MATH_HAVE_FIXED_GLIBC)) || defined(__QNX__) || defined(__IBMCPP__)) && !defined(BOOST_NO_FENV_H) // // This code was introduced in response to this glibc bug: http://sourceware.org/bugzilla/show_bug.cgi?id=2445 // Basically powl and expl can return garbage when the result is small and certain exception flags are set // on entrance to these functions. This appears to have been fixed in Glibc 2.14 (May 2011). // Much more information in this message thread: https://groups.google.com/forum/#!topic/boost-list/ZT99wtIFlb4 // #include <boost/detail/fenv.hpp> # ifdef FE_ALL_EXCEPT namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost{ namespace math{ namespace detail { struct fpu_guard { fpu_guard() { fegetexceptflag(&m_flags, FE_ALL_EXCEPT); feclearexcept(FE_ALL_EXCEPT); } ~fpu_guard() { fesetexceptflag(&m_flags, FE_ALL_EXCEPT); } private: fexcept_t m_flags; }; } // namespace detail }} // namespaces # define BOOST_FPU_EXCEPTION_GUARD geofeatures_boost::math::detail::fpu_guard local_guard_object; # define BOOST_MATH_INSTRUMENT_FPU do{ fexcept_t cpu_flags; fegetexceptflag(&cpu_flags, FE_ALL_EXCEPT); BOOST_MATH_INSTRUMENT_VARIABLE(cpu_flags); } while(0); # else # define BOOST_FPU_EXCEPTION_GUARD # define BOOST_MATH_INSTRUMENT_FPU # endif #else // All other platforms. # define BOOST_FPU_EXCEPTION_GUARD # define BOOST_MATH_INSTRUMENT_FPU #endif #ifdef BOOST_MATH_INSTRUMENT # include <iostream> # include <iomanip> # include <typeinfo> # define BOOST_MATH_INSTRUMENT_CODE(x) \ std::cout << std::setprecision(35) << __FILE__ << ":" << __LINE__ << " " << x << std::endl; # define BOOST_MATH_INSTRUMENT_VARIABLE(name) BOOST_MATH_INSTRUMENT_CODE(BOOST_STRINGIZE(name) << " = " << name) #else # define BOOST_MATH_INSTRUMENT_CODE(x) # define BOOST_MATH_INSTRUMENT_VARIABLE(name) #endif #endif // BOOST_MATH_TOOLS_CONFIG_HPP
Java
# Copyright 2013 IBM Corp. # # 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. """Handles database requests from other nova services.""" import copy from nova.api.ec2 import ec2utils from nova import block_device from nova.cells import rpcapi as cells_rpcapi from nova.compute import api as compute_api from nova.compute import rpcapi as compute_rpcapi from nova.compute import task_states from nova.compute import utils as compute_utils from nova.compute import vm_states from nova.conductor.tasks import live_migrate from nova.db import base from nova import exception from nova.image import glance from nova import manager from nova import network from nova.network.security_group import openstack_driver from nova import notifications from nova.objects import base as nova_object from nova.objects import instance as instance_obj from nova.objects import migration as migration_obj from nova.openstack.common import excutils from nova.openstack.common.gettextutils import _ from nova.openstack.common import jsonutils from nova.openstack.common import log as logging from nova.openstack.common.rpc import common as rpc_common from nova.openstack.common import timeutils from nova import quota from nova.scheduler import rpcapi as scheduler_rpcapi from nova.scheduler import utils as scheduler_utils LOG = logging.getLogger(__name__) # Instead of having a huge list of arguments to instance_update(), we just # accept a dict of fields to update and use this whitelist to validate it. allowed_updates = ['task_state', 'vm_state', 'expected_task_state', 'power_state', 'access_ip_v4', 'access_ip_v6', 'launched_at', 'terminated_at', 'host', 'node', 'memory_mb', 'vcpus', 'root_gb', 'ephemeral_gb', 'instance_type_id', 'root_device_name', 'launched_on', 'progress', 'vm_mode', 'default_ephemeral_device', 'default_swap_device', 'root_device_name', 'system_metadata', 'updated_at' ] # Fields that we want to convert back into a datetime object. datetime_fields = ['launched_at', 'terminated_at', 'updated_at'] class ConductorManager(manager.Manager): """Mission: Conduct things. The methods in the base API for nova-conductor are various proxy operations performed on behalf of the nova-compute service running on compute nodes. Compute nodes are not allowed to directly access the database, so this set of methods allows them to get specific work done without locally accessing the database. The nova-conductor service also exposes an API in the 'compute_task' namespace. See the ComputeTaskManager class for details. """ RPC_API_VERSION = '1.58' def __init__(self, *args, **kwargs): super(ConductorManager, self).__init__(service_name='conductor', *args, **kwargs) self.security_group_api = ( openstack_driver.get_openstack_security_group_driver()) self._network_api = None self._compute_api = None self.compute_task_mgr = ComputeTaskManager() self.quotas = quota.QUOTAS self.cells_rpcapi = cells_rpcapi.CellsAPI() def create_rpc_dispatcher(self, *args, **kwargs): kwargs['additional_apis'] = [self.compute_task_mgr] return super(ConductorManager, self).create_rpc_dispatcher(*args, **kwargs) @property def network_api(self): # NOTE(danms): We need to instantiate our network_api on first use # to avoid the circular dependency that exists between our init # and network_api's if self._network_api is None: self._network_api = network.API() return self._network_api @property def compute_api(self): if self._compute_api is None: self._compute_api = compute_api.API() return self._compute_api def ping(self, context, arg): # NOTE(russellb) This method can be removed in 2.0 of this API. It is # now a part of the base rpc API. return jsonutils.to_primitive({'service': 'conductor', 'arg': arg}) @rpc_common.client_exceptions(KeyError, ValueError, exception.InvalidUUID, exception.InstanceNotFound, exception.UnexpectedTaskStateError) def instance_update(self, context, instance_uuid, updates, service=None): for key, value in updates.iteritems(): if key not in allowed_updates: LOG.error(_("Instance update attempted for " "'%(key)s' on %(instance_uuid)s"), {'key': key, 'instance_uuid': instance_uuid}) raise KeyError("unexpected update keyword '%s'" % key) if key in datetime_fields and isinstance(value, basestring): updates[key] = timeutils.parse_strtime(value) old_ref, instance_ref = self.db.instance_update_and_get_original( context, instance_uuid, updates) notifications.send_update(context, old_ref, instance_ref, service) return jsonutils.to_primitive(instance_ref) @rpc_common.client_exceptions(exception.InstanceNotFound) def instance_get(self, context, instance_id): return jsonutils.to_primitive( self.db.instance_get(context, instance_id)) @rpc_common.client_exceptions(exception.InstanceNotFound) def instance_get_by_uuid(self, context, instance_uuid, columns_to_join=None): return jsonutils.to_primitive( self.db.instance_get_by_uuid(context, instance_uuid, columns_to_join)) # NOTE(hanlind): This method can be removed in v2.0 of the RPC API. def instance_get_all(self, context): return jsonutils.to_primitive(self.db.instance_get_all(context)) def instance_get_all_by_host(self, context, host, node=None, columns_to_join=None): if node is not None: result = self.db.instance_get_all_by_host_and_node( context.elevated(), host, node) else: result = self.db.instance_get_all_by_host(context.elevated(), host, columns_to_join) return jsonutils.to_primitive(result) # NOTE(comstud): This method is now deprecated and can be removed in # version v2.0 of the RPC API @rpc_common.client_exceptions(exception.MigrationNotFound) def migration_get(self, context, migration_id): migration_ref = self.db.migration_get(context.elevated(), migration_id) return jsonutils.to_primitive(migration_ref) # NOTE(comstud): This method is now deprecated and can be removed in # version v2.0 of the RPC API def migration_get_unconfirmed_by_dest_compute(self, context, confirm_window, dest_compute): migrations = self.db.migration_get_unconfirmed_by_dest_compute( context, confirm_window, dest_compute) return jsonutils.to_primitive(migrations) def migration_get_in_progress_by_host_and_node(self, context, host, node): migrations = self.db.migration_get_in_progress_by_host_and_node( context, host, node) return jsonutils.to_primitive(migrations) # NOTE(comstud): This method can be removed in v2.0 of the RPC API. def migration_create(self, context, instance, values): values.update({'instance_uuid': instance['uuid'], 'source_compute': instance['host'], 'source_node': instance['node']}) migration_ref = self.db.migration_create(context.elevated(), values) return jsonutils.to_primitive(migration_ref) @rpc_common.client_exceptions(exception.MigrationNotFound) def migration_update(self, context, migration, status): migration_ref = self.db.migration_update(context.elevated(), migration['id'], {'status': status}) return jsonutils.to_primitive(migration_ref) @rpc_common.client_exceptions(exception.AggregateHostExists) def aggregate_host_add(self, context, aggregate, host): host_ref = self.db.aggregate_host_add(context.elevated(), aggregate['id'], host) return jsonutils.to_primitive(host_ref) @rpc_common.client_exceptions(exception.AggregateHostNotFound) def aggregate_host_delete(self, context, aggregate, host): self.db.aggregate_host_delete(context.elevated(), aggregate['id'], host) @rpc_common.client_exceptions(exception.AggregateNotFound) def aggregate_get(self, context, aggregate_id): aggregate = self.db.aggregate_get(context.elevated(), aggregate_id) return jsonutils.to_primitive(aggregate) def aggregate_get_by_host(self, context, host, key=None): aggregates = self.db.aggregate_get_by_host(context.elevated(), host, key) return jsonutils.to_primitive(aggregates) def aggregate_metadata_add(self, context, aggregate, metadata, set_delete=False): new_metadata = self.db.aggregate_metadata_add(context.elevated(), aggregate['id'], metadata, set_delete) return jsonutils.to_primitive(new_metadata) @rpc_common.client_exceptions(exception.AggregateMetadataNotFound) def aggregate_metadata_delete(self, context, aggregate, key): self.db.aggregate_metadata_delete(context.elevated(), aggregate['id'], key) def aggregate_metadata_get_by_host(self, context, host, key='availability_zone'): result = self.db.aggregate_metadata_get_by_host(context, host, key) return jsonutils.to_primitive(result) def bw_usage_update(self, context, uuid, mac, start_period, bw_in=None, bw_out=None, last_ctr_in=None, last_ctr_out=None, last_refreshed=None, update_cells=True): if [bw_in, bw_out, last_ctr_in, last_ctr_out].count(None) != 4: self.db.bw_usage_update(context, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed, update_cells=update_cells) usage = self.db.bw_usage_get(context, uuid, start_period, mac) return jsonutils.to_primitive(usage) # NOTE(russellb) This method can be removed in 2.0 of this API. It is # deprecated in favor of the method in the base API. def get_backdoor_port(self, context): return self.backdoor_port def security_group_get_by_instance(self, context, instance): group = self.db.security_group_get_by_instance(context, instance['uuid']) return jsonutils.to_primitive(group) def security_group_rule_get_by_security_group(self, context, secgroup): rules = self.db.security_group_rule_get_by_security_group( context, secgroup['id']) return jsonutils.to_primitive(rules, max_depth=4) def provider_fw_rule_get_all(self, context): rules = self.db.provider_fw_rule_get_all(context) return jsonutils.to_primitive(rules) def agent_build_get_by_triple(self, context, hypervisor, os, architecture): info = self.db.agent_build_get_by_triple(context, hypervisor, os, architecture) return jsonutils.to_primitive(info) def block_device_mapping_update_or_create(self, context, values, create=None): if create is None: bdm = self.db.block_device_mapping_update_or_create(context, values) elif create is True: bdm = self.db.block_device_mapping_create(context, values) else: bdm = self.db.block_device_mapping_update(context, values['id'], values) # NOTE:comstud): 'bdm' is always in the new format, so we # account for this in cells/messaging.py self.cells_rpcapi.bdm_update_or_create_at_top(context, bdm, create=create) def block_device_mapping_get_all_by_instance(self, context, instance, legacy=True): bdms = self.db.block_device_mapping_get_all_by_instance( context, instance['uuid']) if legacy: bdms = block_device.legacy_mapping(bdms) return jsonutils.to_primitive(bdms) def block_device_mapping_destroy(self, context, bdms=None, instance=None, volume_id=None, device_name=None): if bdms is not None: for bdm in bdms: self.db.block_device_mapping_destroy(context, bdm['id']) # NOTE(comstud): bdm['id'] will be different in API cell, # so we must try to destroy by device_name or volume_id. # We need an instance_uuid in order to do this properly, # too. # I hope to clean a lot of this up in the object # implementation. instance_uuid = (bdm['instance_uuid'] or (instance and instance['uuid'])) if not instance_uuid: continue # Better to be safe than sorry. device_name is not # NULLable, however it could be an empty string. if bdm['device_name']: self.cells_rpcapi.bdm_destroy_at_top( context, instance_uuid, device_name=bdm['device_name']) elif bdm['volume_id']: self.cells_rpcapi.bdm_destroy_at_top( context, instance_uuid, volume_id=bdm['volume_id']) elif instance is not None and volume_id is not None: self.db.block_device_mapping_destroy_by_instance_and_volume( context, instance['uuid'], volume_id) self.cells_rpcapi.bdm_destroy_at_top( context, instance['uuid'], volume_id=volume_id) elif instance is not None and device_name is not None: self.db.block_device_mapping_destroy_by_instance_and_device( context, instance['uuid'], device_name) self.cells_rpcapi.bdm_destroy_at_top( context, instance['uuid'], device_name=device_name) else: # NOTE(danms): This shouldn't happen raise exception.Invalid(_("Invalid block_device_mapping_destroy" " invocation")) def instance_get_all_by_filters(self, context, filters, sort_key, sort_dir, columns_to_join=None): result = self.db.instance_get_all_by_filters( context, filters, sort_key, sort_dir, columns_to_join=columns_to_join) return jsonutils.to_primitive(result) # NOTE(hanlind): This method can be removed in v2.0 of the RPC API. def instance_get_all_hung_in_rebooting(self, context, timeout): result = self.db.instance_get_all_hung_in_rebooting(context, timeout) return jsonutils.to_primitive(result) def instance_get_active_by_window(self, context, begin, end=None, project_id=None, host=None): # Unused, but cannot remove until major RPC version bump result = self.db.instance_get_active_by_window(context, begin, end, project_id, host) return jsonutils.to_primitive(result) def instance_get_active_by_window_joined(self, context, begin, end=None, project_id=None, host=None): result = self.db.instance_get_active_by_window_joined( context, begin, end, project_id, host) return jsonutils.to_primitive(result) def instance_destroy(self, context, instance): self.db.instance_destroy(context, instance['uuid']) def instance_info_cache_delete(self, context, instance): self.db.instance_info_cache_delete(context, instance['uuid']) def instance_info_cache_update(self, context, instance, values): self.db.instance_info_cache_update(context, instance['uuid'], values) def instance_type_get(self, context, instance_type_id): result = self.db.flavor_get(context, instance_type_id) return jsonutils.to_primitive(result) def instance_fault_create(self, context, values): result = self.db.instance_fault_create(context, values) return jsonutils.to_primitive(result) # NOTE(kerrin): This method can be removed in v2.0 of the RPC API. def vol_get_usage_by_time(self, context, start_time): result = self.db.vol_get_usage_by_time(context, start_time) return jsonutils.to_primitive(result) # NOTE(kerrin): The last_refreshed argument is unused by this method # and can be removed in v2.0 of the RPC API. def vol_usage_update(self, context, vol_id, rd_req, rd_bytes, wr_req, wr_bytes, instance, last_refreshed=None, update_totals=False): vol_usage = self.db.vol_usage_update(context, vol_id, rd_req, rd_bytes, wr_req, wr_bytes, instance['uuid'], instance['project_id'], instance['user_id'], instance['availability_zone'], update_totals) # We have just updated the database, so send the notification now self.notifier.info(context, 'volume.usage', compute_utils.usage_volume_info(vol_usage)) @rpc_common.client_exceptions(exception.ComputeHostNotFound, exception.HostBinaryNotFound) def service_get_all_by(self, context, topic=None, host=None, binary=None): if not any((topic, host, binary)): result = self.db.service_get_all(context) elif all((topic, host)): if topic == 'compute': result = self.db.service_get_by_compute_host(context, host) # FIXME(comstud) Potentially remove this on bump to v2.0 result = [result] else: result = self.db.service_get_by_host_and_topic(context, host, topic) elif all((host, binary)): result = self.db.service_get_by_args(context, host, binary) elif topic: result = self.db.service_get_all_by_topic(context, topic) elif host: result = self.db.service_get_all_by_host(context, host) return jsonutils.to_primitive(result) def action_event_start(self, context, values): evt = self.db.action_event_start(context, values) return jsonutils.to_primitive(evt) def action_event_finish(self, context, values): evt = self.db.action_event_finish(context, values) return jsonutils.to_primitive(evt) def service_create(self, context, values): svc = self.db.service_create(context, values) return jsonutils.to_primitive(svc) @rpc_common.client_exceptions(exception.ServiceNotFound) def service_destroy(self, context, service_id): self.db.service_destroy(context, service_id) def compute_node_create(self, context, values): result = self.db.compute_node_create(context, values) return jsonutils.to_primitive(result) def compute_node_update(self, context, node, values, prune_stats=False): result = self.db.compute_node_update(context, node['id'], values, prune_stats) return jsonutils.to_primitive(result) def compute_node_delete(self, context, node): result = self.db.compute_node_delete(context, node['id']) return jsonutils.to_primitive(result) @rpc_common.client_exceptions(exception.ServiceNotFound) def service_update(self, context, service, values): svc = self.db.service_update(context, service['id'], values) return jsonutils.to_primitive(svc) def task_log_get(self, context, task_name, begin, end, host, state=None): result = self.db.task_log_get(context, task_name, begin, end, host, state) return jsonutils.to_primitive(result) def task_log_begin_task(self, context, task_name, begin, end, host, task_items=None, message=None): result = self.db.task_log_begin_task(context.elevated(), task_name, begin, end, host, task_items, message) return jsonutils.to_primitive(result) def task_log_end_task(self, context, task_name, begin, end, host, errors, message=None): result = self.db.task_log_end_task(context.elevated(), task_name, begin, end, host, errors, message) return jsonutils.to_primitive(result) def notify_usage_exists(self, context, instance, current_period=False, ignore_missing_network_data=True, system_metadata=None, extra_usage_info=None): compute_utils.notify_usage_exists(self.notifier, context, instance, current_period, ignore_missing_network_data, system_metadata, extra_usage_info) def security_groups_trigger_handler(self, context, event, args): self.security_group_api.trigger_handler(event, context, *args) def security_groups_trigger_members_refresh(self, context, group_ids): self.security_group_api.trigger_members_refresh(context, group_ids) def network_migrate_instance_start(self, context, instance, migration): self.network_api.migrate_instance_start(context, instance, migration) def network_migrate_instance_finish(self, context, instance, migration): self.network_api.migrate_instance_finish(context, instance, migration) def quota_commit(self, context, reservations, project_id=None, user_id=None): quota.QUOTAS.commit(context, reservations, project_id=project_id, user_id=user_id) def quota_rollback(self, context, reservations, project_id=None, user_id=None): quota.QUOTAS.rollback(context, reservations, project_id=project_id, user_id=user_id) def get_ec2_ids(self, context, instance): ec2_ids = {} ec2_ids['instance-id'] = ec2utils.id_to_ec2_inst_id(instance['uuid']) ec2_ids['ami-id'] = ec2utils.glance_id_to_ec2_id(context, instance['image_ref']) for image_type in ['kernel', 'ramdisk']: if '%s_id' % image_type in instance: image_id = instance['%s_id' % image_type] ec2_image_type = ec2utils.image_type(image_type) ec2_id = ec2utils.glance_id_to_ec2_id(context, image_id, ec2_image_type) ec2_ids['%s-id' % image_type] = ec2_id return ec2_ids # NOTE(danms): This method is now deprecated and can be removed in # version v2.0 of the RPC API def compute_stop(self, context, instance, do_cast=True): # NOTE(mriedem): Clients using an interface before 1.43 will be sending # dicts so we need to handle that here since compute/api::stop() # requires an object. if isinstance(instance, dict): instance = instance_obj.Instance._from_db_object( context, instance_obj.Instance(), instance) self.compute_api.stop(context, instance, do_cast) # NOTE(comstud): This method is now deprecated and can be removed in # version v2.0 of the RPC API def compute_confirm_resize(self, context, instance, migration_ref): if isinstance(instance, dict): attrs = ['metadata', 'system_metadata', 'info_cache', 'security_groups'] instance = instance_obj.Instance._from_db_object( context, instance_obj.Instance(), instance, expected_attrs=attrs) if isinstance(migration_ref, dict): migration_ref = migration_obj.Migration._from_db_object( context.elevated(), migration_ref) self.compute_api.confirm_resize(context, instance, migration=migration_ref) def compute_unrescue(self, context, instance): self.compute_api.unrescue(context, instance) def _object_dispatch(self, target, method, context, args, kwargs): """Dispatch a call to an object method. This ensures that object methods get called and any exception that is raised gets wrapped in a ClientException for forwarding back to the caller (without spamming the conductor logs). """ try: # NOTE(danms): Keep the getattr inside the try block since # a missing method is really a client problem return getattr(target, method)(context, *args, **kwargs) except Exception: raise rpc_common.ClientException() def object_class_action(self, context, objname, objmethod, objver, args, kwargs): """Perform a classmethod action on an object.""" objclass = nova_object.NovaObject.obj_class_from_name(objname, objver) return self._object_dispatch(objclass, objmethod, context, args, kwargs) def object_action(self, context, objinst, objmethod, args, kwargs): """Perform an action on an object.""" oldobj = copy.copy(objinst) result = self._object_dispatch(objinst, objmethod, context, args, kwargs) updates = dict() # NOTE(danms): Diff the object with the one passed to us and # generate a list of changes to forward back for field in objinst.fields: if not objinst.obj_attr_is_set(field): # Avoid demand-loading anything continue if (not oldobj.obj_attr_is_set(field) or oldobj[field] != objinst[field]): updates[field] = objinst._attr_to_primitive(field) # This is safe since a field named this would conflict with the # method anyway updates['obj_what_changed'] = objinst.obj_what_changed() return updates, result # NOTE(danms): This method is now deprecated and can be removed in # v2.0 of the RPC API def compute_reboot(self, context, instance, reboot_type): self.compute_api.reboot(context, instance, reboot_type) class ComputeTaskManager(base.Base): """Namespace for compute methods. This class presents an rpc API for nova-conductor under the 'compute_task' namespace. The methods here are compute operations that are invoked by the API service. These methods see the operation to completion, which may involve coordinating activities on multiple compute nodes. """ RPC_API_NAMESPACE = 'compute_task' RPC_API_VERSION = '1.6' def __init__(self): super(ComputeTaskManager, self).__init__() self.compute_rpcapi = compute_rpcapi.ComputeAPI() self.scheduler_rpcapi = scheduler_rpcapi.SchedulerAPI() self.image_service = glance.get_default_image_service() self.quotas = quota.QUOTAS @rpc_common.client_exceptions(exception.NoValidHost, exception.ComputeServiceUnavailable, exception.InvalidHypervisorType, exception.UnableToMigrateToSelf, exception.DestinationHypervisorTooOld, exception.InvalidLocalStorage, exception.InvalidSharedStorage, exception.MigrationPreCheckError) def migrate_server(self, context, instance, scheduler_hint, live, rebuild, flavor, block_migration, disk_over_commit, reservations=None): if instance and not isinstance(instance, instance_obj.Instance): # NOTE(danms): Until v2 of the RPC API, we need to tolerate # old-world instance objects here attrs = ['metadata', 'system_metadata', 'info_cache', 'security_groups'] instance = instance_obj.Instance._from_db_object( context, instance_obj.Instance(), instance, expected_attrs=attrs) if live and not rebuild and not flavor: self._live_migrate(context, instance, scheduler_hint, block_migration, disk_over_commit) elif not live and not rebuild and flavor: instance_uuid = instance['uuid'] with compute_utils.EventReporter(context, ConductorManager(), 'cold_migrate', instance_uuid): self._cold_migrate(context, instance, flavor, scheduler_hint['filter_properties'], reservations) else: raise NotImplementedError() def _cold_migrate(self, context, instance, flavor, filter_properties, reservations): image_ref = instance.image_ref image = compute_utils.get_image_metadata( context, self.image_service, image_ref, instance) request_spec = scheduler_utils.build_request_spec( context, image, [instance], instance_type=flavor) try: hosts = self.scheduler_rpcapi.select_destinations( context, request_spec, filter_properties) host_state = hosts[0] except exception.NoValidHost as ex: vm_state = instance['vm_state'] if not vm_state: vm_state = vm_states.ACTIVE updates = {'vm_state': vm_state, 'task_state': None} self._set_vm_state_and_notify(context, 'migrate_server', updates, ex, request_spec) if reservations: self.quotas.rollback(context, reservations) LOG.warning(_("No valid host found for cold migrate")) return try: scheduler_utils.populate_filter_properties(filter_properties, host_state) # context is not serializable filter_properties.pop('context', None) # TODO(timello): originally, instance_type in request_spec # on compute.api.resize does not have 'extra_specs', so we # remove it for now to keep tests backward compatibility. request_spec['instance_type'].pop('extra_specs') (host, node) = (host_state['host'], host_state['nodename']) self.compute_rpcapi.prep_resize( context, image, instance, flavor, host, reservations, request_spec=request_spec, filter_properties=filter_properties, node=node) except Exception as ex: with excutils.save_and_reraise_exception(): updates = {'vm_state': vm_states.ERROR, 'task_state': None} self._set_vm_state_and_notify(context, 'migrate_server', updates, ex, request_spec) if reservations: self.quotas.rollback(context, reservations) def _set_vm_state_and_notify(self, context, method, updates, ex, request_spec): scheduler_utils.set_vm_state_and_notify( context, 'compute_task', method, updates, ex, request_spec, self.db) def _live_migrate(self, context, instance, scheduler_hint, block_migration, disk_over_commit): destination = scheduler_hint.get("host") try: live_migrate.execute(context, instance, destination, block_migration, disk_over_commit) except (exception.NoValidHost, exception.ComputeServiceUnavailable, exception.InvalidHypervisorType, exception.UnableToMigrateToSelf, exception.DestinationHypervisorTooOld, exception.InvalidLocalStorage, exception.InvalidSharedStorage, exception.MigrationPreCheckError) as ex: with excutils.save_and_reraise_exception(): #TODO(johngarbutt) - eventually need instance actions here request_spec = {'instance_properties': { 'uuid': instance['uuid'], }, } scheduler_utils.set_vm_state_and_notify(context, 'compute_task', 'migrate_server', dict(vm_state=instance['vm_state'], task_state=None, expected_task_state=task_states.MIGRATING,), ex, request_spec, self.db) except Exception as ex: with excutils.save_and_reraise_exception(): request_spec = {'instance_properties': { 'uuid': instance['uuid'], }, } scheduler_utils.set_vm_state_and_notify(context, 'compute_task', 'migrate_server', {'vm_state': vm_states.ERROR}, ex, request_spec, self.db) def build_instances(self, context, instances, image, filter_properties, admin_password, injected_files, requested_networks, security_groups, block_device_mapping, legacy_bdm=True): request_spec = scheduler_utils.build_request_spec(context, image, instances) # NOTE(alaski): For compatibility until a new scheduler method is used. request_spec.update({'block_device_mapping': block_device_mapping, 'security_group': security_groups}) self.scheduler_rpcapi.run_instance(context, request_spec=request_spec, admin_password=admin_password, injected_files=injected_files, requested_networks=requested_networks, is_first_time=True, filter_properties=filter_properties, legacy_bdm_in_spec=legacy_bdm) def _get_image(self, context, image_id): if not image_id: return None return self.image_service.show(context, image_id) def _delete_image(self, context, image_id): (image_service, image_id) = glance.get_remote_image_service(context, image_id) return image_service.delete(context, image_id) def _schedule_instances(self, context, image, filter_properties, *instances): request_spec = scheduler_utils.build_request_spec(context, image, instances) # dict(host='', nodename='', limits='') hosts = self.scheduler_rpcapi.select_destinations(context, request_spec, filter_properties) return hosts def unshelve_instance(self, context, instance): sys_meta = instance.system_metadata if instance.vm_state == vm_states.SHELVED: instance.task_state = task_states.POWERING_ON instance.save(expected_task_state=task_states.UNSHELVING) self.compute_rpcapi.start_instance(context, instance) snapshot_id = sys_meta.get('shelved_image_id') if snapshot_id: self._delete_image(context, snapshot_id) elif instance.vm_state == vm_states.SHELVED_OFFLOADED: try: with compute_utils.EventReporter(context, self.db, 'get_image_info', instance.uuid): image = self._get_image(context, sys_meta['shelved_image_id']) except exception.ImageNotFound: with excutils.save_and_reraise_exception(): LOG.error(_('Unshelve attempted but vm_state not SHELVED ' 'or SHELVED_OFFLOADED'), instance=instance) instance.vm_state = vm_states.ERROR instance.save() hosts = self._schedule_instances(context, image, [], instance) host = hosts.pop(0)['host'] self.compute_rpcapi.unshelve_instance(context, instance, host, image) else: LOG.error(_('Unshelve attempted but vm_state not SHELVED or ' 'SHELVED_OFFLOADED'), instance=instance) instance.vm_state = vm_states.ERROR instance.save() return for key in ['shelved_at', 'shelved_image_id', 'shelved_host']: if key in sys_meta: del(sys_meta[key]) instance.system_metadata = sys_meta instance.save()
Java
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports System.Threading.Tasks Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Completion.SuggestionMode Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public Class SuggestionModeCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests Public Sub New(workspaceFixture As VisualBasicTestWorkspaceFixture) MyBase.New(workspaceFixture) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration1() As Task Dim markup = <a>Class C $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration2() As Task Dim markup = <a>Class C Public $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration3() As Task Dim markup = <a>Module M Public $$ End Module</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration4() As Task Dim markup = <a>Structure S Public $$ End Structure</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration5() As Task Dim markup = <a>Class C WithEvents $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration6() As Task Dim markup = <a>Class C Protected Friend $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration1() As Task Dim markup = <a>Class C Public Sub Bar($$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration2() As Task Dim markup = <a>Class C Public Sub Bar(Optional foo as Integer, $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration3() As Task Dim markup = <a>Class C Public Sub Bar(Optional $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration4() As Task Dim markup = <a>Class C Public Sub Bar(Optional x $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration5() As Task Dim markup = <a>Class C Public Sub Bar(Optional x As $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration6() As Task Dim markup = <a>Class C Public Sub Bar(Optional x As Integer $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration7() As Task Dim markup = <a>Class C Public Sub Bar(ByVal $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration8() As Task Dim markup = <a>Class C Public Sub Bar(ByVal x $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration9() As Task Dim markup = <a>Class C Sub Foo $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration10() As Task Dim markup = <a>Class C Public Property SomeProp $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectClause1() As Task Dim markup = <a>Class z Sub bar() Dim a = New Integer(1, 2, 3) {} Dim foo = From z In a Select $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectClause2() As Task Dim markup = <a>Class z Sub bar() Dim a = New Integer(1, 2, 3) {} Dim foo = From z In a Select 1, $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement1() As Task Dim markup = <a>Class z Sub bar() For $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement2() As Task Dim markup = <a>Class z Sub bar() For $$ = 1 To 10 Next End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <WorkItem(545351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545351")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBuilderWhenOptionExplicitOff() As Task Dim markup = <a>Option Explicit Off Class C1 Sub M() Console.WriteLine($$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(546659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546659")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestUsingStatement() As Task Dim markup = <a> Class C1 Sub M() Using $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOptionExplicitOffStatementLevel1() As Task Dim markup = <a> Option Explicit Off Class C1 Sub M() $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOptionExplicitOffStatementLevel2() As Task Dim markup = <a> Option Explicit Off Class C1 Sub M() a = $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(960416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960416")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestReadonlyField() As Task Dim markup = <a> Class C1 Readonly $$ Sub M() End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(1044441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044441")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function BuilderInDebugger() As Task Dim markup = <a> Class C1 Sub Foo() Dim __o = $$ End Sub End Class </a> Await VerifyBuilderAsync(markup, CompletionTrigger.Default, useDebuggerOptions:=True) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceDeclarationName_Unqualified() As Task Dim markup = <a> Namespace $$ End Class </a> Await VerifyBuilderAsync(markup, CompletionTrigger.Default) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceDeclarationName_Qualified() As Task Dim markup = <a> Namespace A.$$ End Class </a> Await VerifyBuilderAsync(markup, CompletionTrigger.Default) End Function Private Function VerifyNotBuilderAsync(markup As XElement, Optional triggerInfo As CompletionTrigger? = Nothing, Optional useDebuggerOptions As Boolean = False) As Task Return VerifySuggestionModeWorkerAsync(markup, isBuilder:=False, triggerInfo:=triggerInfo, useDebuggerOptions:=useDebuggerOptions) End Function Private Function VerifyBuilderAsync(markup As XElement, Optional triggerInfo As CompletionTrigger? = Nothing, Optional useDebuggerOptions As Boolean = False) As Task Return VerifySuggestionModeWorkerAsync(markup, isBuilder:=True, triggerInfo:=triggerInfo, useDebuggerOptions:=useDebuggerOptions) End Function Private Async Function VerifySuggestionModeWorkerAsync(markup As XElement, isBuilder As Boolean, triggerInfo As CompletionTrigger?, Optional useDebuggerOptions As Boolean = False) As Task Dim code As String = Nothing Dim position As Integer = 0 MarkupTestFile.GetPosition(markup.NormalizedValue, code, position) Using workspaceFixture = New VisualBasicTestWorkspaceFixture() Dim options = If(useDebuggerOptions, (Await workspaceFixture.GetWorkspaceAsync()).Options.WithDebuggerCompletionOptions(), (Await workspaceFixture.GetWorkspaceAsync()).Options) Dim document1 = Await workspaceFixture.UpdateDocumentAsync(code, SourceCodeKind.Regular) Await CheckResultsAsync(document1, position, isBuilder, triggerInfo, options) If Await CanUseSpeculativeSemanticModelAsync(document1, position) Then Dim document2 = Await workspaceFixture.UpdateDocumentAsync(code, SourceCodeKind.Regular, cleanBeforeUpdate:=False) Await CheckResultsAsync(document2, position, isBuilder, triggerInfo, options) End If End Using End Function Private Async Function CheckResultsAsync(document As Document, position As Integer, isBuilder As Boolean, triggerInfo As CompletionTrigger?, options As OptionSet) As Task triggerInfo = If(triggerInfo, CompletionTrigger.CreateInsertionTrigger("a"c)) Dim service = GetCompletionService(document.Project.Solution.Workspace) Dim context = Await service.GetContextAsync( service.ExclusiveProviders?(0), document, position, triggerInfo.Value, options, CancellationToken.None) If isBuilder Then Assert.NotNull(context) Assert.NotNull(context.SuggestionModeItem) Else If context IsNot Nothing Then Assert.True(context.SuggestionModeItem Is Nothing, "group.Builder = " & If(context.SuggestionModeItem IsNot Nothing, context.SuggestionModeItem.DisplayText, "null")) End If End If End Function Friend Overrides Function CreateCompletionProvider() As CompletionProvider Return New VisualBasicSuggestionModeCompletionProvider() End Function End Class End Namespace
Java
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Orchestration.Airflow.Service.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedImageVersionsClientSnippets { /// <summary>Snippet for ListImageVersions</summary> public void ListImageVersionsRequestObject() { // Snippet: ListImageVersions(ListImageVersionsRequest, CallSettings) // Create client ImageVersionsClient imageVersionsClient = ImageVersionsClient.Create(); // Initialize request argument(s) ListImageVersionsRequest request = new ListImageVersionsRequest { Parent = "", IncludePastReleases = false, }; // Make the request PagedEnumerable<ListImageVersionsResponse, ImageVersion> response = imageVersionsClient.ListImageVersions(request); // Iterate over all response items, lazily performing RPCs as required foreach (ImageVersion item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListImageVersionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ImageVersion item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ImageVersion> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ImageVersion item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListImageVersionsAsync</summary> public async Task ListImageVersionsRequestObjectAsync() { // Snippet: ListImageVersionsAsync(ListImageVersionsRequest, CallSettings) // Create client ImageVersionsClient imageVersionsClient = await ImageVersionsClient.CreateAsync(); // Initialize request argument(s) ListImageVersionsRequest request = new ListImageVersionsRequest { Parent = "", IncludePastReleases = false, }; // Make the request PagedAsyncEnumerable<ListImageVersionsResponse, ImageVersion> response = imageVersionsClient.ListImageVersionsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ImageVersion item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListImageVersionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ImageVersion item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ImageVersion> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ImageVersion item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListImageVersions</summary> public void ListImageVersions() { // Snippet: ListImageVersions(string, string, int?, CallSettings) // Create client ImageVersionsClient imageVersionsClient = ImageVersionsClient.Create(); // Initialize request argument(s) string parent = ""; // Make the request PagedEnumerable<ListImageVersionsResponse, ImageVersion> response = imageVersionsClient.ListImageVersions(parent); // Iterate over all response items, lazily performing RPCs as required foreach (ImageVersion item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListImageVersionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ImageVersion item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ImageVersion> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ImageVersion item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListImageVersionsAsync</summary> public async Task ListImageVersionsAsync() { // Snippet: ListImageVersionsAsync(string, string, int?, CallSettings) // Create client ImageVersionsClient imageVersionsClient = await ImageVersionsClient.CreateAsync(); // Initialize request argument(s) string parent = ""; // Make the request PagedAsyncEnumerable<ListImageVersionsResponse, ImageVersion> response = imageVersionsClient.ListImageVersionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ImageVersion item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListImageVersionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ImageVersion item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ImageVersion> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ImageVersion item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
Java
/* * Rules for CKEditor content */ .textEditorContent { font-size: 0.9em; word-wrap: break-word; word-break: break-word; } .textEditorContent img { height: auto; max-width: 100%; max-height: 100%; } .textEditorContent ul { margin: inherit; padding: 10px 40px; } .textEditorContent .description table, .textEditorContent .description th, .textEditorContent .description td { border: 1px dotted #d3d3d3; } .textEditorContent .description abbr[title] { border: none; } .textEditorContent .description select { font-family: unset; color: initial; } .textEditorContent .description h1, .textEditorContent .description h2, .textEditorContent .description h3, .textEditorContent .description h4, .textEditorContent .description h5, .textEditorContent .description h6, .textEditorContent .description p, .textEditorContent .description ul { margin: 0.5em 0; } .textEditorContent .description hr { border-color: #ccc; }
Java
/** * Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com> */ package com.typesafe.config.impl; import java.io.ObjectStreamException; import java.io.Serializable; import java.math.BigInteger; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; 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 com.typesafe.config.ConfigException; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigOrigin; import com.typesafe.config.ConfigRenderOptions; import com.typesafe.config.ConfigValue; final class SimpleConfigObject extends AbstractConfigObject implements Serializable { private static final long serialVersionUID = 2L; // this map should never be modified - assume immutable final private Map<String, AbstractConfigValue> value; final private boolean resolved; final private boolean ignoresFallbacks; SimpleConfigObject(ConfigOrigin origin, Map<String, AbstractConfigValue> value, ResolveStatus status, boolean ignoresFallbacks) { super(origin); if (value == null) throw new ConfigException.BugOrBroken( "creating config object with null map"); this.value = value; this.resolved = status == ResolveStatus.RESOLVED; this.ignoresFallbacks = ignoresFallbacks; // Kind of an expensive debug check. Comment out? if (status != ResolveStatus.fromValues(value.values())) throw new ConfigException.BugOrBroken("Wrong resolved status on " + this); } SimpleConfigObject(ConfigOrigin origin, Map<String, AbstractConfigValue> value) { this(origin, value, ResolveStatus.fromValues(value.values()), false /* ignoresFallbacks */); } @Override public SimpleConfigObject withOnlyKey(String key) { return withOnlyPath(Path.newKey(key)); } @Override public SimpleConfigObject withoutKey(String key) { return withoutPath(Path.newKey(key)); } // gets the object with only the path if the path // exists, otherwise null if it doesn't. this ensures // that if we have { a : { b : 42 } } and do // withOnlyPath("a.b.c") that we don't keep an empty // "a" object. @Override protected SimpleConfigObject withOnlyPathOrNull(Path path) { String key = path.first(); Path next = path.remainder(); AbstractConfigValue v = value.get(key); if (next != null) { if (v != null && (v instanceof AbstractConfigObject)) { v = ((AbstractConfigObject) v).withOnlyPathOrNull(next); } else { // if the path has more elements but we don't have an object, // then the rest of the path does not exist. v = null; } } if (v == null) { return null; } else { return new SimpleConfigObject(origin(), Collections.singletonMap(key, v), v.resolveStatus(), ignoresFallbacks); } } @Override SimpleConfigObject withOnlyPath(Path path) { SimpleConfigObject o = withOnlyPathOrNull(path); if (o == null) { return new SimpleConfigObject(origin(), Collections.<String, AbstractConfigValue> emptyMap(), ResolveStatus.RESOLVED, ignoresFallbacks); } else { return o; } } @Override SimpleConfigObject withoutPath(Path path) { String key = path.first(); Path next = path.remainder(); AbstractConfigValue v = value.get(key); if (v != null && next != null && v instanceof AbstractConfigObject) { v = ((AbstractConfigObject) v).withoutPath(next); Map<String, AbstractConfigValue> updated = new HashMap<String, AbstractConfigValue>( value); updated.put(key, v); return new SimpleConfigObject(origin(), updated, ResolveStatus.fromValues(updated .values()), ignoresFallbacks); } else if (next != null || v == null) { // can't descend, nothing to remove return this; } else { Map<String, AbstractConfigValue> smaller = new HashMap<String, AbstractConfigValue>( value.size() - 1); for (Map.Entry<String, AbstractConfigValue> old : value.entrySet()) { if (!old.getKey().equals(key)) smaller.put(old.getKey(), old.getValue()); } return new SimpleConfigObject(origin(), smaller, ResolveStatus.fromValues(smaller .values()), ignoresFallbacks); } } @Override public SimpleConfigObject withValue(String key, ConfigValue v) { if (v == null) throw new ConfigException.BugOrBroken( "Trying to store null ConfigValue in a ConfigObject"); Map<String, AbstractConfigValue> newMap; if (value.isEmpty()) { newMap = Collections.singletonMap(key, (AbstractConfigValue) v); } else { newMap = new HashMap<String, AbstractConfigValue>(value); newMap.put(key, (AbstractConfigValue) v); } return new SimpleConfigObject(origin(), newMap, ResolveStatus.fromValues(newMap.values()), ignoresFallbacks); } @Override SimpleConfigObject withValue(Path path, ConfigValue v) { String key = path.first(); Path next = path.remainder(); if (next == null) { return withValue(key, v); } else { AbstractConfigValue child = value.get(key); if (child != null && child instanceof AbstractConfigObject) { // if we have an object, add to it return withValue(key, ((AbstractConfigObject) child).withValue(next, v)); } else { // as soon as we have a non-object, replace it entirely SimpleConfig subtree = ((AbstractConfigValue) v).atPath( SimpleConfigOrigin.newSimple("withValue(" + next.render() + ")"), next); return withValue(key, subtree.root()); } } } @Override protected AbstractConfigValue attemptPeekWithPartialResolve(String key) { return value.get(key); } private SimpleConfigObject newCopy(ResolveStatus newStatus, ConfigOrigin newOrigin, boolean newIgnoresFallbacks) { return new SimpleConfigObject(newOrigin, value, newStatus, newIgnoresFallbacks); } @Override protected SimpleConfigObject newCopy(ResolveStatus newStatus, ConfigOrigin newOrigin) { return newCopy(newStatus, newOrigin, ignoresFallbacks); } @Override protected SimpleConfigObject withFallbacksIgnored() { if (ignoresFallbacks) return this; else return newCopy(resolveStatus(), origin(), true /* ignoresFallbacks */); } @Override ResolveStatus resolveStatus() { return ResolveStatus.fromBoolean(resolved); } @Override public SimpleConfigObject replaceChild(AbstractConfigValue child, AbstractConfigValue replacement) { HashMap<String, AbstractConfigValue> newChildren = new HashMap<String, AbstractConfigValue>(value); for (Map.Entry<String, AbstractConfigValue> old : newChildren.entrySet()) { if (old.getValue() == child) { if (replacement != null) old.setValue(replacement); else newChildren.remove(old.getKey()); return new SimpleConfigObject(origin(), newChildren, ResolveStatus.fromValues(newChildren.values()), ignoresFallbacks); } } throw new ConfigException.BugOrBroken("SimpleConfigObject.replaceChild did not find " + child + " in " + this); } @Override public boolean hasDescendant(AbstractConfigValue descendant) { for (AbstractConfigValue child : value.values()) { if (child == descendant) return true; } // now do the expensive search for (AbstractConfigValue child : value.values()) { if (child instanceof Container && ((Container) child).hasDescendant(descendant)) return true; } return false; } @Override protected boolean ignoresFallbacks() { return ignoresFallbacks; } @Override public Map<String, Object> unwrapped() { Map<String, Object> m = new HashMap<String, Object>(); for (Map.Entry<String, AbstractConfigValue> e : value.entrySet()) { m.put(e.getKey(), e.getValue().unwrapped()); } return m; } @Override protected SimpleConfigObject mergedWithObject(AbstractConfigObject abstractFallback) { requireNotIgnoringFallbacks(); if (!(abstractFallback instanceof SimpleConfigObject)) { throw new ConfigException.BugOrBroken( "should not be reached (merging non-SimpleConfigObject)"); } SimpleConfigObject fallback = (SimpleConfigObject) abstractFallback; boolean changed = false; boolean allResolved = true; Map<String, AbstractConfigValue> merged = new HashMap<String, AbstractConfigValue>(); Set<String> allKeys = new HashSet<String>(); allKeys.addAll(this.keySet()); allKeys.addAll(fallback.keySet()); for (String key : allKeys) { AbstractConfigValue first = this.value.get(key); AbstractConfigValue second = fallback.value.get(key); AbstractConfigValue kept; if (first == null) kept = second; else if (second == null) kept = first; else kept = first.withFallback(second); merged.put(key, kept); if (first != kept) changed = true; if (kept.resolveStatus() == ResolveStatus.UNRESOLVED) allResolved = false; } ResolveStatus newResolveStatus = ResolveStatus.fromBoolean(allResolved); boolean newIgnoresFallbacks = fallback.ignoresFallbacks(); if (changed) return new SimpleConfigObject(mergeOrigins(this, fallback), merged, newResolveStatus, newIgnoresFallbacks); else if (newResolveStatus != resolveStatus() || newIgnoresFallbacks != ignoresFallbacks()) return newCopy(newResolveStatus, origin(), newIgnoresFallbacks); else return this; } private SimpleConfigObject modify(NoExceptionsModifier modifier) { try { return modifyMayThrow(modifier); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ConfigException.BugOrBroken("unexpected checked exception", e); } } private SimpleConfigObject modifyMayThrow(Modifier modifier) throws Exception { Map<String, AbstractConfigValue> changes = null; for (String k : keySet()) { AbstractConfigValue v = value.get(k); // "modified" may be null, which means remove the child; // to do that we put null in the "changes" map. AbstractConfigValue modified = modifier.modifyChildMayThrow(k, v); if (modified != v) { if (changes == null) changes = new HashMap<String, AbstractConfigValue>(); changes.put(k, modified); } } if (changes == null) { return this; } else { Map<String, AbstractConfigValue> modified = new HashMap<String, AbstractConfigValue>(); boolean sawUnresolved = false; for (String k : keySet()) { if (changes.containsKey(k)) { AbstractConfigValue newValue = changes.get(k); if (newValue != null) { modified.put(k, newValue); if (newValue.resolveStatus() == ResolveStatus.UNRESOLVED) sawUnresolved = true; } else { // remove this child; don't put it in the new map. } } else { AbstractConfigValue newValue = value.get(k); modified.put(k, newValue); if (newValue.resolveStatus() == ResolveStatus.UNRESOLVED) sawUnresolved = true; } } return new SimpleConfigObject(origin(), modified, sawUnresolved ? ResolveStatus.UNRESOLVED : ResolveStatus.RESOLVED, ignoresFallbacks()); } } private static final class ResolveModifier implements Modifier { final Path originalRestrict; ResolveContext context; final ResolveSource source; ResolveModifier(ResolveContext context, ResolveSource source) { this.context = context; this.source = source; originalRestrict = context.restrictToChild(); } @Override public AbstractConfigValue modifyChildMayThrow(String key, AbstractConfigValue v) throws NotPossibleToResolve { if (context.isRestrictedToChild()) { if (key.equals(context.restrictToChild().first())) { Path remainder = context.restrictToChild().remainder(); if (remainder != null) { ResolveResult<? extends AbstractConfigValue> result = context.restrict(remainder).resolve(v, source); context = result.context.unrestricted().restrict(originalRestrict); return result.value; } else { // we don't want to resolve the leaf child. return v; } } else { // not in the restrictToChild path return v; } } else { // no restrictToChild, resolve everything ResolveResult<? extends AbstractConfigValue> result = context.unrestricted().resolve(v, source); context = result.context.unrestricted().restrict(originalRestrict); return result.value; } } } @Override ResolveResult<? extends AbstractConfigObject> resolveSubstitutions(ResolveContext context, ResolveSource source) throws NotPossibleToResolve { if (resolveStatus() == ResolveStatus.RESOLVED) return ResolveResult.make(context, this); final ResolveSource sourceWithParent = source.pushParent(this); try { ResolveModifier modifier = new ResolveModifier(context, sourceWithParent); AbstractConfigValue value = modifyMayThrow(modifier); return ResolveResult.make(modifier.context, value).asObjectResult(); } catch (NotPossibleToResolve e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ConfigException.BugOrBroken("unexpected checked exception", e); } } @Override SimpleConfigObject relativized(final Path prefix) { return modify(new NoExceptionsModifier() { @Override public AbstractConfigValue modifyChild(String key, AbstractConfigValue v) { return v.relativized(prefix); } }); } // this is only Serializable to chill out a findbugs warning static final private class RenderComparator implements java.util.Comparator<String>, Serializable { private static final long serialVersionUID = 1L; private static boolean isAllDigits(String s) { int length = s.length(); // empty string doesn't count as a number // string longer than "max number of digits in a long" cannot be parsed as a long if (length == 0) return false; for (int i = 0; i < length; ++i) { char c = s.charAt(i); if (!Character.isDigit(c)) return false; } return true; } // This is supposed to sort numbers before strings, // and sort the numbers numerically. The point is // to make objects which are really list-like // (numeric indices) appear in order. @Override public int compare(String a, String b) { boolean aDigits = isAllDigits(a); boolean bDigits = isAllDigits(b); if (aDigits && bDigits) { return new BigInteger(a).compareTo(new BigInteger(b)); } else if (aDigits) { return -1; } else if (bDigits) { return 1; } else { return a.compareTo(b); } } } @Override protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { if (isEmpty()) { sb.append("{}"); } else { boolean outerBraces = options.getJson() || !atRoot; int innerIndent; if (outerBraces) { innerIndent = indent + 1; sb.append("{"); if (options.getFormatted()) sb.append('\n'); } else { innerIndent = indent; } int separatorCount = 0; String[] keys = keySet().toArray(new String[size()]); Arrays.sort(keys, new RenderComparator()); for (String k : keys) { AbstractConfigValue v; v = value.get(k); if (options.getOriginComments()) { String[] lines = v.origin().description().split("\n"); for (String l : lines) { indent(sb, indent + 1, options); sb.append('#'); if (!l.isEmpty()) sb.append(' '); sb.append(l); sb.append("\n"); } } if (options.getComments()) { for (String comment : v.origin().comments()) { indent(sb, innerIndent, options); sb.append("#"); if (!comment.startsWith(" ")) sb.append(' '); sb.append(comment); sb.append("\n"); } } indent(sb, innerIndent, options); v.render(sb, innerIndent, false /* atRoot */, k, options); if (options.getFormatted()) { if (options.getJson()) { sb.append(","); separatorCount = 2; } else { separatorCount = 1; } sb.append('\n'); } else { sb.append(","); separatorCount = 1; } } // chop last commas/newlines sb.setLength(sb.length() - separatorCount); if (outerBraces) { if (options.getFormatted()) { sb.append('\n'); // put a newline back if (outerBraces) indent(sb, indent, options); } sb.append("}"); } } if (atRoot && options.getFormatted()) sb.append('\n'); } @Override public AbstractConfigValue get(Object key) { return value.get(key); } private static boolean mapEquals(Map<String, ConfigValue> a, Map<String, ConfigValue> b) { if (a == b) return true; Set<String> aKeys = a.keySet(); Set<String> bKeys = b.keySet(); if (!aKeys.equals(bKeys)) return false; for (String key : aKeys) { if (!a.get(key).equals(b.get(key))) return false; } return true; } private static int mapHash(Map<String, ConfigValue> m) { // the keys have to be sorted, otherwise we could be equal // to another map but have a different hashcode. List<String> keys = new ArrayList<String>(); keys.addAll(m.keySet()); Collections.sort(keys); int valuesHash = 0; for (String k : keys) { valuesHash += m.get(k).hashCode(); } return 41 * (41 + keys.hashCode()) + valuesHash; } @Override protected boolean canEqual(Object other) { return other instanceof ConfigObject; } @Override public boolean equals(Object other) { // note that "origin" is deliberately NOT part of equality. // neither are other "extras" like ignoresFallbacks or resolve status. if (other instanceof ConfigObject) { // optimization to avoid unwrapped() for two ConfigObject, // which is what AbstractConfigValue does. return canEqual(other) && mapEquals(this, ((ConfigObject) other)); } else { return false; } } @Override public int hashCode() { // note that "origin" is deliberately NOT part of equality // neither are other "extras" like ignoresFallbacks or resolve status. return mapHash(this); } @Override public boolean containsKey(Object key) { return value.containsKey(key); } @Override public Set<String> keySet() { return value.keySet(); } @Override public boolean containsValue(Object v) { return value.containsValue(v); } @Override public Set<Map.Entry<String, ConfigValue>> entrySet() { // total bloat just to work around lack of type variance HashSet<java.util.Map.Entry<String, ConfigValue>> entries = new HashSet<Map.Entry<String, ConfigValue>>(); for (Map.Entry<String, AbstractConfigValue> e : value.entrySet()) { entries.add(new AbstractMap.SimpleImmutableEntry<String, ConfigValue>( e.getKey(), e .getValue())); } return entries; } @Override public boolean isEmpty() { return value.isEmpty(); } @Override public int size() { return value.size(); } @Override public Collection<ConfigValue> values() { return new HashSet<ConfigValue>(value.values()); } final private static String EMPTY_NAME = "empty config"; final private static SimpleConfigObject emptyInstance = empty(SimpleConfigOrigin .newSimple(EMPTY_NAME)); final static SimpleConfigObject empty() { return emptyInstance; } final static SimpleConfigObject empty(ConfigOrigin origin) { if (origin == null) return empty(); else return new SimpleConfigObject(origin, Collections.<String, AbstractConfigValue> emptyMap()); } final static SimpleConfigObject emptyMissing(ConfigOrigin baseOrigin) { return new SimpleConfigObject(SimpleConfigOrigin.newSimple( baseOrigin.description() + " (not found)"), Collections.<String, AbstractConfigValue> emptyMap()); } // serialization all goes through SerializedConfigValue private Object writeReplace() throws ObjectStreamException { return new SerializedConfigValue(this); } }
Java
<?php for ($i = 0; $i < $this->length; ++$i) { if (is_object($objectOrArray)) { $value = $this->readProperty($objectOrArray, $i); // arrays need to be treated separately (due to PHP bug?) // http://bugs.php.net/bug.php?id=52133 } elseif (is_array($objectOrArray)) { $property = $this->elements[$i]; if (!array_key_exists($property, $objectOrArray)) { $objectOrArray[$property] = $i + 1 < $this->length ? array() : null; } $value =& $objectOrArray[$property]; } else { throw new UnexpectedTypeException($objectOrArray, 'object or array'); } $objectOrArray =& $value; } return $value;
Java
/* * Copyright 2015 AppDynamics, 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.appdynamicspilot.rest; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; public class ShoppingCart implements java.io.Serializable { Logger log = Logger.getLogger(ShoppingCart.class); private List<ShoppingCartItem> items; public ShoppingCart() { items = new ArrayList<ShoppingCartItem>(); } public void addItem(ShoppingCartItem item) { items.add(item); } public void removeItem(ShoppingCartItem item) { items.remove(item); } public List<ShoppingCartItem> getAllItems() { return items; } public double getCartTotal() { double total = 0.0; for (ShoppingCartItem item : items) { total += item.getPrice(); } return total; } public void clear() { items.clear(); } }
Java
var express = require( 'express' ), router = require( './router' ); var app = express(); app.set('port', (process.env.PORT || 3000)); router.define( app ); // Set up port // ======================================================== app.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')); });
Java
import backgroundImages from '@const/background-images'; import * as actions from './actions.js'; import Background from './class.js'; // const getObj = (indexString) => { /* const [type, index] = indexString.split('-') if (typeof index === 'undefined') return {} return store.getState().bgimgState.list[type][index] */ // } const getListInitial = (type) => { let list = []; if (type === 'default') { list = backgroundImages.map( (filename, index) => new Background(filename, type + '-' + index) ); } /* const dir = type == 'custom' ? thePath.bgimgs_custom : thePath.bgimgs const parseData = (name) => { return { name: name } } if (self.nw) { const fs = require('fs') const path = require('path') const getList = (dir) => { return fs.readdirSync(dir) .filter(function (file) { return !fs.lstatSync(path.join(dir, file)).isDirectory() }) .map(function (filename) { return { name: filename, time: fs.statSync(path.join(dir, filename)).mtime.getTime() }; }) .sort(function (a, b) { return b.time - a.time; }) .map(function (o) { return o.name; }) } getList(dir) .forEach(function (name) { list.push(parseData( name, type === 'default' )) }) } else { } */ return list; }; export const initList = (currentIndex = 'default-0') => { const listDefault = getListInitial('default'); const listCustom = getListInitial('custom'); const [type, index] = currentIndex.split('-'); const current = eval( 'list' + type.substr(0, 1).toUpperCase() + type.substr(1) )[index]; // const currentPath = current ? { // original: current.getPath(), // blured: current.getPath('blured') // } : {} return (dispatch) => { dispatch( actions.init({ list: { default: listDefault, custom: listCustom, }, current, //, // currentIndex, // currentPath }) ); }; }; export const add = (/*filename*/) => {}; export const remove = (/*indexCustom*/) => {}; export const change = (obj) => { return (dispatch) => { dispatch(actions.change(obj)); }; }; export const mainImgLoaded = () => (dispatch) => dispatch(actions.mainLoaded());
Java
package org.carlspring.strongbox.validation; import javax.inject.Inject; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.carlspring.strongbox.authorization.service.AuthorizationConfigService; import org.springframework.util.StringUtils; /** * @author Pablo Tirado */ public class UniqueRoleNameValidator implements ConstraintValidator<UniqueRoleName, String> { @Inject private AuthorizationConfigService authorizationConfigService; @Override public void initialize(UniqueRoleName constraint) { // empty by design } @Override public boolean isValid(String roleName, ConstraintValidatorContext context) { return StringUtils.isEmpty(roleName) || !authorizationConfigService.get().getRoles().stream().anyMatch(r -> r.getName().equals(roleName)); } }
Java
# Copyright (C) 2014-2016 MongoDB, 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. module Mongo module ServerSelector # Encapsulates specifications for selecting servers, with the # primary preferred, given a list of candidates. # # @since 2.0.0 class PrimaryPreferred include Selectable # Get the name of the server mode type. # # @example Get the name of the server mode for this preference. # preference.name # # @return [ Symbol ] :primary_preferred # # @since 2.0.0 def name :primary_preferred end # Whether the slaveOk bit should be set on wire protocol messages. # I.e. whether the operation can be performed on a secondary server. # # @return [ true ] true # # @since 2.0.0 def slave_ok? true end # Whether tag sets are allowed to be defined for this server preference. # # @return [ true ] true # # @since 2.0.0 def tags_allowed? true end # Convert this server preference definition into a format appropriate # for a mongos server. # # @example Convert this server preference definition into a format # for mongos. # preference = Mongo::ServerSelector::PrimaryPreferred.new # preference.to_mongos # # @return [ Hash ] The server preference formatted for a mongos server. # # @since 2.0.0 def to_mongos preference = { :mode => 'primaryPreferred' } preference.merge!({ :tags => tag_sets }) unless tag_sets.empty? preference.merge!({ maxStalenessSeconds: max_staleness }) if max_staleness preference end private # Select servers taking into account any defined tag sets and # local threshold, with the primary preferred. # # @example Select servers given a list of candidates, # with the primary preferred. # preference = Mongo::ServerSelector::PrimaryPreferred.new # preference.select([candidate_1, candidate_2]) # # @return [ Array ] A list of servers matching tag sets and acceptable # latency with the primary preferred. # # @since 2.0.0 def select(candidates) primary = primary(candidates) secondaries = near_servers(secondaries(candidates)) primary.first ? primary : secondaries end def max_staleness_allowed? true end end end end
Java
#chmod change a file's access permision: ``` chomd mode file ``` ``` chmod -R 777 [dir_name] //所有人可以读,写,执行 chmod 777 [file_name] chmod a=rwx [file_name] chmod ugo+r [file_name] //所有人可以读 chmod a+r [file_name] chmod ug+w,o-w [filename] //用户和用户组内用户可以写,其他人可以写 。 chmod -R a+r * ``` first 7 -->User second 7-->Group third 7 -->Other all r=4 w=2 x=1 rwx=4+2+1=7 rw-=4+2=6 r-x=4+1=5 提交文件的时候用: ``` chmod -R 777 [dir_name] //所有人可以读,写,执行 ```
Java
/* Copyright 2014 The Kubernetes 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. */ // Package options contains flags and options for initializing an apiserver package options import ( "net" "strings" "time" "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/apiserver" "k8s.io/kubernetes/pkg/genericapiserver" kubeletclient "k8s.io/kubernetes/pkg/kubelet/client" "k8s.io/kubernetes/pkg/master/ports" "k8s.io/kubernetes/pkg/util" utilnet "k8s.io/kubernetes/pkg/util/net" "github.com/spf13/pflag" ) // APIServer runs a kubernetes api server. type APIServer struct { *genericapiserver.ServerRunOptions APIGroupPrefix string APIPrefix string AdmissionControl string AdmissionControlConfigFile string AdvertiseAddress net.IP AllowPrivileged bool AuthorizationMode string AuthorizationPolicyFile string BasicAuthFile string CloudConfigFile string CloudProvider string CorsAllowedOriginList []string DeprecatedStorageVersion string EnableLogsSupport bool EnableProfiling bool EnableWatchCache bool EtcdPathPrefix string EtcdServerList []string EtcdServersOverrides []string EventTTL time.Duration ExternalHost string KeystoneURL string KubeletConfig kubeletclient.KubeletClientConfig KubernetesServiceNodePort int MasterCount int MasterServiceNamespace string MaxConnectionBytesPerSec int64 MinRequestTimeout int OIDCCAFile string OIDCClientID string OIDCIssuerURL string OIDCUsernameClaim string RuntimeConfig util.ConfigurationMap SSHKeyfile string SSHUser string ServiceAccountKeyFile string ServiceAccountLookup bool ServiceClusterIPRange net.IPNet // TODO: make this a list ServiceNodePortRange utilnet.PortRange StorageVersions string TokenAuthFile string } // NewAPIServer creates a new APIServer object with default parameters func NewAPIServer() *APIServer { s := APIServer{ ServerRunOptions: genericapiserver.NewServerRunOptions(), APIGroupPrefix: "/apis", APIPrefix: "/api", AdmissionControl: "AlwaysAdmit", AuthorizationMode: "AlwaysAllow", EnableLogsSupport: true, EtcdPathPrefix: genericapiserver.DefaultEtcdPathPrefix, EventTTL: 1 * time.Hour, MasterCount: 1, MasterServiceNamespace: api.NamespaceDefault, RuntimeConfig: make(util.ConfigurationMap), StorageVersions: registered.AllPreferredGroupVersions(), KubeletConfig: kubeletclient.KubeletClientConfig{ Port: ports.KubeletPort, EnableHttps: true, HTTPTimeout: time.Duration(5) * time.Second, }, } return &s } // AddFlags adds flags for a specific APIServer to the specified FlagSet func (s *APIServer) AddFlags(fs *pflag.FlagSet) { // Note: the weird ""+ in below lines seems to be the only way to get gofmt to // arrange these text blocks sensibly. Grrr. fs.IntVar(&s.InsecurePort, "insecure-port", s.InsecurePort, ""+ "The port on which to serve unsecured, unauthenticated access. Default 8080. It is assumed "+ "that firewall rules are set up such that this port is not reachable from outside of "+ "the cluster and that port 443 on the cluster's public address is proxied to this "+ "port. This is performed by nginx in the default setup.") fs.IntVar(&s.InsecurePort, "port", s.InsecurePort, "DEPRECATED: see --insecure-port instead") fs.MarkDeprecated("port", "see --insecure-port instead") fs.IPVar(&s.InsecureBindAddress, "insecure-bind-address", s.InsecureBindAddress, ""+ "The IP address on which to serve the --insecure-port (set to 0.0.0.0 for all interfaces). "+ "Defaults to localhost.") fs.IPVar(&s.InsecureBindAddress, "address", s.InsecureBindAddress, "DEPRECATED: see --insecure-bind-address instead") fs.MarkDeprecated("address", "see --insecure-bind-address instead") fs.IPVar(&s.BindAddress, "bind-address", s.BindAddress, ""+ "The IP address on which to listen for the --secure-port port. The "+ "associated interface(s) must be reachable by the rest of the cluster, and by CLI/web "+ "clients. If blank, all interfaces will be used (0.0.0.0).") fs.IPVar(&s.AdvertiseAddress, "advertise-address", s.AdvertiseAddress, ""+ "The IP address on which to advertise the apiserver to members of the cluster. This "+ "address must be reachable by the rest of the cluster. If blank, the --bind-address "+ "will be used. If --bind-address is unspecified, the host's default interface will "+ "be used.") fs.IPVar(&s.BindAddress, "public-address-override", s.BindAddress, "DEPRECATED: see --bind-address instead") fs.MarkDeprecated("public-address-override", "see --bind-address instead") fs.IntVar(&s.SecurePort, "secure-port", s.SecurePort, ""+ "The port on which to serve HTTPS with authentication and authorization. If 0, "+ "don't serve HTTPS at all.") fs.StringVar(&s.TLSCertFile, "tls-cert-file", s.TLSCertFile, ""+ "File containing x509 Certificate for HTTPS. (CA cert, if any, concatenated after server cert). "+ "If HTTPS serving is enabled, and --tls-cert-file and --tls-private-key-file are not provided, "+ "a self-signed certificate and key are generated for the public address and saved to /var/run/kubernetes.") fs.StringVar(&s.TLSPrivateKeyFile, "tls-private-key-file", s.TLSPrivateKeyFile, "File containing x509 private key matching --tls-cert-file.") fs.StringVar(&s.CertDirectory, "cert-dir", s.CertDirectory, "The directory where the TLS certs are located (by default /var/run/kubernetes). "+ "If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored.") fs.StringVar(&s.APIPrefix, "api-prefix", s.APIPrefix, "The prefix for API requests on the server. Default '/api'.") fs.MarkDeprecated("api-prefix", "--api-prefix is deprecated and will be removed when the v1 API is retired.") fs.StringVar(&s.DeprecatedStorageVersion, "storage-version", s.DeprecatedStorageVersion, "The version to store the legacy v1 resources with. Defaults to server preferred") fs.MarkDeprecated("storage-version", "--storage-version is deprecated and will be removed when the v1 API is retired. See --storage-versions instead.") fs.StringVar(&s.StorageVersions, "storage-versions", s.StorageVersions, "The versions to store resources with. "+ "Different groups may be stored in different versions. Specified in the format \"group1/version1,group2/version2...\". "+ "This flag expects a complete list of storage versions of ALL groups registered in the server. "+ "It defaults to a list of preferred versions of all registered groups, which is derived from the KUBE_API_VERSIONS environment variable.") fs.StringVar(&s.CloudProvider, "cloud-provider", s.CloudProvider, "The provider for cloud services. Empty string for no provider.") fs.StringVar(&s.CloudConfigFile, "cloud-config", s.CloudConfigFile, "The path to the cloud provider configuration file. Empty string for no configuration file.") fs.DurationVar(&s.EventTTL, "event-ttl", s.EventTTL, "Amount of time to retain events. Default 1 hour.") fs.StringVar(&s.BasicAuthFile, "basic-auth-file", s.BasicAuthFile, "If set, the file that will be used to admit requests to the secure port of the API server via http basic authentication.") fs.StringVar(&s.ClientCAFile, "client-ca-file", s.ClientCAFile, "If set, any request presenting a client certificate signed by one of the authorities in the client-ca-file is authenticated with an identity corresponding to the CommonName of the client certificate.") fs.StringVar(&s.TokenAuthFile, "token-auth-file", s.TokenAuthFile, "If set, the file that will be used to secure the secure port of the API server via token authentication.") fs.StringVar(&s.OIDCIssuerURL, "oidc-issuer-url", s.OIDCIssuerURL, "The URL of the OpenID issuer, only HTTPS scheme will be accepted. If set, it will be used to verify the OIDC JSON Web Token (JWT)") fs.StringVar(&s.OIDCClientID, "oidc-client-id", s.OIDCClientID, "The client ID for the OpenID Connect client, must be set if oidc-issuer-url is set") fs.StringVar(&s.OIDCCAFile, "oidc-ca-file", s.OIDCCAFile, "If set, the OpenID server's certificate will be verified by one of the authorities in the oidc-ca-file, otherwise the host's root CA set will be used") fs.StringVar(&s.OIDCUsernameClaim, "oidc-username-claim", "sub", ""+ "The OpenID claim to use as the user name. Note that claims other than the default ('sub') is not "+ "guaranteed to be unique and immutable. This flag is experimental, please see the authentication documentation for further details.") fs.StringVar(&s.ServiceAccountKeyFile, "service-account-key-file", s.ServiceAccountKeyFile, "File containing PEM-encoded x509 RSA private or public key, used to verify ServiceAccount tokens. If unspecified, --tls-private-key-file is used.") fs.BoolVar(&s.ServiceAccountLookup, "service-account-lookup", s.ServiceAccountLookup, "If true, validate ServiceAccount tokens exist in etcd as part of authentication.") fs.StringVar(&s.KeystoneURL, "experimental-keystone-url", s.KeystoneURL, "If passed, activates the keystone authentication plugin") fs.StringVar(&s.AuthorizationMode, "authorization-mode", s.AuthorizationMode, "Ordered list of plug-ins to do authorization on secure port. Comma-delimited list of: "+strings.Join(apiserver.AuthorizationModeChoices, ",")) fs.StringVar(&s.AuthorizationPolicyFile, "authorization-policy-file", s.AuthorizationPolicyFile, "File with authorization policy in csv format, used with --authorization-mode=ABAC, on the secure port.") fs.StringVar(&s.AdmissionControl, "admission-control", s.AdmissionControl, "Ordered list of plug-ins to do admission control of resources into cluster. Comma-delimited list of: "+strings.Join(admission.GetPlugins(), ", ")) fs.StringVar(&s.AdmissionControlConfigFile, "admission-control-config-file", s.AdmissionControlConfigFile, "File with admission control configuration.") fs.StringSliceVar(&s.EtcdServerList, "etcd-servers", s.EtcdServerList, "List of etcd servers to watch (http://ip:port), comma separated. Mutually exclusive with -etcd-config") fs.StringSliceVar(&s.EtcdServersOverrides, "etcd-servers-overrides", s.EtcdServersOverrides, "Per-resource etcd servers overrides, comma separated. The individual override format: group/resource#servers, where servers are http://ip:port, semicolon separated.") fs.StringVar(&s.EtcdPathPrefix, "etcd-prefix", s.EtcdPathPrefix, "The prefix for all resource paths in etcd.") fs.BoolVar(&s.EtcdQuorumRead, "etcd-quorum-read", s.EtcdQuorumRead, "If true, enable quorum read") fs.StringSliceVar(&s.CorsAllowedOriginList, "cors-allowed-origins", s.CorsAllowedOriginList, "List of allowed origins for CORS, comma separated. An allowed origin can be a regular expression to support subdomain matching. If this list is empty CORS will not be enabled.") fs.BoolVar(&s.AllowPrivileged, "allow-privileged", s.AllowPrivileged, "If true, allow privileged containers.") fs.IPNetVar(&s.ServiceClusterIPRange, "service-cluster-ip-range", s.ServiceClusterIPRange, "A CIDR notation IP range from which to assign service cluster IPs. This must not overlap with any IP ranges assigned to nodes for pods.") fs.IPNetVar(&s.ServiceClusterIPRange, "portal-net", s.ServiceClusterIPRange, "Deprecated: see --service-cluster-ip-range instead.") fs.MarkDeprecated("portal-net", "see --service-cluster-ip-range instead.") fs.Var(&s.ServiceNodePortRange, "service-node-port-range", "A port range to reserve for services with NodePort visibility. Example: '30000-32767'. Inclusive at both ends of the range.") fs.Var(&s.ServiceNodePortRange, "service-node-ports", "Deprecated: see --service-node-port-range instead.") fs.MarkDeprecated("service-node-ports", "see --service-node-port-range instead.") fs.StringVar(&s.MasterServiceNamespace, "master-service-namespace", s.MasterServiceNamespace, "The namespace from which the kubernetes master services should be injected into pods") fs.IntVar(&s.MasterCount, "apiserver-count", s.MasterCount, "The number of apiservers running in the cluster") fs.Var(&s.RuntimeConfig, "runtime-config", "A set of key=value pairs that describe runtime configuration that may be passed to apiserver. apis/<groupVersion> key can be used to turn on/off specific api versions. apis/<groupVersion>/<resource> can be used to turn on/off specific resources. api/all and api/legacy are special keys to control all and legacy api versions respectively.") fs.BoolVar(&s.EnableProfiling, "profiling", true, "Enable profiling via web interface host:port/debug/pprof/") // TODO: enable cache in integration tests. fs.BoolVar(&s.EnableWatchCache, "watch-cache", true, "Enable watch caching in the apiserver") fs.StringVar(&s.ExternalHost, "external-hostname", "", "The hostname to use when generating externalized URLs for this master (e.g. Swagger API Docs.)") fs.IntVar(&s.MaxRequestsInFlight, "max-requests-inflight", 400, "The maximum number of requests in flight at a given time. When the server exceeds this, it rejects requests. Zero for no limit.") fs.IntVar(&s.MinRequestTimeout, "min-request-timeout", 1800, "An optional field indicating the minimum number of seconds a handler must keep a request open before timing it out. Currently only honored by the watch request handler, which picks a randomized value above this number as the connection timeout, to spread out load.") fs.StringVar(&s.LongRunningRequestRE, "long-running-request-regexp", s.LongRunningRequestRE, "A regular expression matching long running requests which should be excluded from maximum inflight request handling.") fs.StringVar(&s.SSHUser, "ssh-user", "", "If non-empty, use secure SSH proxy to the nodes, using this user name") fs.StringVar(&s.SSHKeyfile, "ssh-keyfile", "", "If non-empty, use secure SSH proxy to the nodes, using this user keyfile") fs.Int64Var(&s.MaxConnectionBytesPerSec, "max-connection-bytes-per-sec", 0, "If non-zero, throttle each user connection to this number of bytes/sec. Currently only applies to long-running requests") // Kubelet related flags: fs.BoolVar(&s.KubeletConfig.EnableHttps, "kubelet-https", s.KubeletConfig.EnableHttps, "Use https for kubelet connections") fs.UintVar(&s.KubeletConfig.Port, "kubelet-port", s.KubeletConfig.Port, "Kubelet port") fs.MarkDeprecated("kubelet-port", "kubelet-port is deprecated and will be removed") fs.DurationVar(&s.KubeletConfig.HTTPTimeout, "kubelet-timeout", s.KubeletConfig.HTTPTimeout, "Timeout for kubelet operations") fs.StringVar(&s.KubeletConfig.CertFile, "kubelet-client-certificate", s.KubeletConfig.CertFile, "Path to a client cert file for TLS.") fs.StringVar(&s.KubeletConfig.KeyFile, "kubelet-client-key", s.KubeletConfig.KeyFile, "Path to a client key file for TLS.") fs.StringVar(&s.KubeletConfig.CAFile, "kubelet-certificate-authority", s.KubeletConfig.CAFile, "Path to a cert. file for the certificate authority.") // See #14282 for details on how to test/try this option out. TODO remove this comment once this option is tested in CI. fs.IntVar(&s.KubernetesServiceNodePort, "kubernetes-service-node-port", 0, "If non-zero, the Kubernetes master service (which apiserver creates/maintains) will be of type NodePort, using this as the value of the port. If zero, the Kubernetes master service will be of type ClusterIP.") // TODO: delete this flag as soon as we identify and fix all clients that send malformed updates, like #14126. fs.BoolVar(&validation.RepairMalformedUpdates, "repair-malformed-updates", true, "If true, server will do its best to fix the update request to pass the validation, e.g., setting empty UID in update request to its existing value. This flag can be turned off after we fix all the clients that send malformed updates.") }
Java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/proton/Proton_EXPORTS.h> #include <aws/proton/ProtonRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Proton { namespace Model { /** */ class AWS_PROTON_API DeleteEnvironmentTemplateVersionRequest : public ProtonRequest { public: DeleteEnvironmentTemplateVersionRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "DeleteEnvironmentTemplateVersion"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The environment template major version to delete.</p> */ inline const Aws::String& GetMajorVersion() const{ return m_majorVersion; } /** * <p>The environment template major version to delete.</p> */ inline bool MajorVersionHasBeenSet() const { return m_majorVersionHasBeenSet; } /** * <p>The environment template major version to delete.</p> */ inline void SetMajorVersion(const Aws::String& value) { m_majorVersionHasBeenSet = true; m_majorVersion = value; } /** * <p>The environment template major version to delete.</p> */ inline void SetMajorVersion(Aws::String&& value) { m_majorVersionHasBeenSet = true; m_majorVersion = std::move(value); } /** * <p>The environment template major version to delete.</p> */ inline void SetMajorVersion(const char* value) { m_majorVersionHasBeenSet = true; m_majorVersion.assign(value); } /** * <p>The environment template major version to delete.</p> */ inline DeleteEnvironmentTemplateVersionRequest& WithMajorVersion(const Aws::String& value) { SetMajorVersion(value); return *this;} /** * <p>The environment template major version to delete.</p> */ inline DeleteEnvironmentTemplateVersionRequest& WithMajorVersion(Aws::String&& value) { SetMajorVersion(std::move(value)); return *this;} /** * <p>The environment template major version to delete.</p> */ inline DeleteEnvironmentTemplateVersionRequest& WithMajorVersion(const char* value) { SetMajorVersion(value); return *this;} /** * <p>The environment template minor version to delete.</p> */ inline const Aws::String& GetMinorVersion() const{ return m_minorVersion; } /** * <p>The environment template minor version to delete.</p> */ inline bool MinorVersionHasBeenSet() const { return m_minorVersionHasBeenSet; } /** * <p>The environment template minor version to delete.</p> */ inline void SetMinorVersion(const Aws::String& value) { m_minorVersionHasBeenSet = true; m_minorVersion = value; } /** * <p>The environment template minor version to delete.</p> */ inline void SetMinorVersion(Aws::String&& value) { m_minorVersionHasBeenSet = true; m_minorVersion = std::move(value); } /** * <p>The environment template minor version to delete.</p> */ inline void SetMinorVersion(const char* value) { m_minorVersionHasBeenSet = true; m_minorVersion.assign(value); } /** * <p>The environment template minor version to delete.</p> */ inline DeleteEnvironmentTemplateVersionRequest& WithMinorVersion(const Aws::String& value) { SetMinorVersion(value); return *this;} /** * <p>The environment template minor version to delete.</p> */ inline DeleteEnvironmentTemplateVersionRequest& WithMinorVersion(Aws::String&& value) { SetMinorVersion(std::move(value)); return *this;} /** * <p>The environment template minor version to delete.</p> */ inline DeleteEnvironmentTemplateVersionRequest& WithMinorVersion(const char* value) { SetMinorVersion(value); return *this;} /** * <p>The name of the environment template.</p> */ inline const Aws::String& GetTemplateName() const{ return m_templateName; } /** * <p>The name of the environment template.</p> */ inline bool TemplateNameHasBeenSet() const { return m_templateNameHasBeenSet; } /** * <p>The name of the environment template.</p> */ inline void SetTemplateName(const Aws::String& value) { m_templateNameHasBeenSet = true; m_templateName = value; } /** * <p>The name of the environment template.</p> */ inline void SetTemplateName(Aws::String&& value) { m_templateNameHasBeenSet = true; m_templateName = std::move(value); } /** * <p>The name of the environment template.</p> */ inline void SetTemplateName(const char* value) { m_templateNameHasBeenSet = true; m_templateName.assign(value); } /** * <p>The name of the environment template.</p> */ inline DeleteEnvironmentTemplateVersionRequest& WithTemplateName(const Aws::String& value) { SetTemplateName(value); return *this;} /** * <p>The name of the environment template.</p> */ inline DeleteEnvironmentTemplateVersionRequest& WithTemplateName(Aws::String&& value) { SetTemplateName(std::move(value)); return *this;} /** * <p>The name of the environment template.</p> */ inline DeleteEnvironmentTemplateVersionRequest& WithTemplateName(const char* value) { SetTemplateName(value); return *this;} private: Aws::String m_majorVersion; bool m_majorVersionHasBeenSet; Aws::String m_minorVersion; bool m_minorVersionHasBeenSet; Aws::String m_templateName; bool m_templateNameHasBeenSet; }; } // namespace Model } // namespace Proton } // namespace Aws
Java
/* * Copyright 2016 Netbrasoft * * 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 br.com.netbrasoft.gnuob.api.category; import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToCountCategory; import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToFindCategory; import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToFindCategoryById; import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToMergeCategory; import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToPersistCategory; import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToRefreshCategory; import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToRemoveCategory; import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.CAN_NOT_INITIALIZE_THE_DEFAULT_WSDL_FROM_0; import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.CATEGORY_WEB_SERVICE_REPOSITORY_NAME; import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.GNUOB_SOAP_CATEGORY_WEBSERVICE_WSDL; import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.HTTP_LOCALHOST_8080_GNUOB_SOAP_CATEGORY_WEB_SERVICE_IMPL_WSDL; import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.UNCHECKED_VALUE; import static java.lang.System.getProperty; import static org.slf4j.LoggerFactory.getLogger; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.javasimon.aop.Monitored; import org.slf4j.Logger; import org.springframework.stereotype.Repository; import br.com.netbrasoft.gnuob.api.Category; import br.com.netbrasoft.gnuob.api.CategoryWebServiceImpl; import br.com.netbrasoft.gnuob.api.CategoryWebServiceImplService; import br.com.netbrasoft.gnuob.api.MetaData; import br.com.netbrasoft.gnuob.api.OrderBy; import br.com.netbrasoft.gnuob.api.Paging; import br.com.netbrasoft.gnuob.api.generic.IGenericTypeWebServiceRepository; @Monitored @Repository(CATEGORY_WEB_SERVICE_REPOSITORY_NAME) public class CategoryWebServiceRepository<C extends Category> implements IGenericTypeWebServiceRepository<C> { private static final Logger LOGGER = getLogger(CategoryWebServiceRepository.class); private static final URL WSDL_LOCATION; static { URL url = null; try { url = new URL(getProperty(GNUOB_SOAP_CATEGORY_WEBSERVICE_WSDL, HTTP_LOCALHOST_8080_GNUOB_SOAP_CATEGORY_WEB_SERVICE_IMPL_WSDL)); } catch (final MalformedURLException e) { LOGGER.info(CAN_NOT_INITIALIZE_THE_DEFAULT_WSDL_FROM_0, getProperty(GNUOB_SOAP_CATEGORY_WEBSERVICE_WSDL, HTTP_LOCALHOST_8080_GNUOB_SOAP_CATEGORY_WEB_SERVICE_IMPL_WSDL)); } WSDL_LOCATION = url; } private transient CategoryWebServiceImpl categoryWebServiceImpl = null; private CategoryWebServiceImpl getCategoryWebServiceImpl() { if (categoryWebServiceImpl == null) { categoryWebServiceImpl = new CategoryWebServiceImplService(WSDL_LOCATION).getCategoryWebServiceImplPort(); } return categoryWebServiceImpl; } @Override public long count(final MetaData credentials, final C categoryExample) { return getCategoryWebServiceImpl().countCategory(wrapToCountCategory(categoryExample), credentials).getReturn(); } @Override @SuppressWarnings(UNCHECKED_VALUE) public List<C> find(final MetaData credentials, final C categoryExample, final Paging paging, final OrderBy orderingProperty) { return (List<C>) getCategoryWebServiceImpl() .findCategory(wrapToFindCategory(categoryExample, paging, orderingProperty), credentials).getReturn(); } @Override @SuppressWarnings(UNCHECKED_VALUE) public C find(final MetaData credentials, final C categoryExample) { return (C) getCategoryWebServiceImpl().findCategoryById(wrapToFindCategoryById(categoryExample), credentials) .getReturn(); } @Override @SuppressWarnings(UNCHECKED_VALUE) public C persist(final MetaData credentials, final C category) { return (C) getCategoryWebServiceImpl().persistCategory(wrapToPersistCategory(category), credentials).getReturn(); } @Override @SuppressWarnings(UNCHECKED_VALUE) public C merge(final MetaData credentials, final C category) { return (C) getCategoryWebServiceImpl().mergeCategory(wrapToMergeCategory(category), credentials).getReturn(); } @Override @SuppressWarnings(UNCHECKED_VALUE) public C refresh(final MetaData credentials, final C category) { return (C) getCategoryWebServiceImpl().refreshCategory(wrapToRefreshCategory(category), credentials).getReturn(); } @Override public void remove(final MetaData credentials, final C category) { getCategoryWebServiceImpl().removeCategory(wrapToRemoveCategory(category), credentials); } }
Java
package org.wso2.carbon.apimgt.rest.api.publisher.v1.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.ArrayList; import java.util.List; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AlertTypeDTO; import javax.validation.constraints.*; import io.swagger.annotations.*; import java.util.Objects; import javax.xml.bind.annotation.*; import org.wso2.carbon.apimgt.rest.api.util.annotations.Scope; public class AlertTypesListDTO { private Integer count = null; private List<AlertTypeDTO> alerts = new ArrayList<>(); /** * The number of alerts **/ public AlertTypesListDTO count(Integer count) { this.count = count; return this; } @ApiModelProperty(example = "3", value = "The number of alerts") @JsonProperty("count") public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } /** **/ public AlertTypesListDTO alerts(List<AlertTypeDTO> alerts) { this.alerts = alerts; return this; } @ApiModelProperty(value = "") @JsonProperty("alerts") public List<AlertTypeDTO> getAlerts() { return alerts; } public void setAlerts(List<AlertTypeDTO> alerts) { this.alerts = alerts; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AlertTypesListDTO alertTypesList = (AlertTypesListDTO) o; return Objects.equals(count, alertTypesList.count) && Objects.equals(alerts, alertTypesList.alerts); } @Override public int hashCode() { return Objects.hash(count, alerts); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AlertTypesListDTO {\n"); sb.append(" count: ").append(toIndentedString(count)).append("\n"); sb.append(" alerts: ").append(toIndentedString(alerts)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
Java
cordova.define('cordova/plugin_list', function(require, exports, module) { module.exports = [ { "file": "plugins/cordova-plugin-whitelist/whitelist.js", "id": "cordova-plugin-whitelist.whitelist", "pluginId": "cordova-plugin-whitelist", "runs": true }, { "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js", "id": "cordova-plugin-file.DirectoryEntry", "pluginId": "cordova-plugin-file", "clobbers": [ "window.DirectoryEntry" ] }, { "file": "plugins/cordova-plugin-file/www/DirectoryReader.js", "id": "cordova-plugin-file.DirectoryReader", "pluginId": "cordova-plugin-file", "clobbers": [ "window.DirectoryReader" ] }, { "file": "plugins/cordova-plugin-file/www/Entry.js", "id": "cordova-plugin-file.Entry", "pluginId": "cordova-plugin-file", "clobbers": [ "window.Entry" ] }, { "file": "plugins/cordova-plugin-file/www/File.js", "id": "cordova-plugin-file.File", "pluginId": "cordova-plugin-file", "clobbers": [ "window.File" ] }, { "file": "plugins/cordova-plugin-file/www/FileEntry.js", "id": "cordova-plugin-file.FileEntry", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileEntry" ] }, { "file": "plugins/cordova-plugin-file/www/FileError.js", "id": "cordova-plugin-file.FileError", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileError" ] }, { "file": "plugins/cordova-plugin-file/www/FileReader.js", "id": "cordova-plugin-file.FileReader", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileReader" ] }, { "file": "plugins/cordova-plugin-file/www/FileSystem.js", "id": "cordova-plugin-file.FileSystem", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileSystem" ] }, { "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js", "id": "cordova-plugin-file.FileUploadOptions", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileUploadOptions" ] }, { "file": "plugins/cordova-plugin-file/www/FileUploadResult.js", "id": "cordova-plugin-file.FileUploadResult", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileUploadResult" ] }, { "file": "plugins/cordova-plugin-file/www/FileWriter.js", "id": "cordova-plugin-file.FileWriter", "pluginId": "cordova-plugin-file", "clobbers": [ "window.FileWriter" ] }, { "file": "plugins/cordova-plugin-file/www/Flags.js", "id": "cordova-plugin-file.Flags", "pluginId": "cordova-plugin-file", "clobbers": [ "window.Flags" ] }, { "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js", "id": "cordova-plugin-file.LocalFileSystem", "pluginId": "cordova-plugin-file", "clobbers": [ "window.LocalFileSystem" ], "merges": [ "window" ] }, { "file": "plugins/cordova-plugin-file/www/Metadata.js", "id": "cordova-plugin-file.Metadata", "pluginId": "cordova-plugin-file", "clobbers": [ "window.Metadata" ] }, { "file": "plugins/cordova-plugin-file/www/ProgressEvent.js", "id": "cordova-plugin-file.ProgressEvent", "pluginId": "cordova-plugin-file", "clobbers": [ "window.ProgressEvent" ] }, { "file": "plugins/cordova-plugin-file/www/fileSystems.js", "id": "cordova-plugin-file.fileSystems", "pluginId": "cordova-plugin-file" }, { "file": "plugins/cordova-plugin-file/www/requestFileSystem.js", "id": "cordova-plugin-file.requestFileSystem", "pluginId": "cordova-plugin-file", "clobbers": [ "window.requestFileSystem" ] }, { "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js", "id": "cordova-plugin-file.resolveLocalFileSystemURI", "pluginId": "cordova-plugin-file", "merges": [ "window" ] }, { "file": "plugins/cordova-plugin-file/www/android/FileSystem.js", "id": "cordova-plugin-file.androidFileSystem", "pluginId": "cordova-plugin-file", "merges": [ "FileSystem" ] }, { "file": "plugins/cordova-plugin-file/www/fileSystems-roots.js", "id": "cordova-plugin-file.fileSystems-roots", "pluginId": "cordova-plugin-file", "runs": true }, { "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js", "id": "cordova-plugin-file.fileSystemPaths", "pluginId": "cordova-plugin-file", "merges": [ "cordova" ], "runs": true }, { "file": "plugins/cordova-plugin-file-transfer/www/FileTransferError.js", "id": "cordova-plugin-file-transfer.FileTransferError", "pluginId": "cordova-plugin-file-transfer", "clobbers": [ "window.FileTransferError" ] }, { "file": "plugins/cordova-plugin-file-transfer/www/FileTransfer.js", "id": "cordova-plugin-file-transfer.FileTransfer", "pluginId": "cordova-plugin-file-transfer", "clobbers": [ "window.FileTransfer" ] }, { "file": "plugins/cordova-plugin-device/www/device.js", "id": "cordova-plugin-device.device", "pluginId": "cordova-plugin-device", "clobbers": [ "device" ] }, { "file": "plugins/de.appplant.cordova.plugin.email-composer/www/email_composer.js", "id": "de.appplant.cordova.plugin.email-composer.EmailComposer", "pluginId": "de.appplant.cordova.plugin.email-composer", "clobbers": [ "cordova.plugins.email", "plugin.email" ] } ]; module.exports.metadata = // TOP OF METADATA {} // BOTTOM OF METADATA });
Java
function CredentialTypesStrings (BaseString) { BaseString.call(this, 'credential_types'); let t = this.t; let ns = this.credential_types; ns.deleteCredentialType = { CREDENTIAL_TYPE_IN_USE: t.s('This credential type is currently being used by one or more credentials. Credentials that use this credential type must be deleted before the credential type can be deleted.') }; } CredentialTypesStrings.$inject = ['BaseStringService']; export default CredentialTypesStrings;
Java
package libnetwork import ( "fmt" ) // ErrNoSuchNetwork is returned when a network query finds no result type ErrNoSuchNetwork string func (nsn ErrNoSuchNetwork) Error() string { return fmt.Sprintf("network %s not found", string(nsn)) } // BadRequest denotes the type of this error func (nsn ErrNoSuchNetwork) BadRequest() {} // ErrNoSuchEndpoint is returned when a endpoint query finds no result type ErrNoSuchEndpoint string func (nse ErrNoSuchEndpoint) Error() string { return fmt.Sprintf("endpoint %s not found", string(nse)) } // BadRequest denotes the type of this error func (nse ErrNoSuchEndpoint) BadRequest() {} // ErrInvalidNetworkDriver is returned if an invalid driver // name is passed. type ErrInvalidNetworkDriver string func (ind ErrInvalidNetworkDriver) Error() string { return fmt.Sprintf("invalid driver bound to network: %s", string(ind)) } // BadRequest denotes the type of this error func (ind ErrInvalidNetworkDriver) BadRequest() {} // ErrInvalidJoin is returned if a join is attempted on an endpoint // which already has a container joined. type ErrInvalidJoin struct{} func (ij ErrInvalidJoin) Error() string { return "a container has already joined the endpoint" } // BadRequest denotes the type of this error func (ij ErrInvalidJoin) BadRequest() {} // ErrNoContainer is returned when the endpoint has no container // attached to it. type ErrNoContainer struct{} func (nc ErrNoContainer) Error() string { return "a container has already joined the endpoint" } // Maskable denotes the type of this error func (nc ErrNoContainer) Maskable() {} // ErrInvalidID is returned when a query-by-id method is being invoked // with an empty id parameter type ErrInvalidID string func (ii ErrInvalidID) Error() string { return fmt.Sprintf("invalid id: %s", string(ii)) } // BadRequest denotes the type of this error func (ii ErrInvalidID) BadRequest() {} // ErrInvalidName is returned when a query-by-name or resource create method is // invoked with an empty name parameter type ErrInvalidName string func (in ErrInvalidName) Error() string { return fmt.Sprintf("invalid name: %s", string(in)) } // BadRequest denotes the type of this error func (in ErrInvalidName) BadRequest() {} // ErrInvalidConfigFile type is returned when an invalid LibNetwork config file is detected type ErrInvalidConfigFile string func (cf ErrInvalidConfigFile) Error() string { return fmt.Sprintf("Invalid Config file %q", string(cf)) } // NetworkTypeError type is returned when the network type string is not // known to libnetwork. type NetworkTypeError string func (nt NetworkTypeError) Error() string { return fmt.Sprintf("unknown driver %q", string(nt)) } // NotFound denotes the type of this error func (nt NetworkTypeError) NotFound() {} // NetworkNameError is returned when a network with the same name already exists. type NetworkNameError string func (nnr NetworkNameError) Error() string { return fmt.Sprintf("network with name %s already exists", string(nnr)) } // Forbidden denotes the type of this error func (nnr NetworkNameError) Forbidden() {} // UnknownNetworkError is returned when libnetwork could not find in it's database // a network with the same name and id. type UnknownNetworkError struct { name string id string } func (une *UnknownNetworkError) Error() string { return fmt.Sprintf("unknown network %s id %s", une.name, une.id) } // NotFound denotes the type of this error func (une *UnknownNetworkError) NotFound() {} // ActiveEndpointsError is returned when a network is deleted which has active // endpoints in it. type ActiveEndpointsError struct { name string id string } func (aee *ActiveEndpointsError) Error() string { return fmt.Sprintf("network with name %s id %s has active endpoints", aee.name, aee.id) } // Forbidden denotes the type of this error func (aee *ActiveEndpointsError) Forbidden() {} // UnknownEndpointError is returned when libnetwork could not find in it's database // an endpoint with the same name and id. type UnknownEndpointError struct { name string id string } func (uee *UnknownEndpointError) Error() string { return fmt.Sprintf("unknown endpoint %s id %s", uee.name, uee.id) } // NotFound denotes the type of this error func (uee *UnknownEndpointError) NotFound() {} // ActiveContainerError is returned when an endpoint is deleted which has active // containers attached to it. type ActiveContainerError struct { name string id string } func (ace *ActiveContainerError) Error() string { return fmt.Sprintf("endpoint with name %s id %s has active containers", ace.name, ace.id) } // Forbidden denotes the type of this error func (ace *ActiveContainerError) Forbidden() {} // InvalidContainerIDError is returned when an invalid container id is passed // in Join/Leave type InvalidContainerIDError string func (id InvalidContainerIDError) Error() string { return fmt.Sprintf("invalid container id %s", string(id)) } // BadRequest denotes the type of this error func (id InvalidContainerIDError) BadRequest() {}
Java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/servicediscovery/model/PublicDnsPropertiesMutable.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace ServiceDiscovery { namespace Model { PublicDnsPropertiesMutable::PublicDnsPropertiesMutable() : m_sOAHasBeenSet(false) { } PublicDnsPropertiesMutable::PublicDnsPropertiesMutable(JsonView jsonValue) : m_sOAHasBeenSet(false) { *this = jsonValue; } PublicDnsPropertiesMutable& PublicDnsPropertiesMutable::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("SOA")) { m_sOA = jsonValue.GetObject("SOA"); m_sOAHasBeenSet = true; } return *this; } JsonValue PublicDnsPropertiesMutable::Jsonize() const { JsonValue payload; if(m_sOAHasBeenSet) { payload.WithObject("SOA", m_sOA.Jsonize()); } return payload; } } // namespace Model } // namespace ServiceDiscovery } // namespace Aws
Java
# please insert nothing before this line: -*- mode: cperl; cperl-indent-level: 4; cperl-continued-statement-offset: 4; indent-tabs-mode: nil -*- package TestApache::scanhdrs2; use strict; use warnings FATAL => 'all'; use Apache::Test; use Apache2::Const -compile => 'OK'; sub handler { my $r = shift; my $location = $r->args; print "Location: $location\n\n"; Apache2::Const::OK; } 1; __END__ SetHandler perl-script PerlOptions +ParseHeaders
Java
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hawkular.agent.monitor.inventory; import org.hawkular.agent.monitor.inventory.dmr.DMRResource; import org.hawkular.agent.monitor.inventory.dmr.DMRResourceType; import org.hawkular.dmrclient.Address; import org.jboss.dmr.ModelNode; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.traverse.BreadthFirstIterator; import org.jgrapht.traverse.DepthFirstIterator; import org.junit.Assert; import org.junit.Test; public class ResourceManagerTest { @Test public void testEmptyResourceManager() { ResourceManager<DMRResource> rm = new ResourceManager<>(); Assert.assertNull(rm.getResource(new ID("foo"))); Assert.assertTrue(rm.getAllResources().isEmpty()); Assert.assertTrue(rm.getRootResources().isEmpty()); Assert.assertFalse(rm.getBreadthFirstIterator().hasNext()); Assert.assertFalse(rm.getDepthFirstIterator().hasNext()); } @Test public void testResourceManager() { DMRResourceType type = new DMRResourceType(new ID("resType"), new Name("resTypeName")); ResourceManager<DMRResource> rm = new ResourceManager<>(); DMRResource root1 = new DMRResource(new ID("root1"), new Name("root1Name"), null, type, null, new Address(), new ModelNode()); DMRResource root2 = new DMRResource(new ID("root2"), new Name("root2Name"), null, type, null, new Address(), new ModelNode()); DMRResource child1 = new DMRResource(new ID("child1"), new Name("child1Name"), null, type, root1, new Address(), new ModelNode()); DMRResource child2 = new DMRResource(new ID("child2"), new Name("child2Name"), null, type, root1, new Address(), new ModelNode()); DMRResource grandChild1 = new DMRResource(new ID("grand1"), new Name("grand1Name"), null, type, child1, new Address(), new ModelNode()); // add root1 rm.addResource(root1); Assert.assertEquals(1, rm.getAllResources().size()); Assert.assertTrue(rm.getAllResources().contains(root1)); Assert.assertEquals(root1, rm.getResource(root1.getID())); DepthFirstIterator<DMRResource, DefaultEdge> dIter = rm.getDepthFirstIterator(); Assert.assertEquals(root1, dIter.next()); Assert.assertFalse(dIter.hasNext()); BreadthFirstIterator<DMRResource, DefaultEdge> bIter = rm.getBreadthFirstIterator(); Assert.assertEquals(root1, bIter.next()); Assert.assertFalse(bIter.hasNext()); Assert.assertEquals(1, rm.getRootResources().size()); Assert.assertTrue(rm.getRootResources().contains(root1)); // add child1 rm.addResource(child1); Assert.assertEquals(2, rm.getAllResources().size()); Assert.assertTrue(rm.getAllResources().contains(child1)); Assert.assertEquals(child1, rm.getResource(child1.getID())); // add grandChild1 rm.addResource(grandChild1); Assert.assertEquals(3, rm.getAllResources().size()); Assert.assertTrue(rm.getAllResources().contains(grandChild1)); Assert.assertEquals(grandChild1, rm.getResource(grandChild1.getID())); // add root2 rm.addResource(root2); Assert.assertEquals(4, rm.getAllResources().size()); Assert.assertTrue(rm.getAllResources().contains(root2)); Assert.assertEquals(root2, rm.getResource(root2.getID())); Assert.assertEquals(2, rm.getRootResources().size()); Assert.assertTrue(rm.getRootResources().contains(root2)); // add child2 rm.addResource(child2); Assert.assertEquals(5, rm.getAllResources().size()); Assert.assertTrue(rm.getAllResources().contains(child2)); Assert.assertEquals(child2, rm.getResource(child2.getID())); // // the tree now looks like: // // root1 root2 // / \ // child1 child2 // | // grandchild1 // Assert.assertEquals(2, rm.getChildren(root1).size()); Assert.assertTrue(rm.getChildren(root1).contains(child1)); Assert.assertTrue(rm.getChildren(root1).contains(child2)); Assert.assertEquals(1, rm.getChildren(child1).size()); Assert.assertTrue(rm.getChildren(child1).contains(grandChild1)); Assert.assertEquals(0, rm.getChildren(grandChild1).size()); Assert.assertEquals(0, rm.getChildren(root2).size()); Assert.assertEquals(null, rm.getParent(root1)); Assert.assertEquals(null, rm.getParent(root2)); Assert.assertEquals(root1, rm.getParent(child1)); Assert.assertEquals(root1, rm.getParent(child2)); Assert.assertEquals(child1, rm.getParent(grandChild1)); /* * WHY DOESN'T THIS ITERATE LIKE IT SHOULD? * // iterate depth first which should be: // root1 -> child1 -> grandchild1 -> child2 -> root2 dIter = rm.getDepthFirstIterator(); Assert.assertEquals(root1, dIter.next()); Assert.assertEquals(child1, dIter.next()); Assert.assertEquals(grandChild1, dIter.next()); Assert.assertEquals(child2, dIter.next()); Assert.assertEquals(root2, dIter.next()); Assert.assertFalse(dIter.hasNext()); // iterate breadth first which should be (assuming roots are done in order) // root1 -> child1 -> child2 -> grandchild1 -> root2 bIter = rm.getBreadthFirstIterator(); Assert.assertEquals(root1, bIter.next()); Assert.assertEquals(child1, bIter.next()); Assert.assertEquals(child2, bIter.next()); Assert.assertEquals(grandChild1, bIter.next()); Assert.assertEquals(root2, bIter.next()); Assert.assertFalse(bIter.hasNext()); * * THE ABOVE DOESN'T WORK AS EXPECTED */ } }
Java
/** * 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.camel.component.docker.headers; import java.util.Map; import com.github.dockerjava.api.command.ListContainersCmd; import org.apache.camel.component.docker.DockerConstants; import org.apache.camel.component.docker.DockerOperation; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; /** * Validates List Containers Request headers are applied properly */ public class ListContainersCmdHeaderTest extends BaseDockerHeaderTest<ListContainersCmd> { @Mock private ListContainersCmd mockObject; @Test public void listContainerHeaderTest() { boolean showSize = true; boolean showAll = false; int limit = 2; String since = "id1"; String before = "id2"; Map<String, Object> headers = getDefaultParameters(); headers.put(DockerConstants.DOCKER_LIMIT, limit); headers.put(DockerConstants.DOCKER_SHOW_ALL, showAll); headers.put(DockerConstants.DOCKER_SHOW_SIZE, showSize); headers.put(DockerConstants.DOCKER_SINCE, since); headers.put(DockerConstants.DOCKER_BEFORE, before); template.sendBodyAndHeaders("direct:in", "", headers); Mockito.verify(dockerClient, Mockito.times(1)).listContainersCmd(); Mockito.verify(mockObject, Mockito.times(1)).withShowAll(Matchers.eq(showAll)); Mockito.verify(mockObject, Mockito.times(1)).withShowSize(Matchers.eq(showSize)); Mockito.verify(mockObject, Mockito.times(1)).withLimit(Matchers.eq(limit)); Mockito.verify(mockObject, Mockito.times(1)).withSince(Matchers.eq(since)); Mockito.verify(mockObject, Mockito.times(1)).withBefore(Matchers.eq(before)); } @Override protected void setupMocks() { Mockito.when(dockerClient.listContainersCmd()).thenReturn(mockObject); } @Override protected DockerOperation getOperation() { return DockerOperation.LIST_CONTAINERS; } }
Java
<!DOCTYPE html> <!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <meta charset="utf-8"/> <title>DHP Đăng nhập quản trị</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1.0" name="viewport"/> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta content="" name="description"/> <meta content="" name="author"/> <!-- BEGIN GLOBAL MANDATORY STYLES --> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css"/> <link href="/assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/> <link href="/assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css"/> <link href="/assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="/assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"/> <!-- END GLOBAL MANDATORY STYLES --> <!-- BEGIN PAGE LEVEL STYLES --> <link href="/assets/admin/pages/css/login.css" rel="stylesheet" type="text/css"/> <!-- END PAGE LEVEL SCRIPTS --> <!-- BEGIN THEME STYLES --> <link href="/assets/global/css/components.css" rel="stylesheet" type="text/css"/> <link href="/assets/global/css/plugins.css" rel="stylesheet" type="text/css"/> <link href="/assets/admin/layout/css/layout.css" rel="stylesheet" type="text/css"/> <link href="/assets/admin/layout/css/themes/default.css" rel="stylesheet" type="text/css" id="style_color"/> <link href="/assets/admin/layout/css/custom.css" rel="stylesheet" type="text/css"/> <!-- END THEME STYLES --> <link rel="shortcut icon" href="favicon.ico"/> </head> <!-- END HEAD --> <!-- BEGIN BODY --> <body class="login"> <!-- BEGIN SIDEBAR TOGGLER BUTTON --> <div class="menu-toggler sidebar-toggler"> </div> <!-- END SIDEBAR TOGGLER BUTTON --> <!-- BEGIN LOGO --> <div class="logo"> <a href="index.html"> <img src="/assets/admin/layout/img/logo-big.png" alt=""/> </a> </div> <!-- END LOGO --> <!-- BEGIN LOGIN --> <div class="content"> @if (count($errors) > 0) <div class="alert alert-danger"> <strong>Lỗi!</strong> Sai thông tin đăng nhập.<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <!-- BEGIN LOGIN FORM --> <form class="login-form" action="{{ url('/auth/login') }}" method="post"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <h3 class="form-title">Đăng nhập</h3> <div class="alert alert-danger display-hide"> <button class="close" data-close="alert"></button> <span> Nhập email và mật khẩu. </span> </div> <div class="form-group"> <!--ie8, ie9 does not support html5 placeholder, so we just show field title for that--> <label class="control-label visible-ie8 visible-ie9">Tên đăng nhập</label> <input class="form-control form-control-solid placeholder-no-fix" type="email" autocomplete="off" placeholder="Email đăng nhập" name="email" value="{{ old('email') }}"/> </div> <div class="form-group"> <label class="control-label visible-ie8 visible-ie9">Mật khẩu</label> <input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Mật khẩu" name="password"/> </div> <div class="form-actions"> <button type="submit" class="btn btn-success uppercase">Đăng nhập</button> <label class="rememberme check"> <input type="checkbox" name="remember" value="1"/>Nhớ </label> <a id="forget-password" class="forget-password" href="{{ url('/password/email') }}">Quên mật khẩu?</a> </div> </form> <!-- END LOGIN FORM --> <!-- BEGIN FORGOT PASSWORD FORM --> <form class="forget-form" action="index.html" method="post"> <h3>Khôi phục mật khẩu?</h3> <p> Vui lòng nhập email để khôi phục mật khẩu. </p> <div class="form-group"> <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Email" name="email"/> </div> <div class="form-actions"> <button type="button" id="back-btn" class="btn btn-default">Trở về</button> <button type="submit" class="btn btn-success uppercase pull-right">Gửi</button> </div> </form> <!-- END FORGOT PASSWORD FORM --> </div> <div class="copyright"> 2015 © DHP Viet Nam </div> <!-- END LOGIN --> <!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) --> <!-- BEGIN CORE PLUGINS --> <!--[if lt IE 9]> <script src="/assets/global/plugins/respond.min.js"></script> <script src="/assets/global/plugins/excanvas.min.js"></script> <![endif]--> <script src="/assets/global/plugins/jquery.min.js" type="text/javascript"></script> <script src="/assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script> <script src="/assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="/assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script> <script src="/assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <!-- BEGIN PAGE LEVEL PLUGINS --> <script src="/assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script> <!-- END PAGE LEVEL PLUGINS --> <!-- BEGIN PAGE LEVEL SCRIPTS --> <script src="/assets/global/scripts/metronic.js" type="text/javascript"></script> <script src="/assets/admin/layout/scripts/layout.js" type="text/javascript"></script> <script src="/assets/admin/pages/scripts/login.js" type="text/javascript"></script> <!-- END PAGE LEVEL SCRIPTS --> <script> jQuery(document).ready(function() { Metronic.init(); // init metronic core components Layout.init(); // init current layout Login.init(); }); </script> <!-- END JAVASCRIPTS --> </body> <!-- END BODY --> </html>
Java
/* * 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.shardingsphere.elasticjob.lite.spring.boot.reg.snapshot; import static org.junit.Assert.assertNotNull; import org.apache.shardingsphere.elasticjob.lite.internal.snapshot.SnapshotService; import org.apache.shardingsphere.elasticjob.lite.spring.boot.job.fixture.EmbedTestingServer; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; @SpringBootTest @SpringBootApplication @ActiveProfiles("snapshot") public class ElasticJobSnapshotServiceConfigurationTest extends AbstractJUnit4SpringContextTests { @BeforeClass public static void init() { EmbedTestingServer.start(); } @Test public void assertSnapshotServiceConfiguration() { assertNotNull(applicationContext); assertNotNull(applicationContext.getBean(SnapshotService.class)); } }
Java
// bsla_scanf.cpp -*-C++-*- #include <bsla_scanf.h> #include <bsls_ident.h> BSLS_IDENT("$Id$ $CSID$") // ---------------------------------------------------------------------------- // Copyright 2019 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
Java
/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2015-2017 Imperial College London * Copyright 2015-2017 Andreas Schuh * * 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 "mirtk/Common.h" #include "mirtk/Options.h" #include "mirtk/ImageConfig.h" #include "mirtk/IOConfig.h" #include "mirtk/DataOp.h" #include "mirtk/DataStatistics.h" #include "mirtk/DataFunctions.h" #if MIRTK_Image_WITH_VTK #include "vtkDataSet.h" #include "vtkSmartPointer.h" #include "vtkPointData.h" #include "vtkCellData.h" #include "vtkDataArray.h" #endif using namespace mirtk; using namespace mirtk::data; using namespace mirtk::data::op; using namespace mirtk::data::statistic; // ============================================================================= // Help // ============================================================================= // ----------------------------------------------------------------------------- void PrintHelp(const char *name) { cout << "\n"; cout << "Usage: " << name << " <input> [options]\n"; cout << "\n"; cout << "Description:\n"; cout << " This tool can be used for basic calculations from a sequence of data values read\n"; cout << " either from an image or a VTK pointset. It can be used, for example, to add two\n"; cout << " data sequences and to divide the result by a constant. The current sequence can\n"; cout << " be written to an output file again using :option:`-out`. Additionally, statistics\n"; cout << " of the current data sequence can be computed such as the mean or variance.\n"; cout << " The order of the data transformations and calculation of statistics is determined\n"; cout << " by the order of the command-line arguments.\n"; cout << "\n"; cout << " The data mask is used to include/exclude values from subsequent operations.\n"; cout << " Initially, all NaN values in the input data sequence are excluded.\n"; cout << " Further values can be excluded using one or more of the masking operations.\n"; cout << " Using the mask, operations can be performed on only a subset of the data,\n"; cout << " and the mask then reset using :option:`-reset-mask`.\n"; cout << "\n"; cout << " By default, data statistics are printed to STDOUT in a human readable format.\n"; cout << " This output can be appended to a text file using :option:`-append` instead.\n"; cout << " For a more machine readable output, e.g., as comma separated values (CSV),\n"; cout << " specify a delimiting string using :option:`-delimiter`. In this case, a header\n"; cout << " line is also printed when :option:`-header` is given with optional user\n"; cout << " specified column names for the individual output values.\n"; cout << "\n"; cout << "Input options:\n"; cout << " -pd, -point-data, -scalars <name> Name of input point data array. (default: active SCALARS array)\n"; cout << " -cd, -cell-data <name> Name of input cell data array. Overrides :option:`-pd`.\n"; cout << "\n"; cout << "Data masking options:\n"; cout << " -even\n"; cout << " Exclude values which are not an even number when cast to an integer.\n"; cout << " -odd\n"; cout << " Exclude values which are not an odd number when cast to an integer.\n"; cout << " -label <value|lower..upper>...\n"; cout << " Include data points with a value equal to either one of the given values.\n"; cout << " Closed intervals of values can be specified as \"lower..upper\".\n"; cout << " For example, \"-label 1 3 5..6 10 20..50\". This option is a shorthand for\n"; cout << " :option:`-mask-all` :option:`-threshold-inside` <lower> <upper> :option:`-invert-mask`\n"; cout << " where one :option:`-threshold-inside` operation is performed for each argument.\n"; cout << " -mask <value>... | <file> [<scalars>] [<value>]\n"; cout << " Exclude values equal a given threshold or with specified input mask <value>.\n"; cout << " The default mask value of values to be excluded is zero. When the input file\n"; cout << " is a point set file (e.g., .vtk, .vtp), the optional <scalars> argument can be\n"; cout << " used to specify the name of the point/cell data array to use as mask.\n"; cout << " Note that this operation does not modify the data values, but only marks them\n"; cout << " to be ignored from now on. Use :option:`-pad` following this operation to\n"; cout << " replace these values by a constant background value.\n"; cout << " -mask-all\n"; cout << " Exclude all values.\n"; cout << " -reset-mask\n"; cout << " Reset mask to include all values again.\n"; cout << " -invert-mask\n"; cout << " Invert mask to include all values that where excluded before and\n"; cout << " exclude all values that were included before.\n"; cout << " -set, -inside <value>\n"; cout << " Set new value for all currently included data values.\n"; cout << " -pad, -outside <value>\n"; cout << " Set new value for all currently excluded data values.\n"; cout << "\n"; cout << "Data thresholding options:\n"; cout << " -threshold <lower> [<upper>]\n"; cout << " This masking operation is equivalent to :option:`-threshold-outside`.\n"; cout << " When no upper threshold is specified, it defaults to +inf. Therefore,\n"; cout << " \"-threshold 0\" will exclude all negative values.\n"; cout << " -percentile-threshold, -pct-threshold <lower>\n"; cout << " This masking operation is equivalent to :option:`-threshold-outside-percentiles`.\n"; cout << " with an upper threshold of +inf. Therefore, \"-threshold 0\" excludes all negative values.\n"; cout << " -threshold-percentiles, -threshold-pcts <lower> <upper>\n"; cout << " This masking operation is equivalent to :option:`-threshold-outside-percentiles`.\n"; cout << " -threshold-inside, -mask-inside <lower> <upper>\n"; cout << " Exclude values which are inside a given closed interval.\n"; cout << " When the lower threshold is greater than the upper threshold,\n"; cout << " values less than or equal to the upper threshold and values greater\n"; cout << " than or equal to the lower threshold are excluded.\n"; cout << " -threshold-inside-percentiles, -threshold-inside-pcts, -mask-inside-percentiles, -mask-inside-pct <lower> <upper>\n"; cout << " Exclude values which are inside a given closed interval of percentiles.\n"; cout << " When the lower percentile is greater than the upper percentile,\n"; cout << " values less than or equal to the upper percentile and values greater\n"; cout << " than or equal to the lower percentile are excluded.\n"; cout << " -threshold-outside, -mask-outside <lower> <upper>\n"; cout << " Exclude values which are outside a given open interval.\n"; cout << " When the lower threshold is greater than the upper threshold,\n"; cout << " values inside the closed interval <upper>..<lower> are excluded.\n"; cout << " -threshold-outside-percentiles, -threshold-outside-pcts, -mask-outside-percentiles, -mask-outside-pcts <lower> <upper>\n"; cout << " Exclude values which are outside a given open interval of percentiles.\n"; cout << " When the lower percentile is greater than the upper percentile,\n"; cout << " values inside the closed interval <upper>..<lower> are excluded.\n"; cout << " -threshold-lt, -lower-threshold, -mask-lt <value>\n"; cout << " Exclude values less than a given threshold.\n"; cout << " -threshold-lt-percentile, -threshold-lt-pct, -lower-percentile-threshold, -lower-pct-threshold, -mask-lt-percentile, -mask-lt-pct <value>\n"; cout << " Exclude values less than a given precentile.\n"; cout << " -threshold-le, -mask-le, -mask-below <value>\n"; cout << " Exclude values less than or equal to a given threshold.\n"; cout << " -threshold-le-percentile, -threshold-le-pct, -mask-le-percentile, -mask-le-pct, -mask-below-percentile, -mask-below-pct <value>\n"; cout << " Exclude values less than or equal to a given percentile.\n"; cout << " -threshold-ge, -mask-ge, -mask-above <value>\n"; cout << " Exclude values greater than or equal to a given threshold.\n"; cout << " -threshold-ge-percentile, -threshold-ge-pct, -mask-ge-percentile, -mask-ge-pct, -mask-above-percentile, -mask-above-pct <value>\n"; cout << " Exclude values greater than or equal to a given percentile.\n"; cout << " -threshold-gt, -upper-threshold, -mask-gt <value>\n"; cout << " Exclude values greater than a given threshold.\n"; cout << " -threshold-gt-percentile, -threshold-gt-pct, -upper-percentile-threshold, -upper-pct-threshold, -mask-gt-percentile, -mask-gt-pct <value>\n"; cout << " Exclude values greater than a given percentile.\n"; cout << "\n"; cout << "Data rescaling options:\n"; cout << " -binarize <lower> [<upper>]\n"; cout << " Set values inside the closed interval <lower>..<upper> to one,\n"; cout << " and all other values to zero. The default upper threshold is +inf.\n"; cout << " When the lower threshold is greater than the upper threshold,\n"; cout << " values inside the closed interval <upper>..<lower> are set to zero\n"; cout << " and all other values to one instead. This operation is short for:\n"; cout << " :option:`-threshold-inside` <lower> <upper> :option:`-set` 1 :option:`-pad` 0\n"; cout << " -clamp <lower> <upper>\n"; cout << " Clamp values which are less than a lower or greater than an upper threshold.\n"; cout << " -clamp-percentiles, -clamp-pcts <lower> <upper>\n"; cout << " Clamp values which are less than a lower percentile or greater than an upper percentile.\n"; cout << " -clamp-below, -clamp-lt <value>\n"; cout << " Clamp values less than a given threshold.\n"; cout << " -clamp-below-percentile, -clamp-below-pct, -clamp-lt-percentile, -clamp-lt-pct <value>\n"; cout << " Clamp values less than a given percentile.\n"; cout << " -clamp-above, -clamp-gt <value>\n"; cout << " Clamp values greater than a given threshold.\n"; cout << " -clamp-above-percentile, -clamp-above-pct, -clamp-gt-percentile, -clamp-gt-pct <value>\n"; cout << " Clamp values greater than a given percentile.\n"; cout << " -rescale <min> <max>\n"; cout << " Linearly rescale values to the interval [min, max].\n"; cout << " -map <from> <to>...\n"; cout << " Replaces values equal to <from> by the specified <to> value. Multiple pairs of <from>\n"; cout << " and <to> value replacements can be specified in order to perform the substitutions in\n"; cout << " one step. For example, to swap the two values 1 and 2, use ``-map 1 2 2 1``.\n"; cout << "\n"; cout << "Arithmetic operation options:\n"; cout << " -add, -plus <value> | <file> [<scalars>]\n"; cout << " Add constant value or data sequence read from specified file.\n"; cout << " Another name for this option is the '+' sign, see Examples.\n"; cout << " -sub, -subtract, -minus <value> | <file> [<scalars>]\n"; cout << " Subtract constant value or data sequence read from specified file.\n"; cout << " Another name for this option is the '-' sign, see Examples.\n"; cout << " -mul, -multiply-with, -times <value> | <file> [<scalars>]\n"; cout << " Multiply by constant value or data sequence read from specified file.\n"; cout << " Another name for this option is the '*' sign, see Examples.\n"; cout << " -div, -divide-by, -over <value> | sum | <file> [<scalars>]\n"; cout << " Divide by constant value or data sequence read from specified file.\n"; cout << " When the argument is \"sum\", the divisor is the sum of the values.\n"; cout << " When dividing by zero values in the input file, the result is NaN.\n"; cout << " Use :option:`-mask` with argument NaN and :option:`-pad` to replace\n"; cout << " these undefined values by a constant such as zero.\n"; cout << " Another name for this option is the '/' sign, see Examples.\n"; cout << " -div-with-zero <value> | sum | <file> [<scalars>]\n"; cout << " Same as :option:`-div`, but set result to zero in case of division by zero.\n"; cout << " -abs\n"; cout << " Replace values by their respective absolute value.\n"; cout << " -pow, -power <exponent>\n"; cout << " Raise values to the power of the given exponent.\n"; cout << " -sq, -square\n"; cout << " Raise values to the power of 2 (i.e, -pow 2).\n"; cout << " -sqrt\n"; cout << " Calculate square root of each value (i.e, -pow .5).\n"; cout << " -exp\n"; cout << " Calculate exponential of data sequence.\n"; cout << " -log [<threshold>] [<base>]\n"; cout << " Compute logarithm after applying an optional threshold.\n"; cout << " (default threshold: min double, default base: e)\n"; cout << " -lb, -log2 [<threshold>]\n"; cout << " Compute binary logarithm, alias for :option:`-log` with base 2.\n"; cout << " -ln, -loge [<threshold>]\n"; cout << " Compute natural logarithm, alias for :option:`-log` with base e.\n"; cout << " -lg, -log10 [<threshold>]\n"; cout << " Compute logarithm to base 10, alias for :option:`-log` with base 10.\n"; cout << " -mod, -fmod <denominator>\n"; cout << " Compute modulo division of each value with specified denominator.\n"; cout << " -floor\n"; cout << " Round floating point values to largest integer value that is not greater.\n"; cout << " -ceil\n"; cout << " Round floating point values to smallest integer value that is greater.\n"; cout << " -round\n"; cout << " Round floating point values to the nearest integer value, away from zero for halfway cases.\n"; cout << "\n"; cout << "Data output options:\n"; cout << " -out, -o, -output <file> [<type>] [<name>]\n"; cout << " Write current data sequence to file in the format of the input file.\n"; cout << " Output data type can be: uchar, short, ushort, int, uint, float, double.\n"; cout << " The optional <name> argument can be used to save the modified data\n"; cout << " of an input point set data array with a different name along with the\n"; cout << " input data. Otherwise, the input data values are replaced by the modified\n"; cout << " values and stored with point data array name is unchanged.\n"; cout << " Another name for this option is the '=' sign, but the optional arguments are\n"; cout << " are not supported by this alternative notation. See Examples for usage.\n"; cout << "\n"; cout << "Data statistics options:\n"; cout << " -append <file>\n"; cout << " Append output to a file. (default: STDOUT)\n"; cout << " -delimiter, -delim, -d, -sep\n"; cout << " Delimiting character(s). (default: '')\n"; cout << " -header [<name>...]\n"; cout << " Request output of header line if delimiter was specified as well.\n"; cout << " If the output is appended to a text file, the header is only printed\n"; cout << " if it does not exist. If no or fewer custom column names are given,\n"; cout << " the default names for each statistic are printed. (default: none)\n"; cout << " -prefix <str>...\n"; cout << " One or more prefix strings to print. If no delimiter is specified,\n"; cout << " the concatenated strings are printed before each line of the output.\n"; cout << " Otherwise, each prefix string is printed as entry for the first columns\n"; cout << " in the delimited output row, separated by the specified delimiter. (default: none)\n"; cout << " -precision, -digits <int>\n"; cout << " Number of significant digits. (default: 5)\n"; cout << " -median\n"; cout << " Print median value, i.e., 50th percentile. (default: off)\n"; cout << " -mean, -avg, -average\n"; cout << " Print mean value. (default: on)\n"; cout << " -variance, -var\n"; cout << " Print variance of values. (default: off)\n"; cout << " -sigma, -std, -stddev, -stdev, -sd\n"; cout << " Print standard deviation of values. (default: on)\n"; cout << " -normal-distribution\n"; cout << " Print mean and standard deviation of values.\n"; cout << " Other option names: -mean+sigma, -mean+sd, -avg+std,... (default: off)\n"; cout << " -mad, -mean-absolute-difference, -mean-absolute-deviation\n"; cout << " Print mean absolute difference/deviation around the mean. (default: off)\n"; cout << " -mad-median, -median-absolute-difference, -median-absolute-deviation\n"; cout << " Print mean absolute difference/deviation around the median. (default: off)\n"; cout << " -minimum, -min\n"; cout << " Print minimum value. (default: off)\n"; cout << " -maximum, -max\n"; cout << " Print maximum value. (default: off)\n"; cout << " -extrema, -minmax\n"; cout << " Print minimum and maximum value. (default: on)\n"; cout << " -range\n"; cout << " Print range of values (i.e., max - min). (default: off)\n"; cout << " -percentile, -pct, -p <n>...\n"; cout << " Print n-th percentile. (default: none)\n"; cout << " -lower-percentile-mean, -lpctavg <n>\n"; cout << " Print mean intensity of values less than or equal to the n-th percentile. (default: off)\n"; cout << " -upper-percentile-mean, -upctavg <n>\n"; cout << " Print mean intensity of values greater than or equal to the n-th percentile. (default: off)\n"; cout << " -sum\n"; cout << " Print sum of values. Can be used to count values within a certain range using a thresholding\n"; cout << " followed by :option:`-set` 1 before summing these values. (default: off)\n"; cout << " -count\n"; cout << " Print number of values inside the mask, i.e., values not currently excluded. (default: off)\n"; PrintCommonOptions(cout); cout << "\n"; cout << "Examples:\n"; cout << "\n"; cout << " " << name << " mni305.nii.gz\n"; cout << " Mean = 26.9753\n"; cout << " Standard deviation = 50.3525\n"; cout << " Extrema = [0, 254]\n"; cout << " Range = 254\n"; cout << "\n"; cout << " " << name << " mni305.nii.gz -pct 77\n"; cout << " 77th percentile = 25\n"; cout << "\n"; cout << " " << name << " mni305.nii.gz -padding 25 -range -percentile 25 50 75 -prefix MNI305 '[>25]'\n"; cout << " MNI305 [>25] range = 254\n"; cout << " MNI305 [>25] 25th percentile = 69\n"; cout << " MNI305 [>25] 50th percentile = 113\n"; cout << " MNI305 [>25] 75th percentile = 150\n"; cout << "\n"; cout << " " << name << " mni305.nii.gz -d , -prefix MNI305\n"; cout << " MNI305,26.9753,50.3525,0,254,254 [no newline at end of line]\n"; cout << "\n"; cout << " " << name << " mni305.nii.gz -d , -prefix MNI305 -header\n"; cout << " ,Mean,Sigma,Min,Max,Range\n"; cout << " MNI305,26.9753,50.3525,0,254,254\n"; cout << "\n"; cout << " " << name << " mni305.nii.gz -d , -prefix MNI305 -header ID Mean SD\n"; cout << " ID,Mean,SD,Min,Max,Range\n"; cout << " MNI305,26.9753,50.3525,0,254,254\n"; cout << "\n"; cout << " " << name << " a.nii.gz + b.nii.gz = c.nii.gz\n"; cout << "\n"; cout << " " << name << " a.vtk + b.nii.gz - 10 / c.nii = d.vtk\n"; cout << " Adds data values at identical sequential memory indices in a and b,\n"; cout << " subtracts the constant 10, and then divides by the values in image c.\n"; cout << "\n"; cout << " Note: Operations are always executed from left to right,\n"; cout << " i.e., no mathematical operator precedence is considered!\n"; cout << "\n"; } // ============================================================================= // Main // ============================================================================= // ----------------------------------------------------------------------------- // Some special options do not start with a '-' as otherwise required #undef HAS_ARGUMENT #define HAS_ARGUMENT \ _IsArgument(ARGIDX, argc, argv) && \ strcmp(argv[ARGIDX+1], "+") != 0 && \ strcmp(argv[ARGIDX+1], "/") != 0 && \ strcmp(argv[ARGIDX+1], "=") != 0 // ----------------------------------------------------------------------------- int main(int argc, char **argv) { InitializeIOLibrary(); // Initial data values REQUIRES_POSARGS(1); const char *input_name = POSARG(1); UniquePtr<double[]> data; int datatype = MIRTK_VOXEL_DOUBLE; ImageAttributes attr; #if MIRTK_Image_WITH_VTK const char *scalars_name = nullptr; bool cell_data = false; for (ARGUMENTS_AFTER(1)) { if (OPTION("-point-data") || OPTION("-pointdata") || OPTION("-pd") || OPTION("-scalars")) { scalars_name = ARGUMENT; cell_data = false; } else if (OPTION("-cell-data") || OPTION("-celldata") || OPTION("-cd")) { scalars_name = ARGUMENT; cell_data = true; } } vtkSmartPointer<vtkDataSet> dataset; vtkSmartPointer<vtkDataSetAttributes> arrays; int n = Read(input_name, data, &datatype, &attr, &dataset, scalars_name, cell_data); if (dataset) { if (cell_data) { arrays = dataset->GetCellData(); } else { arrays = dataset->GetPointData(); } } #else // MIRTK_Image_WITH_VTK int n = Read(input_name, data, &datatype, &attr); #endif // MIRTK_Image_WITH_VTK // Optional arguments const double inf = numeric_limits<double>::infinity(); const double nan = numeric_limits<double>::quiet_NaN(); double a, b; int p; const char *append_name = NULL; const char *delimiter = NULL; bool print_header = false; int digits = 5; Array<string> header; Array<string> prefix; Array<UniquePtr<Op> > ops; for (ARGUMENTS_AFTER(1)) { if (OPTION("-append")) { append_name = ARGUMENT; } else if (OPTION("-point-data") || OPTION("-pointdata") || OPTION("-pd") || OPTION("-scalars")) { #if MIRTK_Image_WITH_VTK // Parsed before Read above scalars_name = ARGUMENT; cell_data = false; #else FatalError("Cannot process -point-data of VTK file because MIRTK Image library was built without VTK!"); #endif // MIRTK_Image_WITH_VTK } else if (OPTION("-cell-data") || OPTION("-celldata") || OPTION("-cd")) { #if MIRTK_Image_WITH_VTK // Parsed before Read above scalars_name = ARGUMENT; cell_data = true; #else FatalError("Cannot process -cell-data of VTK file because MIRTK Image library was built without VTK!"); #endif // MIRTK_Image_WITH_VTK } else if (OPTION("-prefix")) { do { prefix.push_back(ARGUMENT); } while (HAS_ARGUMENT); } else if (OPTION("-header")) { print_header = true; while (HAS_ARGUMENT) header.push_back(ARGUMENT); // Masking } else if (OPTION("-label")) { ops.push_back(UniquePtr<Op>(new ResetMask(true))); do { const char *arg = ARGUMENT; const Array<string> parts = Split(arg, ".."); if (parts.size() == 1) { if (!FromString(parts[0], a)) a = nan; b = a; } else if (parts.size() == 2) { if (!FromString(parts[0], a) || !FromString(parts[1], b)) { a = b = nan; } } else { a = b = nan; } if (IsNaN(a) || IsNaN(b)) { FatalError("Invalid -label argument: " << arg); } ops.push_back(UniquePtr<Op>(new MaskInsideInterval(a, b))); } while (HAS_ARGUMENT); ops.push_back(UniquePtr<Op>(new InvertMask())); } else if (OPTION("-mask-all")) { ops.push_back(UniquePtr<Op>(new ResetMask(false))); } else if (OPTION("-reset-mask")) { ops.push_back(UniquePtr<Op>(new ResetMask(true))); } else if (OPTION("-invert-mask")) { ops.push_back(UniquePtr<Op>(new InvertMask())); } else if (OPTION("-mask")) { double c; do { const char *arg = ARGUMENT; if (FromString(arg, c)) { ops.push_back(UniquePtr<Op>(new Mask(c))); } else { const char *fname = arg; const char *aname = nullptr; if (HAS_ARGUMENT) { arg = ARGUMENT; if (HAS_ARGUMENT) { aname = arg; PARSE_ARGUMENT(c); } else if (!FromString(arg, c)) { aname = arg, c = 0.; } } else { c = 0.; #if MIRTK_Image_WITH_VTK if (dataset && arrays->HasArray(fname)) { aname = fname; fname = input_name; } #endif } UniquePtr<Mask> op(new Mask(fname, c)); if (aname) { #if MIRTK_Image_WITH_VTK op->ArrayName(aname); op->IsCellData(cell_data); #else FatalError("Cannot read point set files when build without VTK or wrong usage!"); #endif } ops.push_back(UniquePtr<Op>(op.release())); break; } } while (HAS_ARGUMENT); } else if (OPTION("-threshold-outside") || OPTION("-mask-outside")) { PARSE_ARGUMENT(a); PARSE_ARGUMENT(b); ops.push_back(UniquePtr<Op>(new MaskOutsideOpenInterval(a, b))); } else if (OPTION("-threshold-outside-percentiles") || OPTION("-threshold-outside-pcts") || OPTION("-mask-outside-percentiles") || OPTION("-mask-outside-pcts")) { PARSE_ARGUMENT(p); Statistic *a = new Percentile(p); a->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(a)); PARSE_ARGUMENT(p); Statistic *b = new Percentile(p); b->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(b)); Op *op = new MaskOutsideOpenInterval(&a->Value(), &b->Value()); ops.push_back(UniquePtr<Op>(op)); } else if (OPTION("-threshold")) { PARSE_ARGUMENT(a); if (HAS_ARGUMENT) PARSE_ARGUMENT(b); else b = inf; ops.push_back(UniquePtr<Op>(new MaskOutsideInterval(a, b))); } else if (OPTION("-percentile-threshold") || OPTION("-pct-threshold")) { PARSE_ARGUMENT(p); Statistic *a = new Percentile(p); a->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(a)); Op *op = new MaskOutsideInterval(&a->Value(), inf); ops.push_back(UniquePtr<Op>(op)); } else if (OPTION("-threshold-percentiles") || OPTION("-threshold-pcts")) { PARSE_ARGUMENT(p); Statistic *a = new Percentile(p); a->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(a)); PARSE_ARGUMENT(p); Statistic *b = new Percentile(p); b->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(b)); Op *op = new MaskOutsideInterval(&a->Value(), &b->Value()); ops.push_back(UniquePtr<Op>(op)); } else if (OPTION("-threshold-inside") || OPTION("-mask-inside")) { PARSE_ARGUMENT(a); PARSE_ARGUMENT(b); ops.push_back(UniquePtr<Op>(new MaskInsideInterval(a, b))); } else if (OPTION("-threshold-inside-percentiles") || OPTION("-threshold-inside-pcts") || OPTION("-mask-inside-percentiles") || OPTION("-mask-inside-pcts")) { PARSE_ARGUMENT(p); Statistic *a = new Percentile(p); a->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(a)); PARSE_ARGUMENT(p); Statistic *b = new Percentile(p); b->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(b)); Op *op = new MaskInsideInterval(&a->Value(), &b->Value()); ops.push_back(UniquePtr<Op>(op)); } else if (OPTION("-threshold-lt") || OPTION("-lower-threshold") || OPTION("-mask-lt")) { PARSE_ARGUMENT(a); ops.push_back(UniquePtr<Op>(new MaskOutsideInterval(a, inf))); } else if (OPTION("-threshold-lt-percentile") || OPTION("-threshold-lt-pct") || OPTION("-lower-percentile-threshold") || OPTION("-lower-pct-threshold") || OPTION("-mask-lt-percentile") || OPTION("-mask-lt-pct")) { PARSE_ARGUMENT(p); Statistic *a = new Percentile(p); a->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(a)); ops.push_back(UniquePtr<Op>(new MaskOutsideInterval(&a->Value(), inf))); } else if (OPTION("-threshold-le") || OPTION("-mask-below") || OPTION("-mask-le")) { PARSE_ARGUMENT(a); ops.push_back(UniquePtr<Op>(new MaskOutsideOpenInterval(a, inf))); } else if (OPTION("-threshold-le-percentile") || OPTION("-threshold-le-pct") || OPTION("-mask-below-percentile") || OPTION("-mask-below-pct") || OPTION("-mask-le-percentile") || OPTION("-mask-le-pct")) { PARSE_ARGUMENT(p); Statistic *a = new Percentile(p); a->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(a)); ops.push_back(UniquePtr<Op>(new MaskOutsideOpenInterval(&a->Value(), inf))); } else if (OPTION("-threshold-ge") || OPTION("-mask-above") || OPTION("-mask-ge")) { PARSE_ARGUMENT(b); ops.push_back(UniquePtr<Op>(new MaskOutsideOpenInterval(-inf, b))); } else if (OPTION("-threshold-ge-percentile") || OPTION("-threshold-ge-pct") || OPTION("-mask-above-percentile") || OPTION("-mask-above-pct") || OPTION("-mask-ge-percentile") || OPTION("-mask-ge-pct")) { PARSE_ARGUMENT(p); Statistic *b = new Percentile(p); b->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(b)); ops.push_back(UniquePtr<Op>(new MaskOutsideOpenInterval(-inf, &b->Value()))); } else if (OPTION("-threshold-gt") || OPTION("-upper-threshold") || OPTION("-mask-gt")) { PARSE_ARGUMENT(b); ops.push_back(UniquePtr<Op>(new MaskOutsideInterval(-inf, b))); } else if (OPTION("-threshold-gt-percentile") || OPTION("-threshold-gt-pct") || OPTION("-upper-percentile-threshold") || OPTION("-upper-pct-threshold") || OPTION("-mask-gt-percentile") || OPTION("-mask-gt-pct")) { PARSE_ARGUMENT(p); Statistic *b = new Percentile(p); b->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(b)); ops.push_back(UniquePtr<Op>(new MaskOutsideInterval(-inf, &b->Value()))); } else if (OPTION("-even")) { ops.push_back(UniquePtr<Op>(new MaskOddValues())); } else if (OPTION("-odd")) { ops.push_back(UniquePtr<Op>(new MaskEvenValues())); // Clamping } else if (OPTION("-clamp")) { PARSE_ARGUMENT(a); PARSE_ARGUMENT(b); ops.push_back(UniquePtr<Op>(new Clamp(a, b))); } else if (OPTION("-clamp-percentiles") || OPTION("-clamp-pcts")) { PARSE_ARGUMENT(p); Statistic *a = new Percentile(p); a->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(a)); PARSE_ARGUMENT(p); Statistic *b = new Percentile(p); b->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(b)); ops.push_back(UniquePtr<Op>(new Clamp(&a->Value(), &b->Value()))); } else if (OPTION("-clamp-lt") || OPTION("-clamp-below")) { PARSE_ARGUMENT(a); ops.push_back(UniquePtr<Op>(new LowerThreshold(a))); } else if (OPTION("-clamp-lt-percentile") || OPTION("-clamp-lt-pct") || OPTION("-clamp-below-percentile") || OPTION("-clamp-below-pct")) { PARSE_ARGUMENT(p); Statistic *a = new Percentile(p); a->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(a)); ops.push_back(UniquePtr<Op>(new LowerThreshold(&a->Value()))); } else if (OPTION("-clamp-gt") || OPTION("-clamp-above")) { PARSE_ARGUMENT(b); ops.push_back(UniquePtr<Op>(new UpperThreshold(b))); } else if (OPTION("-clamp-gt-percentile") || OPTION("-clamp-gt-pct") || OPTION("-clamp-above-percentile") || OPTION("-clamp-above-pct")) { PARSE_ARGUMENT(p); Statistic *b = new Percentile(p); b->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(b)); ops.push_back(UniquePtr<Op>(new UpperThreshold(&b->Value()))); } else if (OPTION("-rescale")) { double min, max; if (!FromString(ARGUMENT, min)) { cerr << "Invalid -rescale minimum, must be a number!" << endl; exit(1); } if (!FromString(ARGUMENT, max)) { cerr << "Invalid -rescale maximum, must be a number!" << endl; exit(1); } ops.push_back(UniquePtr<Op>(new Rescale(min, max))); } else if (OPTION("-set") || OPTION("-inside")) { double inside_value; if (!FromString(ARGUMENT, inside_value)) { cerr << "Invalid -inside value, must be a number!" << endl; exit(1); } ops.push_back(UniquePtr<Op>(new SetInsideValue(inside_value))); } else if (OPTION("-pad") || OPTION("-outside")) { double outside_value; if (!FromString(ARGUMENT, outside_value)) { cerr << "Invalid -outside value, must be a number!" << endl; exit(1); } ops.push_back(UniquePtr<Op>(new SetOutsideValue(outside_value))); // Data transformations } else if (OPTION("-binarize")) { PARSE_ARGUMENT(a); if (HAS_ARGUMENT) PARSE_ARGUMENT(b); else b = inf; ops.push_back(UniquePtr<Op>(new Binarize(a, b))); } else if (OPTION("-map")) { UniquePtr<Map> map(new Map()); do { const char * const arg1 = ARGUMENT; const char * const arg2 = ARGUMENT; if (!FromString(arg1, a) || !FromString(arg2, b)) { FatalError("Arguments of -map option must be pairs of two numbers (i.e., number of arguments must be even)!"); } map->Insert(a, b); } while (HAS_ARGUMENT); ops.push_back(UniquePtr<Op>(map.release())); } else if (OPTION("-add") || OPTION("-plus") || OPTION("+")) { const char *arg = ARGUMENT; double c; if (FromString(arg, c)) { ops.push_back(UniquePtr<Op>(new Add(c))); } else { const char *fname = arg; const char *aname = nullptr; if (HAS_ARGUMENT) { aname = ARGUMENT; } else { #if MIRTK_Image_WITH_VTK if (dataset && arrays->HasArray(fname)) { aname = fname; fname = input_name; } #endif } UniquePtr<Add> op(new Add(fname)); if (aname) { #if MIRTK_Image_WITH_VTK op->ArrayName(aname); op->IsCellData(cell_data); #else FatalError("Cannot read scalars from point set file when build without VTK or wrong usage!"); #endif } ops.push_back(UniquePtr<Op>(op.release())); } } else if (OPTION("-sub") || OPTION("-subtract") || OPTION("-minus") || OPTION("-")) { const char *arg = ARGUMENT; double c; if (FromString(arg, c)) { ops.push_back(UniquePtr<Op>(new Sub(c))); } else { const char *fname = arg; const char *aname = nullptr; if (HAS_ARGUMENT) { aname = ARGUMENT; } else { #if MIRTK_Image_WITH_VTK if (dataset && arrays->HasArray(fname)) { aname = fname; fname = input_name; } #endif } UniquePtr<Sub> op(new Sub(fname)); if (aname) { #if MIRTK_Image_WITH_VTK op->ArrayName(aname); op->IsCellData(cell_data); #else FatalError("Cannot read point set files when build without VTK or wrong usage!"); #endif } ops.push_back(UniquePtr<Op>(op.release())); } } else if (OPTION("-mul") || OPTION("-multiply-by") || OPTION("-times") || OPTION("*")) { const char *arg = ARGUMENT; double c; if (FromString(arg, c)) { ops.push_back(UniquePtr<Op>(new Mul(c))); } else { const char *fname = arg; const char *aname = nullptr; if (HAS_ARGUMENT) { aname = ARGUMENT; } else { #if MIRTK_Image_WITH_VTK if (dataset && arrays->HasArray(fname)) { aname = fname; fname = input_name; } #endif } UniquePtr<Mul> op(new Mul(fname)); if (aname) { #if MIRTK_Image_WITH_VTK op->ArrayName(aname); op->IsCellData(cell_data); #else FatalError("Cannot read point set files when build without VTK or wrong usage!"); #endif } ops.push_back(UniquePtr<Op>(op.release())); } } else if (OPTION("-div") || OPTION("-divide-by") || OPTION("-over") || OPTION("/")) { const char *arg = ARGUMENT; double c; if (ToLower(arg) == "sum") { Statistic *a = new Sum(); a->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(a)); ops.push_back(UniquePtr<Op>(new Div(&a->Value()))); } else if (FromString(arg, c)) { if (fequal(c, .0)) { cerr << "Invalid -div argument, value must not be zero!" << endl; exit(1); } ops.push_back(UniquePtr<Op>(new Div(c))); } else { const char *fname = arg; const char *aname = nullptr; if (HAS_ARGUMENT) { aname = ARGUMENT; } else { #if MIRTK_Image_WITH_VTK if (dataset && arrays->HasArray(fname)) { aname = fname; fname = input_name; } #endif } UniquePtr<Div> op(new Div(fname)); if (aname) { #if MIRTK_Image_WITH_VTK op->ArrayName(aname); op->IsCellData(cell_data); #else FatalError("Cannot read point set files when build without VTK or wrong usage!"); #endif } ops.push_back(UniquePtr<Op>(op.release())); } } else if (OPTION("-div-with-zero")) { const char *arg = ARGUMENT; double c; if (ToLower(arg) == "sum") { Statistic *a = new Sum(); a->Hidden(verbose < 1); ops.push_back(UniquePtr<Op>(a)); ops.push_back(UniquePtr<Op>(new DivWithZero(&a->Value()))); } else if (FromString(arg, c)) { ops.push_back(UniquePtr<Op>(new DivWithZero(c))); } else { const char *fname = arg; const char *aname = nullptr; if (HAS_ARGUMENT) { aname = ARGUMENT; } else { #if MIRTK_Image_WITH_VTK if (dataset && arrays->HasArray(fname)) { aname = fname; fname = input_name; } #endif } UniquePtr<DivWithZero> op(new DivWithZero(fname)); if (aname) { #if MIRTK_Image_WITH_VTK op->ArrayName(aname); op->IsCellData(cell_data); #else FatalError("Cannot read point set files when build without VTK or wrong usage!"); #endif } ops.push_back(UniquePtr<Op>(op.release())); } } else if (OPTION("-abs")) { ops.push_back(UniquePtr<Op>(new Abs())); } else if (OPTION("-pow") || OPTION("-power")) { const char *arg = ARGUMENT; double exponent; if (!FromString(arg, exponent)) { cerr << "Invalid -power value, must be a number!" << endl; exit(1); } ops.push_back(UniquePtr<Op>(new Pow(exponent))); } else if (OPTION("-sqrt")) { ops.push_back(UniquePtr<Op>(new Pow(.5))); } else if (OPTION("-square") || OPTION("-sq")) { ops.push_back(UniquePtr<Op>(new Pow(2.0))); } else if (OPTION("-exp")) { ops.push_back(UniquePtr<Op>(new Exp())); } else if (OPTION("-log") || OPTION("-log2") || OPTION("-loge") || OPTION("-log10") || OPTION("-lb") || OPTION("-ln") || OPTION("-lg")) { a = numeric_limits<double>::min(); if (HAS_ARGUMENT) { PARSE_ARGUMENT(a); if (a <= .0) { cerr << "Invalid -log threshold argument, must be a positive number" << endl; exit(1); } } Op *op = nullptr; if (strcmp(OPTNAME, "-log") == 0) { if (HAS_ARGUMENT) { double base; if (!FromString(ARGUMENT, base)) { char c; if (!FromString(ARGUMENT, c) || c != 'e') { cerr << "Invalid -log base argument, must be a positive number or character e" << endl; exit(1); } op = new Ln(a); } else { op = new Log(base, a); } } else { op = new Ln(a); } } else if (strcmp(OPTNAME, "-log2") == 0 || strcmp(OPTNAME, "-lb") == 0) { op = new Lb(a); } else if (strcmp(OPTNAME, "-log10") == 0 || strcmp(OPTNAME, "-lg") == 0) { op = new Lg(a); } else if (strcmp(OPTNAME, "-loge") == 0 || strcmp(OPTNAME, "-ln") == 0) { op = new Ln(a); } ops.push_back(UniquePtr<Op>(op)); } else if (OPTION("-mod") || OPTION("-fmod")) { const char *arg = ARGUMENT; double denominator; if (!FromString(arg, denominator) || abs(denominator) < 1e-12) { cerr << "Invalid -mod value, must be a non-zero number!" << endl; exit(1); } ops.push_back(UniquePtr<Op>(new Mod(denominator))); } else if (OPTION("-floor")) { ops.push_back(UniquePtr<Op>(new Floor())); } else if (OPTION("-ceil")) { ops.push_back(UniquePtr<Op>(new Ceil())); } else if (OPTION("-round")) { ops.push_back(UniquePtr<Op>(new Round())); } else if (OPTION("=")) { const char *fname = ARGUMENT; #if MIRTK_Image_WITH_VTK ops.push_back(UniquePtr<Op>(new Write(fname, datatype, attr, dataset, scalars_name, scalars_name))); #else ops.push_back(UniquePtr<Op>(new Write(fname, datatype, attr))); #endif } else if (OPTION("-o") || OPTION("-out") || OPTION("-output")) { const char *fname = ARGUMENT; int dtype = datatype; #if MIRTK_Image_WITH_VTK const char *output_scalars_name = scalars_name; #endif if (HAS_ARGUMENT) { const char *arg = ARGUMENT; dtype = ToDataType(arg); if (dtype == MIRTK_VOXEL_UNKNOWN) { cerr << "Invalid -out data type " << arg << endl; exit(1); } if (HAS_ARGUMENT) { #if MIRTK_Image_WITH_VTK output_scalars_name = ARGUMENT; #else Warning("Output scalars array name argument of -output option ignored"); #endif } } #if MIRTK_Image_WITH_VTK ops.push_back(UniquePtr<Op>(new Write(fname, dtype, attr, dataset, scalars_name, output_scalars_name, cell_data))); #else ops.push_back(UniquePtr<Op>(new Write(fname, dtype, attr))); #endif // Data statistics } else if (OPTION("-median")) { ops.push_back(UniquePtr<Op>(new Median())); } else if (OPTION("-mean") || OPTION("-average") || OPTION("-avg")) { ops.push_back(UniquePtr<Op>(new Mean())); } else if (OPTION("-sigma") || OPTION("-stddev") || OPTION("-stdev") || OPTION("-std") || OPTION("-sd")) { ops.push_back(UniquePtr<Op>(new StDev())); } else if (OPTION("-normal-distribution") || OPTION("-mean+sigma") || OPTION("-mean+stddev") || OPTION("-mean+stdev") || OPTION("-mean+std") || OPTION("-mean+sd") || OPTION("-avg+sigma") || OPTION("-avg+stddev") || OPTION("-avg+stdev") || OPTION("-avg+std") || OPTION("-avg+sd")) { ops.push_back(UniquePtr<Op>(new NormalDistribution())); } else if (OPTION("-variance") || OPTION("-var")) { ops.push_back(UniquePtr<Op>(new Var())); } else if (OPTION("-mean-absolute-difference") || OPTION("-mean-absolute-deviation") || OPTION("-mad") || OPTION("-mad-mean")) { ops.push_back(UniquePtr<Op>(new MeanAbsoluteDifference())); } else if (OPTION("-median-absolute-difference") || OPTION("-median-absolute-deviation") || OPTION("-mad-median")) { ops.push_back(UniquePtr<Op>(new MedianAbsoluteDifference())); } else if (OPTION("-minimum") || OPTION("-min")) { ops.push_back(UniquePtr<Op>(new Min())); } else if (OPTION("-maximum") || OPTION("-max")) { ops.push_back(UniquePtr<Op>(new Max())); } else if (OPTION("-extrema") || OPTION("-minmax")) { ops.push_back(UniquePtr<Op>(new Extrema())); } else if (OPTION("-range")) { ops.push_back(UniquePtr<Op>(new Range())); } else if (OPTION("-percentile") || OPTION("-pct") || OPTION("-p")) { do { int p; if (FromString(ARGUMENT, p) && 0 <= p && p <= 100) { ops.push_back(UniquePtr<Op>(new Percentile(p))); } else { cerr << "Invalid -percentile value, must be integer in the range [0, 100]!" << endl; exit(1); } } while (HAS_ARGUMENT); } else if (OPTION("-lower-percentile-mean") || OPTION("-lpctavg")) { do { int p; if (FromString(ARGUMENT, p) && 0 <= p && p <= 100) { ops.push_back(UniquePtr<Op>(new LowerPercentileMean(p))); } else { cerr << "Invalid -lower-percentile-mean value, must be integer in the range [0, 100]!" << endl; exit(1); } } while (HAS_ARGUMENT); } else if (OPTION("-upper-percentile-mean") || OPTION("-upctavg")) { do { int p; if (FromString(ARGUMENT, p) && 0 <= p && p <= 100) { ops.push_back(UniquePtr<Op>(new UpperPercentileMean(p))); } else { cerr << "Invalid -upper-percentile-mean value, must be integer in the range [0, 100]!" << endl; exit(1); } } while (HAS_ARGUMENT); } else if (OPTION("-sum")) { ops.push_back(UniquePtr<Op>(new Sum())); } else if (OPTION("-count")) { ops.push_back(UniquePtr<Op>(new Count())); } else if (OPTION("-delimiter") || OPTION("-delim") || OPTION("-d") || OPTION("-sep")) { delimiter = ARGUMENT; } else if (OPTION("-precision") || OPTION("-digits")) { if (!FromString(ARGUMENT, digits) || digits < 0) { cerr << "Invalid -precision argument, value must be non-negative integer!" << endl; exit(1); } } else { HANDLE_COMMON_OR_UNKNOWN_OPTION(); } } // If delimiter explicitly set to empty string, use none if (delimiter && delimiter[0] == '\0') delimiter = NULL; // Default statistics to compute if (ops.empty()) { ops.push_back(UniquePtr<Statistic>(new Mean())); ops.push_back(UniquePtr<Statistic>(new StDev())); ops.push_back(UniquePtr<Statistic>(new Extrema())); ops.push_back(UniquePtr<Statistic>(new Range())); } // Initial data mask UniquePtr<bool[]> mask(new bool[n]); for (int i = 0; i < n; ++i) { if (IsNaN(data[i])) { mask[i] = false; } else { mask[i] = true; } } // Process input data, either transform it or compute statistics from it for (size_t i = 0; i < ops.size(); ++i) { ops[i]->Process(n, data.get(), mask.get()); } mask.reset(); // Open output file to append to or use STDOUT if none specified ofstream ofs; if (append_name) { if (print_header) { ifstream ifs(append_name); if (ifs.is_open()) { print_header = false; ifs.close(); } } ofs.open(append_name, ios_base::app); if (!ofs.is_open()) { FatalError("Cannot append to file " << append_name); } } ostream &out = (ofs.is_open() ? ofs : cout); // Print column names if requested if (delimiter && print_header) { size_t c = 0; for (size_t i = 0; i < prefix.size(); ++i, ++c) { if (c > 0) out << delimiter; if (c < header.size()) out << header[c]; } for (size_t i = 0; i < ops.size(); ++i) { Statistic *stat = dynamic_cast<Statistic *>(ops[i].get()); if (stat != nullptr && !stat->Hidden()) { for (size_t j = 0; j < stat->Names().size(); ++j, ++c) { if (c > 0) out << delimiter; if (c < header.size()) out << header[c]; else out << stat->Names()[j]; } } } out << endl; } // Print image statistics if (delimiter) { for (size_t i = 0; i < prefix.size(); ++i) { if (i > 0) out << delimiter; out << prefix[i]; } bool first = prefix.empty(); for (size_t i = 0; i < ops.size(); ++i) { Statistic *stat = dynamic_cast<Statistic *>(ops[i].get()); if (stat != nullptr && !stat->Hidden() && !stat->Names().empty()) { if (!first) out << delimiter; else first = false; stat->PrintValues(out, digits, delimiter); } } // No newline at end of row if printing results to STDOUT which in this // case is usually assigned to a string in a calling script if (print_header || ofs.is_open()) out << endl; } else { string prefix_string; for (size_t i = 0; i < prefix.size(); ++i) { if (i > 0) prefix_string += ' '; prefix_string += prefix[i]; } for (size_t i = 0; i < ops.size(); ++i) { Statistic *stat = dynamic_cast<Statistic *>(ops[i].get()); if (stat != nullptr && !stat->Hidden()) { stat->Print(out, digits, prefix_string.c_str()); } } } ofs.close(); return 0; }
Java
<%# Copyright 2013-2017 the original author or authors. This file is part of the JHipster project, see https://jhipster.github.io/ for more information. 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 { SpyObject } from './spyobject'; import { Principal } from '../../../../main/webapp/app/shared/auth/principal.service'; import Spy = jasmine.Spy; export class MockPrincipal extends SpyObject { identitySpy: Spy; fakeResponse: any; constructor() { super(Principal); this.fakeResponse = {}; this.identitySpy = this.spy('identity').andReturn(Promise.resolve(this.fakeResponse)); } setResponse(json: any): void { this.fakeResponse = json; } }
Java
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.codeInsight.template.macro; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.template.*; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.util.TypeConversionUtil; import org.jetbrains.annotations.NotNull; /** * @author ven */ public class IterableComponentTypeMacro implements Macro { public String getName() { return "iterableComponentType"; } public String getDescription() { return CodeInsightBundle.message("macro.iterable.component.type"); } public String getDefaultValue() { return "a"; } public Result calculateResult(@NotNull Expression[] params, ExpressionContext context) { if (params.length != 1) return null; final Result result = params[0].calculateResult(context); if (result == null) return null; Project project = context.getProject(); PsiDocumentManager.getInstance(project).commitAllDocuments(); PsiExpression expr = MacroUtil.resultToPsiExpression(result, context); if (expr == null) return null; PsiType type = expr.getType(); if (type instanceof PsiArrayType) { return new PsiTypeResult(((PsiArrayType)type).getComponentType(), project); } if (type instanceof PsiClassType) { PsiClassType.ClassResolveResult resolveResult = ((PsiClassType)type).resolveGenerics(); PsiClass aClass = resolveResult.getElement(); if (aClass != null) { PsiClass iterableClass = JavaPsiFacade.getInstance(project).findClass("java.lang.Iterable", aClass.getResolveScope()); if (iterableClass != null) { PsiSubstitutor substitutor = TypeConversionUtil.getClassSubstitutor(iterableClass, aClass, resolveResult.getSubstitutor()); if (substitutor != null) { PsiType parameterType = substitutor.substitute(iterableClass.getTypeParameters()[0]); if (parameterType instanceof PsiCapturedWildcardType) { parameterType = ((PsiCapturedWildcardType)parameterType).getWildcard(); } if (parameterType != null) { if (parameterType instanceof PsiWildcardType) { if (((PsiWildcardType)parameterType).isExtends()) { return new PsiTypeResult(((PsiWildcardType)parameterType).getBound(), project); } else return null; } return new PsiTypeResult(parameterType, project); } } } } } return null; } public Result calculateQuickResult(@NotNull Expression[] params, ExpressionContext context) { return calculateResult(params, context); } public LookupElement[] calculateLookupItems(@NotNull Expression[] params, ExpressionContext context) { return LookupElement.EMPTY_ARRAY; } }
Java
const ng = require('angular'); ng.module('porybox.static', ['ngRoute']).config(['$routeProvider', $routeProvider => { [ 'about', 'donate', 'extracting-pokemon-files', 'faq', 'how-to-pk6-1-bvs', 'how-to-pk6-2-homebrew', 'how-to-pk6-3-4-save-files', 'how-to-pk6-6-decrypted-powersaves', 'how-to-pk7-1-bvs', 'how-to-pk7-2-homebrew', 'how-to-pk7-3-digital-save-files', 'how-to-pk7-4-tea', 'markdown', 'privacy-policy', 'tos' ].forEach(pageName => { $routeProvider.when(`/${pageName}`, {templateUrl: `/static/${pageName}.html`}); }); $routeProvider.when('/extracting-pk6-files', {redirectTo: '/extracting-pokemon-files'}); }]);
Java
--- ID_PAGE: 22591 PG_TITLE: How to use LOD --- Babylon.js comes with an integrated support for level of detail. This feature allows you to specify different meshes based on distance to viewer. For instance, here is how to define 4 levels of details for a given mesh: ```javascript var knot00 = BABYLON.Mesh.CreateTorusKnot("knot0", 0.5, 0.2, 128, 64, 2, 3, scene); var knot01 = BABYLON.Mesh.CreateTorusKnot("knot1", 0.5, 0.2, 32, 16, 2, 3, scene); var knot02 = BABYLON.Mesh.CreateTorusKnot("knot2", 0.5, 0.2, 24, 12, 2, 3, scene); var knot03 = BABYLON.Mesh.CreateTorusKnot("knot3", 0.5, 0.2, 16, 8, 2, 3, scene); knot00.addLODLevel(15, knot01); knot00.addLODLevel(30, knot02); knot00.addLODLevel(45, knot03); knot00.addLODLevel(55, null); ``` The first parameter used with ```addLODLevel``` defines the distance to the camera. Beyond this distance, the specified level is used. Each level is independent and can have its own material. By defining a level of detail to null, you disable rendering of the current mesh, when it is viewed beyond the indicated distance to camera. When a mesh is used as a level of detail for another mesh, it is linked to it and cannot be rendered directly. You can remove a LOD level by using ```removeLODLevel```: ```javascript knot00.removeLODLevel(knot02); knot00.removeLODLevel(null); ``` Try: [LOD playground](http://www.babylonjs-playground.com/#QE7KM) ## Using LOD and instances By default, instances will use LOD defined on root mesh. You do not have to specify anything on instances: ```javascript var count = 3; var scale = 4; var knot00 = BABYLON.Mesh.CreateTorusKnot("knot0", 0.5, 0.2, 128, 64, 2, 3, scene); var knot01 = BABYLON.Mesh.CreateTorusKnot("knot1", 0.5, 0.2, 32, 16, 2, 3, scene); var knot02 = BABYLON.Mesh.CreateTorusKnot("knot2", 0.5, 0.2, 24, 12, 2, 3, scene); var knot03 = BABYLON.Mesh.CreateTorusKnot("knot3", 0.5, 0.2, 16, 8, 2, 3, scene); knot00.setEnabled(false); knot00.addLODLevel(15, knot01); knot00.addLODLevel(30, knot02); knot00.addLODLevel(45, knot03); knot00.addLODLevel(55, null); for (var x = -count; x <= count; x++) {     for (var y = -count; y <= count; y++) {         for (var z = 5; z < 10; z++) {             var knot = knot00.createInstance("knotI"),             knot.position = new BABYLON.Vector3(x * scale, y * scale, z * scale);         }     } } ``` Try: [LOD and instances playground](http://www.babylonjs-playground.com/#14ESWC)
Java
Follow these simple instructions to install this custom symbol; the overall process should only take a minutes. 1. In Windows Explorer, navigate to the "PIPC\PIVision" installation folder on your PI Vision server; typically, it's located in "C:\Program Files\PIPC\PIVision" 2. From within the folder named "PIVision", navigate to the "\Scripts\app\editor\symbols" sub-folder. 3. Within the folder named "symbols", if there is not already a folder called "ext", create a folder called "ext". 4. This is a symbol that uses the free plotly library; thus, download the plotly library .js file, located at https://cdn.plot.ly/plotly-latest.min.js. Now that the "ext" folder exists, or already exits, copy and paste the plotly-latest.min.js file that you just downloaded into the "ext" folder. 5. Now that the "ext" folder exists, or already exits, open it, and paste into the "ext" folder the one .js and two .html files contained in the custom symbol .ZIP folder that you were sent. 6. Within the folder named "ext", if there is not already a folder called "Icons", create a folder called "Icons". 7. Now that the "Icons" folder exists, or already exits, open it, and paste into the "Icons" folder the one .png image file contained in the custom symbol .ZIP folder that you were sent. The next time you open a web browser and navigate to PI Vision and create a new PI Vision display, you will see this new symbol appear in the top-left-hand corner of the PI Vision display editor.
Java
--- title: Action Collection --- # Action Collection Design * Extract common code from the Resource Reporter and Data Collector. * Expose a general purpose API for querying a record of all actions taken during the Chef run. * Enable utilities like the 'zap' cookbook to be written to interact properly with Custom Resources. The Action Collection tracks all actions taken by all Chef resources. The resources can be in recipe code, as sub-resources of custom resources or they may be built "by hand". Since the Action Collection hooks the events which are fired from the `run_action` method on Chef::Resource it does not matter how the resources were built (as long as they were correctly passed the Chef `run_context`). This is complementary, but superior, to the resource collection which has an incomplete picture of what might happen or has happened in the run since there are many common ways of invoking resource actions which are not captured by how the resource collection is built. Replaying the sequence of actions in the Action Collection would be closer to replaying the chef-client converge than trying to re-converge the resource collection (although both of those models are still flawed in the presence of any imperative code that controls the shape of those objects). This design extracts common duplicated code from the Data Collection and old Resource Reporter, and is designed to be used by other consumers which need to ask questions like "in this run, what file resources had actions fired on them?", which can then be used to answer questions like "which files is Chef managing in this directory?". # Usage ## Action Collection Event Hook Registration Consumers may register an event handler which hooks the `action_collection_registration` hook. This event is fired directly before recipes are compiled and converged (after library loading, attributes, etc). This is just before the earliest point in time that a resource should fire an action so represents the latest point that a consumer should make a decision about if it needs the Action Collection to be enabled or not. Consumers can hook this method. They will be passed the Action Collection instance, which can be saved by the caller to be queried later. They should then register themselves with the Action Collection (since without registering any interest, the Action Collection will disable itself). ```ruby def action_collection_registration(action_collection) @action_collection = action_collection action_collection.register(self) end ``` ## Library Registration Any cookbook library code may also register itself with the Action Collection. The Action Collection will be registered with the `run_context` after it is created, so registration may be accomplished easily: ```ruby Chef.run_context.action_collection.register(self) ``` ## Action Collection Requires Registration If one of the prior methods is not used to register for the Action Collection, then the Action Collection will disable itself and will not compile the Action Collection in order to not waste the memory overhead of tracking the actions during the run. The Data Collector takes advantage of this since if the run start message from the Data Collector is refused by the server, then the Data Collector disables itself, and then does not register with the Action Collection, which would disable the Action Collection. This makes use of the delayed hooking through the `action_collection_regsitration` so that the Data Collector never registers itself after it is disabled. ## Searching There is a function `filtered_collection` which returns "slices" off of the `ActionCollection` object. The `max_nesting` argument can be used to prune how deep into sub-resources the returned view goes (`max_nesting: 0` will return only resources in recipe context, with any hand created resources, but no subresources). There are also 5 different states of the action: `up_to_date`, `skipped`, `updated`, `failed`, `unprocessed` which can be filtered on. All of these are true by default, so they must be disabled to remove them from the filtered collection. The `ActionCollection` object itself implements enumerable and returns `ActionRecord` objects (see the `ActionCollection` code for the fields exposed on `ActionRecord`s). This would return all file resources in any state in the recipe context: ``` Chef.run_context.action_collection.filtered_collection(max_nesting: 0).select { |rec| rec.new_resource.is_a?(Chef::Resource::File) } ``` NOTE: As the Action Collection API was initially designed around the Resource Reporter and Data Collector use cases, the searching API is currently rudimentary and could easily lift some of the searching features on the name of the resource from the resource collection, and could use a more fluent API for composing searches. # Implementation Details ## Resource Event Lifecycle Hooks Resources actions fire off several events in sequence: 1. `resource_action_start` - this is always fired first 2. `resource_current_state_loaded` - this is normally always second, but may be skipped in the case of a resource which throws an exception during `load_current_resource` (which means that the `current_resource` off the `ActionRecord` may be nil). 3. `resource_up_to_date` / `resource_skipped` / `resource_updated` / `resource_failed` - one of these is always called which corresponds to the state of the action. 4. `resource_completed` - this is always fired last For skipped resources, the conditional will be saved in the `ActionRecord`. For failed resources the exception is saved in the `ActionRecord`. ## Unprocessed Resources The unprocessed resource concept is to report on resources which are left in the resource collection after a failure. A successful Chef run should never leave any unprocessed resources (`action :nothing` resources are still inspected by the resource collection and are processed). There must be an exception thrown during the execution of the resource collection, and the unprocessed resources were never visited by the runner that executes the resource collection. This list will be necessarily incomplete of any unprocessed sub-resources in custom resources, since the run was aborted before those resources executed actions and built their own sub-resource collections. This was a design requirement of the Data Collector. To implement this in a more sane manner the runner that evaluates the resource collection now tracks the resources that it visits.
Java
This sample Android app demonstrates having several maps as pages in a `ViewPager`. This app is covered in [the chapter on Maps V2](https://commonsware.com/Android/previews/mapping-with-maps-v2) in [*The Busy Coder's Guide to Android Development*](https://commonsware.com/Android/).
Java
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.openapi.fileEditor.impl; import com.intellij.AppTopics; import com.intellij.CommonBundle; import com.intellij.codeStyle.CodeStyleFacade; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.TransactionGuard; import com.intellij.openapi.application.TransactionGuardImpl; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.PrioritizedDocumentListener; import com.intellij.openapi.editor.impl.EditorFactoryImpl; import com.intellij.openapi.editor.impl.TrailingSpacesStripper; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.fileEditor.impl.text.TextEditorImpl; import com.intellij.openapi.fileTypes.BinaryFileTypeDecompilers; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.UnknownFileType; import com.intellij.openapi.project.*; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem; import com.intellij.pom.core.impl.PomModelImpl; import com.intellij.psi.ExternalChangeAction; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.SingleRootFileViewProvider; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.testFramework.LightVirtualFile; import com.intellij.ui.UIBundle; import com.intellij.ui.components.JBScrollPane; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.nio.charset.Charset; import java.util.*; import java.util.List; public class FileDocumentManagerImpl extends FileDocumentManager implements VirtualFileListener, VetoableProjectManagerListener, SafeWriteRequestor { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl"); public static final Key<Document> HARD_REF_TO_DOCUMENT_KEY = Key.create("HARD_REF_TO_DOCUMENT_KEY"); private static final Key<String> LINE_SEPARATOR_KEY = Key.create("LINE_SEPARATOR_KEY"); private static final Key<VirtualFile> FILE_KEY = Key.create("FILE_KEY"); private static final Key<Boolean> MUST_RECOMPUTE_FILE_TYPE = Key.create("Must recompute file type"); private final Set<Document> myUnsavedDocuments = ContainerUtil.newConcurrentSet(); private final MessageBus myBus; private static final Object lock = new Object(); private final FileDocumentManagerListener myMultiCaster; private final TrailingSpacesStripper myTrailingSpacesStripper = new TrailingSpacesStripper(); private boolean myOnClose; private volatile MemoryDiskConflictResolver myConflictResolver = new MemoryDiskConflictResolver(); private final PrioritizedDocumentListener myPhysicalDocumentChangeTracker = new PrioritizedDocumentListener() { @Override public int getPriority() { return Integer.MIN_VALUE; } @Override public void documentChanged(DocumentEvent e) { final Document document = e.getDocument(); if (!ApplicationManager.getApplication().hasWriteAction(ExternalChangeAction.ExternalDocumentChange.class)) { myUnsavedDocuments.add(document); } final Runnable currentCommand = CommandProcessor.getInstance().getCurrentCommand(); Project project = currentCommand == null ? null : CommandProcessor.getInstance().getCurrentCommandProject(); if (project == null) project = ProjectUtil.guessProjectForFile(getFile(document)); String lineSeparator = CodeStyleFacade.getInstance(project).getLineSeparator(); document.putUserData(LINE_SEPARATOR_KEY, lineSeparator); // avoid documents piling up during batch processing if (areTooManyDocumentsInTheQueue(myUnsavedDocuments)) { saveAllDocumentsLater(); } } }; public FileDocumentManagerImpl(@NotNull VirtualFileManager virtualFileManager, @NotNull ProjectManager projectManager) { virtualFileManager.addVirtualFileListener(this); projectManager.addProjectManagerListener(this); myBus = ApplicationManager.getApplication().getMessageBus(); myBus.connect().subscribe(ProjectManager.TOPIC, this); InvocationHandler handler = (proxy, method, args) -> { multiCast(method, args); return null; }; final ClassLoader loader = FileDocumentManagerListener.class.getClassLoader(); myMultiCaster = (FileDocumentManagerListener)Proxy.newProxyInstance(loader, new Class[]{FileDocumentManagerListener.class}, handler); } private static void unwrapAndRethrow(Exception e) { Throwable unwrapped = e; if (e instanceof InvocationTargetException) { unwrapped = e.getCause() == null ? e : e.getCause(); } if (unwrapped instanceof Error) throw (Error)unwrapped; if (unwrapped instanceof RuntimeException) throw (RuntimeException)unwrapped; LOG.error(unwrapped); } @SuppressWarnings("OverlyBroadCatchBlock") private void multiCast(@NotNull Method method, Object[] args) { try { method.invoke(myBus.syncPublisher(AppTopics.FILE_DOCUMENT_SYNC), args); } catch (ClassCastException e) { LOG.error("Arguments: "+ Arrays.toString(args), e); } catch (Exception e) { unwrapAndRethrow(e); } // Allows pre-save document modification for (FileDocumentManagerListener listener : getListeners()) { try { method.invoke(listener, args); } catch (Exception e) { unwrapAndRethrow(e); } } // stripping trailing spaces try { method.invoke(myTrailingSpacesStripper, args); } catch (Exception e) { unwrapAndRethrow(e); } } @Override @Nullable public Document getDocument(@NotNull final VirtualFile file) { ApplicationManager.getApplication().assertReadAccessAllowed(); DocumentEx document = (DocumentEx)getCachedDocument(file); if (document == null) { if (!file.isValid() || file.isDirectory() || isBinaryWithoutDecompiler(file)) return null; boolean tooLarge = FileUtilRt.isTooLarge(file.getLength()); if (file.getFileType().isBinary() && tooLarge) return null; final CharSequence text = tooLarge ? LoadTextUtil.loadText(file, getPreviewCharCount(file)) : LoadTextUtil.loadText(file); synchronized (lock) { document = (DocumentEx)getCachedDocument(file); if (document != null) return document; // Double checking document = (DocumentEx)createDocument(text, file); document.setModificationStamp(file.getModificationStamp()); final FileType fileType = file.getFileType(); document.setReadOnly(tooLarge || !file.isWritable() || fileType.isBinary()); if (!(file instanceof LightVirtualFile || file.getFileSystem() instanceof NonPhysicalFileSystem)) { document.addDocumentListener(myPhysicalDocumentChangeTracker); } if (file instanceof LightVirtualFile) { registerDocument(document, file); } else { document.putUserData(FILE_KEY, file); cacheDocument(file, document); } } myMultiCaster.fileContentLoaded(file, document); } return document; } public static boolean areTooManyDocumentsInTheQueue(Collection<Document> documents) { if (documents.size() > 100) return true; int totalSize = 0; for (Document document : documents) { totalSize += document.getTextLength(); if (totalSize > FileUtilRt.LARGE_FOR_CONTENT_LOADING) return true; } return false; } private static Document createDocument(final CharSequence text, VirtualFile file) { boolean acceptSlashR = file instanceof LightVirtualFile && StringUtil.indexOf(text, '\r') >= 0; boolean freeThreaded = Boolean.TRUE.equals(file.getUserData(SingleRootFileViewProvider.FREE_THREADED)); return ((EditorFactoryImpl)EditorFactory.getInstance()).createDocument(text, acceptSlashR, freeThreaded); } @Override @Nullable public Document getCachedDocument(@NotNull VirtualFile file) { Document hard = file.getUserData(HARD_REF_TO_DOCUMENT_KEY); return hard != null ? hard : getDocumentFromCache(file); } public static void registerDocument(@NotNull final Document document, @NotNull VirtualFile virtualFile) { synchronized (lock) { document.putUserData(FILE_KEY, virtualFile); virtualFile.putUserData(HARD_REF_TO_DOCUMENT_KEY, document); } } @Override @Nullable public VirtualFile getFile(@NotNull Document document) { return document.getUserData(FILE_KEY); } @TestOnly public void dropAllUnsavedDocuments() { if (!ApplicationManager.getApplication().isUnitTestMode()) { throw new RuntimeException("This method is only for test mode!"); } ApplicationManager.getApplication().assertWriteAccessAllowed(); if (!myUnsavedDocuments.isEmpty()) { myUnsavedDocuments.clear(); fireUnsavedDocumentsDropped(); } } private void saveAllDocumentsLater() { // later because some document might have been blocked by PSI right now ApplicationManager.getApplication().invokeLater(() -> { if (ApplicationManager.getApplication().isDisposed()) { return; } final Document[] unsavedDocuments = getUnsavedDocuments(); for (Document document : unsavedDocuments) { VirtualFile file = getFile(document); if (file == null) continue; Project project = ProjectUtil.guessProjectForFile(file); if (project == null) continue; if (PsiDocumentManager.getInstance(project).isDocumentBlockedByPsi(document)) continue; saveDocument(document); } }); } @Override public void saveAllDocuments() { saveAllDocuments(true); } /** * @param isExplicit caused by user directly (Save action) or indirectly (e.g. Compile) */ public void saveAllDocuments(boolean isExplicit) { ApplicationManager.getApplication().assertIsDispatchThread(); ((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed(); myMultiCaster.beforeAllDocumentsSaving(); if (myUnsavedDocuments.isEmpty()) return; final Map<Document, IOException> failedToSave = new HashMap<>(); final Set<Document> vetoed = new HashSet<>(); while (true) { int count = 0; for (Document document : myUnsavedDocuments) { if (failedToSave.containsKey(document)) continue; if (vetoed.contains(document)) continue; try { doSaveDocument(document, isExplicit); } catch (IOException e) { //noinspection ThrowableResultOfMethodCallIgnored failedToSave.put(document, e); } catch (SaveVetoException e) { vetoed.add(document); } count++; } if (count == 0) break; } if (!failedToSave.isEmpty()) { handleErrorsOnSave(failedToSave); } } @Override public void saveDocument(@NotNull final Document document) { saveDocument(document, true); } public void saveDocument(@NotNull final Document document, final boolean explicit) { ApplicationManager.getApplication().assertIsDispatchThread(); ((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed(); if (!myUnsavedDocuments.contains(document)) return; try { doSaveDocument(document, explicit); } catch (IOException e) { handleErrorsOnSave(Collections.singletonMap(document, e)); } catch (SaveVetoException ignored) { } } @Override public void saveDocumentAsIs(@NotNull Document document) { VirtualFile file = getFile(document); boolean spaceStrippingEnabled = true; if (file != null) { spaceStrippingEnabled = TrailingSpacesStripper.isEnabled(file); TrailingSpacesStripper.setEnabled(file, false); } try { saveDocument(document); } finally { if (file != null) { TrailingSpacesStripper.setEnabled(file, spaceStrippingEnabled); } } } private static class SaveVetoException extends Exception {} private void doSaveDocument(@NotNull final Document document, boolean isExplicit) throws IOException, SaveVetoException { VirtualFile file = getFile(document); if (file == null || file instanceof LightVirtualFile || file.isValid() && !isFileModified(file)) { removeFromUnsaved(document); return; } if (file.isValid() && needsRefresh(file)) { file.refresh(false, false); if (!myUnsavedDocuments.contains(document)) return; } if (!maySaveDocument(file, document, isExplicit)) { throw new SaveVetoException(); } WriteAction.run(() -> doSaveDocumentInWriteAction(document, file)); } private boolean maySaveDocument(VirtualFile file, Document document, boolean isExplicit) { return !myConflictResolver.hasConflict(file) && Arrays.stream(Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)).allMatch(vetoer -> vetoer.maySaveDocument(document, isExplicit)); } private void doSaveDocumentInWriteAction(@NotNull final Document document, @NotNull final VirtualFile file) throws IOException { if (!file.isValid()) { removeFromUnsaved(document); return; } if (!file.equals(getFile(document))) { registerDocument(document, file); } if (!isSaveNeeded(document, file)) { if (document instanceof DocumentEx) { ((DocumentEx)document).setModificationStamp(file.getModificationStamp()); } removeFromUnsaved(document); updateModifiedProperty(file); return; } PomModelImpl.guardPsiModificationsIn(() -> { myMultiCaster.beforeDocumentSaving(document); LOG.assertTrue(file.isValid()); String text = document.getText(); String lineSeparator = getLineSeparator(document, file); if (!lineSeparator.equals("\n")) { text = StringUtil.convertLineSeparators(text, lineSeparator); } Project project = ProjectLocator.getInstance().guessProjectForFile(file); LoadTextUtil.write(project, file, this, text, document.getModificationStamp()); myUnsavedDocuments.remove(document); LOG.assertTrue(!myUnsavedDocuments.contains(document)); myTrailingSpacesStripper.clearLineModificationFlags(document); }); } private static void updateModifiedProperty(@NotNull VirtualFile file) { for (Project project : ProjectManager.getInstance().getOpenProjects()) { FileEditorManager fileEditorManager = FileEditorManager.getInstance(project); for (FileEditor editor : fileEditorManager.getAllEditors(file)) { if (editor instanceof TextEditorImpl) { ((TextEditorImpl)editor).updateModifiedProperty(); } } } } private void removeFromUnsaved(@NotNull Document document) { myUnsavedDocuments.remove(document); fireUnsavedDocumentsDropped(); LOG.assertTrue(!myUnsavedDocuments.contains(document)); } private static boolean isSaveNeeded(@NotNull Document document, @NotNull VirtualFile file) throws IOException { if (file.getFileType().isBinary() || document.getTextLength() > 1000 * 1000) { // don't compare if the file is too big return true; } byte[] bytes = file.contentsToByteArray(); CharSequence loaded = LoadTextUtil.getTextByBinaryPresentation(bytes, file, false, false); return !Comparing.equal(document.getCharsSequence(), loaded); } private static boolean needsRefresh(final VirtualFile file) { final VirtualFileSystem fs = file.getFileSystem(); return fs instanceof NewVirtualFileSystem && file.getTimeStamp() != ((NewVirtualFileSystem)fs).getTimeStamp(file); } @NotNull public static String getLineSeparator(@NotNull Document document, @NotNull VirtualFile file) { String lineSeparator = LoadTextUtil.getDetectedLineSeparator(file); if (lineSeparator == null) { lineSeparator = document.getUserData(LINE_SEPARATOR_KEY); assert lineSeparator != null : document; } return lineSeparator; } @Override @NotNull public String getLineSeparator(@Nullable VirtualFile file, @Nullable Project project) { String lineSeparator = file == null ? null : LoadTextUtil.getDetectedLineSeparator(file); if (lineSeparator == null) { CodeStyleFacade settingsManager = project == null ? CodeStyleFacade.getInstance() : CodeStyleFacade.getInstance(project); lineSeparator = settingsManager.getLineSeparator(); } return lineSeparator; } @Override public boolean requestWriting(@NotNull Document document, Project project) { final VirtualFile file = getInstance().getFile(document); if (project != null && file != null && file.isValid()) { return !file.getFileType().isBinary() && ReadonlyStatusHandler.ensureFilesWritable(project, file); } if (document.isWritable()) { return true; } document.fireReadOnlyModificationAttempt(); return false; } @Override public void reloadFiles(@NotNull final VirtualFile... files) { for (VirtualFile file : files) { if (file.exists()) { final Document doc = getCachedDocument(file); if (doc != null) { reloadFromDisk(doc); } } } } @Override @NotNull public Document[] getUnsavedDocuments() { if (myUnsavedDocuments.isEmpty()) { return Document.EMPTY_ARRAY; } List<Document> list = new ArrayList<>(myUnsavedDocuments); return list.toArray(new Document[list.size()]); } @Override public boolean isDocumentUnsaved(@NotNull Document document) { return myUnsavedDocuments.contains(document); } @Override public boolean isFileModified(@NotNull VirtualFile file) { final Document doc = getCachedDocument(file); return doc != null && isDocumentUnsaved(doc) && doc.getModificationStamp() != file.getModificationStamp(); } @Override public void propertyChanged(@NotNull VirtualFilePropertyEvent event) { final VirtualFile file = event.getFile(); if (VirtualFile.PROP_WRITABLE.equals(event.getPropertyName())) { final Document document = getCachedDocument(file); if (document != null) { ApplicationManager.getApplication().runWriteAction((ExternalChangeAction)() -> document.setReadOnly(!file.isWritable())); } } else if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) { Document document = getCachedDocument(file); if (document != null) { // a file is linked to a document - chances are it is an "unknown text file" now if (isBinaryWithoutDecompiler(file)) { unbindFileFromDocument(file, document); } } } } private void unbindFileFromDocument(@NotNull VirtualFile file, @NotNull Document document) { removeDocumentFromCache(file); file.putUserData(HARD_REF_TO_DOCUMENT_KEY, null); document.putUserData(FILE_KEY, null); } private static boolean isBinaryWithDecompiler(@NotNull VirtualFile file) { final FileType ft = file.getFileType(); return ft.isBinary() && BinaryFileTypeDecompilers.INSTANCE.forFileType(ft) != null; } private static boolean isBinaryWithoutDecompiler(@NotNull VirtualFile file) { final FileType fileType = file.getFileType(); return fileType.isBinary() && BinaryFileTypeDecompilers.INSTANCE.forFileType(fileType) == null; } @Override public void contentsChanged(@NotNull VirtualFileEvent event) { if (event.isFromSave()) return; final VirtualFile file = event.getFile(); final Document document = getCachedDocument(file); if (document == null) { myMultiCaster.fileWithNoDocumentChanged(file); return; } if (isBinaryWithDecompiler(file)) { myMultiCaster.fileWithNoDocumentChanged(file); // This will generate PSI event at FileManagerImpl } if (document.getModificationStamp() == event.getOldModificationStamp() || !isDocumentUnsaved(document)) { reloadFromDisk(document); } } @Override public void reloadFromDisk(@NotNull final Document document) { ApplicationManager.getApplication().assertIsDispatchThread(); final VirtualFile file = getFile(document); assert file != null; if (!fireBeforeFileContentReload(file, document)) { return; } final Project project = ProjectLocator.getInstance().guessProjectForFile(file); boolean[] isReloadable = {isReloadable(file, document, project)}; if (isReloadable[0]) { CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction( new ExternalChangeAction.ExternalDocumentChange(document, project) { @Override public void run() { if (!isBinaryWithoutDecompiler(file)) { LoadTextUtil.setCharsetWasDetectedFromBytes(file, null); file.setBOM(null); // reset BOM in case we had one and the external change stripped it away file.setCharset(null, null, false); boolean wasWritable = document.isWritable(); document.setReadOnly(false); boolean tooLarge = FileUtilRt.isTooLarge(file.getLength()); CharSequence reloaded = tooLarge ? LoadTextUtil.loadText(file, getPreviewCharCount(file)) : LoadTextUtil.loadText(file); isReloadable[0] = isReloadable(file, document, project); if (isReloadable[0]) { DocumentEx documentEx = (DocumentEx)document; documentEx.replaceText(reloaded, file.getModificationStamp()); } document.setReadOnly(!wasWritable); } } } ), UIBundle.message("file.cache.conflict.action"), null, UndoConfirmationPolicy.REQUEST_CONFIRMATION); } if (isReloadable[0]) { myMultiCaster.fileContentReloaded(file, document); } else { unbindFileFromDocument(file, document); myMultiCaster.fileWithNoDocumentChanged(file); } myUnsavedDocuments.remove(document); } private static boolean isReloadable(@NotNull VirtualFile file, @NotNull Document document, @Nullable Project project) { PsiFile cachedPsiFile = project == null ? null : PsiDocumentManager.getInstance(project).getCachedPsiFile(document); return !(FileUtilRt.isTooLarge(file.getLength()) && file.getFileType().isBinary()) && (cachedPsiFile == null || cachedPsiFile instanceof PsiFileImpl || isBinaryWithDecompiler(file)); } @TestOnly void setAskReloadFromDisk(@NotNull Disposable disposable, @NotNull MemoryDiskConflictResolver newProcessor) { final MemoryDiskConflictResolver old = myConflictResolver; myConflictResolver = newProcessor; Disposer.register(disposable, () -> myConflictResolver = old); } @Override public void fileDeleted(@NotNull VirtualFileEvent event) { Document doc = getCachedDocument(event.getFile()); if (doc != null) { myTrailingSpacesStripper.documentDeleted(doc); } } @Override public void beforeContentsChange(@NotNull VirtualFileEvent event) { VirtualFile virtualFile = event.getFile(); // check file type in second order to avoid content detection running if (virtualFile.getLength() == 0 && virtualFile.getFileType() == UnknownFileType.INSTANCE) { virtualFile.putUserData(MUST_RECOMPUTE_FILE_TYPE, Boolean.TRUE); } myConflictResolver.beforeContentChange(event); } public static boolean recomputeFileTypeIfNecessary(@NotNull VirtualFile virtualFile) { if (virtualFile.getUserData(MUST_RECOMPUTE_FILE_TYPE) != null) { virtualFile.getFileType(); virtualFile.putUserData(MUST_RECOMPUTE_FILE_TYPE, null); return true; } return false; } @Override public boolean canClose(@NotNull Project project) { if (!myUnsavedDocuments.isEmpty()) { myOnClose = true; try { saveAllDocuments(); } finally { myOnClose = false; } } return myUnsavedDocuments.isEmpty(); } private void fireUnsavedDocumentsDropped() { myMultiCaster.unsavedDocumentsDropped(); } private boolean fireBeforeFileContentReload(final VirtualFile file, @NotNull Document document) { for (FileDocumentSynchronizationVetoer vetoer : Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)) { try { if (!vetoer.mayReloadFileContent(file, document)) { return false; } } catch (Exception e) { LOG.error(e); } } myMultiCaster.beforeFileContentReload(file, document); return true; } @NotNull private static FileDocumentManagerListener[] getListeners() { return FileDocumentManagerListener.EP_NAME.getExtensions(); } private static int getPreviewCharCount(@NotNull VirtualFile file) { Charset charset = EncodingManager.getInstance().getEncoding(file, false); float bytesPerChar = charset == null ? 2 : charset.newEncoder().averageBytesPerChar(); return (int)(FileUtilRt.LARGE_FILE_PREVIEW_SIZE / bytesPerChar); } private void handleErrorsOnSave(@NotNull Map<Document, IOException> failures) { if (ApplicationManager.getApplication().isUnitTestMode()) { IOException ioException = ContainerUtil.getFirstItem(failures.values()); if (ioException != null) { throw new RuntimeException(ioException); } return; } for (IOException exception : failures.values()) { LOG.warn(exception); } final String text = StringUtil.join(failures.values(), Throwable::getMessage, "\n"); final DialogWrapper dialog = new DialogWrapper(null) { { init(); setTitle(UIBundle.message("cannot.save.files.dialog.title")); } @Override protected void createDefaultActions() { super.createDefaultActions(); myOKAction.putValue(Action.NAME, UIBundle .message(myOnClose ? "cannot.save.files.dialog.ignore.changes" : "cannot.save.files.dialog.revert.changes")); myOKAction.putValue(DEFAULT_ACTION, null); if (!myOnClose) { myCancelAction.putValue(Action.NAME, CommonBundle.getCloseButtonText()); } } @Override protected JComponent createCenterPanel() { final JPanel panel = new JPanel(new BorderLayout(0, 5)); panel.add(new JLabel(UIBundle.message("cannot.save.files.dialog.message")), BorderLayout.NORTH); final JTextPane area = new JTextPane(); area.setText(text); area.setEditable(false); area.setMinimumSize(new Dimension(area.getMinimumSize().width, 50)); panel.add(new JBScrollPane(area, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER), BorderLayout.CENTER); return panel; } }; if (dialog.showAndGet()) { for (Document document : failures.keySet()) { reloadFromDisk(document); } } } private final Map<VirtualFile, Document> myDocumentCache = ContainerUtil.createConcurrentWeakValueMap(); // used in Upsource protected void cacheDocument(@NotNull VirtualFile file, @NotNull Document document) { myDocumentCache.put(file, document); } // used in Upsource protected void removeDocumentFromCache(@NotNull VirtualFile file) { myDocumentCache.remove(file); } // used in Upsource protected Document getDocumentFromCache(@NotNull VirtualFile file) { return myDocumentCache.get(file); } }
Java
/** * 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. */ using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Org.Apache.REEF.Utilities.Diagnostics; using Org.Apache.REEF.Utilities.Logging; using Org.Apache.REEF.Wake.StreamingCodec; using Org.Apache.REEF.Wake.Util; namespace Org.Apache.REEF.Wake.Remote.Impl { /// <summary> /// Server to handle incoming remote messages. /// </summary> /// <typeparam name="T">Generic Type of message. It is constrained to have implemented IWritable and IType interface</typeparam> internal sealed class StreamingTransportServer<T> : IDisposable { private static readonly Logger LOGGER = Logger.GetLogger(typeof(TransportServer<>)); private TcpListener _listener; private readonly CancellationTokenSource _cancellationSource; private readonly IObserver<TransportEvent<T>> _remoteObserver; private readonly ITcpPortProvider _tcpPortProvider; private readonly IStreamingCodec<T> _streamingCodec; private bool _disposed; private Task _serverTask; /// <summary> /// Constructs a TransportServer to listen for remote events. /// Listens on the specified remote endpoint. When it receives a remote /// event, it will invoke the specified remote handler. /// </summary> /// <param name="address">Endpoint address to listen on</param> /// <param name="remoteHandler">The handler to invoke when receiving incoming /// remote messages</param> /// <param name="tcpPortProvider">Find port numbers if listenport is 0</param> /// <param name="streamingCodec">Streaming codec</param> internal StreamingTransportServer( IPAddress address, IObserver<TransportEvent<T>> remoteHandler, ITcpPortProvider tcpPortProvider, IStreamingCodec<T> streamingCodec) { _listener = new TcpListener(address, 0); _remoteObserver = remoteHandler; _tcpPortProvider = tcpPortProvider; _cancellationSource = new CancellationTokenSource(); _cancellationSource.Token.ThrowIfCancellationRequested(); _streamingCodec = streamingCodec; _disposed = false; } /// <summary> /// Returns the listening endpoint for the TransportServer /// </summary> public IPEndPoint LocalEndpoint { get { return _listener.LocalEndpoint as IPEndPoint; } } /// <summary> /// Starts listening for incoming remote messages. /// </summary> public void Run() { FindAPortAndStartListener(); _serverTask = Task.Run(() => StartServer()); } private void FindAPortAndStartListener() { var foundAPort = false; var exception = new SocketException((int)SocketError.AddressAlreadyInUse); for (var enumerator = _tcpPortProvider.GetEnumerator(); !foundAPort && enumerator.MoveNext();) { _listener = new TcpListener(LocalEndpoint.Address, enumerator.Current); try { _listener.Start(); foundAPort = true; } catch (SocketException e) { exception = e; } } if (!foundAPort) { Exceptions.Throw(exception, "Could not find a port to listen on", LOGGER); } LOGGER.Log(Level.Info, String.Format("Listening on {0}", _listener.LocalEndpoint.ToString())); } /// <summary> /// Close the TransportServer and all open connections /// </summary> public void Dispose() { if (!_disposed) { _cancellationSource.Cancel(); try { _listener.Stop(); } catch (SocketException) { LOGGER.Log(Level.Info, "Disposing of transport server before listener is created."); } if (_serverTask != null) { _serverTask.Wait(); // Give the TransportServer Task 500ms to shut down, ignore any timeout errors try { CancellationTokenSource serverDisposeTimeout = new CancellationTokenSource(500); _serverTask.Wait(serverDisposeTimeout.Token); } catch (Exception e) { Console.Error.WriteLine(e); } finally { _serverTask.Dispose(); } } } _disposed = true; } /// <summary> /// Helper method to start TransportServer. This will /// be run in an asynchronous Task. /// </summary> /// <returns>An asynchronous Task for the running server.</returns> private async Task StartServer() { try { while (!_cancellationSource.Token.IsCancellationRequested) { TcpClient client = await _listener.AcceptTcpClientAsync().ConfigureAwait(false); ProcessClient(client).Forget(); } } catch (InvalidOperationException) { LOGGER.Log(Level.Info, "TransportServer has been closed."); } catch (OperationCanceledException) { LOGGER.Log(Level.Info, "TransportServer has been closed."); } } /// <summary> /// Receives event from connected TcpClient and invokes handler on the event. /// </summary> /// <param name="client">The connected client</param> private async Task ProcessClient(TcpClient client) { // Keep reading messages from client until they disconnect or timeout CancellationToken token = _cancellationSource.Token; using (ILink<T> link = new StreamingLink<T>(client, _streamingCodec)) { while (!token.IsCancellationRequested) { T message = await link.ReadAsync(token); if (message == null) { break; } TransportEvent<T> transportEvent = new TransportEvent<T>(message, link); _remoteObserver.OnNext(transportEvent); } LOGGER.Log(Level.Error, "ProcessClient close the Link. IsCancellationRequested: " + token.IsCancellationRequested); } } } }
Java
/* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.cluster.impl; import com.hazelcast.config.Config; import com.hazelcast.config.InterfacesConfig; import com.hazelcast.config.NetworkConfig; import com.hazelcast.config.TcpIpConfig; import com.hazelcast.instance.Node; import com.hazelcast.internal.cluster.impl.AbstractJoiner; import com.hazelcast.internal.cluster.impl.ClusterServiceImpl; import com.hazelcast.internal.cluster.impl.SplitBrainJoinMessage; import com.hazelcast.internal.cluster.impl.operations.JoinMastershipClaimOp; import com.hazelcast.nio.Address; import com.hazelcast.nio.Connection; import com.hazelcast.spi.properties.GroupProperty; import com.hazelcast.util.AddressUtil; import com.hazelcast.util.AddressUtil.AddressMatcher; import com.hazelcast.util.AddressUtil.InvalidAddressException; import com.hazelcast.util.Clock; import com.hazelcast.util.EmptyStatement; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static com.hazelcast.util.AddressUtil.AddressHolder; public class TcpIpJoiner extends AbstractJoiner { private static final long JOIN_RETRY_WAIT_TIME = 1000L; private static final int LOOK_FOR_MASTER_MAX_TRY_COUNT = 20; private final int maxPortTryCount; private volatile boolean claimingMaster; public TcpIpJoiner(Node node) { super(node); int tryCount = node.getProperties().getInteger(GroupProperty.TCP_JOIN_PORT_TRY_COUNT); if (tryCount <= 0) { throw new IllegalArgumentException(String.format("%s should be greater than zero! Current value: %d", GroupProperty.TCP_JOIN_PORT_TRY_COUNT, tryCount)); } maxPortTryCount = tryCount; } public boolean isClaimingMaster() { return claimingMaster; } protected int getConnTimeoutSeconds() { return config.getNetworkConfig().getJoin().getTcpIpConfig().getConnectionTimeoutSeconds(); } @Override public void doJoin() { final Address targetAddress = getTargetAddress(); if (targetAddress != null) { long maxJoinMergeTargetMillis = node.getProperties().getMillis(GroupProperty.MAX_JOIN_MERGE_TARGET_SECONDS); joinViaTargetMember(targetAddress, maxJoinMergeTargetMillis); if (!clusterService.isJoined()) { joinViaPossibleMembers(); } } else if (config.getNetworkConfig().getJoin().getTcpIpConfig().getRequiredMember() != null) { Address requiredMember = getRequiredMemberAddress(); long maxJoinMillis = getMaxJoinMillis(); joinViaTargetMember(requiredMember, maxJoinMillis); } else { joinViaPossibleMembers(); } } private void joinViaTargetMember(Address targetAddress, long maxJoinMillis) { try { if (targetAddress == null) { throw new IllegalArgumentException("Invalid target address -> NULL"); } if (logger.isFineEnabled()) { logger.fine("Joining over target member " + targetAddress); } if (targetAddress.equals(node.getThisAddress()) || isLocalAddress(targetAddress)) { clusterJoinManager.setThisMemberAsMaster(); return; } long joinStartTime = Clock.currentTimeMillis(); Connection connection; while (shouldRetry() && (Clock.currentTimeMillis() - joinStartTime < maxJoinMillis)) { connection = node.connectionManager.getOrConnect(targetAddress); if (connection == null) { //noinspection BusyWait Thread.sleep(JOIN_RETRY_WAIT_TIME); continue; } if (logger.isFineEnabled()) { logger.fine("Sending joinRequest " + targetAddress); } clusterJoinManager.sendJoinRequest(targetAddress, true); //noinspection BusyWait Thread.sleep(JOIN_RETRY_WAIT_TIME); } } catch (final Exception e) { logger.warning(e); } } private void joinViaPossibleMembers() { try { blacklistedAddresses.clear(); Collection<Address> possibleAddresses = getPossibleAddresses(); boolean foundConnection = tryInitialConnection(possibleAddresses); if (!foundConnection) { logger.fine("This node will assume master role since no possible member where connected to."); clusterJoinManager.setThisMemberAsMaster(); return; } long maxJoinMillis = getMaxJoinMillis(); long startTime = Clock.currentTimeMillis(); while (shouldRetry() && (Clock.currentTimeMillis() - startTime < maxJoinMillis)) { tryToJoinPossibleAddresses(possibleAddresses); if (clusterService.isJoined()) { return; } if (isAllBlacklisted(possibleAddresses)) { logger.fine( "This node will assume master role since none of the possible members accepted join request."); clusterJoinManager.setThisMemberAsMaster(); return; } boolean masterCandidate = isThisNodeMasterCandidate(possibleAddresses); if (masterCandidate) { boolean consensus = claimMastership(possibleAddresses); if (consensus) { if (logger.isFineEnabled()) { Set<Address> votingEndpoints = new HashSet<Address>(possibleAddresses); votingEndpoints.removeAll(blacklistedAddresses.keySet()); logger.fine("Setting myself as master after consensus!" + " Voting endpoints: " + votingEndpoints); } clusterJoinManager.setThisMemberAsMaster(); claimingMaster = false; return; } } else { if (logger.isFineEnabled()) { logger.fine("Cannot claim myself as master! Will try to connect a possible master..."); } } claimingMaster = false; lookForMaster(possibleAddresses); } } catch (Throwable t) { logger.severe(t); } } @SuppressWarnings("checkstyle:npathcomplexity") private boolean claimMastership(Collection<Address> possibleAddresses) { if (logger.isFineEnabled()) { Set<Address> votingEndpoints = new HashSet<Address>(possibleAddresses); votingEndpoints.removeAll(blacklistedAddresses.keySet()); logger.fine("Claiming myself as master node! Asking to endpoints: " + votingEndpoints); } claimingMaster = true; Collection<Future<Boolean>> responses = new LinkedList<Future<Boolean>>(); for (Address address : possibleAddresses) { if (isBlacklisted(address)) { continue; } if (node.getConnectionManager().getConnection(address) != null) { Future<Boolean> future = node.nodeEngine.getOperationService() .createInvocationBuilder(ClusterServiceImpl.SERVICE_NAME, new JoinMastershipClaimOp(), address).setTryCount(1).invoke(); responses.add(future); } } final long maxWait = TimeUnit.SECONDS.toMillis(10); long waitTime = 0L; boolean consensus = true; for (Future<Boolean> response : responses) { long t = Clock.currentTimeMillis(); try { consensus = response.get(1, TimeUnit.SECONDS); } catch (Exception e) { logger.finest(e); consensus = false; } finally { waitTime += (Clock.currentTimeMillis() - t); } if (!consensus) { break; } if (waitTime > maxWait) { consensus = false; break; } } return consensus; } private boolean isThisNodeMasterCandidate(Collection<Address> possibleAddresses) { int thisHashCode = node.getThisAddress().hashCode(); for (Address address : possibleAddresses) { if (isBlacklisted(address)) { continue; } if (node.connectionManager.getConnection(address) != null) { if (thisHashCode > address.hashCode()) { return false; } } } return true; } private void tryToJoinPossibleAddresses(Collection<Address> possibleAddresses) throws InterruptedException { long connectionTimeoutMillis = TimeUnit.SECONDS.toMillis(getConnTimeoutSeconds()); long start = Clock.currentTimeMillis(); while (!clusterService.isJoined() && Clock.currentTimeMillis() - start < connectionTimeoutMillis) { Address masterAddress = clusterService.getMasterAddress(); if (isAllBlacklisted(possibleAddresses) && masterAddress == null) { return; } if (masterAddress != null) { if (logger.isFineEnabled()) { logger.fine("Sending join request to " + masterAddress); } clusterJoinManager.sendJoinRequest(masterAddress, true); } else { sendMasterQuestion(possibleAddresses); } if (!clusterService.isJoined()) { Thread.sleep(JOIN_RETRY_WAIT_TIME); } } } private boolean tryInitialConnection(Collection<Address> possibleAddresses) throws InterruptedException { long connectionTimeoutMillis = TimeUnit.SECONDS.toMillis(getConnTimeoutSeconds()); long start = Clock.currentTimeMillis(); while (Clock.currentTimeMillis() - start < connectionTimeoutMillis) { if (isAllBlacklisted(possibleAddresses)) { return false; } if (logger.isFineEnabled()) { logger.fine("Will send master question to each address in: " + possibleAddresses); } if (sendMasterQuestion(possibleAddresses)) { return true; } Thread.sleep(JOIN_RETRY_WAIT_TIME); } return false; } private boolean isAllBlacklisted(Collection<Address> possibleAddresses) { return blacklistedAddresses.keySet().containsAll(possibleAddresses); } @SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity"}) private void lookForMaster(Collection<Address> possibleAddresses) throws InterruptedException { int tryCount = 0; while (clusterService.getMasterAddress() == null && tryCount++ < LOOK_FOR_MASTER_MAX_TRY_COUNT) { sendMasterQuestion(possibleAddresses); //noinspection BusyWait Thread.sleep(JOIN_RETRY_WAIT_TIME); if (isAllBlacklisted(possibleAddresses)) { break; } } if (clusterService.isJoined()) { return; } if (isAllBlacklisted(possibleAddresses) && clusterService.getMasterAddress() == null) { if (logger.isFineEnabled()) { logger.fine("Setting myself as master! No possible addresses remaining to connect..."); } clusterJoinManager.setThisMemberAsMaster(); return; } long maxMasterJoinTime = getMaxJoinTimeToMasterNode(); long start = Clock.currentTimeMillis(); while (shouldRetry() && Clock.currentTimeMillis() - start < maxMasterJoinTime) { Address master = clusterService.getMasterAddress(); if (master != null) { if (logger.isFineEnabled()) { logger.fine("Joining to master " + master); } clusterJoinManager.sendJoinRequest(master, true); } else { break; } //noinspection BusyWait Thread.sleep(JOIN_RETRY_WAIT_TIME); } if (!clusterService.isJoined()) { Address master = clusterService.getMasterAddress(); if (master != null) { logger.warning("Couldn't join to the master: " + master); } else { if (logger.isFineEnabled()) { logger.fine("Couldn't find a master! But there was connections available: " + possibleAddresses); } } } } private boolean sendMasterQuestion(Collection<Address> possibleAddresses) { if (logger.isFineEnabled()) { logger.fine("NOT sending master question to blacklisted endpoints: " + blacklistedAddresses); } boolean sent = false; for (Address address : possibleAddresses) { if (isBlacklisted(address)) { continue; } if (logger.isFineEnabled()) { logger.fine("Sending master question to " + address); } if (clusterJoinManager.sendMasterQuestion(address)) { sent = true; } } return sent; } private Address getRequiredMemberAddress() { TcpIpConfig tcpIpConfig = config.getNetworkConfig().getJoin().getTcpIpConfig(); String host = tcpIpConfig.getRequiredMember(); try { AddressHolder addressHolder = AddressUtil.getAddressHolder(host, config.getNetworkConfig().getPort()); if (AddressUtil.isIpAddress(addressHolder.getAddress())) { return new Address(addressHolder.getAddress(), addressHolder.getPort()); } InterfacesConfig interfaces = config.getNetworkConfig().getInterfaces(); if (interfaces.isEnabled()) { InetAddress[] inetAddresses = InetAddress.getAllByName(addressHolder.getAddress()); if (inetAddresses.length > 1) { for (InetAddress inetAddress : inetAddresses) { if (AddressUtil.matchAnyInterface(inetAddress.getHostAddress(), interfaces.getInterfaces())) { return new Address(inetAddress, addressHolder.getPort()); } } } else if (AddressUtil.matchAnyInterface(inetAddresses[0].getHostAddress(), interfaces.getInterfaces())) { return new Address(addressHolder.getAddress(), addressHolder.getPort()); } } else { return new Address(addressHolder.getAddress(), addressHolder.getPort()); } } catch (final Exception e) { logger.warning(e); } return null; } @SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity"}) protected Collection<Address> getPossibleAddresses() { final Collection<String> possibleMembers = getMembers(); final Set<Address> possibleAddresses = new HashSet<Address>(); final NetworkConfig networkConfig = config.getNetworkConfig(); for (String possibleMember : possibleMembers) { AddressHolder addressHolder = AddressUtil.getAddressHolder(possibleMember); try { boolean portIsDefined = addressHolder.getPort() != -1 || !networkConfig.isPortAutoIncrement(); int count = portIsDefined ? 1 : maxPortTryCount; int port = addressHolder.getPort() != -1 ? addressHolder.getPort() : networkConfig.getPort(); AddressMatcher addressMatcher = null; try { addressMatcher = AddressUtil.getAddressMatcher(addressHolder.getAddress()); } catch (InvalidAddressException ignore) { EmptyStatement.ignore(ignore); } if (addressMatcher != null) { final Collection<String> matchedAddresses; if (addressMatcher.isIPv4()) { matchedAddresses = AddressUtil.getMatchingIpv4Addresses(addressMatcher); } else { // for IPv6 we are not doing wildcard matching matchedAddresses = Collections.singleton(addressHolder.getAddress()); } for (String matchedAddress : matchedAddresses) { addPossibleAddresses(possibleAddresses, null, InetAddress.getByName(matchedAddress), port, count); } } else { final String host = addressHolder.getAddress(); final InterfacesConfig interfaces = networkConfig.getInterfaces(); if (interfaces.isEnabled()) { final InetAddress[] inetAddresses = InetAddress.getAllByName(host); for (InetAddress inetAddress : inetAddresses) { if (AddressUtil.matchAnyInterface(inetAddress.getHostAddress(), interfaces.getInterfaces())) { addPossibleAddresses(possibleAddresses, host, inetAddress, port, count); } } } else { addPossibleAddresses(possibleAddresses, host, null, port, count); } } } catch (UnknownHostException e) { logger.warning("Cannot resolve hostname '" + addressHolder.getAddress() + "'. Please make sure host is valid and reachable."); if (logger.isFineEnabled()) { logger.fine("Error during resolving possible target!", e); } } } possibleAddresses.remove(node.getThisAddress()); return possibleAddresses; } private void addPossibleAddresses(final Set<Address> possibleAddresses, final String host, final InetAddress inetAddress, final int port, final int count) throws UnknownHostException { for (int i = 0; i < count; i++) { int currentPort = port + i; Address address; if (host != null && inetAddress != null) { address = new Address(host, inetAddress, currentPort); } else if (host != null) { address = new Address(host, currentPort); } else { address = new Address(inetAddress, currentPort); } if (!isLocalAddress(address)) { possibleAddresses.add(address); } } } private boolean isLocalAddress(final Address address) throws UnknownHostException { final Address thisAddress = node.getThisAddress(); final boolean local = thisAddress.getInetSocketAddress().equals(address.getInetSocketAddress()); if (logger.isFineEnabled()) { logger.fine(address + " is local? " + local); } return local; } protected Collection<String> getMembers() { return getConfigurationMembers(config); } public static Collection<String> getConfigurationMembers(Config config) { final TcpIpConfig tcpIpConfig = config.getNetworkConfig().getJoin().getTcpIpConfig(); final Collection<String> configMembers = tcpIpConfig.getMembers(); final Set<String> possibleMembers = new HashSet<String>(); for (String member : configMembers) { // split members defined in tcp-ip configuration by comma(,) semi-colon(;) space( ). String[] members = member.split("[,; ]"); Collections.addAll(possibleMembers, members); } return possibleMembers; } @Override public void searchForOtherClusters() { final Collection<Address> possibleAddresses; try { possibleAddresses = getPossibleAddresses(); } catch (Throwable e) { logger.severe(e); return; } possibleAddresses.remove(node.getThisAddress()); possibleAddresses.removeAll(node.getClusterService().getMemberAddresses()); if (possibleAddresses.isEmpty()) { return; } for (Address address : possibleAddresses) { SplitBrainJoinMessage response = sendSplitBrainJoinMessage(address); if (shouldMerge(response)) { logger.warning(node.getThisAddress() + " is merging [tcp/ip] to " + address); setTargetAddress(address); startClusterMerge(address); return; } } } @Override public String getType() { return "tcp-ip"; } }
Java
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """mixup: Beyond Empirical Risk Minimization. Adaption to SSL of MixUp: https://arxiv.org/abs/1710.09412 """ import functools import os import tensorflow as tf from absl import app from absl import flags from libml import data, utils, models from libml.utils import EasyDict FLAGS = flags.FLAGS class Mixup(models.MultiModel): def augment(self, x, l, beta, **kwargs): del kwargs mix = tf.distributions.Beta(beta, beta).sample([tf.shape(x)[0], 1, 1, 1]) mix = tf.maximum(mix, 1 - mix) xmix = x * mix + x[::-1] * (1 - mix) lmix = l * mix[:, :, 0, 0] + l[::-1] * (1 - mix[:, :, 0, 0]) return xmix, lmix def model(self, batch, lr, wd, ema, **kwargs): hwc = [self.dataset.height, self.dataset.width, self.dataset.colors] xt_in = tf.placeholder(tf.float32, [batch] + hwc, 'xt') # For training x_in = tf.placeholder(tf.float32, [None] + hwc, 'x') y_in = tf.placeholder(tf.float32, [batch] + hwc, 'y') l_in = tf.placeholder(tf.int32, [batch], 'labels') wd *= lr classifier = lambda x, **kw: self.classifier(x, **kw, **kwargs).logits def get_logits(x): logits = classifier(x, training=True) return logits x, labels_x = self.augment(xt_in, tf.one_hot(l_in, self.nclass), **kwargs) logits_x = get_logits(x) post_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) y, labels_y = self.augment(y_in, tf.nn.softmax(get_logits(y_in)), **kwargs) labels_y = tf.stop_gradient(labels_y) logits_y = get_logits(y) loss_xe = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels_x, logits=logits_x) loss_xe = tf.reduce_mean(loss_xe) loss_xeu = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels_y, logits=logits_y) loss_xeu = tf.reduce_mean(loss_xeu) tf.summary.scalar('losses/xe', loss_xe) tf.summary.scalar('losses/xeu', loss_xeu) ema = tf.train.ExponentialMovingAverage(decay=ema) ema_op = ema.apply(utils.model_vars()) ema_getter = functools.partial(utils.getter_ema, ema) post_ops.append(ema_op) post_ops.extend([tf.assign(v, v * (1 - wd)) for v in utils.model_vars('classify') if 'kernel' in v.name]) train_op = tf.train.AdamOptimizer(lr).minimize(loss_xe + loss_xeu, colocate_gradients_with_ops=True) with tf.control_dependencies([train_op]): train_op = tf.group(*post_ops) return EasyDict( xt=xt_in, x=x_in, y=y_in, label=l_in, train_op=train_op, classify_raw=tf.nn.softmax(classifier(x_in, training=False)), # No EMA, for debugging. classify_op=tf.nn.softmax(classifier(x_in, getter=ema_getter, training=False))) def main(argv): utils.setup_main() del argv # Unused. dataset = data.DATASETS()[FLAGS.dataset]() log_width = utils.ilog2(dataset.width) model = Mixup( os.path.join(FLAGS.train_dir, dataset.name), dataset, lr=FLAGS.lr, wd=FLAGS.wd, arch=FLAGS.arch, batch=FLAGS.batch, nclass=dataset.nclass, ema=FLAGS.ema, beta=FLAGS.beta, scales=FLAGS.scales or (log_width - 2), filters=FLAGS.filters, repeat=FLAGS.repeat) model.train(FLAGS.train_kimg << 10, FLAGS.report_kimg << 10) if __name__ == '__main__': utils.setup_tf() flags.DEFINE_float('wd', 0.02, 'Weight decay.') flags.DEFINE_float('ema', 0.999, 'Exponential moving average of params.') flags.DEFINE_float('beta', 0.5, 'Mixup beta distribution.') flags.DEFINE_integer('scales', 0, 'Number of 2x2 downscalings in the classifier.') flags.DEFINE_integer('filters', 32, 'Filter size of convolutions.') flags.DEFINE_integer('repeat', 4, 'Number of residual layers per stage.') FLAGS.set_default('dataset', 'cifar10.3@250-5000') FLAGS.set_default('batch', 64) FLAGS.set_default('lr', 0.002) FLAGS.set_default('train_kimg', 1 << 16) app.run(main)
Java
package connect import ( "strings" "testing" ) func TestCatalogCommand_noTabs(t *testing.T) { t.Parallel() if strings.ContainsRune(New().Help(), '\t') { t.Fatal("help has tabs") } }
Java
/** * 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. */ #ifndef ORC_STRIPE_STREAM_HH #define ORC_STRIPE_STREAM_HH #include "orc/Int128.hh" #include "orc/OrcFile.hh" #include "orc/Reader.hh" #include "Timezone.hh" #include "TypeImpl.hh" namespace orc { class RowReaderImpl; /** * StripeStream Implementation */ class StripeStreamsImpl: public StripeStreams { private: const RowReaderImpl& reader; const proto::StripeInformation& stripeInfo; const proto::StripeFooter& footer; const uint64_t stripeIndex; const uint64_t stripeStart; InputStream& input; const Timezone& writerTimezone; const Timezone& readerTimezone; public: StripeStreamsImpl(const RowReaderImpl& reader, uint64_t index, const proto::StripeInformation& stripeInfo, const proto::StripeFooter& footer, uint64_t stripeStart, InputStream& input, const Timezone& writerTimezone, const Timezone& readerTimezone); virtual ~StripeStreamsImpl() override; virtual const std::vector<bool> getSelectedColumns() const override; virtual proto::ColumnEncoding getEncoding(uint64_t columnId ) const override; virtual std::unique_ptr<SeekableInputStream> getStream(uint64_t columnId, proto::Stream_Kind kind, bool shouldStream) const override; MemoryPool& getMemoryPool() const override; const Timezone& getWriterTimezone() const override; const Timezone& getReaderTimezone() const override; std::ostream* getErrorStream() const override; bool getThrowOnHive11DecimalOverflow() const override; int32_t getForcedScaleOnHive11Decimal() const override; }; /** * StreamInformation Implementation */ class StreamInformationImpl: public StreamInformation { private: StreamKind kind; uint64_t column; uint64_t offset; uint64_t length; public: StreamInformationImpl(uint64_t _offset, const proto::Stream& stream ): kind(static_cast<StreamKind>(stream.kind())), column(stream.column()), offset(_offset), length(stream.length()) { // PASS } ~StreamInformationImpl() override; StreamKind getKind() const override { return kind; } uint64_t getColumnId() const override { return column; } uint64_t getOffset() const override { return offset; } uint64_t getLength() const override { return length; } }; /** * StripeInformation Implementation */ class StripeInformationImpl : public StripeInformation { uint64_t offset; uint64_t indexLength; uint64_t dataLength; uint64_t footerLength; uint64_t numRows; InputStream* stream; MemoryPool& memory; CompressionKind compression; uint64_t blockSize; mutable std::unique_ptr<proto::StripeFooter> stripeFooter; void ensureStripeFooterLoaded() const; public: StripeInformationImpl(uint64_t _offset, uint64_t _indexLength, uint64_t _dataLength, uint64_t _footerLength, uint64_t _numRows, InputStream* _stream, MemoryPool& _memory, CompressionKind _compression, uint64_t _blockSize ) : offset(_offset), indexLength(_indexLength), dataLength(_dataLength), footerLength(_footerLength), numRows(_numRows), stream(_stream), memory(_memory), compression(_compression), blockSize(_blockSize) { // PASS } virtual ~StripeInformationImpl() override { // PASS } uint64_t getOffset() const override { return offset; } uint64_t getLength() const override { return indexLength + dataLength + footerLength; } uint64_t getIndexLength() const override { return indexLength; } uint64_t getDataLength()const override { return dataLength; } uint64_t getFooterLength() const override { return footerLength; } uint64_t getNumberOfRows() const override { return numRows; } uint64_t getNumberOfStreams() const override { ensureStripeFooterLoaded(); return static_cast<uint64_t>(stripeFooter->streams_size()); } std::unique_ptr<StreamInformation> getStreamInformation(uint64_t streamId ) const override; ColumnEncodingKind getColumnEncoding(uint64_t colId) const override { ensureStripeFooterLoaded(); return static_cast<ColumnEncodingKind>(stripeFooter-> columns(static_cast<int>(colId)) .kind()); } uint64_t getDictionarySize(uint64_t colId) const override { ensureStripeFooterLoaded(); return static_cast<ColumnEncodingKind>(stripeFooter-> columns(static_cast<int>(colId)) .dictionarysize()); } const std::string& getWriterTimezone() const override { ensureStripeFooterLoaded(); return stripeFooter->writertimezone(); } }; } #endif
Java
@charset "utf-8"; /* CSS Document */
Java
# Copyright 2015 Metaswitch Networks # # 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 unittest from mock import patch, Mock, call from nose_parameterized import parameterized from netaddr import IPAddress, IPNetwork from subprocess import CalledProcessError from calico_ctl.bgp import * from calico_ctl import container from calico_ctl import utils from pycalico.datastore_datatypes import Endpoint, IPPool class TestContainer(unittest.TestCase): @parameterized.expand([ ({'<CONTAINER>':'node1', 'ip':1, 'add':1, '<IP>':'127.a.0.1'}, True), ({'<CONTAINER>':'node1', 'ip':1, 'add':1, '<IP>':'aa:bb::zz'}, True), ({'add':1, '<CONTAINER>':'node1', '<IP>':'127.a.0.1'}, True), ({'add':1, '<CONTAINER>':'node1', '<IP>':'aa:bb::zz'}, True) ]) def test_validate_arguments(self, case, sys_exit_called): """ Test validate_arguments for calicoctl container command """ with patch('sys.exit', autospec=True) as m_sys_exit: # Call method under test container.validate_arguments(case) # Assert method exits if bad input self.assertEqual(m_sys_exit.called, sys_exit_called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.netns', autospec=True) def test_container_add(self, m_netns, m_get_pool_or_exit, m_client, m_get_container_info_or_exit, m_enforce_root): """ Test container_add method of calicoctl container command """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'}, 'HostConfig': {'NetworkMode': "not host"} } m_client.get_endpoint.side_effect = KeyError m_client.get_default_next_hops.return_value = 'next_hops' # Call method under test test_return = container.container_add('container1', '1.1.1.1', 'interface') # Assert m_enforce_root.assert_called_once_with() m_get_container_info_or_exit.assert_called_once_with('container1') m_client.get_endpoint.assert_called_once_with( hostname=utils.hostname, orchestrator_id=utils.ORCHESTRATOR_ID, workload_id=666 ) m_get_pool_or_exit.assert_called_once_with(IPAddress('1.1.1.1')) m_client.get_default_next_hops.assert_called_once_with(utils.hostname) # Check an enpoint object was returned self.assertTrue(isinstance(test_return, Endpoint)) self.assertTrue(m_netns.create_veth.called) self.assertTrue(m_netns.move_veth_into_ns.called) self.assertTrue(m_netns.add_ip_to_ns_veth.called) self.assertTrue(m_netns.add_ns_default_route.called) self.assertTrue(m_netns.get_ns_veth_mac.called) self.assertTrue(m_client.set_endpoint.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) def test_container_add_container_host_ns(self, m_client, m_get_container_info_or_exit, m_enforce_root): """ Test container_add method of calicoctl container command when the container shares the host namespace. """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'}, 'HostConfig': {'NetworkMode': 'host'} } m_client.get_endpoint.side_effect = KeyError # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_add, 'container1', '1.1.1.1', 'interface') m_enforce_root.assert_called_once_with() @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) def test_container_add_existing_container( self, m_get_pool_or_exit, m_client, m_get_container_info_or_exit, m_enforce_root): """ Test container_add when a container already exists. Do not raise an exception when the client tries 'get_endpoint' Assert that the system then exits and all expected calls are made """ # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_add, 'container1', '1.1.1.1', 'interface') # Assert only expected calls were made self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertFalse(m_get_pool_or_exit.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) def test_container_add_container_not_running( self, m_get_pool_or_exit, m_client, m_get_container_info_or_exit, m_enforce_root): """ Test container_add when a container is not running get_container_info_or_exit returns a running state of value 0 Assert that the system then exits and all expected calls are made """ # Set up mock object m_client.get_endpoint.side_effect = KeyError m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 0, 'Pid': 'Pid_info'} } # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_add, 'container1', '1.1.1.1', 'interface') # Assert only expected calls were made self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertFalse(m_get_pool_or_exit.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) def test_container_add_not_ipv4_configured( self, m_get_pool_or_exit, m_client, m_get_container_info_or_exit, m_enforce_root): """ Test container_add when the client cannot obtain next hop IPs client.get_default_next_hops returns an empty dictionary, which produces a KeyError when trying to determine the IP. Assert that the system then exits and all expected calls are made """ # Set up mock objects m_client.get_endpoint.side_effect = KeyError m_client.get_default_next_hops.return_value = {} # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_add, 'container1', '1.1.1.1', 'interface') # Assert only expected calls were made self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_client.get_default_next_hops.called) self.assertFalse(m_client.assign_address.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.netns', autospec=True) def test_container_add_ip_previously_assigned( self, m_netns, m_get_pool_or_exit, m_client, m_get_container_info_or_exit, m_enforce_root): """ Test container_add when an ip address is already assigned in pool client.assign_address returns an empty list. Assert that the system then exits and all expected calls are made """ # Set up mock object m_client.get_endpoint.side_effect = KeyError m_client.assign_address.return_value = [] # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_add, 'container1', '1.1.1.1', 'interface') # Assert only expected calls were made self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_client.get_default_next_hops.called) self.assertTrue(m_client.assign_address.called) self.assertFalse(m_netns.create_veth.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_container_id', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.netns', autospec=True) def test_container_remove(self, m_netns, m_client, m_get_container_id, m_enforce_root): """ Test for container_remove of calicoctl container command """ # Set up mock objects m_get_container_id.return_value = 666 ipv4_nets = set() ipv4_nets.add(IPNetwork(IPAddress('1.1.1.1'))) ipv6_nets = set() m_endpoint = Mock(spec=Endpoint) m_endpoint.ipv4_nets = ipv4_nets m_endpoint.ipv6_nets = ipv6_nets m_endpoint.endpoint_id = 12 m_endpoint.name = "eth1234" ippool = IPPool('1.1.1.1/24') m_client.get_endpoint.return_value = m_endpoint m_client.get_ip_pools.return_value = [ippool] # Call method under test container.container_remove('container1') # Assert m_enforce_root.assert_called_once_with() m_get_container_id.assert_called_once_with('container1') m_client.get_endpoint.assert_called_once_with( hostname=utils.hostname, orchestrator_id=utils.ORCHESTRATOR_ID, workload_id=666 ) self.assertEqual(m_client.unassign_address.call_count, 1) m_netns.remove_veth.assert_called_once_with("eth1234") m_client.remove_workload.assert_called_once_with( utils.hostname, utils.ORCHESTRATOR_ID, 666) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_container_id', autospec=True) @patch('calico_ctl.container.client', autospec=True) def test_container_remove_no_endpoint( self, m_client, m_get_container_id, m_enforce_root): """ Test for container_remove when the client cannot obtain an endpoint client.get_endpoint raises a KeyError. Assert that the system then exits and all expected calls are made """ # Set up mock objects m_client.get_endpoint.side_effect = KeyError # Call function under test expecting a SystemExit self.assertRaises(SystemExit, container.container_remove, 'container1') # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_container_id.called) self.assertTrue(m_client.get_endpoint.called) self.assertFalse(m_client.get_ip_pools.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.netns', autospec=True) def test_container_ip_add_ipv4( self, m_netns, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test for container_ip_add with an ipv4 ip argument Assert that the correct calls associated with an ipv4 address are made """ # Set up mock objects pool_return = 'pool' m_get_pool_or_exit.return_value = pool_return m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } m_endpoint = Mock() m_client.get_endpoint.return_value = m_endpoint # Set up arguments to pass to method under test container_name = 'container1' ip = '1.1.1.1' ip_addr = IPAddress(ip) interface = 'interface' # Call method under test container.container_ip_add(container_name, ip, interface) # Assert m_enforce_root.assert_called_once_with() m_get_pool_or_exit.assert_called_once_with(ip_addr) m_get_container_info_or_exit.assert_called_once_with(container_name) m_client.get_endpoint.assert_called_once_with( hostname=utils.hostname, orchestrator_id=utils.ORCHESTRATOR_ID, workload_id=666 ) m_client.assign_address.assert_called_once_with(pool_return, ip_addr) m_endpoint.ipv4_nets.add.assert_called_once_with(IPNetwork(ip_addr)) m_client.update_endpoint.assert_called_once_with(m_endpoint) m_netns.add_ip_to_ns_veth.assert_called_once_with( 'Pid_info', ip_addr, interface ) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.netns', autospec=True) def test_container_ip_add_ipv6( self, m_netns, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test for container_ip_add with an ipv6 ip argument Assert that the correct calls associated with an ipv6 address are made """ # Set up mock objects pool_return = 'pool' m_get_pool_or_exit.return_value = pool_return m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } m_endpoint = Mock() m_client.get_endpoint.return_value = m_endpoint # Set up arguments to pass to method under test container_name = 'container1' ip = '1::1' ip_addr = IPAddress(ip) interface = 'interface' # Call method under test container.container_ip_add(container_name, ip, interface) # Assert m_enforce_root.assert_called_once_with() m_get_pool_or_exit.assert_called_once_with(ip_addr) m_get_container_info_or_exit.assert_called_once_with(container_name) m_client.get_endpoint.assert_called_once_with( hostname=utils.hostname, orchestrator_id=utils.ORCHESTRATOR_ID, workload_id=666 ) m_client.assign_address.assert_called_once_with(pool_return, ip_addr) m_endpoint.ipv6_nets.add.assert_called_once_with(IPNetwork(ip_addr)) m_client.update_endpoint.assert_called_once_with(m_endpoint) m_netns.add_ip_to_ns_veth.assert_called_once_with( 'Pid_info', ip_addr, interface ) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client.get_endpoint', autospec=True) def test_container_ip_add_container_not_running( self, m_client_get_endpoint, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test for container_ip_add when the container is not running get_container_info_or_exit returns a running state of value 0. Assert that the system then exits and all expected calls are made """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 0, 'Pid': 'Pid_info'} } # Set up arguments to pass to method under test container_name = 'container1' ip = '1.1.1.1' interface = 'interface' # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_ip_add, container_name, ip, interface) # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_get_pool_or_exit.called) self.assertFalse(m_client_get_endpoint.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.print_container_not_in_calico_msg', autospec=True) def test_container_ip_add_container_not_in_calico( self, m_print_container_not_in_calico_msg, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test for container_ip_add when the container is not networked into calico client.get_endpoint raises a KeyError. Assert that the system then exits and all expected calls are made """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } m_client.get_endpoint.return_value = Mock() m_client.get_endpoint.side_effect = KeyError # Set up arguments to pass to method under test container_name = 'container1' ip = '1.1.1.1' interface = 'interface' # Call method under test expecting a System Exit self.assertRaises(SystemExit, container.container_ip_add, container_name, ip, interface) # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) m_print_container_not_in_calico_msg.assert_called_once_with(container_name) self.assertFalse(m_client.assign_address.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.netns', autospec=True) def test_container_ip_add_fail_assign_address( self, m_netns, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test for container_ip_add when the client cannot assign an IP client.assign_address returns an empty list. Assert that the system then exits and all expected calls are made """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } m_client.assign_address.return_value = [] # Set up arguments to pass to method under test container_name = 'container1' ip = '1.1.1.1' interface = 'interface' # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_ip_add, container_name, ip, interface) # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertFalse(m_netns.add_ip_to_ns_veth.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.netns.add_ip_to_ns_veth', autospec=True) def test_container_ip_add_error_updating_datastore( self, m_netns_add_ip_to_ns_veth, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test for container_ip_add when the client fails to update endpoint client.update_endpoint raises a KeyError. Assert that the system then exits and all expected calls are made """ # Set up mock objects m_get_pool_or_exit.return_value = 'pool' m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } m_client.update_endpoint.side_effect = KeyError # Set up arguments to pass to method under test container_name = 'container1' ip = '1.1.1.1' interface = 'interface' # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_ip_add, container_name, ip, interface) # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertTrue(m_client.assign_address.called) m_client.unassign_address.assert_called_once_with('pool', ip) self.assertFalse(m_netns_add_ip_to_ns_veth.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.netns.add_ip_to_ns_veth', autospec=True) def test_container_ip_add_netns_error_ipv4( self, m_netns_add_ip_to_ns_veth, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test container_ip_add when netns cannot add an ipv4 to interface netns.add_ip_to_ns_veth throws a CalledProcessError. Assert that the system then exits and all expected calls are made """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } m_get_pool_or_exit.return_value = 'pool' m_endpoint = Mock() m_client.get_endpoint.return_value = m_endpoint err = CalledProcessError( 1, m_netns_add_ip_to_ns_veth, "Error updating container") m_netns_add_ip_to_ns_veth.side_effect = err # Set up arguments to pass to method under test container_name = 'container1' ip = '1.1.1.1' interface = 'interface' # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_ip_add, container_name, ip, interface) # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertTrue(m_client.assign_address.called) self.assertTrue(m_netns_add_ip_to_ns_veth.called) m_endpoint.ipv4_nets.remove.assert_called_once_with( IPNetwork(IPAddress(ip)) ) m_client.update_endpoint.assert_has_calls([ call(m_endpoint), call(m_endpoint)]) m_client.unassign_address.assert_called_once_with('pool', ip) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.print_container_not_in_calico_msg', autospec=True) @patch('calico_ctl.container.netns.add_ip_to_ns_veth', autospec=True) def test_container_ip_add_netns_error_ipv6( self, m_netns, m_print_container_not_in_calico_msg, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test container_ip_add when netns cannot add an ipv6 to interface netns.add_ip_to_ns_veth throws a CalledProcessError. Assert that the system then exits and all expected calls are made """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } m_get_pool_or_exit.return_value = 'pool' m_endpoint = Mock() m_client.get_endpoint.return_value = m_endpoint err = CalledProcessError(1, m_netns, "Error updating container") m_netns.side_effect = err # Set up arguments to pass to method under test container_name = 'container1' ip = '1::1' interface = 'interface' # Call method under test self.assertRaises(SystemExit, container.container_ip_add, container_name, ip, interface) # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertTrue(m_client.assign_address.called) self.assertTrue(m_netns.called) m_endpoint.ipv6_nets.remove.assert_called_once_with( IPNetwork(IPAddress(ip)) ) m_client.update_endpoint.assert_has_calls([ call(m_endpoint), call(m_endpoint)]) m_client.unassign_address.assert_called_once_with('pool', ip) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.netns', autospec=True) def test_container_ip_remove_ipv4(self, m_netns, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test container_ip_remove with an ipv4 ip argument """ # Set up mock objects m_get_pool_or_exit.return_value = 'pool' m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } ipv4_nets = set() ipv4_nets.add(IPNetwork(IPAddress('1.1.1.1'))) m_endpoint = Mock(spec=Endpoint) m_endpoint.ipv4_nets = ipv4_nets m_client.get_endpoint.return_value = m_endpoint # Set up arguments to pass to method under test container_name = 'container1' ip = '1.1.1.1' interface = 'interface' # Call method under test container.container_ip_remove(container_name, ip, interface) # Assert m_enforce_root.assert_called_once_with() m_get_pool_or_exit.assert_called_once_with(IPAddress(ip)) m_get_container_info_or_exit.assert_called_once_with(container_name) m_client.get_endpoint.assert_called_once_with( hostname=utils.hostname, orchestrator_id=utils.ORCHESTRATOR_ID, workload_id=666 ) m_client.update_endpoint.assert_called_once_with(m_endpoint) m_netns.remove_ip_from_ns_veth.assert_called_once_with( 'Pid_info', IPAddress(ip), interface ) m_client.unassign_address.assert_called_once_with('pool', ip) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.netns', autospec=True) def test_container_ip_remove_ipv6(self, m_netns, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test for container_ip_remove with an ipv6 ip argument """ # Set up mock objects m_get_pool_or_exit.return_value = 'pool' m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } ipv6_nets = set() ipv6_nets.add(IPNetwork(IPAddress('1::1'))) m_endpoint = Mock(spec=Endpoint) m_endpoint.ipv6_nets = ipv6_nets m_client.get_endpoint.return_value = m_endpoint # Set up arguments to pass to method under test container_name = 'container1' ip = '1::1' interface = 'interface' # Call method under test container.container_ip_remove(container_name, ip, interface) # Assert m_enforce_root.assert_called_once_with() m_get_pool_or_exit.assert_called_once_with(IPAddress(ip)) m_get_container_info_or_exit.assert_called_once_with(container_name) m_client.get_endpoint.assert_called_once_with( hostname=utils.hostname, orchestrator_id=utils.ORCHESTRATOR_ID, workload_id=666 ) m_client.update_endpoint.assert_called_once_with(m_endpoint) m_netns.remove_ip_from_ns_veth.assert_called_once_with( 'Pid_info', IPAddress(ip), interface ) m_client.unassign_address.assert_called_once_with('pool', ip) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) def test_container_ip_remove_not_running( self, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test for container_ip_remove when the container is not running get_container_info_or_exit returns a running state of value 0. Assert that the system then exits and all expected calls are made """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 0, 'Pid': 'Pid_info'} } # Set up arguments to pass to method under test container_name = 'container1' ip = '1::1' interface = 'interface' # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_ip_remove, container_name, ip, interface) # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertFalse(m_client.get_endpoint.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) def test_container_ip_remove_ip_not_assigned( self, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test container_ip_remove when an IP address is not assigned to a container client.get_endpoint returns an endpoint with no ip nets Assert that the system then exits and all expected calls are made """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } ipv6_nets = set() m_endpoint = Mock(spec=Endpoint) m_endpoint.ipv6_nets = ipv6_nets m_client.get_endpoint.return_value = m_endpoint # Set up arguments to pass to method under test container_name = 'container1' ip = '1::1' interface = 'interface' # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_ip_remove, container_name, ip, interface) # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertFalse(m_client.update_endpoint.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) def test_container_ip_remove_container_not_on_calico( self, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test for container_ip_remove when container is not networked into Calico client.get_endpoint raises a KeyError Assert that the system then exits and all expected calls are made """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } m_client.get_endpoint.side_effect = KeyError # Set up arguments to pass to method under test container_name = 'container1' ip = '1::1' interface = 'interface' # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_ip_remove, container_name, ip, interface) # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertFalse(m_client.update_endpoint.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.netns', autospec=True) def test_container_ip_remove_fail_updating_datastore( self, m_netns, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test container_ip_remove when client fails to update endpoint in datastore client.update_endpoint throws a KeyError Assert that the system then exits and all expected calls are made """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } ipv6_nets = set() ipv6_nets.add(IPNetwork(IPAddress('1::1'))) m_endpoint = Mock(spec=Endpoint) m_endpoint.ipv6_nets = ipv6_nets m_client.get_endpoint.return_value = m_endpoint m_client.update_endpoint.side_effect = KeyError # Set up arguments to pass to method under test container_name = 'container1' ip = '1::1' interface = 'interface' # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_ip_remove, container_name, ip, interface) # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertTrue(m_client.update_endpoint.called) self.assertFalse(m_netns.remove_ip_from_ns_veth.called) @patch('calico_ctl.container.enforce_root', autospec=True) @patch('calico_ctl.container.get_pool_or_exit', autospec=True) @patch('calico_ctl.container.get_container_info_or_exit', autospec=True) @patch('calico_ctl.container.client', autospec=True) @patch('calico_ctl.container.netns', autospec=True) def test_container_ip_remove_netns_error( self, m_netns, m_client, m_get_container_info_or_exit, m_get_pool_or_exit, m_enforce_root): """ Test container_ip_remove when client fails on removing ip from interface netns.remove_ip_from_ns_veth raises a CalledProcessError Assert that the system then exits and all expected calls are made """ # Set up mock objects m_get_container_info_or_exit.return_value = { 'Id': 666, 'State': {'Running': 1, 'Pid': 'Pid_info'} } ipv6_nets = set() ipv6_nets.add(IPNetwork(IPAddress('1::1'))) m_endpoint = Mock(spec=Endpoint) m_endpoint.ipv6_nets = ipv6_nets m_client.get_endpoint.return_value = m_endpoint err = CalledProcessError(1, m_netns, "Error removing ip") m_netns.remove_ip_from_ns_veth.side_effect = err # Set up arguments to pass to method under test container_name = 'container1' ip = '1::1' interface = 'interface' # Call method under test expecting a SystemExit self.assertRaises(SystemExit, container.container_ip_remove, container_name, ip, interface) # Assert self.assertTrue(m_enforce_root.called) self.assertTrue(m_get_pool_or_exit.called) self.assertTrue(m_get_container_info_or_exit.called) self.assertTrue(m_client.get_endpoint.called) self.assertTrue(m_client.update_endpoint.called) self.assertTrue(m_netns.remove_ip_from_ns_veth.called) self.assertFalse(m_client.unassign_address.called)
Java
/* * Copyright 2021 ThoughtWorks, 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.thoughtworks.go.server.perf.commands; import com.thoughtworks.go.config.Agent; import com.thoughtworks.go.server.service.AgentRuntimeInfo; import com.thoughtworks.go.server.service.AgentService; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Optional; import java.util.UUID; public class RegisterAgentCommand extends AgentPerformanceCommand { public RegisterAgentCommand(AgentService agentService) { this.agentService = agentService; } @Override Optional<String> execute() { return registerAgent(); } private Optional<String> registerAgent() { InetAddress localHost = getInetAddress(); Agent agent = new Agent("Perf-Test-Agent-" + UUID.randomUUID(), localHost.getHostName(), localHost.getHostAddress(), UUID.randomUUID().toString()); AgentRuntimeInfo agentRuntimeInfo = AgentRuntimeInfo.fromServer(agent, false, "location", 233232L, "osx"); agentService.requestRegistration(agentRuntimeInfo); return Optional.ofNullable(agent.getUuid()); } private InetAddress getInetAddress() { InetAddress localHost; try { localHost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { throw new RuntimeException(e); } return localHost; } }
Java
/* * Software License Agreement (Apache License) * * Copyright (c) 2014, Southwest Research 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. */ #ifndef CERES_COSTS_UTILS_TEST_HPP_ #define CERES_COSTS_UTILS_TEST_HPP_ #include "ceres/ceres.h" #include "ceres/rotation.h" #include <industrial_extrinsic_cal/basic_types.h> namespace industrial_extrinsic_cal { /* local prototypes of helper functions */ /*! \brief print a quaternion plus position as a homogeneous transform * \param qx quaternion x value * \param qy quaternion y value * \param qz quaternion z value * \param qw quaternion w value * \param tx position x value * \param ty position y value * \param tz position z value */ void printQTasH(double qx, double qy, double qz, double qw, double tx, double ty, double tz); /*! \brief print an angle axis transform as a homogeneous transform * \param x angle axis x value * \param y angle axis y value * \param z angle axis z value * \param tx position x value * \param ty position y value * \param tz position z value */ void printAATasH(double ax, double ay, double az, double tx, double ty, double tz); /*! \brief print angle axis to homogeneous transform inverse * \param ax angle axis x value * \param ay angle axis y value * \param az angle axis z value * \param tx position x value * \param ty position y value * \param tz position z value */ void printAATasHI(double ax, double ay, double az, double tx, double ty, double tz); /*! \brief print angle axis as euler angles * \param ax angle axis x value * \param ay angle axis y value * \param az angle axis z value */ void printAAasEuler(double ax, double ay, double az); /*! \brief print Camera Parameters * \param CameraParameters include intrinsic and extrinsic * \param words to provide as a header */ void printCameraParameters(CameraParameters C, std::string words); /*! \brief computes image of point in cameras image plane * \param C both intrinsic and extrinsic camera parameters * \param P the point to be projected into image */ Observation projectPointWithDistortion(CameraParameters camera_parameters, Point3d point); Observation projectPointNoDistortion(CameraParameters camera_params, Point3d point_to_project); Observation projectPointWithDistortion(CameraParameters C, Point3d P) { double p[3]; double pt[3]; pt[0] = P.x; pt[1] = P.y; pt[2] = P.z; /* transform point into camera frame */ /* note, camera transform takes points from camera frame into world frame */ double aa[3]; aa[0] = C.pb_extrinsics[0]; aa[1] = C.pb_extrinsics[1]; aa[2] = C.pb_extrinsics[2]; ceres::AngleAxisRotatePoint(aa, pt, p); // apply camera translation double xp1 = p[0] + C.pb_extrinsics[3]; double yp1 = p[1] + C.pb_extrinsics[4]; double zp1 = p[2] + C.pb_extrinsics[5]; // p[0] +=C.pb_extrinsics[3]; // p[1] +=C.pb_extrinsics[4]; // p[2] +=C.pb_extrinsics[5]; double xp = xp1 / zp1; double yp = yp1 / zp1; // calculate terms for polynomial distortion double r2 = xp * xp + yp * yp; double r4 = r2 * r2; double r6 = r2 * r4; double xp2 = xp * xp; /* temporary variables square of others */ double yp2 = yp * yp; /* apply the distortion coefficients to refine pixel location */ double xpp = xp + C.distortion_k1 * r2 * xp + C.distortion_k2 * r4 * xp + C.distortion_k3 * r6 * xp + C.distortion_p2 * (r2 + 2 * xp2) + 2 * C.distortion_p1 * xp * yp; double ypp = yp + C.distortion_k1 * r2 * yp + C.distortion_k2 * r4 * yp + C.distortion_k3 * r6 * yp + C.distortion_p1 * (r2 + 2 * yp2) + 2 * C.distortion_p2 * xp * yp; /* perform projection using focal length and camera center into image plane */ Observation O; O.point_id = 0; O.image_loc_x = C.focal_length_x * xpp + C.center_x; O.image_loc_y = C.focal_length_y * ypp + C.center_y; return (O); } Observation projectPointNoDistortion(CameraParameters C, Point3d P) { double p[3]; // rotated into camera frame double point[3]; // world location of point double aa[3]; // angle axis representation of camera transform double tx = C.position[0]; // location of origin in camera frame x double ty = C.position[1]; // location of origin in camera frame y double tz = C.position[2]; // location of origin in camera frame z double fx = C.focal_length_x; // focal length x double fy = C.focal_length_y; // focal length y double cx = C.center_x; // optical center x double cy = C.center_y; // optical center y aa[0] = C.angle_axis[0]; aa[1] = C.angle_axis[1]; aa[2] = C.angle_axis[2]; point[0] = P.x; point[1] = P.y; point[2] = P.z; /** rotate and translate points into camera frame */ ceres::AngleAxisRotatePoint(aa, point, p); // apply camera translation double xp1 = p[0] + tx; double yp1 = p[1] + ty; double zp1 = p[2] + tz; // scale into the image plane by distance away from camera double xp = xp1 / zp1; double yp = yp1 / zp1; // perform projection using focal length and camera center into image plane Observation O; O.image_loc_x = fx * xp + cx; O.image_loc_y = fy * yp + cy; return (O); } } // end of namespace #endif
Java
<?php /* * Copyright 2014 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. */ namespace Google\Service\CloudSourceRepositories; class UpdateProjectConfigRequest extends \Google\Model { protected $projectConfigType = ProjectConfig::class; protected $projectConfigDataType = ''; /** * @var string */ public $updateMask; /** * @param ProjectConfig */ public function setProjectConfig(ProjectConfig $projectConfig) { $this->projectConfig = $projectConfig; } /** * @return ProjectConfig */ public function getProjectConfig() { return $this->projectConfig; } /** * @param string */ public function setUpdateMask($updateMask) { $this->updateMask = $updateMask; } /** * @return string */ public function getUpdateMask() { return $this->updateMask; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(UpdateProjectConfigRequest::class, 'Google_Service_CloudSourceRepositories_UpdateProjectConfigRequest');
Java
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <!-- Title and other stuffs --> <title>插件3页面 Bootstrap响应式后台管理系统模版Mac - JS代码网</title> <meta name="keywords" content="Bootstrap模版,Bootstrap模版下载,Bootstrap教程,Bootstrap中文,后台管理系统模版,后台模版下载,后台管理系统,后台管理模版" /> <meta name="description" content="JS代码网提供Bootstrap模版,后台管理系统模版,后台管理界面,Bootstrap教程,Bootstrap中文翻译等相关Bootstrap插件下载" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="author" content=""> <!-- Stylesheets --> <link href="style/bootstrap.css" rel="stylesheet"> <!-- Font awesome icon --> <link rel="stylesheet" href="style/font-awesome.css"> <!-- jQuery UI --> <link rel="stylesheet" href="style/jquery-ui.css"> <!-- Calendar --> <link rel="stylesheet" href="style/fullcalendar.css"> <!-- prettyPhoto --> <link rel="stylesheet" href="style/prettyPhoto.css"> <!-- Star rating --> <link rel="stylesheet" href="style/rateit.css"> <!-- Date picker --> <link rel="stylesheet" href="style/bootstrap-datetimepicker.min.css"> <!-- CLEditor --> <link rel="stylesheet" href="style/jquery.cleditor.css"> <!-- Uniform --> <link rel="stylesheet" href="style/uniform.default.css"> <!-- Bootstrap toggle --> <link rel="stylesheet" href="style/bootstrap-switch.css"> <!-- Main stylesheet --> <link href="style/style.css" rel="stylesheet"> <!-- Widgets stylesheet --> <link href="style/widgets.css" rel="stylesheet"> <!-- HTML5 Support for IE --> <!--[if lt IE 9]> <script src="js/html5shim.js"></script> <![endif]--> <!-- Favicon --> <link rel="shortcut icon" href="img/favicon/favicon.png"> </head> <body> <div class="navbar navbar-fixed-top bs-docs-nav" role="banner"> <div class="conjtainer"> <!-- Menu button for smallar screens --> <div class="navbar-header"> <button class="navbar-toggle btn-navbar" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse"> <span>Menu</span> </button> <!-- Site name for smallar screens --> <a href="index.html" class="navbar-brand hidden-lg">MacBeth</a> </div> <!-- Navigation starts --> <nav class="collapse navbar-collapse bs-navbar-collapse" role="navigation"> <ul class="nav navbar-nav"> <!-- Upload to server link. Class "dropdown-big" creates big dropdown --> <li class="dropdown dropdown-big"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="label label-success"><i class="icon-cloud-upload"></i></span> Upload to Cloud</a> <!-- Dropdown --> <ul class="dropdown-menu"> <li> <!-- Progress bar --> <p>Photo Upload in Progress</p> <!-- Bootstrap progress bar --> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"> <span class="sr-only">40% Complete</span> </div> </div> <hr /> <!-- Progress bar --> <p>Video Upload in Progress</p> <!-- Bootstrap progress bar --> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> <span class="sr-only">80% Complete</span> </div> </div> <hr /> <!-- Dropdown menu footer --> <div class="drop-foot"> <a href="#">View All</a> </div> </li> </ul> </li> <!-- Sync to server link --> <li class="dropdown dropdown-big"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="label label-danger"><i class="icon-refresh"></i></span> Sync with Server</a> <!-- Dropdown --> <ul class="dropdown-menu"> <li> <!-- Using "icon-spin" class to rotate icon. --> <p><span class="label label-info"><i class="icon-cloud"></i></span> Syncing Members Lists to Server</p> <hr /> <p><span class="label label-warning"><i class="icon-cloud"></i></span> Syncing Bookmarks Lists to Cloud</p> <hr /> <!-- Dropdown menu footer --> <div class="drop-foot"> <a href="#">View All</a> </div> </li> </ul> </li> </ul> <!-- Search form --> <form class="navbar-form navbar-left" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> </form> <!-- Links --> <ul class="nav navbar-nav pull-right"> <li class="dropdown pull-right"> <a data-toggle="dropdown" class="dropdown-toggle" href="#"> <i class="icon-user"></i> Admin <b class="caret"></b> </a> <!-- Dropdown menu --> <ul class="dropdown-menu"> <li><a href="#"><i class="icon-user"></i> Profile</a></li> <li><a href="#"><i class="icon-cogs"></i> Settings</a></li> <li><a href="login.html"><i class="icon-off"></i> Logout</a></li> </ul> </li> </ul> </nav> </div> </div> <!-- Header starts --> <header> <div class="container"> <div class="row"> <!-- Logo section --> <div class="col-md-4"> <!-- Logo. --> <div class="logo"> <h1><a href="#">Mac<span class="bold"></span></a></h1> <p class="meta">后台管理系统</p> </div> <!-- Logo ends --> </div> <!-- Button section --> <div class="col-md-4"> <!-- Buttons --> <ul class="nav nav-pills"> <!-- Comment button with number of latest comments count --> <li class="dropdown dropdown-big"> <a class="dropdown-toggle" href="#" data-toggle="dropdown"> <i class="icon-comments"></i> Chats <span class="label label-info">6</span> </a> <ul class="dropdown-menu"> <li> <!-- Heading - h5 --> <h5><i class="icon-comments"></i> Chats</h5> <!-- Use hr tag to add border --> <hr /> </li> <li> <!-- List item heading h6 --> <h6><a href="#">Hi :)</a> <span class="label label-warning pull-right">10:42</span></h6> <div class="clearfix"></div> <hr /> </li> <li> <h6><a href="#">How are you?</a> <span class="label label-warning pull-right">20:42</span></h6> <div class="clearfix"></div> <hr /> </li> <li> <h6><a href="#">What are you doing?</a> <span class="label label-warning pull-right">14:42</span></h6> <div class="clearfix"></div> <hr /> </li> <li> <div class="drop-foot"> <a href="#">View All</a> </div> </li> </ul> </li> <!-- Message button with number of latest messages count--> <li class="dropdown dropdown-big"> <a class="dropdown-toggle" href="#" data-toggle="dropdown"> <i class="icon-envelope-alt"></i> Inbox <span class="label label-primary">6</span> </a> <ul class="dropdown-menu"> <li> <!-- Heading - h5 --> <h5><i class="icon-envelope-alt"></i> Messages</h5> <!-- Use hr tag to add border --> <hr /> </li> <li> <!-- List item heading h6 --> <h6><a href="#">Hello how are you?</a></h6> <!-- List item para --> <p>Quisque eu consectetur erat eget semper...</p> <hr /> </li> <li> <h6><a href="#">Today is wonderful?</a></h6> <p>Quisque eu consectetur erat eget semper...</p> <hr /> </li> <li> <div class="drop-foot"> <a href="#">View All</a> </div> </li> </ul> </li> <!-- Members button with number of latest members count --> <li class="dropdown dropdown-big"> <a class="dropdown-toggle" href="#" data-toggle="dropdown"> <i class="icon-user"></i> Users <span class="label label-success">6</span> </a> <ul class="dropdown-menu"> <li> <!-- Heading - h5 --> <h5><i class="icon-user"></i> Users</h5> <!-- Use hr tag to add border --> <hr /> </li> <li> <!-- List item heading h6--> <h6><a href="#">Ravi Kumar</a> <span class="label label-warning pull-right">Free</span></h6> <div class="clearfix"></div> <hr /> </li> <li> <h6><a href="#">Balaji</a> <span class="label label-important pull-right">Premium</span></h6> <div class="clearfix"></div> <hr /> </li> <li> <h6><a href="#">Kumarasamy</a> <span class="label label-warning pull-right">Free</span></h6> <div class="clearfix"></div> <hr /> </li> <li> <div class="drop-foot"> <a href="#">View All</a> </div> </li> </ul> </li> </ul> </div> <!-- Data section --> <div class="col-md-4"> <div class="header-data"> <!-- Traffic data --> <div class="hdata"> <div class="mcol-left"> <!-- Icon with red background --> <i class="icon-signal bred"></i> </div> <div class="mcol-right"> <!-- Number of visitors --> <p><a href="#">7000</a> <em>visits</em></p> </div> <div class="clearfix"></div> </div> <!-- Members data --> <div class="hdata"> <div class="mcol-left"> <!-- Icon with blue background --> <i class="icon-user bblue"></i> </div> <div class="mcol-right"> <!-- Number of visitors --> <p><a href="#">3000</a> <em>users</em></p> </div> <div class="clearfix"></div> </div> <!-- revenue data --> <div class="hdata"> <div class="mcol-left"> <!-- Icon with green background --> <i class="icon-money bgreen"></i> </div> <div class="mcol-right"> <!-- Number of visitors --> <p><a href="#">5000</a><em>orders</em></p> </div> <div class="clearfix"></div> </div> </div> </div> </div> </div> </header> <!-- Header ends --> <!-- Main content starts --> <div class="content"> <!-- Sidebar --> <div class="sidebar"> <div class="sidebar-dropdown"><a href="#">Navigation</a></div> <!--- Sidebar navigation --> <!-- If the main navigation has sub navigation, then add the class "has_sub" to "li" of main navigation. --> <ul id="nav"> <!-- Main menu with font awesome icon --> <li><a href="index.html"><i class="icon-home"></i> Dashboard</a> <!-- Sub menu markup <ul> <li><a href="#">Submenu #1</a></li> <li><a href="#">Submenu #2</a></li> <li><a href="#">Submenu #3</a></li> </ul>--> </li> <li class="has_sub"><a href="#" class="open"><i class="icon-list-alt"></i> Widgets <span class="pull-right"><i class="icon-chevron-right"></i></span></a> <ul> <li><a href="widgets1.html">Widgets #1</a></li> <li><a href="widgets2.html">Widgets #2</a></li> <li><a href="widgets3.html">Widgets #3</a></li> </ul> </li> <li class="has_sub"><a href="#"><i class="icon-file-alt"></i> Pages #1 <span class="pull-right"><i class="icon-chevron-right"></i></span></a> <ul> <li><a href="post.html">Post</a></li> <li><a href="login.html">Login</a></li> <li><a href="register.html">Register</a></li> <li><a href="support.html">Support</a></li> <li><a href="invoice.html">Invoice</a></li> <li><a href="profile.html">Profile</a></li> <li><a href="gallery.html">Gallery</a></li> </ul> </li> <li class="has_sub"><a href="#"><i class="icon-file-alt"></i> Pages #2 <span class="pull-right"><i class="icon-chevron-right"></i></span></a> <ul> <li><a href="media.html">Media</a></li> <li><a href="statement.html">Statement</a></li> <li><a href="error.html">Error</a></li> <li><a href="error-log.html">Error Log</a></li> <li><a href="calendar.html">Calendar</a></li> <li><a href="grid.html">Grid</a></li> </ul> </li> <li><a href="charts.html"><i class="icon-bar-chart"></i> Charts</a></li> <li><a href="tables.html"><i class="icon-table"></i> Tables</a></li> <li><a href="forms.html"><i class="icon-tasks"></i> Forms</a></li> <li><a href="ui.html"><i class="icon-magic"></i> User Interface</a></li> <li><a href="calendar.html"><i class="icon-calendar"></i> Calendar</a></li> </ul> </div> <!-- Sidebar ends --> <!-- Main bar --> <div class="mainbar"> <!-- Page heading --> <div class="page-head"> <h2 class="pull-left"><i class="icon-list-alt"></i> Widgets</h2> <!-- Breadcrumb --> <div class="bread-crumb pull-right"> <a href="index.html"><i class="icon-home"></i> Home</a> <!-- Divider --> <span class="divider">/</span> <a href="#" class="bread-current">Dashboard</a> </div> <div class="clearfix"></div> </div> <!-- Page heading ends --> <!-- Matter --> <div class="matter"> <div class="container"> <div class="row"> <!-- Operating System --> <div class="col-md-4"> <div class="widget"> <!-- Widget title --> <div class="widget-head"> <div class="pull-left">Operating System</div> <div class="widget-icons pull-right"> <a href="#" class="wminimize"><i class="icon-chevron-up"></i></a> <a href="#" class="wclose"><i class="icon-remove"></i></a> </div> <div class="clearfix"></div> </div> <div class="widget-content referrer"> <!-- Widget content --> <table class="table table-striped table-bordered table-hover"> <tr> <th><center>#</center></th> <th>Operating System</th> <th>Visits</th> </tr> <tr> <td><img src="img/icons/windows.png" alt="" /> <td>Windows 7</td> <td>3,005</td> </tr> <tr> <td><img src="img/icons/android.png" alt="" /> <td>Android ICS</td> <td>2,505</td> </tr> <tr> <td><img src="img/icons/ios.png" alt="" /> <td>Apple IOS</td> <td>1,405</td> </tr> <tr> <td><img src="img/icons/linux.png" alt="" /> <td>Linux</td> <td>4,005</td> </tr> <tr> <td><img src="img/icons/mac.png" alt="" /> <td>Mac</td> <td>505</td> </tr> <tr> <td><img src="img/icons/metro.png" alt="" /> <td>Windows Mobile</td> <td>305</td> </tr> </table> <div class="widget-foot"> </div> </div> </div> </div> <!-- Browsers --> <div class="col-md-4"> <div class="widget"> <!-- Widget title --> <div class="widget-head"> <div class="pull-left">Browsers</div> <div class="widget-icons pull-right"> <a href="#" class="wminimize"><i class="icon-chevron-up"></i></a> <a href="#" class="wclose"><i class="icon-remove"></i></a> </div> <div class="clearfix"></div> </div> <div class="widget-content referrer"> <!-- Widget content --> <table class="table table-striped table-bordered table-hover"> <tr> <th><center>#</center></th> <th>Browsers</th> <th>Visits</th> </tr> <tr> <td><img src="img/icons/chrome.png" alt="" /> <td>Google Chrome</td> <td>3,005</td> </tr> <tr> <td><img src="img/icons/firefox.png" alt="" /> <td>Mozilla Firefox</td> <td>2,505</td> </tr> <tr> <td><img src="img/icons/ie.png" alt="" /> <td>Internet Explorer</td> <td>1,405</td> </tr> <tr> <td><img src="img/icons/opera.png" alt="" /> <td>Opera</td> <td>4,005</td> </tr> <tr> <td><img src="img/icons/safari.png" alt="" /> <td>Safari</td> <td>505</td> </tr> </table> <div class="widget-foot"> </div> </div> </div> </div> <!-- Recent News --> <div class="col-md-4"> <div class="widget"> <!-- Widget title --> <div class="widget-head"> <div class="pull-left">Recent News</div> <div class="widget-icons pull-right"> <a href="#" class="wminimize"><i class="icon-chevron-up"></i></a> <a href="#" class="wclose"><i class="icon-remove"></i></a> </div> <div class="clearfix"></div> </div> <div class="widget-content referrer"> <!-- Widget content --> <div class="padd"> <ul class="latest-news"> <li> <!-- Title and date --> <h6><a href="#">Morbi ac felis nec </a> - <span>Jan 1, 2012</span></h6> <p>Suspendisse potenti. Morbi ac felis fermentum. Aenean lacus hendrerit sed rhoncus erat hendrerit. </p> </li> <li> <!-- Title and date --> <h6><a href="#">Aac felis nec imperdiet</a> - <span>Jan 1, 2012</span></h6> <p>Suspendisse potenti. Morbi ac felis fermentum. Aenean lacus hendrerit sed rhoncus erat hendrerit. </p> </li> <li> <!-- Title and date --> <h6><a href="#">Felis nec imperdiet</a> - <span>Jan 1, 2012</span></h6> <p>Suspendisse potenti. Morbi ac felis fermentum. Aenean hendrerit sed rhoncus erat hendrerit. </p> </li> </ul> </div> <div class="widget-foot"> </div> </div> </div> </div> </div> <div class="row"> <!-- Task widget --> <div class="col-md-5"> <div class="widget"> <!-- Widget title --> <div class="widget-head"> <div class="pull-left">Tasks</div> <div class="widget-icons pull-right"> <a href="#" class="wminimize"><i class="icon-chevron-up"></i></a> <a href="#" class="wclose"><i class="icon-remove"></i></a> </div> <div class="clearfix"></div> </div> <div class="widget-content"> <!-- Widget content --> <!-- Task list starts --> <ul class="task"> <li> <!-- Checkbox --> <span class="uni"><input value="check1" type="checkbox"></span> <!-- Task --> Goto Shopping in Walmart <span class="label label-danger">Important</span> <!-- Delete button --> <a href="#" class="pull-right"><i class="icon-remove"></i></a> </li> <li> <!-- Checkbox --> <span class="uni"><input value="check1" type="checkbox"></span> <!-- Task --> Download some action movies <!-- Delete button --> <a href="#" class="pull-right"><i class="icon-remove"></i></a> </li> <li> <!-- Checkbox --> <span class="uni"><input value="check1" type="checkbox"></span> <!-- Task --> Read Harry Potter VII Book <span class="label label-danger">Important</span> <!-- Delete button --> <a href="#" class="pull-right"><i class="icon-remove"></i></a> </li> <li> <!-- Checkbox --> <span class="uni"><input value="check1" type="checkbox"></span> <!-- Task --> Collect cash from friends for camp <!-- Delete button --> <a href="#" class="pull-right"><i class="icon-remove"></i></a> </li> <li> <!-- Checkbox --> <span class="uni"><input value="check1" type="checkbox"></span> <!-- Task --> Sleep till tomorrow everning <!-- Delete button --> <a href="#" class="pull-right"><i class="icon-remove"></i></a> </li> </ul> <div class="clearfix"></div> <div class="widget-foot"> </div> </div> </div> </div> <div class="col-md-7"> <div class="widget"> <div class="widget-head"> <div class="pull-left">Quick Posts</div> <div class="widget-icons pull-right"> <a href="#" class="wminimize"><i class="icon-chevron-up"></i></a> <a href="#" class="wclose"><i class="icon-remove"></i></a> </div> <div class="clearfix"></div> </div> <div class="widget-content"> <div class="padd"> <div class="form quick-post"> <!-- Edit profile form (not working)--> <form class="form-horizontal"> <!-- Title --> <div class="form-group"> <label class="control-label col-lg-3" for="title">Title</label> <div class="col-lg-9"> <input type="text" class="form-control" id="title"> </div> </div> <!-- Content --> <div class="form-group"> <label class="control-label col-lg-3" for="content">Content</label> <div class="col-lg-9"> <textarea class="form-control" id="content"></textarea> </div> </div> <!-- Cateogry --> <div class="form-group"> <label class="control-label col-lg-3">Category</label> <div class="col-lg-9"> <select class="form-control"> <option value="">- Choose Cateogry -</option> <option value="1">General</option> <option value="2">News</option> <option value="3">Media</option> <option value="4">Funny</option> </select> </div> </div> <!-- Tags --> <div class="form-group"> <label class="control-label col-lg-3" for="tags">Tags</label> <div class="col-lg-9"> <input type="text" class="form-control" id="tags"> </div> </div> <!-- Buttons --> <div class="form-group"> <!-- Buttons --> <div class="col-lg-offset-2 col-lg-9"> <button type="submit" class="btn btn-success">Publish</button> <button type="submit" class="btn btn-danger">Save Draft</button> <button type="reset" class="btn btn-default">Reset</button> </div> </div> </form> </div> </div> <div class="widget-foot"> <!-- Footer goes here --> </div> </div> </div> </div> </div> </div> </div> <!-- Matter ends --> </div> <!-- Mainbar ends --> <div class="clearfix"></div> </div> <!-- Content ends --> <!-- Footer starts --> <footer> <div class="container"> <div class="row"> <div class="col-md-12"> <!-- Copyright info --> <p class="copy">Copyright &copy; 2012 | <a href="#">Your Site</a> </p> </div> </div> </div> </footer> <!-- Footer ends --> <!-- Scroll to top --> <span class="totop"><a href="#"><i class="icon-chevron-up"></i></a></span> <!-- JS --> <script src="js/jquery.js"></script> <!-- jQuery --> <script src="js/bootstrap.js"></script> <!-- Bootstrap --> <script src="js/jquery-ui-1.9.2.custom.min.js"></script> <!-- jQuery UI --> <script src="js/fullcalendar.min.js"></script> <!-- Full Google Calendar - Calendar --> <script src="js/jquery.rateit.min.js"></script> <!-- RateIt - Star rating --> <script src="js/jquery.prettyPhoto.js"></script> <!-- prettyPhoto --> <!-- jQuery Flot --> <script src="js/excanvas.min.js"></script> <script src="js/jquery.flot.js"></script> <script src="js/jquery.flot.resize.js"></script> <script src="js/jquery.flot.pie.js"></script> <script src="js/jquery.flot.stack.js"></script> <!-- jQuery Notification - Noty --> <script src="js/jquery.noty.js"></script> <!-- jQuery Notify --> <script src="js/themes/default.js"></script> <!-- jQuery Notify --> <script src="js/layouts/bottom.js"></script> <!-- jQuery Notify --> <script src="js/layouts/topRight.js"></script> <!-- jQuery Notify --> <script src="js/layouts/top.js"></script> <!-- jQuery Notify --> <!-- jQuery Notification ends --> <script src="js/sparklines.js"></script> <!-- Sparklines --> <script src="js/jquery.cleditor.min.js"></script> <!-- CLEditor --> <script src="js/bootstrap-datetimepicker.min.js"></script> <!-- Date picker --> <script src="js/jquery.uniform.min.js"></script> <!-- jQuery Uniform --> <script src="js/bootstrap-switch.min.js"></script> <!-- Bootstrap Toggle --> <script src="js/filter.js"></script> <!-- Filter for support page --> <script src="js/custom.js"></script> <!-- Custom codes --> <script src="js/charts.js"></script> <!-- Charts & Graphs --> </body> </html>
Java
/* * (C) Johannes Kepler University Linz, Austria, 2005-2013 * Institute for Systems Engineering and Automation (SEA) * * The software may only be used for academic purposes (teaching, scientific * research). Any redistribution or commercialization of the software program * and documentation (or any part thereof) requires prior written permission of * the JKU. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * This software program and documentation are copyrighted by Johannes Kepler * University Linz, Austria (the JKU). The software program and documentation * are supplied AS IS, without any accompanying services from the JKU. The JKU * does not warrant that the operation of the program will be uninterrupted or * error-free. The end-user understands that the program was developed for * research purposes and is advised not to rely exclusively on the program for * any reason. * * IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, * SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE * AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHOR * SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE AUTHOR HAS * NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. */ /* * ArtifactIsNotACollectionException.java created on 13.03.2013 * * (c) alexander noehrer */ package at.jku.sea.cloud.exceptions; /** * @author alexander noehrer */ public class ArtifactIsNotACollectionException extends RuntimeException { private static final long serialVersionUID = 1L; public ArtifactIsNotACollectionException(final long version, final long id) { super("artifact (id=" + id + ", version=" + version + ") is not a collection"); } }
Java
/* * Copyright 2010-2012 Ning, Inc. * * Ning 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 com.ning.metrics.collector.filtering; import com.ning.metrics.collector.endpoint.ParsedRequest; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; public class TestPatternSetFilter { @Test(groups = "fast") public void testNullValue() throws Exception { final Filter<ParsedRequest> filter = new PatternSetFilter(createFieldExtractor(null), createPatternSet("pattern1", "pattern2")); Assert.assertEquals(filter.passesFilter(null, null), false); } @Test(groups = "fast") public void testEmptySetPatternEventRESTRequestFilter() throws Exception { final Filter<ParsedRequest> filter = new PatternSetFilter(createFieldExtractor("test-host"), Collections.<Pattern>emptySet()); Assert.assertEquals(filter.passesFilter(null, null), false); } @Test(groups = "fast") public void testSinglePatternEventRESTRequestFilter() throws Exception { final Filter<ParsedRequest> filterShouldMatch = new PatternSetFilter(createFieldExtractor("test-host"), createPatternSet("test-host")); Assert.assertEquals(filterShouldMatch.passesFilter(null, null), true); final Filter<ParsedRequest> filterDoesNotMatch = new PatternSetFilter(createFieldExtractor("test-host"), createPatternSet("mugen")); Assert.assertEquals(filterDoesNotMatch.passesFilter(null, null), false); } @Test(groups = "fast") public void testMultiplePatternEventRESTRequestFilter() throws Exception { final Filter<ParsedRequest> trueFilter = new PatternSetFilter(createFieldExtractor("test-host"), createPatternSet("test-host", "nothing")); Assert.assertTrue(trueFilter.passesFilter(null, null)); final Filter<ParsedRequest> falseFilter = new PatternSetFilter(createFieldExtractor("test-host"), createPatternSet("mugen", "nothing")); Assert.assertFalse(falseFilter.passesFilter(null, null)); } @Test(groups = "fast") public void testSinglePatternEventInclusionFilter() throws Exception { final Filter<ParsedRequest> filterShouldMatch = new EventInclusionFilter(createFieldExtractor("test-host"), createPatternSet("test-host")); Assert.assertEquals(filterShouldMatch.passesFilter(null, null), false); final Filter<ParsedRequest> filterDoesNotMatch = new EventInclusionFilter(createFieldExtractor("test-host"), createPatternSet("mugen")); Assert.assertEquals(filterDoesNotMatch.passesFilter(null, null), true); } private Set<Pattern> createPatternSet(final String... patterns) { final Set<Pattern> patternSet = new HashSet<Pattern>(); for (final String str : patterns) { patternSet.add(Pattern.compile(str)); } return patternSet; } private FieldExtractor createFieldExtractor(final String value) { return new FieldExtractor() { @Override public String getField(final String eventName, final ParsedRequest annotation) { return value; } }; } }
Java
/* * 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.management.internal.cli.commands; import static org.assertj.core.api.Assertions.assertThat; import org.apache.geode.test.junit.rules.GfshShellConnectionRule; import org.apache.geode.test.junit.categories.DistributedTest; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TemporaryFolder; import java.io.File; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @Category(DistributedTest.class) public class ExportLogsStatsOverHttpDUnitTest extends ExportLogsStatsDUnitTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Override public void connectIfNeeded() throws Exception { if (!connector.isConnected()) connector.connect(httpPort, GfshShellConnectionRule.PortType.http); } @Test public void testExportWithDir() throws Exception { connectIfNeeded(); File dir = temporaryFolder.newFolder(); // export the logs connector.executeCommand("export logs --dir=" + dir.getAbsolutePath()); // verify that the message contains a path to the user.dir String message = connector.getGfshOutput(); assertThat(message).contains("Logs exported to: "); assertThat(message).contains(dir.getAbsolutePath()); String zipPath = getZipPathFromCommandResult(message); Set<String> actualZipEntries = new ZipFile(zipPath).stream().map(ZipEntry::getName).collect(Collectors.toSet()); assertThat(actualZipEntries).isEqualTo(expectedZipEntries); // also verify that the zip file on locator is deleted assertThat(Arrays.stream(locator.getWorkingDir().listFiles()) .filter(file -> file.getName().endsWith(".zip")).collect(Collectors.toSet())).isEmpty(); } protected String getZipPathFromCommandResult(String message) { return message.replaceAll("Logs exported to: ", "").trim(); } }
Java
# Copyright (C) 2014-2016 MongoDB, 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. module Mongo module Operation # Adds behaviour for updating the selector for operations # that may take a write concern. # # @since 2.4.0 module TakesWriteConcern private def update_selector_for_write_concern(sel, server) if write_concern && server.features.collation_enabled? sel.merge(writeConcern: write_concern.options) else sel end end end end end
Java
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Web.Razor.Parser { [Flags] public enum BalancingModes { None = 0, BacktrackOnFailure = 1, NoErrorOnFailure = 2, AllowCommentsAndTemplates = 4, AllowEmbeddedTransitions = 8 } }
Java
/* * Copyright 2014 Click Travel Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.clicktravel.infrastructure.persistence.aws.dynamodb; import static com.clicktravel.common.random.Randoms.randomId; import static com.clicktravel.common.random.Randoms.randomString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec; import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec; import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec; import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; import com.clicktravel.cheddar.infrastructure.persistence.database.ItemId; import com.clicktravel.cheddar.infrastructure.persistence.database.configuration.DatabaseSchemaHolder; import com.clicktravel.cheddar.infrastructure.persistence.database.configuration.ItemConfiguration; import com.clicktravel.cheddar.infrastructure.persistence.database.exception.NonExistentItemException; import com.clicktravel.cheddar.infrastructure.persistence.database.exception.OptimisticLockException; import com.clicktravel.common.random.Randoms; @RunWith(PowerMockRunner.class) @PrepareForTest({ DynamoDocumentStoreTemplate.class }) public class DynamoDocumentStoreTemplateTest { private DatabaseSchemaHolder mockDatabaseSchemaHolder; private String schemaName; private String tableName; private AmazonDynamoDB mockAmazonDynamoDbClient; private DynamoDB mockDynamoDBClient; @Before public void setup() throws Exception { schemaName = randomString(10); tableName = randomString(10); mockDatabaseSchemaHolder = mock(DatabaseSchemaHolder.class); when(mockDatabaseSchemaHolder.schemaName()).thenReturn(schemaName); mockAmazonDynamoDbClient = mock(AmazonDynamoDB.class); mockDynamoDBClient = mock(DynamoDB.class); whenNew(DynamoDB.class).withParameterTypes(AmazonDynamoDB.class).withArguments(eq(mockAmazonDynamoDbClient)) .thenReturn(mockDynamoDBClient); } @SuppressWarnings("deprecation") @Test public void shouldCreate_withItem() { // Given final ItemId itemId = new ItemId(randomId()); final StubItem stubItem = generateRandomStubItem(itemId); final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName); final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration); when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations); final Table mockTable = mock(Table.class); when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable); final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate( mockDatabaseSchemaHolder); dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient); final Item mockTableItem = mock(Item.class); when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem)); // When final StubItem returnedItem = dynamoDocumentStoreTemplate.create(stubItem); // Then final ArgumentCaptor<PutItemSpec> getItemRequestCaptor = ArgumentCaptor.forClass(PutItemSpec.class); verify(mockTable).putItem(getItemRequestCaptor.capture()); final PutItemSpec spec = getItemRequestCaptor.getValue(); assertEquals(itemId.value(), spec.getItem().get("id")); assertEquals(itemId.value(), returnedItem.getId()); assertEquals(stubItem.getStringProperty(), returnedItem.getStringProperty()); assertEquals(stubItem.getStringProperty2(), returnedItem.getStringProperty2()); assertEquals(stubItem.getStringSetProperty(), returnedItem.getStringSetProperty()); } @SuppressWarnings("deprecation") @Test public void shouldNotCreate_withItem() { // Given final ItemId itemId = new ItemId(randomId()); final StubItem stubItem = generateRandomStubItem(itemId); final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName); final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration); when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations); final Table mockTable = mock(Table.class); when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable); final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate( mockDatabaseSchemaHolder); dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient); final Item mockTableItem = mock(Item.class); when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem)); doThrow(RuntimeException.class).when(mockTable).putItem(any(PutItemSpec.class)); RuntimeException thrownException = null; // When try { dynamoDocumentStoreTemplate.create(stubItem); } catch (final RuntimeException runtimeException) { thrownException = runtimeException; } // Then assertNotNull(thrownException); } @SuppressWarnings("deprecation") @Test public void shouldRead_withItemIdAndItemClass() throws Exception { // Given final ItemId itemId = new ItemId(randomId()); final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName); final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration); when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations); final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate( mockDatabaseSchemaHolder); dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient); final Table mockTable = mock(Table.class); when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable); final Item mockTableItem = mock(Item.class); when(mockTable.getItem(any(GetItemSpec.class))).thenReturn(mockTableItem); final StubItem stubItem = generateRandomStubItem(itemId); when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem)); // When final StubItem returnedItem = dynamoDocumentStoreTemplate.read(itemId, StubItem.class); // Then final ArgumentCaptor<GetItemSpec> getItemRequestCaptor = ArgumentCaptor.forClass(GetItemSpec.class); verify(mockTable).getItem(getItemRequestCaptor.capture()); final GetItemSpec spec = getItemRequestCaptor.getValue(); assertEquals(1, spec.getKeyComponents().size()); assertEquals(itemId.value(), spec.getKeyComponents().iterator().next().getValue()); assertEquals(itemId.value(), returnedItem.getId()); assertEquals(stubItem.getStringProperty(), returnedItem.getStringProperty()); assertEquals(stubItem.getStringProperty2(), returnedItem.getStringProperty2()); assertEquals(stubItem.getStringSetProperty(), returnedItem.getStringSetProperty()); } @SuppressWarnings("deprecation") @Test public void shouldNotRead_withNonExistentItemExceptionNoItem() throws Exception { // Given final ItemId itemId = new ItemId(randomId()); final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName); final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration); when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations); final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate( mockDatabaseSchemaHolder); dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient); final Table mockTable = mock(Table.class); when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable); when(mockTable.getItem(any(GetItemSpec.class))).thenReturn(null); NonExistentItemException thrownException = null; // When try { dynamoDocumentStoreTemplate.read(itemId, StubItem.class); } catch (final NonExistentItemException nonExistentItemException) { thrownException = nonExistentItemException; } // Then assertNotNull(thrownException); } @SuppressWarnings("deprecation") @Test public void shouldNotRead_withNonExistentItemExceptionNoContent() throws Exception { // Given final ItemId itemId = new ItemId(randomId()); final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName); final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration); when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations); final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate( mockDatabaseSchemaHolder); dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient); final Table mockTable = mock(Table.class); when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable); final Item mockTableItem = mock(Item.class); when(mockTable.getItem(any(GetItemSpec.class))).thenReturn(mockTableItem); when(mockTableItem.toJSON()).thenReturn(""); NonExistentItemException thrownException = null; // When try { dynamoDocumentStoreTemplate.read(itemId, StubItem.class); } catch (final NonExistentItemException nonExistentItemException) { thrownException = nonExistentItemException; } // Then assertNotNull(thrownException); } @SuppressWarnings("deprecation") @Test public void shouldUpdate_withItem() { // Given final ItemId itemId = new ItemId(randomId()); final StubItem stubItem = generateRandomStubItem(itemId); final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName); final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration); when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations); final Table mockTable = mock(Table.class); when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable); final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate( mockDatabaseSchemaHolder); dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient); final Item mockTableItem = mock(Item.class); when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem)); // When final StubItem returnedItem = dynamoDocumentStoreTemplate.update(stubItem); // Then final ArgumentCaptor<PutItemSpec> getItemRequestCaptor = ArgumentCaptor.forClass(PutItemSpec.class); verify(mockTable).putItem(getItemRequestCaptor.capture()); final PutItemSpec spec = getItemRequestCaptor.getValue(); assertEquals(itemId.value(), spec.getItem().get("id")); assertEquals(itemId.value(), returnedItem.getId()); assertEquals(stubItem.getStringProperty(), returnedItem.getStringProperty()); assertEquals(stubItem.getStringProperty2(), returnedItem.getStringProperty2()); assertEquals(stubItem.getStringSetProperty(), returnedItem.getStringSetProperty()); } @SuppressWarnings("deprecation") @Test public void shouldNotUpdate_withItem() { // Given final ItemId itemId = new ItemId(randomId()); final StubItem stubItem = generateRandomStubItem(itemId); final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName); final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration); when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations); final Table mockTable = mock(Table.class); when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable); final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate( mockDatabaseSchemaHolder); dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient); final Item mockTableItem = mock(Item.class); when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem)); doThrow(ConditionalCheckFailedException.class).when(mockTable).putItem(any(PutItemSpec.class)); OptimisticLockException thrownException = null; // When try { dynamoDocumentStoreTemplate.update(stubItem); } catch (final OptimisticLockException optimisticLockException) { thrownException = optimisticLockException; } // Then assertNotNull(thrownException); } @SuppressWarnings("deprecation") @Test public void shouldDelete_withItem() { // Given final ItemId itemId = new ItemId(randomId()); final StubItem stubItem = generateRandomStubItem(itemId); final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName); final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration); when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations); final Table mockTable = mock(Table.class); when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable); final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate( mockDatabaseSchemaHolder); dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient); // When dynamoDocumentStoreTemplate.delete(stubItem); // Then final ArgumentCaptor<DeleteItemSpec> getItemRequestCaptor = ArgumentCaptor.forClass(DeleteItemSpec.class); verify(mockTable).deleteItem(getItemRequestCaptor.capture()); } private StubItem generateRandomStubItem(final ItemId itemId) { final StubItem item = new StubItem(); item.setBooleanProperty(Randoms.randomBoolean()); item.setId(itemId.value()); item.setStringProperty(Randoms.randomString()); item.setStringProperty2(Randoms.randomString()); item.setVersion(Randoms.randomLong()); final Set<String> stringSet = new HashSet<String>(); for (int i = 0; i < Randoms.randomInt(20); i++) { stringSet.add(Randoms.randomString()); } item.setStringSetProperty(stringSet); return item; } }
Java
// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is 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. // __END_LICENSE__ /// \file MainWindow.h /// /// #ifndef __STEREO_GUI_MAINWINDOW_H__ #define __STEREO_GUI_MAINWINDOW_H__ #include <QMainWindow> #include <string> #include <vector> // Boost #include <boost/program_options.hpp> #include <vw/Math/Vector.h> #include <vw/InterestPoint/InterestData.h> #include <asp/Core/Common.h> #include <asp/GUI/GuiUtilities.h> // Forward declarations class QAction; class QLabel; class QTabWidget; class QSplitter; namespace vw { namespace gui { enum ViewType {VIEW_SIDE_BY_SIDE, VIEW_IN_SINGLE_WINDOW, VIEW_AS_TILES_ON_GRID}; class MainWidget; class chooseFilesDlg; /// This class handles the menues at the top bar and other application level details. class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(vw::cartography::GdalWriteOptions const& opt, std::vector<std::string> const& images, std::string& output_prefix, // non-const, so we can change it int grid_cols, vw::Vector2i const& window_size, bool single_window, bool use_georef, bool hillshade, bool view_matches, bool delete_temporary_files_on_exit, int argc, char ** argv); virtual ~MainWindow() {} private slots: void forceQuit (); // Ensure the program shuts down. void sizeToFit (); void viewSingleWindow (); void viewSideBySide (); void viewAsTiles (); void turnOnViewMatches (); void turnOffViewMatches (); void deleteImageFromWidget (); void zoomAllToSameRegionAction(int widget_id); void viewMatches (); void addDelMatches (); void saveMatches (); void writeGroundControlPoints (); ///< Write a ground control point file for bundle_adjust void save_screenshot (); void select_region (); void change_cursor (); void run_stereo (); void run_parallel_stereo (); void thresholdCalc (); void thresholdGetSet (); void setPolyColor (); void setLineWidth (); void viewThreshImages (); void viewUnthreshImages (); void contourImages (); void saveVectorLayer (); void viewHillshadedImages (); void viewGeoreferencedImages (); void overlayGeoreferencedImages (); void setZoomAllToSameRegion (); void setZoomAllToSameRegionAux(bool do_zoom); void viewNextImage (); void viewPrevImage (); void profileMode (); void polyEditMode (); void uncheckProfileModeCheckbox (); void uncheckPolyEditModeCheckbox(); void about (); protected: void keyPressEvent(QKeyEvent *event); bool eventFilter(QObject *obj, QEvent *e); private: void run_stereo_or_parallel_stereo(std::string const& cmd); /// Go through m_matches and retain only IPs detected in the first image. /// - If require_all is set, only keep IPs detected in all images. size_t consolidate_matches(bool require_all = true); void createLayout(); void createMenus (); // Event handlers void resizeEvent(QResizeEvent *); void closeEvent (QCloseEvent *); // See if in the middle of editing matches bool editingMatches() const; vw::cartography::GdalWriteOptions m_opt; std::string m_output_prefix; double m_widRatio; // ratio of sidebar to entire win wid std::vector<MainWidget*> m_widgets; ///< One of these for each seperate image pane. chooseFilesDlg * m_chooseFiles; // left sidebar for selecting files QMenu *m_file_menu; QMenu *m_view_menu; QMenu *m_matches_menu; QMenu *m_threshold_menu; QMenu *m_profile_menu; QMenu *m_vector_layer_menu; QMenu *m_help_menu; QAction *m_about_action; QAction *m_thresholdCalc_action; QAction *m_thresholdGetSet_action; QAction *m_setLineWidth_action; QAction *m_setPolyColor_action; QAction *m_sizeToFit_action; QAction *m_viewSingleWindow_action; QAction *m_viewSideBySide_action; QAction *m_viewAsTiles_action; QAction *m_viewHillshadedImages_action; QAction *m_viewGeoreferencedImages_action; QAction *m_overlayGeoreferencedImages_action; QAction *m_viewThreshImages_action; QAction *m_contourImages_action; QAction *m_saveVectorLayer_action; QAction *m_viewUnthreshImages_action; QAction *m_zoomAllToSameRegion_action; QAction *m_viewNextImage_action; QAction *m_viewPrevImage_action; QAction *m_viewMatches_action; QAction *m_addDelMatches_action; QAction *m_saveMatches_action; QAction *m_writeGcp_action; QAction *m_save_screenshot_action; QAction *m_select_region_action; QAction *m_change_cursor_action; QAction *m_run_stereo_action; QAction *m_run_parallel_stereo_action; QAction *m_exit_action; QAction *m_profileMode_action; QAction *m_polyEditMode_action; ViewType m_view_type, m_view_type_old; int m_grid_cols, m_grid_cols_old; bool m_use_georef, m_hillshade, m_view_matches, m_delete_temporary_files_on_exit; bool m_allowMultipleSelections; int m_argc; char ** m_argv; bool m_matches_exist; std::vector<bool> m_hillshade_vec; // Any vector of size equal to number of images must be adjusted when the function // deleteImageFromWidget() is invoked. That includes m_image_files and m_matches. std::vector<std::string> m_image_files; ///< Loaded image files /// Structure to keep track of all interest point matches. MatchList m_matchlist; int m_editMatchPointVecIndex; ///< Point being edited int m_cursor_count; }; }} // namespace vw::gui #endif // __STEREO_GUI_MAINWINDOW_H__
Java
/* * RemoveRelationKnowhow.java * Created on 2013/06/28 * * Copyright (C) 2011-2013 Nippon Telegraph and Telephone Corporation * * 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 tubame.knowhow.plugin.ui.view.remove; import tubame.common.util.CmnStringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tubame.knowhow.plugin.logic.KnowhowManagement; import tubame.knowhow.plugin.model.view.CategoryViewType; import tubame.knowhow.plugin.model.view.KnowhowDetailType; import tubame.knowhow.plugin.model.view.KnowhowViewType; import tubame.knowhow.plugin.model.view.PortabilityKnowhowListViewOperation; import tubame.knowhow.plugin.ui.editor.multi.MaintenanceKnowhowMultiPageEditor; import tubame.knowhow.plugin.ui.editor.multi.docbook.KnowhowDetailEditor; import tubame.knowhow.util.PluginUtil; /** * Make a related item deletion process know-how information.<br/> * Delete stick know-how related to the item to be deleted,<br/> * the item that you want to match the key of its own from the reference list of * key know-how detailed information,<br/> * the parent category.<br/> */ public class RemoveRelationKnowhow implements RemoveRelationItemStrategy { /** Logger */ private static final Logger LOGGER = LoggerFactory .getLogger(RemoveRelationKnowhow.class); /** Know-how entry view item */ private KnowhowViewType knowhowViewType; /** Deleted items */ private PortabilityKnowhowListViewOperation portabilityKnowhowListViewOperation; /** * Constructor.<br/> * * @param portabilityKnowhowListViewOperation * Deleted items */ public RemoveRelationKnowhow( PortabilityKnowhowListViewOperation portabilityKnowhowListViewOperation) { this.portabilityKnowhowListViewOperation = portabilityKnowhowListViewOperation; this.knowhowViewType = (KnowhowViewType) portabilityKnowhowListViewOperation .getKnowhowViewType(); } /** * {@inheritDoc} */ @Override public void removeRelationItem() { RemoveRelationKnowhow.LOGGER.debug(CmnStringUtil.EMPTY); removeKnowhowDetail(); removeEntryViewItem(); } /** * Delete key reference to itself from the parent category that is * registered in the entry view.<br/> * */ private void removeEntryViewItem() { CategoryViewType categoryViewType = (CategoryViewType) portabilityKnowhowListViewOperation .getParent().getKnowhowViewType(); String removeTargetKey = null; for (String knowhowRefKey : categoryViewType.getKnowhowRefKeies()) { if (knowhowViewType.getRegisterKey().equals(knowhowRefKey)) { removeTargetKey = knowhowRefKey; } } if (removeTargetKey != null) { categoryViewType.getKnowhowRefKeies().remove(removeTargetKey); } } /** * Delete the data that matches the key from its own know-how detail data * list.<br/> * Remove know-how detail data that matches the reference key know-how from * its own know-how detail data list.<br/> * */ private void removeKnowhowDetail() { KnowhowDetailType removeTargetItem = null; for (KnowhowDetailType knowhowDetailType : KnowhowManagement .getKnowhowDetailTypes()) { if (knowhowDetailType.getKnowhowDetailId().equals( knowhowViewType.getKnowhowDetailRefKey())) { removeTargetItem = knowhowDetailType; } } if (removeTargetItem != null) { KnowhowManagement.getKnowhowDetailTypes().remove(removeTargetItem); clearKnowhoweDetaileditor(removeTargetItem); } } /** * Initialization of know-how detail page editor.<br/> * * @param removeTargetItem * Deleted items */ private void clearKnowhoweDetaileditor(KnowhowDetailType removeTargetItem) { MaintenanceKnowhowMultiPageEditor knowhowMultiPageEditor = PluginUtil .getKnowhowEditor(); KnowhowDetailEditor detailEditor = knowhowMultiPageEditor .getKnowhowDetailEditor(); if (detailEditor.getKnowhowDetailType() != null) { if (removeTargetItem.getKnowhowDetailId().equals( detailEditor.getKnowhowDetailType().getKnowhowDetailId())) { knowhowMultiPageEditor.clearKnowhowDetail(); } } } }
Java