code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
#!/usr/bin/env rspec require 'spec_helper' require 'mcollective/aggregate/summary' module MCollective class Aggregate describe Summary do describe "#startup_hook" do it "should set the correct result hash" do result = Summary.new(:test, [], "%d", :test_action) result.result.should == {:value => {}, :type => :collection, :output => :test} result.aggregate_format.should == "%d" end it "should set a defauly aggregate_format if one isn't defined" do result = Summary.new(:test, [], nil, :test_action) result.aggregate_format.should == :calculate end end describe "#process_result" do it "should add the value to the result hash" do sum = Summary.new(:test, [], "%d", :test_action) sum.process_result(:foo, {:test => :foo}) sum.result[:value].should == {:foo => 1} end it "should add the reply values to the result hash if value is an array" do sum = Summary.new(:test, [], "%d", :test_action) sum.process_result([:foo, :foo, :bar], {:test => [:foo, :foo, :bar]}) sum.result[:value].should == {:foo => 2, :bar => 1} end end describe "#summarize" do it "should calculate an attractive format" do sum = Summary.new(:test, [], nil, :test_action) sum.result[:value] = {"shrt" => 1, "long key" => 1} sum.summarize.aggregate_format.should == "%8s = %s" end it "should calculate an attractive format when result type is not a string" do sum1 = Summary.new(:test, [], nil, :test_action) sum1.result[:value] = {true => 4, false => 5} sum1.summarize.aggregate_format.should == "%5s = %s" sum2 = Summary.new(:test, [], nil, :test_action) sum2.result[:value] = {1 => 1, 10 => 2} sum2.summarize.aggregate_format.should == "%2s = %s" end end end end end
heathseals/marionette-collective
spec/unit/mcollective/aggregate/summary_spec.rb
Ruby
apache-2.0
1,991
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.CodeAnalysis.ExpressionEvaluator; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal static class TestTypeExtensions { public static string GetTypeName(this Type type, bool escapeKeywordIdentifiers = false) { return CSharpFormatter.Instance.GetTypeName((TypeImpl)type, escapeKeywordIdentifiers); } } }
ManishJayaswal/roslyn
src/ExpressionEvaluator/CSharp/Test/ResultProvider/Helpers/TestTypeExtensions.cs
C#
apache-2.0
563
// Copyright 2013 The Go Circuit Project // Use of this source code is governed by the license for // The Go Circuit Project, found in the LICENSE file. // // Authors: // 2013 Petar Maymounkov <p@gocircuit.org> package tele import ( "github.com/gocircuit/circuit/kit/tele/blend" "github.com/gocircuit/circuit/use/n" ) type Conn struct { addr *Addr sub *blend.Conn } func NewConn(sub *blend.Conn, addr *Addr) *Conn { return &Conn{addr: addr, sub: sub} } func (c *Conn) Read() (v interface{}, err error) { if v, err = c.sub.Read(); err != nil { return nil, err } return } func (c *Conn) Write(v interface{}) (err error) { if err = c.sub.Write(v); err != nil { return err } return nil } func (c *Conn) Close() error { return c.sub.Close() } func (c *Conn) Abort(reason error) { c.sub.Abort(reason) } func (c *Conn) Addr() n.Addr { return c.addr }
bzz/circuit
sys/tele/conn.go
GO
apache-2.0
874
/* Copyright 2016 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. ==============================================================================*/ #include "tensorflow/cc/ops/standard_ops.h" #include "tensorflow/core/kernels/fuzzing/fuzz_session.h" namespace tensorflow { namespace fuzzing { // Fuzz inputs to the example proto decoder. // TODO(dga): Make this more comprehensive. // Right now, it's just a quick PoC to show how to attach the // plumbing, but it needs some real protos to chew on as a // corpus, and the sparse/dense parts should be made more rich // to achieve higher code coverage. class FuzzExampleProtoFastParsing : public FuzzSession { void BuildGraph(const Scope& scope) final { using namespace ::tensorflow::ops; // NOLINT(build/namespaces) // The serialized proto. auto input = Placeholder(scope.WithOpName("input"), DT_STRING); auto in_expanded = ExpandDims(scope, input, Const<int>(scope, 0)); auto names = Const(scope, {"noname"}); std::vector<Output> dense_keys = {Const(scope, {"a"})}; std::vector<Output> sparse_keys; // Empty. std::vector<Output> dense_defaults = {Const(scope, {1.0f})}; DataTypeSlice sparse_types = {}; std::vector<PartialTensorShape> dense_shapes; dense_shapes.push_back(PartialTensorShape()); (void)ParseExample(scope.WithOpName("output"), in_expanded, names, sparse_keys, dense_keys, dense_defaults, sparse_types, dense_shapes); } void FuzzImpl(const uint8_t* data, size_t size) final { // TODO(dga): Test the batch case also. Tensor input_tensor(tensorflow::DT_STRING, TensorShape({})); input_tensor.scalar<string>()() = string(reinterpret_cast<const char*>(data), size); RunInputs({{"input", input_tensor}}); } }; STANDARD_TF_FUZZ_FUNCTION(FuzzExampleProtoFastParsing); } // end namespace fuzzing } // end namespace tensorflow
ghchinoy/tensorflow
tensorflow/core/kernels/fuzzing/example_proto_fast_parsing_fuzz.cc
C++
apache-2.0
2,435
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.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.pentaho.di.core.database.map; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseTransactionListener; /** * This class contains a map between on the one hand * <p/> * the transformation name/thread the partition ID the connection group * <p/> * And on the other hand * <p/> * The database connection The number of times it was opened * * @author Matt */ public class DatabaseConnectionMap { private final ConcurrentMap<String, Database> map; private final AtomicInteger transactionId; private final Map<String, List<DatabaseTransactionListener>> transactionListenersMap; private static final DatabaseConnectionMap connectionMap = new DatabaseConnectionMap(); public static synchronized DatabaseConnectionMap getInstance() { return connectionMap; } private DatabaseConnectionMap() { map = new ConcurrentHashMap<String, Database>(); transactionId = new AtomicInteger( 0 ); transactionListenersMap = new HashMap<String, List<DatabaseTransactionListener>>(); } /** * Tries to obtain an existing <tt>Database</tt> instance for specified parameters. If none is found, then maps the * key's value to <tt>database</tt>. Similarly to {@linkplain ConcurrentHashMap#putIfAbsent(Object, Object)} returns * <tt>null</tt> if there was no value for the specified key and they mapped value otherwise. * * @param connectionGroup connection group * @param partitionID partition's id * @param database database * @return <tt>null</tt> or previous value */ public Database getOrStoreIfAbsent( String connectionGroup, String partitionID, Database database ) { String key = createEntryKey( connectionGroup, partitionID, database ); return map.putIfAbsent( key, database ); } public void removeConnection( String connectionGroup, String partitionID, Database database ) { String key = createEntryKey( connectionGroup, partitionID, database ); map.remove( key ); } /** * @deprecated use {@linkplain #getOrStoreIfAbsent(String, String, Database)} instead */ @Deprecated public synchronized void storeDatabase( String connectionGroup, String partitionID, Database database ) { String key = createEntryKey( connectionGroup, partitionID, database ); map.put( key, database ); } /** * @deprecated use {@linkplain #getOrStoreIfAbsent(String, String, Database)} instead */ @Deprecated public synchronized Database getDatabase( String connectionGroup, String partitionID, Database database ) { String key = createEntryKey( connectionGroup, partitionID, database ); return map.get( key ); } public static String createEntryKey( String connectionGroup, String partitionID, Database database ) { StringBuilder key = new StringBuilder( connectionGroup ); key.append( ':' ).append( database.getDatabaseMeta().getName() ); if ( !Utils.isEmpty( partitionID ) ) { key.append( ':' ).append( partitionID ); } return key.toString(); } public Map<String, Database> getMap() { return map; } public String getNextTransactionId() { return Integer.toString( transactionId.incrementAndGet() ); } public void addTransactionListener( String transactionId, DatabaseTransactionListener listener ) { List<DatabaseTransactionListener> transactionListeners = getTransactionListeners( transactionId ); transactionListeners.add( listener ); } public void removeTransactionListener( String transactionId, DatabaseTransactionListener listener ) { List<DatabaseTransactionListener> transactionListeners = getTransactionListeners( transactionId ); transactionListeners.remove( listener ); } public List<DatabaseTransactionListener> getTransactionListeners( String transactionId ) { List<DatabaseTransactionListener> transactionListeners = transactionListenersMap.get( transactionId ); if ( transactionListeners == null ) { transactionListeners = new ArrayList<DatabaseTransactionListener>(); transactionListenersMap.put( transactionId, transactionListeners ); } return transactionListeners; } public void removeTransactionListeners( String transactionId ) { transactionListenersMap.remove( transactionId ); } }
emartin-pentaho/pentaho-kettle
core/src/main/java/org/pentaho/di/core/database/map/DatabaseConnectionMap.java
Java
apache-2.0
5,471
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; namespace Microsoft.Azure.Management.HDInsight.Models { /// <summary> /// The directory type. /// </summary> public enum DirectoryType { /// <summary> /// active directory type. /// </summary> ActiveDirectory = 1, } }
nemanja88/azure-sdk-for-net
src/ResourceManagement/HDInsight/HDInsight/Generated/Models/DirectoryType.cs
C#
apache-2.0
1,096
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony; /** * WapPushManager constant value definitions */ public class WapPushManagerParams { /** * Application type activity */ public static final int APP_TYPE_ACTIVITY = 0; /** * Application type service */ public static final int APP_TYPE_SERVICE = 1; /** * Process Message return value * Message is handled */ public static final int MESSAGE_HANDLED = 0x1; /** * Process Message return value * Application ID or content type was not found in the application ID table */ public static final int APP_QUERY_FAILED = 0x2; /** * Process Message return value * Receiver application signature check failed */ public static final int SIGNATURE_NO_MATCH = 0x4; /** * Process Message return value * Receiver application was not found */ public static final int INVALID_RECEIVER_NAME = 0x8; /** * Process Message return value * Unknown exception */ public static final int EXCEPTION_CAUGHT = 0x10; /** * Process Message return value * Need further processing after WapPushManager message processing */ public static final int FURTHER_PROCESSING = 0x8000; }
JSDemos/android-sdk-20
src/com/android/internal/telephony/WapPushManagerParams.java
Java
apache-2.0
1,891
require 'test_helper' class TraceSummariesHelperTest < ActionView::TestCase end
rodzyn0688/zipkin
zipkin-web/test/unit/helpers/trace_summaries_helper_test.rb
Ruby
apache-2.0
81
/* * Copyright 2015 LG CNS. * * 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 scouter.client.maria.views; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.TreeColumnLayout; import org.eclipse.jface.viewers.ColumnPixelData; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.IViewSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.ViewPart; import scouter.client.Images; import scouter.client.model.AgentDailyListProxy; import scouter.client.model.DigestModel; import scouter.client.model.RefreshThread; import scouter.client.model.RefreshThread.Refreshable; import scouter.client.model.TextProxy; import scouter.client.net.INetReader; import scouter.client.net.TcpProxy; import scouter.client.popup.DigestDetailDialog; import scouter.client.sorter.TreeLabelSorter; import scouter.client.util.ConsoleProxy; import scouter.client.util.ExUtil; import scouter.client.util.ImageUtil; import scouter.client.util.TimeUtil; import scouter.io.DataInputX; import scouter.lang.DigestKey; import scouter.lang.counters.CounterConstants; import scouter.lang.pack.MapPack; import scouter.lang.pack.Pack; import scouter.lang.pack.PackEnum; import scouter.lang.pack.StatusPack; import scouter.lang.value.ListValue; import scouter.lang.value.MapValue; import scouter.net.RequestCmd; import scouter.util.CastUtil; import scouter.util.DateUtil; import scouter.util.FormatUtil; public class DigestTableView extends ViewPart implements Refreshable { public final static String ID = DigestTableView.class.getName(); double PICO = Math.pow(10, -12); int serverId; Composite parent; TreeViewer viewer; TreeColumnLayout columnLayout; AgentDailyListProxy agentProxy = new AgentDailyListProxy(); RefreshThread thread; boolean isAutoRefresh = false; String date; long stime, etime; HashMap<Integer, DigestModel> root = new HashMap<Integer, DigestModel>(); public void init(IViewSite site) throws PartInitException { super.init(site); String secId = site.getSecondaryId(); this.serverId = CastUtil.cint(secId); } public void createPartControl(Composite parent) { this.parent = parent; GridLayout gridlayout = new GridLayout(1, false); gridlayout.marginHeight = 0; gridlayout.horizontalSpacing = 0; gridlayout.marginWidth = 0; parent.setLayout(gridlayout); columnLayout = new TreeColumnLayout(); Composite mainComp = new Composite(parent, SWT.NONE); mainComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); mainComp.setLayout(columnLayout); viewer = new TreeViewer(mainComp, SWT.FULL_SELECTION | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); createColumns(); final Tree tree = viewer.getTree(); tree.setHeaderVisible(true); tree.setLinesVisible(true); viewer.setLabelProvider(new TreeLabelProvider()); viewer.setContentProvider(new TreeContentProvider()); viewer.setComparator(new TreeLabelSorter(viewer)); viewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { StructuredSelection sel = (StructuredSelection) event.getSelection(); Object o = sel.getFirstElement(); if (o instanceof DigestModel) { DigestModel model = (DigestModel) o; new DigestDetailDialog().show(model, stime, etime, serverId); } } }); viewer.setInput(root); IToolBarManager man = getViewSite().getActionBars().getToolBarManager(); Action actAutoRefresh = new Action("Auto Refresh in 10 sec.", IAction.AS_CHECK_BOX){ public void run() { isAutoRefresh = isChecked(); if (isAutoRefresh) { thread.interrupt(); } } }; actAutoRefresh.setImageDescriptor(ImageUtil.getImageDescriptor(Images.refresh_auto)); man.add(actAutoRefresh); long now = TimeUtil.getCurrentTime(serverId); date = DateUtil.yyyymmdd(now); stime = now - DateUtil.MILLIS_PER_FIVE_MINUTE; etime = now; loadQueryJob.schedule(2000); thread = new RefreshThread(this, 10000); thread.start(); } public void refresh() { if (isAutoRefresh) { root.clear(); long now = TimeUtil.getCurrentTime(serverId); date = DateUtil.yyyymmdd(now); stime = now - DateUtil.MILLIS_PER_FIVE_MINUTE; etime = now; loadQueryJob.schedule(); } } public void setInput(long stime, long etime) { if (loadQueryJob.getState() == Job.WAITING || loadQueryJob.getState() == Job.RUNNING) { MessageDialog.openInformation(null, "STOP", "Previous loading is not yet finished"); return; } if (etime - stime < DateUtil.MILLIS_PER_MINUTE) { stime = etime - DateUtil.MILLIS_PER_MINUTE; } root.clear(); this.stime = stime; this.etime = etime; this.date = DateUtil.yyyymmdd(stime); loadQueryJob.schedule(); } ArrayList<DigestSchema> columnList = new ArrayList<DigestSchema>(); private void createColumns() { columnList.clear(); for (DigestSchema column : DigestSchema.values()) { createTreeViewerColumn(column.getTitle(), column.getWidth(), column.getAlignment(), true, true, column.isNumber()); columnList.add(column); } } private TreeViewerColumn createTreeViewerColumn(String title, int width, int alignment, boolean resizable, boolean moveable, final boolean isNumber) { final TreeViewerColumn viewerColumn = new TreeViewerColumn(viewer, SWT.NONE); final TreeColumn column = viewerColumn.getColumn(); column.setText(title); column.setAlignment(alignment); column.setMoveable(moveable); columnLayout.setColumnData(column, new ColumnPixelData(width, resizable)); column.setData("isNumber", isNumber); column.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { TreeLabelSorter sorter = (TreeLabelSorter) viewer.getComparator(); TreeColumn selectedColumn = (TreeColumn) e.widget; sorter.setColumn(selectedColumn); } }); return viewerColumn; } public void setFocus() { } Job loadQueryJob = new Job("Load Digest List...") { HashMap<DigestKey, MapPack> summaryMap = new HashMap<DigestKey, MapPack>(); HashMap<Integer, StatusPack> firstStatusMap = new HashMap<Integer, StatusPack>(); HashMap<Integer, StatusPack> lastStatusMap = new HashMap<Integer, StatusPack>(); protected IStatus run(final IProgressMonitor monitor) { summaryMap.clear(); firstStatusMap.clear(); lastStatusMap.clear(); monitor.beginTask(DateUtil.hhmmss(stime) + " ~ " + DateUtil.hhmmss(etime), 100); TcpProxy tcp = TcpProxy.getTcpProxy(serverId); try { MapPack param = new MapPack(); ListValue objHashLv = agentProxy.getObjHashLv(date, serverId, CounterConstants.MARIA_PLUGIN); if (objHashLv.size() > 0) { param.put("objHash", objHashLv); param.put("date", date); param.put("time", stime); List<Pack> firstList = tcp.process(RequestCmd.DB_LAST_DIGEST_TABLE, param); for (Pack p : firstList) { StatusPack s = (StatusPack) p; firstStatusMap.put(s.objHash, s); } param.put("stime", stime); param.put("etime", etime); tcp.process(RequestCmd.DB_DIGEST_TABLE, param, new INetReader() { public void process(DataInputX in) throws IOException { Pack p = in.readPack(); switch (p.getPackType()) { case PackEnum.MAP: MapPack m = (MapPack) p; if (m.containsKey("percent")) { monitor.worked(m.getInt("percent")); } else { int objHash = m.getInt("objHash"); int digestHash = m.getInt("digestHash"); summaryMap.put(new DigestKey(objHash, digestHash), m); } break; case PackEnum.PERF_STATUS: StatusPack sp = (StatusPack) p; lastStatusMap.put(sp.objHash, sp); break; } } }); } } catch (Exception e) { ConsoleProxy.errorSafe(e.toString()); } finally { TcpProxy.putTcpProxy(tcp); } Iterator<Integer> itr = lastStatusMap.keySet().iterator(); while (itr.hasNext()) { int objHash = itr.next(); StatusPack firstStatus = firstStatusMap.get(objHash); StatusPack lastStatus = lastStatusMap.get(objHash); HashMap<Integer, MapValue> firstMap = new HashMap<Integer, MapValue>(); if (firstStatus == null) { // nothing } else { // index first values for delta MapValue firstData = firstStatus.data; ListValue firstDigestLv = firstData.getList("DIGEST_TEXT"); for (int i = 0; i < firstDigestLv.size(); i++) { int digestHash = firstDigestLv.getInt(i); MapValue valueMap = new MapValue(); Enumeration<String> keys = firstData.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); valueMap.put(key, firstData.getList(key).get(i)); } firstMap.put(digestHash, valueMap); } } MapValue data = lastStatus.data; ListValue digestLv = data.getList("DIGEST_TEXT"); ListValue schemaNameLv = data.getList("SCHEMA_NAME"); ListValue executionLv = data.getList("COUNT_STAR"); ListValue timerWaitLv = data.getList("SUM_TIMER_WAIT"); ListValue lockTimeLv = data.getList("SUM_LOCK_TIME"); ListValue errorsLv = data.getList("SUM_ERRORS"); ListValue warnsLv = data.getList("SUM_WARNINGS"); ListValue rowsAffectedLv = data.getList("SUM_ROWS_AFFECTED"); ListValue rowsSentLv = data.getList("SUM_ROWS_SENT"); ListValue rowsExaminedLv = data.getList("SUM_ROWS_EXAMINED"); ListValue createdTmpDiskTablesLv = data.getList("SUM_CREATED_TMP_DISK_TABLES"); ListValue createdTmpTablesLv = data.getList("SUM_CREATED_TMP_TABLES"); ListValue selectFullJoin = data.getList("SUM_SELECT_FULL_JOIN"); ListValue selectFullRangeJoin = data.getList("SUM_SELECT_FULL_RANGE_JOIN"); ListValue selectRangeLv = data.getList("SUM_SELECT_RANGE"); ListValue selectRangeCheckLv = data.getList("SUM_SELECT_RANGE_CHECK"); ListValue selectScanLv = data.getList("SUM_SELECT_SCAN"); ListValue sortMergePassesLv = data.getList("SUM_SORT_MERGE_PASSES"); ListValue sortRangeLv = data.getList("SUM_SORT_RANGE"); ListValue sortRowsLv = data.getList("SUM_SORT_ROWS"); ListValue sortScanLv = data.getList("SUM_SORT_SCAN"); ListValue noIndexUsedLv = data.getList("SUM_NO_INDEX_USED"); ListValue noGoodIndexUsedLv = data.getList("SUM_NO_GOOD_INDEX_USED"); ListValue firstSeenLv = data.getList("FIRST_SEEN"); ListValue lastSeenLv = data.getList("LAST_SEEN"); for (int i = 0; i < digestLv.size(); i++) { if (lastSeenLv.getLong(i) < stime || lastSeenLv.getLong(i) > etime) { continue; } DigestModel model = new DigestModel(); int digestHash = digestLv.getInt(i); MapPack m = summaryMap.get(new DigestKey(objHash, digestHash)); if (m == null) continue; long maxTimerWait = m.getLong("MAX_TIMER_WAIT"); long minTimerWait = m.getLong("MIN_TIMER_WAIT"); long avgTimerWait = m.getLong("AVG_TIMER_WAIT"); int count = m.getInt("count"); model.objHash = objHash; model.digestHash = digestHash; model.name = TextProxy.object.getLoadText(date, objHash, serverId); model.database = TextProxy.maria.getLoadText(date, schemaNameLv.getInt(i), serverId); model.firstSeen = firstSeenLv.getLong(i); model.lastSeen = lastSeenLv.getLong(i); model.avgResponseTime = avgTimerWait / (double) count; model.minResponseTime = minTimerWait; model.maxResponseTime = maxTimerWait; MapValue firstValue = firstMap.get(digestHash); if (firstValue == null) { firstValue = new MapValue(); } model.execution = executionLv.getInt(i) - firstValue.getInt("COUNT_STAR"); if (model.execution < 1) { System.out.println("first=>" + firstStatus); System.out.println("last =>" + firstStatus); } model.errorCnt = errorsLv.getInt(i) - firstValue.getInt("SUM_ERRORS"); model.warnCnt = warnsLv.getInt(i) - firstValue.getInt("SUM_WARNINGS"); model.sumResponseTime = timerWaitLv.getLong(i) - firstValue.getLong("SUM_TIMER_WAIT"); model.lockTime = lockTimeLv.getLong(i) - firstValue.getLong("SUM_LOCK_TIME"); model.rowsAffected = rowsAffectedLv.getLong(i) - firstValue.getLong("SUM_ROWS_AFFECTED"); model.rowsSent = rowsSentLv.getLong(i) - firstValue.getLong("SUM_ROWS_SENT"); model.rowsExamined = rowsExaminedLv.getLong(i) - firstValue.getLong("SUM_ROWS_EXAMINED"); model.createdTmpDiskTables = createdTmpDiskTablesLv.getLong(i) - firstValue.getLong("SUM_CREATED_TMP_DISK_TABLES"); model.createdTmpTables = createdTmpTablesLv.getLong(i) - firstValue.getLong("SUM_CREATED_TMP_TABLES"); model.selectFullJoin = selectFullJoin.getLong(i) - firstValue.getLong("SUM_SELECT_FULL_JOIN"); model.selectFullRangeJoin = selectFullRangeJoin.getLong(i) - firstValue.getLong("SUM_SELECT_FULL_RANGE_JOIN"); model.selectRange = selectRangeLv.getLong(i) - firstValue.getLong("SUM_SELECT_RANGE"); model.selectRangeCheck = selectRangeCheckLv.getLong(i) - firstValue.getLong("SUM_SELECT_RANGE_CHECK"); model.selectScan = selectScanLv.getLong(i) - firstValue.getLong("SUM_SELECT_SCAN"); model.sortMergePasses = sortMergePassesLv.getLong(i) - firstValue.getLong("SUM_SORT_MERGE_PASSES"); model.sortRange =sortRangeLv.getLong(i) - firstValue.getLong("SUM_SORT_RANGE"); model.sortRows = sortRowsLv.getLong(i) - firstValue.getLong("SUM_SORT_ROWS"); model.sortScan = sortScanLv.getLong(i) - firstValue.getLong("SUM_SORT_SCAN"); model.noIndexUsed = noIndexUsedLv.getLong(i) - firstValue.getLong("SUM_NO_INDEX_USED"); model.noGoodIndexUsed = noGoodIndexUsedLv.getLong(i) - firstValue.getLong("SUM_NO_GOOD_INDEX_USED"); DigestModel parent = root.get(digestHash); if (parent == null) { parent = new DigestModel(); parent.digestHash = digestHash; String digestTxt = TextProxy.maria.getLoadText(date, digestHash, serverId); parent.name = digestTxt == null ? "unknown hash" : digestTxt; root.put(digestHash, parent); } model.parent = parent; parent.addChild(model); } } Iterator<DigestModel> parents = root.values().iterator(); while (parents.hasNext()) { DigestModel parent = parents.next(); DigestModel[] childs = parent.getChildArray(); if (childs != null) { double sumAvg = 0.0d; for (DigestModel child : childs) { sumAvg += child.avgResponseTime; } parent.avgResponseTime = sumAvg / childs.length; } } monitor.done(); ExUtil.exec(viewer.getTree(), new Runnable() { public void run() { DigestTableView.this.setContentDescription(DateUtil.format(stime, "MM-dd HH:mm:ss") + " ~ " + DateUtil.format(etime, "MM-dd HH:mm:ss") + " (" + root.size() + ")"); viewer.refresh(); } }); return Status.OK_STATUS; } }; class TreeContentProvider implements ITreeContentProvider { public void dispose() { } public void inputChanged(Viewer arg0, Object arg1, Object arg2) { } public Object[] getChildren(Object parentElement) { if (parentElement instanceof DigestModel) { DigestModel parent = (DigestModel) parentElement; Object[] array = parent.getChildArray(); if(array != null) return array; } return new Object[0]; } public Object[] getElements(Object inputElement) { if (inputElement instanceof HashMap) { HashMap map = (HashMap) inputElement; Object[] objArray = new Object[map.size()]; Iterator itr = map.values().iterator(); int cnt = 0; while (itr.hasNext()) { objArray[cnt] = itr.next(); cnt++; } return objArray; } return new Object[0]; } public Object getParent(Object element) { if (element instanceof DigestModel) { return ((DigestModel) element).parent; } return null; } public boolean hasChildren(Object element) { if (element instanceof DigestModel) { return ((DigestModel) element).getChildArray() != null; } return false; } } class TreeLabelProvider implements ITableLabelProvider { public void addListener(ILabelProviderListener listener) { } public void dispose() { } public boolean isLabelProperty(Object element, String property) { return false; } public void removeListener(ILabelProviderListener listener) { } public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { if (element instanceof DigestModel) { DigestModel model = (DigestModel) element; DigestSchema column = columnList.get(columnIndex); switch (column) { case DIGEST_TEXT: return model.name; case SCHEMA_NAME: return model.database; case COUNT_STAR: return FormatUtil.print(model.execution, "#,##0"); case SUM_ERRORS: return FormatUtil.print(model.errorCnt, "#,##0"); case SUM_WARNINGS: return FormatUtil.print(model.warnCnt, "#,##0"); case SUM_TIMER_WAIT: return FormatUtil.print(model.sumResponseTime * PICO, "#,##0.00#"); case AVG_TIMER_WAIT: return FormatUtil.print(model.avgResponseTime * PICO, "#,##0.00#"); case MIN_TIMER_WAIT: return FormatUtil.print(model.minResponseTime * PICO, "#,##0.00#"); case MAX_TIMER_WAIT: return FormatUtil.print(model.maxResponseTime * PICO, "#,##0.00#"); case SUM_LOCK_TIME: return FormatUtil.print(model.lockTime * PICO, "#,##0.00#"); case SUM_ROWS_AFFECTED: return FormatUtil.print(model.rowsAffected, "#,##0"); case SUM_ROWS_SENT: return FormatUtil.print(model.rowsSent, "#,##0"); case SUM_ROWS_EXAMINED: return FormatUtil.print(model.rowsExamined, "#,##0"); case SUM_CREATED_TMP_DISK_TABLES: return FormatUtil.print(model.createdTmpDiskTables, "#,##0"); case SUM_CREATED_TMP_TABLES: return FormatUtil.print(model.createdTmpTables, "#,##0"); case SUM_SELECT_FULL_JOIN: return FormatUtil.print(model.selectFullJoin, "#,##0"); case SUM_SELECT_FULL_RANGE_JOIN: return FormatUtil.print(model.selectFullRangeJoin, "#,##0"); case SUM_SELECT_RANGE: return FormatUtil.print(model.selectRange, "#,##0"); case SUM_SELECT_RANGE_CHECK: return FormatUtil.print(model.selectRangeCheck, "#,##0"); case SUM_SELECT_SCAN: return FormatUtil.print(model.selectScan, "#,##0"); case SUM_SORT_MERGE_PASSES: return FormatUtil.print(model.sortMergePasses, "#,##0"); case SUM_SORT_RANGE: return FormatUtil.print(model.sortRange, "#,##0"); case SUM_SORT_ROWS: return FormatUtil.print(model.sortRows, "#,##0"); case SUM_SORT_SCAN: return FormatUtil.print(model.sortScan, "#,##0"); case SUM_NO_INDEX_USED: return FormatUtil.print(model.noIndexUsed, "#,##0"); case SUM_NO_GOOD_INDEX_USED: return FormatUtil.print(model.noGoodIndexUsed, "#,##0"); case FIRST_SEEN: return DateUtil.timestamp(model.firstSeen); case LAST_SEEN: return DateUtil.timestamp(model.lastSeen); } } return null; } } public void dispose() { super.dispose(); if (loadQueryJob != null && (loadQueryJob.getState() == Job.WAITING || loadQueryJob.getState() == Job.RUNNING)) { loadQueryJob.cancel(); } } public static void main(String[] args) { System.out.println(139871834183L * Math.pow(10, -12)); } }
jahnaviancha/scouter
scouter.client/src/scouter/client/maria/views/DigestTableView.java
Java
apache-2.0
21,743
package org.zstack.sdk; public class GetCandidateVmForAttachingIsoResult { public java.util.List<VmInstanceInventory> inventories; public void setInventories(java.util.List<VmInstanceInventory> inventories) { this.inventories = inventories; } public java.util.List<VmInstanceInventory> getInventories() { return this.inventories; } }
Alvin-Lau/zstack
sdk/src/main/java/org/zstack/sdk/GetCandidateVmForAttachingIsoResult.java
Java
apache-2.0
372
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.FindSymbols { public static partial class SymbolFinder { /// <summary> /// Callback object we pass to the OOP server to hear about the result /// of the FindReferencesEngine as it executes there. /// </summary> internal sealed class FindReferencesServerCallback : IEqualityComparer<SerializableSymbolAndProjectId> { private readonly Solution _solution; private readonly IStreamingFindReferencesProgress _progress; private readonly CancellationToken _cancellationToken; private readonly object _gate = new(); private readonly Dictionary<SerializableSymbolAndProjectId, ISymbol> _definitionMap; public FindReferencesServerCallback( Solution solution, IStreamingFindReferencesProgress progress, CancellationToken cancellationToken) { _solution = solution; _progress = progress; _cancellationToken = cancellationToken; _definitionMap = new Dictionary<SerializableSymbolAndProjectId, ISymbol>(this); } public ValueTask AddItemsAsync(int count) => _progress.ProgressTracker.AddItemsAsync(count); public ValueTask ItemCompletedAsync() => _progress.ProgressTracker.ItemCompletedAsync(); public ValueTask OnStartedAsync() => _progress.OnStartedAsync(); public ValueTask OnCompletedAsync() => _progress.OnCompletedAsync(); public ValueTask OnFindInDocumentStartedAsync(DocumentId documentId) { var document = _solution.GetDocument(documentId); return _progress.OnFindInDocumentStartedAsync(document); } public ValueTask OnFindInDocumentCompletedAsync(DocumentId documentId) { var document = _solution.GetDocument(documentId); return _progress.OnFindInDocumentCompletedAsync(document); } public async ValueTask OnDefinitionFoundAsync(SerializableSymbolAndProjectId definition) { var symbol = await definition.TryRehydrateAsync( _solution, _cancellationToken).ConfigureAwait(false); if (symbol == null) return; lock (_gate) { _definitionMap[definition] = symbol; } await _progress.OnDefinitionFoundAsync(symbol).ConfigureAwait(false); } public async ValueTask OnReferenceFoundAsync( SerializableSymbolAndProjectId definition, SerializableReferenceLocation reference) { ISymbol symbol; lock (_gate) { // The definition may not be in the map if we failed to map it over using TryRehydrateAsync in OnDefinitionFoundAsync. // Just ignore this reference. Note: while this is a degraded experience: // // 1. TryRehydrateAsync logs an NFE so we can track down while we're failing to roundtrip the // definition so we can track down that issue. // 2. NFE'ing and failing to show a result, is much better than NFE'ing and then crashing // immediately afterwards. if (!_definitionMap.TryGetValue(definition, out symbol)) return; } var referenceLocation = await reference.RehydrateAsync( _solution, _cancellationToken).ConfigureAwait(false); await _progress.OnReferenceFoundAsync(symbol, referenceLocation).ConfigureAwait(false); } bool IEqualityComparer<SerializableSymbolAndProjectId>.Equals(SerializableSymbolAndProjectId x, SerializableSymbolAndProjectId y) => y.SymbolKeyData.Equals(x.SymbolKeyData); int IEqualityComparer<SerializableSymbolAndProjectId>.GetHashCode(SerializableSymbolAndProjectId obj) => obj.SymbolKeyData.GetHashCode(); } } }
ErikSchierboom/roslyn
src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.FindReferencesServerCallback.cs
C#
apache-2.0
4,661
/// <reference path='fourslash.ts'/> ////var o = { //// foo() { }, //// bar: 0, //// "some other name": 1 ////}; //// ////o["/*1*/bar"]; ////o["/*2*/ goTo.marker('1'); verify.completionListContains("foo"); verify.completionListAllowsNewIdentifier(); verify.completionListCount(3); goTo.marker('2'); verify.completionListContains("some other name"); verify.completionListAllowsNewIdentifier(); verify.completionListCount(3);
synaptek/TypeScript
tests/cases/fourslash/completionForStringLiteral2.ts
TypeScript
apache-2.0
456
// ---------------------------------------------------------------------------------- // // Copyright 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 // 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.Collections.Generic; using System.Management.Automation; using Microsoft.Azure.Commands.Sql.Common; using Microsoft.Azure.Commands.Sql.ElasticPool.Model; using Microsoft.Azure.Commands.Sql.ElasticPool.Services; namespace Microsoft.Azure.Commands.Sql.ElasticPool.Cmdlet { public abstract class AzureSqlElasticPoolActivityCmdletBase : AzureSqlCmdletBase<IEnumerable<AzureSqlElasticPoolActivityModel>, AzureSqlElasticPoolAdapter> { /// <summary> /// Gets or sets the name of the database server to use. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 1, HelpMessage = "The name of the Azure SQL Server the Elastic Pool is in.")] [ValidateNotNullOrEmpty] public string ServerName { get; set; } /// <summary> /// Gets or sets the name of the ElasticPool to use. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 2, HelpMessage = "The name of the Azure SQL Elastic Pool.")] [ValidateNotNullOrEmpty] public string ElasticPoolName { get; set; } /// <summary> /// Initializes the adapter /// </summary> /// <param name="subscription"></param> /// <returns></returns> protected override AzureSqlElasticPoolAdapter InitModelAdapter(Azure.Common.Authentication.Models.AzureSubscription subscription) { return new AzureSqlElasticPoolAdapter(DefaultProfile.Context); } } }
mayurid/azure-powershell
src/ResourceManager/Sql/Commands.Sql/Elastic Pools/Cmdlet/AzureSqlElasticPoolActivityCmdletBase.cs
C#
apache-2.0
2,382
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), hosted at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * Agfa-Gevaert AG. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): * See listed authors below. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4chee.usr.war.common; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.link.Link; import org.dcm4chee.usr.war.pages.LoginPage; /** * @author Robert David <robert.david@agfa.com> * @version $Revision$ $Date$ * @since 28.09.2009 */ public class PageExpiredErrorPage extends WebPage { public PageExpiredErrorPage() { Link<?> backToLoginLink = new Link<Object>("back-to-login") { private static final long serialVersionUID = 1L; @Override public void onClick() { this.getSession().invalidateNow(); setResponsePage(LoginPage.class); } }; add(backToLoginLink); } }
medicayun/medicayundicom
dcm4chee-usr/trunk/dcm4chee-usr-war/src/main/java/org/dcm4chee/usr/war/common/PageExpiredErrorPage.java
Java
apache-2.0
2,548
/* * 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.core.appender.mom; import java.io.Serializable; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.naming.NamingException; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.appender.AbstractManager; import org.apache.logging.log4j.core.appender.ManagerFactory; import org.apache.logging.log4j.core.net.JndiManager; import org.apache.logging.log4j.status.StatusLogger; /** * JMS connection and session manager. Can be used to access MessageProducer, MessageConsumer, and Message objects * involving a configured ConnectionFactory and Destination. */ public class JmsManager extends AbstractManager { private static final Logger LOGGER = StatusLogger.getLogger(); private static final JmsManagerFactory FACTORY = new JmsManagerFactory(); private final JndiManager jndiManager; private final Connection connection; private final Session session; private final Destination destination; private JmsManager(final String name, final JndiManager jndiManager, final String connectionFactoryName, final String destinationName, final String username, final String password) throws NamingException, JMSException { super(name); this.jndiManager = jndiManager; final ConnectionFactory connectionFactory = this.jndiManager.lookup(connectionFactoryName); if (username != null && password != null) { this.connection = connectionFactory.createConnection(username, password); } else { this.connection = connectionFactory.createConnection(); } this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); this.destination = this.jndiManager.lookup(destinationName); this.connection.start(); } /** * Gets a JmsManager using the specified configuration parameters. * * @param name The name to use for this JmsManager. * @param jndiManager The JndiManager to look up JMS information through. * @param connectionFactoryName The binding name for the {@link javax.jms.ConnectionFactory}. * @param destinationName The binding name for the {@link javax.jms.Destination}. * @param username The username to connect with or {@code null} for no authentication. * @param password The password to use with the given username or {@code null} for no authentication. * @return The JmsManager as configured. */ public static JmsManager getJmsManager(final String name, final JndiManager jndiManager, final String connectionFactoryName, final String destinationName, final String username, final String password) { final JmsConfiguration configuration = new JmsConfiguration(jndiManager, connectionFactoryName, destinationName, username, password); return FACTORY.createManager(name, configuration); } /** * Creates a MessageConsumer on this Destination using the current Session. * * @return A MessageConsumer on this Destination. * @throws JMSException */ public MessageConsumer createMessageConsumer() throws JMSException { return this.session.createConsumer(this.destination); } /** * Creates a MessageProducer on this Destination using the current Session. * * @return A MessageProducer on this Destination. * @throws JMSException */ public MessageProducer createMessageProducer() throws JMSException { return this.session.createProducer(this.destination); } /** * Creates a TextMessage or ObjectMessage from a Serializable object. For instance, when using a text-based * {@link org.apache.logging.log4j.core.Layout} such as {@link org.apache.logging.log4j.core.layout.PatternLayout}, * the {@link org.apache.logging.log4j.core.LogEvent} message will be serialized to a String. When using a * layout such as {@link org.apache.logging.log4j.core.layout.SerializedLayout}, the LogEvent message will be * serialized as a Java object. * * @param object The LogEvent or String message to wrap. * @return A new JMS message containing the provided object. * @throws JMSException */ public Message createMessage(final Serializable object) throws JMSException { if (object instanceof String) { return this.session.createTextMessage((String) object); } return this.session.createObjectMessage(object); } @Override protected void releaseSub() { try { this.session.close(); } catch (final JMSException ignored) { } try { this.connection.close(); } catch (final JMSException ignored) { } this.jndiManager.release(); } private static class JmsConfiguration { private final JndiManager jndiManager; private final String connectionFactoryName; private final String destinationName; private final String username; private final String password; private JmsConfiguration(final JndiManager jndiManager, final String connectionFactoryName, final String destinationName, final String username, final String password) { this.jndiManager = jndiManager; this.connectionFactoryName = connectionFactoryName; this.destinationName = destinationName; this.username = username; this.password = password; } } private static class JmsManagerFactory implements ManagerFactory<JmsManager, JmsConfiguration> { @Override public JmsManager createManager(final String name, final JmsConfiguration data) { try { return new JmsManager(name, data.jndiManager, data.connectionFactoryName, data.destinationName, data.username, data.password); } catch (final Exception e) { LOGGER.error("Error creating JmsManager using ConnectionFactory [{}] and Destination [{}].", data.connectionFactoryName, data.destinationName, e); return null; } } } }
SourceStudyNotes/log4j2
src/main/java/org/apache/logging/log4j/core/appender/mom/JmsManager.java
Java
apache-2.0
7,359
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib 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. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var mgf = require( './../lib' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.strictEqual( typeof mgf, 'function', 'main export is a function' ); t.end(); }); tape( 'attached to the main export is a factory method for generating `mgf` functions', function test( t ) { t.equal( typeof mgf.factory, 'function', 'exports a factory method' ); t.end(); });
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/dists/weibull/mgf/test/test.js
JavaScript
apache-2.0
1,090
// Copyright 2016 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/resource_mgr.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/lib/core/errors.h" using ::tensorflow::shape_inference::InferenceContext; using ::tensorflow::shape_inference::ShapeAndType; using ::tensorflow::shape_inference::ShapeHandle; namespace tensorflow { namespace { Status ValidateVariableResourceHandle(InferenceContext* c, ShapeAndType* shape_and_type) { auto* handle_data = c->input_handle_shapes_and_types(0); if (handle_data == nullptr || handle_data->empty()) { shape_and_type->shape = c->UnknownShape(); shape_and_type->dtype = DT_INVALID; } else { *shape_and_type = (*handle_data)[0]; DataType value_dtype; TF_RETURN_IF_ERROR(c->GetAttr("dtype", &value_dtype)); if (shape_and_type->dtype != value_dtype) { return errors::InvalidArgument( "Trying to read variable with wrong dtype. " "Expected ", DataTypeString(shape_and_type->dtype), " got ", DataTypeString(value_dtype)); } } return Status::OK(); } Status ReadVariableShapeFn(InferenceContext* c) { ShapeAndType shape_and_type; TF_RETURN_IF_ERROR(ValidateVariableResourceHandle(c, &shape_and_type)); c->set_output(0, shape_and_type.shape); return Status::OK(); } Status ReadVariablesShapeFn(InferenceContext* c) { int n; TF_RETURN_IF_ERROR(c->GetAttr("N", &n)); DataTypeVector value_dtypes; TF_RETURN_IF_ERROR(c->GetAttr("dtypes", &value_dtypes)); if (n != value_dtypes.size()) { return errors::InvalidArgument( "Mismatched number of arguments to ReadVariablesOp"); } for (int i = 0; i < n; ++i) { ShapeAndType shape_and_type; auto* handle_data = c->input_handle_shapes_and_types(i); if (handle_data == nullptr || handle_data->empty()) { shape_and_type.shape = c->UnknownShape(); shape_and_type.dtype = DT_INVALID; } else { shape_and_type = (*handle_data)[0]; if (shape_and_type.dtype != value_dtypes[i]) { return errors::InvalidArgument( "Trying to read variable with wrong dtype. " "Expected ", DataTypeString(shape_and_type.dtype), " got ", DataTypeString(value_dtypes[i])); } } c->set_output(i, shape_and_type.shape); } return Status::OK(); } } // namespace REGISTER_OP("VarHandleOp") .Attr("container: string = ''") .Attr("shared_name: string = ''") .Attr("dtype: type") .Attr("shape: shape") .Output("resource: resource") .SetIsStateful() .SetShapeFn([](InferenceContext* c) { c->set_output(0, c->Scalar()); DataType t; TF_RETURN_IF_ERROR(c->GetAttr("dtype", &t)); PartialTensorShape p; TF_RETURN_IF_ERROR(c->GetAttr("shape", &p)); ShapeHandle s; TF_RETURN_IF_ERROR(c->MakeShapeFromPartialTensorShape(p, &s)); c->set_output_handle_shapes_and_types(0, std::vector<ShapeAndType>{{s, t}}); return Status::OK(); }); REGISTER_OP("_VarHandlesOp") .Attr("containers: list(string)") .Attr("shared_names: list(string)") .Attr("N: int >= 0") .Attr("dtypes: list(type)") .Attr("shapes: list(shape)") .Output("resources: N * resource") .SetIsStateful() .SetShapeFn([](InferenceContext* c) { int n; TF_RETURN_IF_ERROR(c->GetAttr("N", &n)); DataTypeVector dtypes; TF_RETURN_IF_ERROR(c->GetAttr("dtypes", &dtypes)); std::vector<PartialTensorShape> shapes; TF_RETURN_IF_ERROR(c->GetAttr("shapes", &shapes)); if (dtypes.size() != n) { return errors::InvalidArgument("Mismatched number of dtypes (n=", n, ", num dtypes=", dtypes.size(), ")"); } if (shapes.size() != n) { return errors::InvalidArgument("Mismatched number of shapes (n=", n, ", num shapes=", shapes.size(), ")"); } for (int i = 0; i < n; ++i) { c->set_output(i, c->Scalar()); ShapeHandle s; TF_RETURN_IF_ERROR(c->MakeShapeFromPartialTensorShape(shapes[i], &s)); c->set_output_handle_shapes_and_types( i, std::vector<ShapeAndType>{{s, dtypes[i]}}); } return Status::OK(); }); REGISTER_OP("ReadVariableOp") .Input("resource: resource") .Output("value: dtype") .Attr("dtype: type") .SetShapeFn(ReadVariableShapeFn); REGISTER_OP("_ReadVariablesOp") .Attr("N: int >= 0") .Input("resources: N * resource") .Output("values: dtypes") .Attr("dtypes: list(type)") .SetShapeFn(ReadVariablesShapeFn); Status ReadGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FunctionDefHelper::Define( // Arg defs {"x: resource", "dy: float"}, // Ret val defs {"dy: float"}, // Attr defs {}, // Nodes {}); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("ReadVariableOp", ReadGrad); REGISTER_OP("DestroyResourceOp") .Input("resource: resource") .Attr("ignore_lookup_error: bool = true") .SetIsStateful() .SetShapeFn(shape_inference::NoOutputs); Status CreateAssignShapeFn(InferenceContext* c) { ShapeAndType handle_shape_and_type; TF_RETURN_IF_ERROR(ValidateVariableResourceHandle(c, &handle_shape_and_type)); ShapeHandle value_shape = c->input(1); ShapeHandle unused; TF_RETURN_IF_ERROR( c->Merge(handle_shape_and_type.shape, value_shape, &unused)); return Status::OK(); } REGISTER_OP("AssignVariableOp") .Input("resource: resource") .Input("value: dtype") .Attr("dtype: type") .SetShapeFn(CreateAssignShapeFn); REGISTER_OP("AssignAddVariableOp") .Input("resource: resource") .Input("value: dtype") .Attr("dtype: type") .SetShapeFn(CreateAssignShapeFn); REGISTER_OP("AssignSubVariableOp") .Input("resource: resource") .Input("value: dtype") .Attr("dtype: type") .SetShapeFn(CreateAssignShapeFn); REGISTER_OP("VarIsInitializedOp") .Input("resource: resource") .Output("is_initialized: bool") .SetShapeFn(tensorflow::shape_inference::ScalarShape); Status VariableShapeShapeFn(InferenceContext* c) { auto* handle_data = c->input_handle_shapes_and_types(0); if (handle_data == nullptr || handle_data->empty()) { c->set_output(0, c->Vector(c->UnknownDim())); return Status::OK(); } ShapeHandle var_shape = (*handle_data)[0].shape; int64 rank = c->RankKnown(var_shape) ? c->Rank(var_shape) : InferenceContext::kUnknownDim; c->set_output(0, c->Vector(rank)); return Status::OK(); } REGISTER_OP("VariableShape") .Input("input: resource") .Output("output: out_type") .Attr("out_type: {int32, int64} = DT_INT32") .SetShapeFn(VariableShapeShapeFn); REGISTER_OP("ResourceGather") .Input("resource: resource") .Input("indices: Tindices") .Attr("validate_indices: bool = true") .Output("output: dtype") .Attr("dtype: type") .Attr("Tindices: {int32,int64}") .SetShapeFn([](InferenceContext* c) { ShapeAndType handle_shape_and_type; TF_RETURN_IF_ERROR( ValidateVariableResourceHandle(c, &handle_shape_and_type)); ShapeHandle unused; TF_RETURN_IF_ERROR( c->WithRankAtLeast(handle_shape_and_type.shape, 1, &unused)); ShapeHandle params_subshape; TF_RETURN_IF_ERROR( c->Subshape(handle_shape_and_type.shape, 1, &params_subshape)); ShapeHandle indices_shape = c->input(1); ShapeHandle out; TF_RETURN_IF_ERROR(c->Concatenate(indices_shape, params_subshape, &out)); c->set_output(0, out); return Status::OK(); }); namespace { Status ResourceScatterUpdateShape(InferenceContext* c) { ShapeAndType handle_shape_and_type; TF_RETURN_IF_ERROR(ValidateVariableResourceHandle(c, &handle_shape_and_type)); ShapeHandle var_shape = handle_shape_and_type.shape; ShapeHandle indices_shape = c->input(1); ShapeHandle unused_updates_shape; ShapeHandle concat; ShapeHandle var_subshape; TF_RETURN_IF_ERROR(c->Subshape(var_shape, 1, &var_subshape)); TF_RETURN_IF_ERROR(c->Concatenate(indices_shape, var_subshape, &concat)); TF_RETURN_IF_ERROR( InferenceContext::Rank(c->input(2)) == 0 ? Status::OK() : c->Merge(c->input(2), concat, &unused_updates_shape)); return Status::OK(); } } // namespace REGISTER_OP("ResourceScatterAdd") .Input("resource: resource") .Input("indices: Tindices") .Input("updates: dtype") .Attr("dtype: numbertype") .Attr("Tindices: {int32, int64}") .SetShapeFn(ResourceScatterUpdateShape); REGISTER_OP("ResourceScatterSub") .Input("resource: resource") .Input("indices: Tindices") .Input("updates: dtype") .Attr("dtype: numbertype") .Attr("Tindices: {int32, int64}") .SetShapeFn(ResourceScatterUpdateShape); REGISTER_OP("ResourceScatterMul") .Input("resource: resource") .Input("indices: Tindices") .Input("updates: dtype") .Attr("dtype: numbertype") .Attr("Tindices: {int32, int64}") .SetShapeFn(ResourceScatterUpdateShape); REGISTER_OP("ResourceScatterDiv") .Input("resource: resource") .Input("indices: Tindices") .Input("updates: dtype") .Attr("dtype: numbertype") .Attr("Tindices: {int32, int64}") .SetShapeFn(ResourceScatterUpdateShape); REGISTER_OP("ResourceScatterMin") .Input("resource: resource") .Input("indices: Tindices") .Input("updates: dtype") .Attr("dtype: numbertype") .Attr("Tindices: {int32, int64}") .SetShapeFn(ResourceScatterUpdateShape); REGISTER_OP("ResourceScatterMax") .Input("resource: resource") .Input("indices: Tindices") .Input("updates: dtype") .Attr("dtype: numbertype") .Attr("Tindices: {int32, int64}") .SetShapeFn(ResourceScatterUpdateShape); REGISTER_OP("ResourceScatterUpdate") .Input("resource: resource") .Input("indices: Tindices") .Input("updates: dtype") .Attr("dtype: type") .Attr("Tindices: {int32, int64}") .SetShapeFn(ResourceScatterUpdateShape); REGISTER_OP("MutexV2") .Attr("container: string = ''") .Attr("shared_name: string = ''") .Output("resource: resource") .SetIsStateful() .SetShapeFn([](InferenceContext* c) { c->set_output(0, c->Scalar()); return Status::OK(); }); REGISTER_OP("MutexLock") .Input("mutex: resource") .Output("mutex_lock: variant") .SetIsStateful() .SetShapeFn([](InferenceContext* c) { c->set_output(0, c->Scalar()); return Status::OK(); }); REGISTER_OP("ConsumeMutexLock") .Input("mutex_lock: variant") .SetIsStateful() .SetShapeFn([](InferenceContext* c) { return Status::OK(); }); } // namespace tensorflow
hfp/tensorflow-xsmm
tensorflow/core/ops/resource_variable_ops.cc
C++
apache-2.0
11,757
require "formula" class Libpng < Formula homepage "http://www.libpng.org/pub/png/libpng.html" url "https://downloads.sf.net/project/libpng/libpng16/1.6.13/libpng-1.6.13.tar.xz" sha1 "5ae32b6b99cef6c5c85feab8edf9d619e1773b15" bottle do cellar :any sha1 "c4c5f94b771ea53620d9b6c508b382b3a40d6c80" => :yosemite sha1 "09af92d209c67dd0719d16866dc26c05bbbef77b" => :mavericks sha1 "23812e76bf0e3f98603c6d22ab69258b219918ca" => :mountain_lion sha1 "af1fe6844a0614652bbc9b60fd84c57e24da93ee" => :lion end keg_only :provided_pre_mountain_lion option :universal def install ENV.universal_binary if build.universal? system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make install" end end
0xbb/homebrew
Library/Formula/libpng.rb
Ruby
bsd-2-clause
844
#!/usr/bin/python # Copyright (c)2011-2014 the Boeing Company. # See the LICENSE file included in this distribution. # # author: Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com> # ''' wlanemanetests.py - This script tests the performance of the WLAN device in CORE by measuring various metrics: - delay experienced when pinging end-to-end - maximum TCP throughput achieved using iperf end-to-end - the CPU used and loss experienced when running an MGEN flow of UDP traffic All MANET nodes are arranged in a row, so that any given node can only communicate with the node to its right or to its left. Performance is measured using traffic that travels across each hop in the network. Static /32 routing is used instead of any dynamic routing protocol. Various underlying network types are tested: - bridged (the CORE default, uses ebtables) - bridged with netem (add link effects to the bridge using tc queues) - EMANE bypass - the bypass model just forwards traffic - EMANE RF-PIPE - the bandwidth (bitrate) is set very high / no restrictions - EMANE RF-PIPE - bandwidth is set similar to netem case - EMANE RF-PIPE - default connectivity is off and pathloss events are generated to connect the nodes in a line Results are printed/logged in CSV format. ''' import os, sys, time, optparse, datetime, math from string import Template try: from core import pycore except ImportError: # hack for Fedora autoconf that uses the following pythondir: if "/usr/lib/python2.6/site-packages" in sys.path: sys.path.append("/usr/local/lib/python2.6/site-packages") if "/usr/lib64/python2.6/site-packages" in sys.path: sys.path.append("/usr/local/lib64/python2.6/site-packages") if "/usr/lib/python2.7/site-packages" in sys.path: sys.path.append("/usr/local/lib/python2.7/site-packages") if "/usr/lib64/python2.7/site-packages" in sys.path: sys.path.append("/usr/local/lib64/python2.7/site-packages") from core import pycore from core.misc import ipaddr from core.misc.utils import mutecall from core.constants import QUAGGA_STATE_DIR from core.emane.emane import Emane from core.emane.bypass import EmaneBypassModel from core.emane.rfpipe import EmaneRfPipeModel try: import emaneeventservice import emaneeventpathloss except Exception, e: try: from emanesh.events import EventService from emanesh.events import PathlossEvent except Exception, e2: raise ImportError, "failed to import EMANE Python bindings:\n%s\n%s" % \ (e, e2) # global Experiment object (for interaction with 'python -i') exp = None # move these to core.misc.utils def readstat(): f = open("/proc/stat", "r") lines = f.readlines() f.close() return lines def numcpus(): lines = readstat() n = 0 for l in lines[1:]: if l[:3] != "cpu": break n += 1 return n def getcputimes(line): # return (user, nice, sys, idle) from a /proc/stat cpu line # assume columns are: # cpu# user nice sys idle iowait irq softirq steal guest (man 5 proc) items = line.split() (user, nice, sys, idle) = map(lambda(x): int(x), items[1:5]) return [user, nice, sys, idle] def calculatecpu(timesa, timesb): for i in range(len(timesa)): timesb[i] -= timesa[i] total = sum(timesb) if total == 0: return 0.0 else: # subtract % time spent in idle time return 100 - ((100.0 * timesb[-1]) / total) # end move these to core.misc.utils class Cmd(object): ''' Helper class for running a command on a node and parsing the result. ''' args = "" def __init__(self, node, verbose=False): ''' Initialize with a CoreNode (LxcNode) ''' self.id = None self.stdin = None self.out = None self.node = node self.verbose = verbose def info(self, msg): ''' Utility method for writing output to stdout.''' print msg sys.stdout.flush() def warn(self, msg): ''' Utility method for writing output to stderr. ''' print >> sys.stderr, "XXX %s:" % self.node.name, msg sys.stderr.flush() def run(self): ''' This is the primary method used for running this command. ''' self.open() status = self.id.wait() r = self.parse() self.cleanup() return r def open(self): ''' Exceute call to node.popen(). ''' self.id, self.stdin, self.out, self.err = \ self.node.popen((self.args)) def parse(self): ''' This method is overloaded by child classes and should return some result. ''' return None def cleanup(self): ''' Close the Popen channels.''' self.stdin.close() self.out.close() self.err.close() tmp = self.id.wait() if tmp: self.warn("nonzero exit status:", tmp) class ClientServerCmd(Cmd): ''' Helper class for running a command on a node and parsing the result. ''' args = "" client_args = "" def __init__(self, node, client_node, verbose=False): ''' Initialize with two CoreNodes, node is the server ''' Cmd.__init__(self, node, verbose) self.client_node = client_node def run(self): ''' Run the server command, then the client command, then kill the server ''' self.open() # server self.client_open() # client status = self.client_id.wait() self.node.cmdresult(['killall', self.args[0]]) # stop the server r = self.parse() self.cleanup() return r def client_open(self): ''' Exceute call to client_node.popen(). ''' self.client_id, self.client_stdin, self.client_out, self.client_err = \ self.client_node.popen((self.client_args)) def parse(self): ''' This method is overloaded by child classes and should return some result. ''' return None def cleanup(self): ''' Close the Popen channels.''' self.stdin.close() self.out.close() self.err.close() tmp = self.id.wait() if tmp: self.warn("nonzero exit status: %s" % tmp) self.warn("command was: %s" % ((self.args, ))) class PingCmd(Cmd): ''' Test latency using ping. ''' def __init__(self, node, verbose=False, addr=None, count=50, interval=0.1, ): Cmd.__init__(self, node, verbose) self.addr = addr self.count = count self.interval = interval self.args = ['ping', '-q', '-c', '%s' % count, '-i', '%s' % interval, addr] def run(self): if self.verbose: self.info("%s initial test ping (max 1 second)..." % self.node.name) (status, result) = self.node.cmdresult(["ping", "-q", "-c", "1", "-w", "1", self.addr]) if status != 0: self.warn("initial ping from %s to %s failed! result:\n%s" % \ (self.node.name, self.addr, result)) return (0.0, 0.0) if self.verbose: self.info("%s pinging %s (%d seconds)..." % \ (self.node.name, self.addr, self.count * self.interval)) return Cmd.run(self) def parse(self): lines = self.out.readlines() avg_latency = 0 mdev = 0 try: stats_str = lines[-1].split('=')[1] stats = stats_str.split('/') avg_latency = float(stats[1]) mdev = float(stats[3].split(' ')[0]) except Exception, e: self.warn("ping parsing exception: %s" % e) return (avg_latency, mdev) class IperfCmd(ClientServerCmd): ''' Test throughput using iperf. ''' def __init__(self, node, client_node, verbose=False, addr=None, time=10): # node is the server ClientServerCmd.__init__(self, node, client_node, verbose) self.addr = addr self.time = time # -s server, -y c CSV report output self.args = ["iperf", "-s", "-y", "c"] self.client_args = ["iperf", "-c", self.addr, "-t", "%s" % self.time] def run(self): if self.verbose: self.info("Launching the iperf server on %s..." % self.node.name) self.info("Running the iperf client on %s (%s seconds)..." % \ (self.client_node.name, self.time)) return ClientServerCmd.run(self) def parse(self): lines = self.out.readlines() try: bps = int(lines[-1].split(',')[-1].strip('\n')) except Exception, e: self.warn("iperf parsing exception: %s" % e) bps = 0 return bps class MgenCmd(ClientServerCmd): ''' Run a test traffic flow using an MGEN sender and receiver. ''' def __init__(self, node, client_node, verbose=False, addr=None, time=10, rate=512): ClientServerCmd.__init__(self, node, client_node, verbose) self.addr = addr self.time = time self.args = ['mgen', 'event', 'listen udp 5000', 'output', '/var/log/mgen.log'] self.rate = rate sendevent = "ON 1 UDP DST %s/5000 PERIODIC [%s]" % \ (addr, self.mgenrate(self.rate)) stopevent = "%s OFF 1" % time self.client_args = ['mgen', 'event', sendevent, 'event', stopevent, 'output', '/var/log/mgen.log'] @staticmethod def mgenrate(kbps): ''' Return a MGEN periodic rate string for the given kilobits-per-sec. Assume 1500 byte MTU, 20-byte IP + 8-byte UDP headers, leaving 1472 bytes for data. ''' bps = (kbps / 8) * 1000.0 maxdata = 1472 pps = math.ceil(bps / maxdata) return "%s %s" % (pps, maxdata) def run(self): if self.verbose: self.info("Launching the MGEN receiver on %s..." % self.node.name) self.info("Running the MGEN sender on %s (%s seconds)..." % \ (self.client_node.name, self.time)) return ClientServerCmd.run(self) def cleanup(self): ''' Close the Popen channels.''' self.stdin.close() self.out.close() self.err.close() tmp = self.id.wait() # non-zero mgen exit status OK def parse(self): ''' Check MGEN receiver's log file for packet sequence numbers, and return the percentage of lost packets. ''' logfile = os.path.join(self.node.nodedir, 'var.log/mgen.log') f = open(logfile, 'r') numlost = 0 lastseq = 0 for line in f.readlines(): fields = line.split() if fields[1] != 'RECV': continue try: seq = int(fields[4].split('>')[1]) except: self.info("Unexpected MGEN line:\n%s" % fields) if seq > (lastseq + 1): numlost += seq - (lastseq + 1) lastseq = seq f.close() if lastseq > 0: loss = 100.0 * numlost / lastseq else: loss = 0 if self.verbose: self.info("Receiver log shows %d of %d packets lost" % \ (numlost, lastseq)) return loss class Experiment(object): ''' Experiment object to organize tests. ''' def __init__(self, opt, start): ''' Initialize with opt and start time. ''' self.session = None # node list self.nodes = [] # WLAN network self.net = None self.verbose = opt.verbose # dict from OptionParser self.opt = opt self.start = start self.numping = opt.numping self.numiperf = opt.numiperf self.nummgen = opt.nummgen self.logbegin() def info(self, msg): ''' Utility method for writing output to stdout. ''' print msg sys.stdout.flush() self.log(msg) def warn(self, msg): ''' Utility method for writing output to stderr. ''' print >> sys.stderr, msg sys.stderr.flush() self.log(msg) def logbegin(self): ''' Start logging. ''' self.logfp = None if not self.opt.logfile: return self.logfp = open(self.opt.logfile, "w") self.log("%s begin: %s\n" % (sys.argv[0], self.start.ctime())) self.log("%s args: %s\n" % (sys.argv[0], sys.argv[1:])) (sysname, rel, ver, machine, nodename) = os.uname() self.log("%s %s %s %s on %s" % (sysname, rel, ver, machine, nodename)) def logend(self): ''' End logging. ''' if not self.logfp: return end = datetime.datetime.now() self.log("%s end: %s (%s)\n" % \ (sys.argv[0], end.ctime(), end - self.start)) self.logfp.flush() self.logfp.close() self.logfp = None def log(self, msg): ''' Write to the log file, if any. ''' if not self.logfp: return print >> self.logfp, msg def reset(self): ''' Prepare for another experiment run. ''' if self.session: self.session.shutdown() del self.session self.session = None self.nodes = [] self.net = None def createbridgedsession(self, numnodes, verbose = False): ''' Build a topology consisting of the given number of LxcNodes connected to a WLAN. ''' # IP subnet prefix = ipaddr.IPv4Prefix("10.0.0.0/16") self.session = pycore.Session() # emulated network self.net = self.session.addobj(cls = pycore.nodes.WlanNode, name = "wlan1") prev = None for i in xrange(1, numnodes + 1): addr = "%s/%s" % (prefix.addr(i), 32) tmp = self.session.addobj(cls = pycore.nodes.CoreNode, objid = i, name = "n%d" % i) tmp.newnetif(self.net, [addr]) self.nodes.append(tmp) self.session.services.addservicestonode(tmp, "router", "IPForward", self.verbose) self.session.services.bootnodeservices(tmp) self.staticroutes(i, prefix, numnodes) # link each node in a chain, with the previous node if prev: self.net.link(prev.netif(0), tmp.netif(0)) prev = tmp def createemanesession(self, numnodes, verbose = False, cls = None, values = None): ''' Build a topology consisting of the given number of LxcNodes connected to an EMANE WLAN. ''' prefix = ipaddr.IPv4Prefix("10.0.0.0/16") self.session = pycore.Session() self.session.node_count = str(numnodes + 1) self.session.master = True self.session.location.setrefgeo(47.57917,-122.13232,2.00000) self.session.location.refscale = 150.0 self.session.cfg['emane_models'] = "RfPipe, Ieee80211abg, Bypass" self.session.emane.loadmodels() self.net = self.session.addobj(cls = pycore.nodes.EmaneNode, objid = numnodes + 1, name = "wlan1") self.net.verbose = verbose #self.session.emane.addobj(self.net) for i in xrange(1, numnodes + 1): addr = "%s/%s" % (prefix.addr(i), 32) tmp = self.session.addobj(cls = pycore.nodes.CoreNode, objid = i, name = "n%d" % i) #tmp.setposition(i * 20, 50, None) tmp.setposition(50, 50, None) tmp.newnetif(self.net, [addr]) self.nodes.append(tmp) self.session.services.addservicestonode(tmp, "router", "IPForward", self.verbose) if values is None: values = cls.getdefaultvalues() self.session.emane.setconfig(self.net.objid, cls._name, values) self.session.instantiate() self.info("waiting %s sec (TAP bring-up)" % 2) time.sleep(2) for i in xrange(1, numnodes + 1): tmp = self.nodes[i-1] self.session.services.bootnodeservices(tmp) self.staticroutes(i, prefix, numnodes) def setnodes(self): ''' Set the sender and receiver nodes for use in this experiment, along with the address of the receiver to be used. ''' self.firstnode = self.nodes[0] self.lastnode = self.nodes[-1] self.lastaddr = self.lastnode.netif(0).addrlist[0].split('/')[0] def staticroutes(self, i, prefix, numnodes): ''' Add static routes on node number i to the other nodes in the chain. ''' routecmd = ["/sbin/ip", "route", "add"] node = self.nodes[i-1] neigh_left = "" neigh_right = "" # add direct interface routes first if i > 1: neigh_left = "%s" % prefix.addr(i - 1) cmd = routecmd + [neigh_left, "dev", node.netif(0).name] (status, result) = node.cmdresult(cmd) if status != 0: self.warn("failed to add interface route: %s" % cmd) if i < numnodes: neigh_right = "%s" % prefix.addr(i + 1) cmd = routecmd + [neigh_right, "dev", node.netif(0).name] (status, result) = node.cmdresult(cmd) if status != 0: self.warn("failed to add interface route: %s" % cmd) # add static routes to all other nodes via left/right neighbors for j in xrange(1, numnodes + 1): if abs(j - i) < 2: continue addr = "%s" % prefix.addr(j) if j < i: gw = neigh_left else: gw = neigh_right cmd = routecmd + [addr, "via", gw] (status, result) = node.cmdresult(cmd) if status != 0: self.warn("failed to add route: %s" % cmd) def setpathloss(self, numnodes): ''' Send EMANE pathloss events to connect all NEMs in a chain. ''' if self.session.emane.version < self.session.emane.EMANE091: service = emaneeventservice.EventService() e = emaneeventpathloss.EventPathloss(1) old = True else: if self.session.emane.version == self.session.emane.EMANE091: dev = 'lo' else: dev = self.session.obj('ctrlnet').brname service = EventService(eventchannel=("224.1.2.8", 45703, dev), otachannel=None) old = False for i in xrange(1, numnodes + 1): rxnem = i # inform rxnem that it can hear node to the left with 10dB noise txnem = rxnem - 1 if txnem > 0: if old: e.set(0, txnem, 10.0, 10.0) service.publish(emaneeventpathloss.EVENT_ID, emaneeventservice.PLATFORMID_ANY, rxnem, emaneeventservice.COMPONENTID_ANY, e.export()) else: e = PathlossEvent() e.append(txnem, forward=10.0, reverse=10.0) service.publish(rxnem, e) # inform rxnem that it can hear node to the right with 10dB noise txnem = rxnem + 1 if txnem > numnodes: continue if old: e.set(0, txnem, 10.0, 10.0) service.publish(emaneeventpathloss.EVENT_ID, emaneeventservice.PLATFORMID_ANY, rxnem, emaneeventservice.COMPONENTID_ANY, e.export()) else: e = PathlossEvent() e.append(txnem, forward=10.0, reverse=10.0) service.publish(rxnem, e) def setneteffects(self, bw = None, delay = None): ''' Set link effects for all interfaces attached to the network node. ''' if not self.net: self.warn("failed to set effects: no network node") return for netif in self.net.netifs(): self.net.linkconfig(netif, bw = bw, delay = delay) def runalltests(self, title=""): ''' Convenience helper to run all defined experiment tests. If tests are run multiple times, this returns the average of those runs. ''' duration = self.opt.duration rate = self.opt.rate if len(title) > 0: self.info("----- running %s tests (duration=%s, rate=%s) -----" % \ (title, duration, rate)) (latency, mdev, throughput, cpu, loss) = (0,0,0,0,0) self.info("number of runs: ping=%d, iperf=%d, mgen=%d" % \ (self.numping, self.numiperf, self.nummgen)) if self.numping > 0: (latency, mdev) = self.pingtest(count=self.numping) if self.numiperf > 0: throughputs = [] for i in range(1, self.numiperf + 1): throughput = self.iperftest(time=duration) if self.numiperf > 1: throughputs += throughput time.sleep(1) # iperf is very CPU intensive if self.numiperf > 1: throughput = sum(throughputs) / len(throughputs) self.info("throughputs=%s" % ["%.2f" % v for v in throughputs]) if self.nummgen > 0: cpus = [] losses = [] for i in range(1, self.nummgen + 1): (cpu, loss) = self.cputest(time=duration, rate=rate) if self.nummgen > 1: cpus += cpu, losses += loss, if self.nummgen > 1: cpu = sum(cpus) / len(cpus) loss = sum(losses) / len(losses) self.info("cpus=%s" % ["%.2f" % v for v in cpus]) self.info("losses=%s" % ["%.2f" % v for v in losses]) return (latency, mdev, throughput, cpu, loss) def pingtest(self, count=50): ''' Ping through a chain of nodes and report the average latency. ''' p = PingCmd(node=self.firstnode, verbose=self.verbose, addr = self.lastaddr, count=count, interval=0.1).run() (latency, mdev) = p self.info("latency (ms): %.03f, %.03f" % (latency, mdev)) return p def iperftest(self, time=10): ''' Run iperf through a chain of nodes and report the maximum throughput. ''' bps = IperfCmd(node=self.lastnode, client_node=self.firstnode, verbose=False, addr=self.lastaddr, time=time).run() self.info("throughput (bps): %s" % bps) return bps def cputest(self, time=10, rate=512): ''' Run MGEN through a chain of nodes and report the CPU usage and percent of lost packets. Rate is in kbps. ''' if self.verbose: self.info("%s initial test ping (max 1 second)..." % \ self.firstnode.name) (status, result) = self.firstnode.cmdresult(["ping", "-q", "-c", "1", "-w", "1", self.lastaddr]) if status != 0: self.warn("initial ping from %s to %s failed! result:\n%s" % \ (self.firstnode.name, self.lastaddr, result)) return (0.0, 0.0) lines = readstat() cpustart = getcputimes(lines[0]) loss = MgenCmd(node=self.lastnode, client_node=self.firstnode, verbose=False, addr=self.lastaddr, time=time, rate=rate).run() lines = readstat() cpuend = getcputimes(lines[0]) percent = calculatecpu(cpustart, cpuend) self.info("CPU usage (%%): %.02f, %.02f loss" % (percent, loss)) return percent, loss def main(): ''' Main routine when running from command-line. ''' usagestr = "usage: %prog [-h] [options] [args]" parser = optparse.OptionParser(usage = usagestr) parser.set_defaults(numnodes = 10, delay = 3, duration = 10, rate = 512, verbose = False, numping = 50, numiperf = 1, nummgen = 1) parser.add_option("-d", "--delay", dest = "delay", type = float, help = "wait time before testing") parser.add_option("-l", "--logfile", dest = "logfile", type = str, help = "log detailed output to the specified file") parser.add_option("-n", "--numnodes", dest = "numnodes", type = int, help = "number of nodes") parser.add_option("-r", "--rate", dest = "rate", type = float, help = "kbps rate to use for MGEN CPU tests") parser.add_option("--numping", dest = "numping", type = int, help = "number of ping latency test runs") parser.add_option("--numiperf", dest = "numiperf", type = int, help = "number of iperf throughput test runs") parser.add_option("--nummgen", dest = "nummgen", type = int, help = "number of MGEN CPU tests runs") parser.add_option("-t", "--time", dest = "duration", type = int, help = "duration in seconds of throughput and CPU tests") parser.add_option("-v", "--verbose", dest = "verbose", action = "store_true", help = "be more verbose") def usage(msg = None, err = 0): sys.stdout.write("\n") if msg: sys.stdout.write(msg + "\n\n") parser.print_help() sys.exit(err) # parse command line opt (opt, args) = parser.parse_args() if opt.numnodes < 2: usage("invalid numnodes: %s" % opt.numnodes) if opt.delay < 0.0: usage("invalid delay: %s" % opt.delay) if opt.rate < 0.0: usage("invalid rate: %s" % opt.rate) for a in args: sys.stderr.write("ignoring command line argument: '%s'\n" % a) results = {} starttime = datetime.datetime.now() exp = Experiment(opt = opt, start=starttime) exp.info("Starting wlanemanetests.py tests %s" % starttime.ctime()) # system sanity checks here emanever, emaneverstr = Emane.detectversionfromcmd() if opt.verbose: exp.info("Detected EMANE version %s" % (emaneverstr,)) # bridged exp.info("setting up bridged tests 1/2 no link effects") exp.info("creating topology: numnodes = %s" % \ (opt.numnodes, )) exp.createbridgedsession(numnodes=opt.numnodes, verbose=opt.verbose) exp.setnodes() exp.info("waiting %s sec (node/route bring-up)" % opt.delay) time.sleep(opt.delay) results['0 bridged'] = exp.runalltests("bridged") exp.info("done; elapsed time: %s" % (datetime.datetime.now() - exp.start)) # bridged with netem exp.info("setting up bridged tests 2/2 with netem") exp.setneteffects(bw=54000000, delay=0) exp.info("waiting %s sec (queue bring-up)" % opt.delay) results['1.0 netem'] = exp.runalltests("netem") exp.info("shutting down bridged session") # bridged with netem (1 Mbps,200ms) exp.info("setting up bridged tests 3/2 with netem") exp.setneteffects(bw=1000000, delay=20000) exp.info("waiting %s sec (queue bring-up)" % opt.delay) results['1.2 netem_1M'] = exp.runalltests("netem_1M") exp.info("shutting down bridged session") # bridged with netem (54 kbps,500ms) exp.info("setting up bridged tests 3/2 with netem") exp.setneteffects(bw=54000, delay=100000) exp.info("waiting %s sec (queue bring-up)" % opt.delay) results['1.4 netem_54K'] = exp.runalltests("netem_54K") exp.info("shutting down bridged session") exp.reset() # EMANE bypass model exp.info("setting up EMANE tests 1/2 with bypass model") exp.createemanesession(numnodes=opt.numnodes, verbose=opt.verbose, cls=EmaneBypassModel, values=None) exp.setnodes() exp.info("waiting %s sec (node/route bring-up)" % opt.delay) time.sleep(opt.delay) results['2.0 bypass'] = exp.runalltests("bypass") exp.info("shutting down bypass session") exp.reset() exp.info("waiting %s sec (between EMANE tests)" % opt.delay) time.sleep(opt.delay) # EMANE RF-PIPE model: no restrictions (max datarate) exp.info("setting up EMANE tests 2/4 with RF-PIPE model") rfpipevals = list(EmaneRfPipeModel.getdefaultvalues()) rfpnames = EmaneRfPipeModel.getnames() rfpipevals[ rfpnames.index('datarate') ] = '4294967295' # max value if emanever < Emane.EMANE091: rfpipevals[ rfpnames.index('pathlossmode') ] = '2ray' rfpipevals[ rfpnames.index('defaultconnectivitymode') ] = '1' else: rfpipevals[ rfpnames.index('propagationmodel') ] = '2ray' exp.createemanesession(numnodes=opt.numnodes, verbose=opt.verbose, cls=EmaneRfPipeModel, values=rfpipevals) exp.setnodes() exp.info("waiting %s sec (node/route bring-up)" % opt.delay) time.sleep(opt.delay) results['3.0 rfpipe'] = exp.runalltests("rfpipe") exp.info("shutting down RF-PIPE session") exp.reset() # EMANE RF-PIPE model: 54M datarate exp.info("setting up EMANE tests 3/4 with RF-PIPE model 54M") rfpipevals = list(EmaneRfPipeModel.getdefaultvalues()) rfpnames = EmaneRfPipeModel.getnames() rfpipevals[ rfpnames.index('datarate') ] = '54000000' # TX delay != propagation delay #rfpipevals[ rfpnames.index('delay') ] = '5000' if emanever < Emane.EMANE091: rfpipevals[ rfpnames.index('pathlossmode') ] = '2ray' rfpipevals[ rfpnames.index('defaultconnectivitymode') ] = '1' else: rfpipevals[ rfpnames.index('propagationmodel') ] = '2ray' exp.createemanesession(numnodes=opt.numnodes, verbose=opt.verbose, cls=EmaneRfPipeModel, values=rfpipevals) exp.setnodes() exp.info("waiting %s sec (node/route bring-up)" % opt.delay) time.sleep(opt.delay) results['4.0 rfpipe54m'] = exp.runalltests("rfpipe54m") exp.info("shutting down RF-PIPE session") exp.reset() # EMANE RF-PIPE model: 54K datarate exp.info("setting up EMANE tests 4/4 with RF-PIPE model pathloss") rfpipevals = list(EmaneRfPipeModel.getdefaultvalues()) rfpnames = EmaneRfPipeModel.getnames() rfpipevals[ rfpnames.index('datarate') ] = '54000' if emanever < Emane.EMANE091: rfpipevals[ rfpnames.index('pathlossmode') ] = 'pathloss' rfpipevals[ rfpnames.index('defaultconnectivitymode') ] = '0' else: rfpipevals[ rfpnames.index('propagationmodel') ] = 'precomputed' exp.createemanesession(numnodes=opt.numnodes, verbose=opt.verbose, cls=EmaneRfPipeModel, values=rfpipevals) exp.setnodes() exp.info("waiting %s sec (node/route bring-up)" % opt.delay) time.sleep(opt.delay) exp.info("sending pathloss events to govern connectivity") exp.setpathloss(opt.numnodes) results['5.0 pathloss'] = exp.runalltests("pathloss") exp.info("shutting down RF-PIPE session") exp.reset() # EMANE RF-PIPE model (512K, 200ms) exp.info("setting up EMANE tests 4/4 with RF-PIPE model pathloss") rfpipevals = list(EmaneRfPipeModel.getdefaultvalues()) rfpnames = EmaneRfPipeModel.getnames() rfpipevals[ rfpnames.index('datarate') ] = '512000' rfpipevals[ rfpnames.index('delay') ] = '200' rfpipevals[ rfpnames.index('pathlossmode') ] = 'pathloss' rfpipevals[ rfpnames.index('defaultconnectivitymode') ] = '0' exp.createemanesession(numnodes=opt.numnodes, verbose=opt.verbose, cls=EmaneRfPipeModel, values=rfpipevals) exp.setnodes() exp.info("waiting %s sec (node/route bring-up)" % opt.delay) time.sleep(opt.delay) exp.info("sending pathloss events to govern connectivity") exp.setpathloss(opt.numnodes) results['5.1 pathloss'] = exp.runalltests("pathloss") exp.info("shutting down RF-PIPE session") exp.reset() # summary of results in CSV format exp.info("----- summary of results (%s nodes, rate=%s, duration=%s) -----" \ % (opt.numnodes, opt.rate, opt.duration)) exp.info("netname:latency,mdev,throughput,cpu,loss") for test in sorted(results.keys()): (latency, mdev, throughput, cpu, loss) = results[test] exp.info("%s:%.03f,%.03f,%d,%.02f,%.02f" % \ (test, latency, mdev, throughput, cpu,loss)) exp.logend() return exp if __name__ == "__main__": exp = main()
D3f0/coreemu
daemon/examples/netns/wlanemanetests.py
Python
bsd-2-clause
33,033
/*global app: true, env: true */ /** Define tags that are known in JSDoc. @module jsdoc/tag/dictionary/definitions @author Michael Mathews <micmath@gmail.com> @license Apache License 2.0 - See file 'LICENSE.md' in this project. */ 'use strict'; var logger = require('jsdoc/util/logger'); var path = require('jsdoc/path'); var Syntax = require('jsdoc/src/syntax').Syntax; function getSourcePaths() { var sourcePaths = env.sourceFiles.slice(0) || []; if (env.opts._) { env.opts._.forEach(function(sourcePath) { var resolved = path.resolve(env.pwd, sourcePath); if (sourcePaths.indexOf(resolved) === -1) { sourcePaths.push(resolved); } }); } return sourcePaths; } function filepathMinusPrefix(filepath) { var sourcePaths = getSourcePaths(); var commonPrefix = path.commonPrefix(sourcePaths); var result = ''; if (filepath) { // always use forward slashes result = (filepath + path.sep).replace(commonPrefix, '') .replace(/\\/g, '/'); } if (result.length > 0 && result[result.length - 1] !== '/') { result += '/'; } return result; } /** @private */ function setDocletKindToTitle(doclet, tag) { doclet.addTag( 'kind', tag.title ); } function setDocletScopeToTitle(doclet, tag) { try { doclet.setScope(tag.title); } catch(e) { logger.error(e.message); } } function setDocletNameToValue(doclet, tag) { if (tag.value && tag.value.description) { // as in a long tag doclet.addTag( 'name', tag.value.description); } else if (tag.text) { // or a short tag doclet.addTag('name', tag.text); } } function setDocletNameToValueName(doclet, tag) { if (tag.value && tag.value.name) { doclet.addTag('name', tag.value.name); } } function setDocletDescriptionToValue(doclet, tag) { if (tag.value) { doclet.addTag( 'description', tag.value ); } } function setDocletTypeToValueType(doclet, tag) { if (tag.value && tag.value.type) { doclet.type = tag.value.type; } } function setNameToFile(doclet, tag) { var name; if (doclet.meta.filename) { name = filepathMinusPrefix(doclet.meta.path) + doclet.meta.filename; doclet.addTag('name', name); } } function setDocletMemberof(doclet, tag) { if (tag.value && tag.value !== '<global>') { doclet.setMemberof(tag.value); } } function applyNamespace(docletOrNs, tag) { if (typeof docletOrNs === 'string') { // ns tag.value = app.jsdoc.name.applyNamespace(tag.value, docletOrNs); } else { // doclet if (!docletOrNs.name) { return; // error? } //doclet.displayname = doclet.name; docletOrNs.longname = app.jsdoc.name.applyNamespace(docletOrNs.name, tag.title); } } function setDocletNameToFilename(doclet, tag) { var name = ''; if (doclet.meta.path) { name = filepathMinusPrefix(doclet.meta.path); } name += doclet.meta.filename.replace(/\.js$/i, ''); doclet.name = name; } function parseBorrows(doclet, tag) { var m = /^(\S+)(?:\s+as\s+(\S+))?$/.exec(tag.text); if (m) { if (m[1] && m[2]) { return { target: m[1], source: m[2] }; } else if (m[1]) { return { target: m[1] }; } } else { return {}; } } function firstWordOf(string) { var m = /^(\S+)/.exec(string); if (m) { return m[1]; } else { return ''; } } /** Populate the given dictionary with all known JSDoc tag definitions. @param {module:jsdoc/tag/dictionary} dictionary */ exports.defineTags = function(dictionary) { dictionary.defineTag('abstract', { mustNotHaveValue: true, onTagged: function(doclet, tag) { // since "abstract" is reserved word in JavaScript let's use "virtual" in code doclet.virtual = true; } }) .synonym('virtual'); dictionary.defineTag('access', { mustHaveValue: true, onTagged: function(doclet, tag) { // only valid values are private and protected, public is default if ( /^(private|protected)$/i.test(tag.value) ) { doclet.access = tag.value.toLowerCase(); } else { delete doclet.access; } } }); dictionary.defineTag('alias', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.alias = tag.value; } }); // Special separator tag indicating that multiple doclets should be generated for the same // comment. Used internally (and by some JSDoc users, although it's not officially supported). // // In the following example, the parser will replace `//**` with an `@also` tag: // // /** // * Foo. // *//** // * Foo with a param. // * @param {string} bar // */ // function foo(bar) {} dictionary.defineTag('also', { onTagged: function(doclet, tag) { // let the parser handle it; we define the tag here to avoid "not a known tag" errors } }); // this symbol inherits from the specified symbol dictionary.defineTag('augments', { mustHaveValue: true, // Allow augments value to be specified as a normal type, e.g. {Type} onTagText: function(text) { var type = require('jsdoc/tag/type'), tagType = type.parse(text, false, true); return tagType.typeExpression || text; }, onTagged: function(doclet, tag) { doclet.augment( firstWordOf(tag.value) ); } }) .synonym('extends'); dictionary.defineTag('author', { mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.author) { doclet.author = []; } doclet.author.push(tag.value); } }); // this symbol has a member that should use the same docs as another symbol dictionary.defineTag('borrows', { mustHaveValue: true, onTagged: function(doclet, tag) { var borrows = parseBorrows(doclet, tag); doclet.borrow(borrows.target, borrows.source); } }); dictionary.defineTag('class', { onTagged: function(doclet, tag) { doclet.addTag('kind', 'class'); // handle special case where both @class and @constructor tags exist in same doclet if (tag.originalTitle === 'class') { var looksLikeDesc = (tag.value || '').match(/\S+\s+\S+/); // multiple words after @class? if ( looksLikeDesc || /@construct(s|or)\b/i.test(doclet.comment) ) { doclet.classdesc = tag.value; // treat the @class tag as a @classdesc tag instead return; } } setDocletNameToValue(doclet, tag); } }) .synonym('constructor'); dictionary.defineTag('classdesc', { onTagged: function(doclet, tag) { doclet.classdesc = tag.value; } }); dictionary.defineTag('constant', { canHaveType: true, canHaveName: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValueName(doclet, tag); setDocletTypeToValueType(doclet, tag); } }) .synonym('const'); dictionary.defineTag('constructs', { onTagged: function(doclet, tag) { var ownerClassName; if (!tag.value) { ownerClassName = '{@thisClass}'; // this can be resolved later in the handlers } else { ownerClassName = firstWordOf(tag.value); } doclet.addTag('alias', ownerClassName); doclet.addTag('kind', 'class'); } }); dictionary.defineTag('copyright', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.copyright = tag.value; } }); dictionary.defineTag('default', { onTagged: function(doclet, tag) { var type; var value; if (tag.value) { doclet.defaultvalue = tag.value; } else if (doclet.meta && doclet.meta.code && doclet.meta.code.value) { type = doclet.meta.code.type; value = doclet.meta.code.value; if (type === Syntax.Literal) { doclet.defaultvalue = String(value); } // TODO: reenable the changes for https://github.com/jsdoc3/jsdoc/pull/419 /* else if (doclet.meta.code.type === 'OBJECTLIT') { doclet.defaultvalue = String(doclet.meta.code.node.toSource()); doclet.defaultvaluetype = 'object'; } */ } } }) .synonym('defaultvalue'); dictionary.defineTag('deprecated', { // value is optional onTagged: function(doclet, tag) { doclet.deprecated = tag.value || true; } }); dictionary.defineTag('description', { mustHaveValue: true }) .synonym('desc'); dictionary.defineTag('enum', { canHaveType: true, onTagged: function(doclet, tag) { doclet.kind = 'member'; doclet.isEnum = true; setDocletTypeToValueType(doclet, tag); } }); dictionary.defineTag('event', { isNamespace: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValue(doclet, tag); } }); dictionary.defineTag('example', { keepsWhitespace: true, removesIndent: true, mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.examples) { doclet.examples = []; } doclet.examples.push(tag.value); } }); dictionary.defineTag('exception', { mustHaveValue: true, canHaveType: true, onTagged: function(doclet, tag) { if (!doclet.exceptions) { doclet.exceptions = []; } doclet.exceptions.push(tag.value); setDocletTypeToValueType(doclet, tag); } }) .synonym('throws'); dictionary.defineTag('exports', { mustHaveValue: true, onTagged: function(doclet, tag) { var modName = firstWordOf(tag.value); doclet.addTag('alias', modName); doclet.addTag('kind', 'module'); } }); dictionary.defineTag('external', { canHaveType: true, isNamespace: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); if (tag.value && tag.value.type) { setDocletTypeToValueType(doclet, tag); doclet.addTag('name', doclet.type.names[0]); } } }) .synonym('host'); dictionary.defineTag('file', { onTagged: function(doclet, tag) { setNameToFile(doclet, tag); setDocletKindToTitle(doclet, tag); setDocletDescriptionToValue(doclet, tag); doclet.preserveName = true; } }) .synonym('fileoverview') .synonym('overview'); dictionary.defineTag('fires', { mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.fires) { doclet.fires = []; } applyNamespace('event', tag); doclet.fires.push(tag.value); } }) .synonym('emits'); dictionary.defineTag('function', { onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValue(doclet, tag); } }) .synonym('func') .synonym('method'); dictionary.defineTag('global', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.scope = 'global'; delete doclet.memberof; } }); dictionary.defineTag('ignore', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.ignore = true; } }); dictionary.defineTag('inner', { onTagged: function(doclet, tag) { setDocletScopeToTitle(doclet, tag); } }); dictionary.defineTag('instance', { onTagged: function(doclet, tag) { setDocletScopeToTitle(doclet, tag); } }); dictionary.defineTag('kind', { mustHaveValue: true }); dictionary.defineTag('lends', { onTagged: function(doclet, tag) { var GLOBAL_LONGNAME = require('jsdoc/doclet').GLOBAL_LONGNAME; doclet.alias = tag.value || GLOBAL_LONGNAME; doclet.addTag('undocumented'); } }); dictionary.defineTag('license', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.license = tag.value; } }); dictionary.defineTag('listens', { mustHaveValue: true, onTagged: function (doclet, tag) { if (!doclet.listens) { doclet.listens = []; } applyNamespace('event', tag); doclet.listens.push(tag.value); // TODO: verify that parameters match the event parameters? } }); dictionary.defineTag('member', { canHaveType: true, canHaveName: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValueName(doclet, tag); setDocletTypeToValueType(doclet, tag); } }) .synonym('var'); dictionary.defineTag('memberof', { mustHaveValue: true, onTagged: function(doclet, tag) { var GLOBAL_LONGNAME = require('jsdoc/doclet').GLOBAL_LONGNAME; if (tag.originalTitle === 'memberof!') { doclet.forceMemberof = true; if (tag.value === GLOBAL_LONGNAME) { doclet.addTag('global'); delete doclet.memberof; } } setDocletMemberof(doclet, tag); } }) .synonym('memberof!'); // this symbol mixes in all of the specified object's members dictionary.defineTag('mixes', { mustHaveValue: true, onTagged: function(doclet, tag) { var source = firstWordOf(tag.value); doclet.mix(source); } }); dictionary.defineTag('mixin', { onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValue(doclet, tag); } }); dictionary.defineTag('module', { canHaveType: true, isNamespace: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValue(doclet, tag); if (!doclet.name) { setDocletNameToFilename(doclet, tag); } setDocletTypeToValueType(doclet, tag); } }); dictionary.defineTag('name', { mustHaveValue: true }); dictionary.defineTag('namespace', { canHaveType: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); setDocletNameToValue(doclet, tag); setDocletTypeToValueType(doclet, tag); } }); dictionary.defineTag('param', { //mustHaveValue: true, // param name can be found in the source code if not provided canHaveType: true, canHaveName: true, onTagged: function(doclet, tag) { if (!doclet.params) { doclet.params = []; } doclet.params.push(tag.value||{}); } }) .synonym('argument') .synonym('arg'); dictionary.defineTag('private', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.access = 'private'; } }); dictionary.defineTag('property', { mustHaveValue: true, canHaveType: true, canHaveName: true, onTagged: function(doclet, tag) { if (!doclet.properties) { doclet.properties = []; } doclet.properties.push(tag.value); } }) .synonym('prop'); dictionary.defineTag('protected', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.access = 'protected'; } }); dictionary.defineTag('public', { mustNotHaveValue: true, onTagged: function(doclet, tag) { delete doclet.access; // public is default } }); // use this instead of old deprecated @final tag dictionary.defineTag('readonly', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.readonly = true; } }); dictionary.defineTag('requires', { mustHaveValue: true, onTagged: function(doclet, tag) { var requiresName; var MODULE_PREFIX = require('jsdoc/name').MODULE_PREFIX; // inline link tags are passed through as-is so that `@requires {@link foo}` works if ( require('jsdoc/tag/inline').isInlineTag(tag.value, 'link\\S*') ) { requiresName = tag.value; } // otherwise, assume it's a module else { requiresName = firstWordOf(tag.value); if (requiresName.indexOf(MODULE_PREFIX) !== 0) { requiresName = MODULE_PREFIX + requiresName; } } if (!doclet.requires) { doclet.requires = []; } doclet.requires.push(requiresName); } }); dictionary.defineTag('returns', { mustHaveValue: true, canHaveType: true, onTagged: function(doclet, tag) { if (!doclet.returns) { doclet.returns = []; } doclet.returns.push(tag.value); } }) .synonym('return'); dictionary.defineTag('see', { mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.see) { doclet.see = []; } doclet.see.push(tag.value); } }); dictionary.defineTag('since', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.since = tag.value; } }); dictionary.defineTag('static', { onTagged: function(doclet, tag) { setDocletScopeToTitle(doclet, tag); } }); dictionary.defineTag('summary', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.summary = tag.value; } }); dictionary.defineTag('this', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet['this'] = firstWordOf(tag.value); } }); dictionary.defineTag('todo', { mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.todo) { doclet.todo = []; } doclet.todo.push(tag.value); } }); dictionary.defineTag('tutorial', { mustHaveValue: true, onTagged: function(doclet, tag) { if (!doclet.tutorials) { doclet.tutorials = []; } doclet.tutorials.push(tag.value); } }); dictionary.defineTag('type', { mustHaveValue: true, canHaveType: true, onTagText: function(text) { // remove line breaks so we can parse the type expression correctly text = text.replace(/[\n\r]/g, ''); // any text must be formatted as a type, but for back compat braces are optional if ( !/^\{[\s\S]+\}$/.test(text) ) { text = '{' + text + '}'; } return text; }, onTagged: function(doclet, tag) { if (tag.value && tag.value.type) { setDocletTypeToValueType(doclet, tag); // for backwards compatibility, we allow @type for functions to imply return type if (doclet.kind === 'function') { doclet.addTag('returns', tag.text); } } } }); dictionary.defineTag('typedef', { canHaveType: true, canHaveName: true, onTagged: function(doclet, tag) { setDocletKindToTitle(doclet, tag); if (tag.value) { setDocletNameToValueName(doclet, tag); // callbacks are always type {function} if (tag.originalTitle === 'callback') { doclet.type = { names: [ 'function' ] }; } else { setDocletTypeToValueType(doclet, tag); } } } }) .synonym('callback'); dictionary.defineTag('undocumented', { mustNotHaveValue: true, onTagged: function(doclet, tag) { doclet.undocumented = true; doclet.comment = ''; } }); dictionary.defineTag('variation', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.variation = tag.value; } }); dictionary.defineTag('version', { mustHaveValue: true, onTagged: function(doclet, tag) { doclet.version = tag.value; } }); };
ad-l/djcl
tools/jsdoc/lib/jsdoc/tag/dictionary/definitions.js
JavaScript
bsd-2-clause
21,625
"""Testing the pytest fixtures themselves which are declared in conftest.py.""" import pytest import responses import requests from requests.exceptions import ConnectionError from olympia.access.models import Group def test_admin_group(admin_group): assert Group.objects.count() == 1 admin_group = Group.objects.get() assert admin_group.name == 'Admins' assert admin_group.rules == '*:*' def test_mozilla_user(mozilla_user): admin_group = mozilla_user.groups.get() assert admin_group.name == 'Admins' assert admin_group.rules == '*:*' @pytest.mark.allow_external_http_requests def test_external_requests_enabled(): with pytest.raises(ConnectionError): requests.get('http://example.invalid') assert len(responses.calls) == 0 def test_external_requests_disabled_by_default(): with pytest.raises(ConnectionError): requests.get('http://example.invalid') assert len(responses.calls) == 1
aviarypl/mozilla-l10n-addons-server
src/olympia/amo/tests/test_pytest_fixtures.py
Python
bsd-3-clause
955
--TEST-- Bug #43483 (get_class_methods() does not list all visible methods) --FILE-- <?php class C { public static function test() { D::prot(); print_r(get_class_methods("D")); } } class D extends C { protected static function prot() { echo "Successfully called D::prot().\n"; } } D::test(); ?> --EXPECT-- Successfully called D::prot(). Array ( [0] => prot [1] => test )
glayzzle/tests
zend/bug43483.phpt
PHP
bsd-3-clause
389
// Copyright (C) 2001, 2004, 2005 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 2, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. // 23.2.2.1 list constructors, copy, and assignment #include <list> #include <testsuite_hooks.h> bool test __attribute__((unused)) = true; // Range constructor // // This test verifies the following. // 23.2.2.1 template list(InputIterator f, InputIterator l, const Allocator& a = Allocator()) // 23.2.2 const_iterator begin() const // 23.2.2 const_iterator end() const // 23.2.2 size_type size() const // void test03() { const int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}; const std::size_t N = sizeof(A) / sizeof(int); std::size_t count; std::list<int>::const_iterator i; // construct from a dissimilar range std::list<int> list0301(A, A + N); for (i = list0301.begin(), count = 0; i != list0301.end(); ++i, ++count) VERIFY(*i == A[count]); VERIFY(count == N); VERIFY(list0301.size() == N); // construct from a similar range std::list<int> list0302(list0301.begin(), list0301.end()); for (i = list0302.begin(), count = 0; i != list0302.end(); ++i, ++count) VERIFY(*i == A[count]); VERIFY(count == N); VERIFY(list0302.size() == N); } int main() { test03(); return 0; }
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/libstdc++-v3/testsuite/23_containers/list/cons/4.cc
C++
bsd-3-clause
2,030
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @format * @emails oncall+javascript_foundation */ 'use strict'; jest.mock('fs'); const getProjectConfig = require('../../ios').projectConfig; const fs = require('fs'); const projects = require('../../__fixtures__/projects'); describe('ios::getProjectConfig', () => { const userConfig = {}; beforeEach(() => { fs.__setMockFilesystem({testDir: projects}); }); it('returns an object with ios project configuration', () => { const folder = '/testDir/nested'; expect(getProjectConfig(folder, userConfig)).not.toBeNull(); expect(typeof getProjectConfig(folder, userConfig)).toBe('object'); }); it('returns `null` if ios project was not found', () => { const folder = '/testDir/empty'; expect(getProjectConfig(folder, userConfig)).toBeNull(); }); it('returns normalized shared library names', () => { const projectConfig = getProjectConfig('/testDir/nested', { sharedLibraries: ['libc++', 'libz.tbd', 'HealthKit', 'HomeKit.framework'], }); expect(projectConfig.sharedLibraries).toEqual([ 'libc++.tbd', 'libz.tbd', 'HealthKit.framework', 'HomeKit.framework', ]); }); });
Bhullnatik/react-native
local-cli/core/__tests__/ios/getProjectConfig.spec.js
JavaScript
bsd-3-clause
1,475
// Test that constructor for the node with name |nodeName| handles the // various possible values for channelCount, channelCountMode, and // channelInterpretation. // The |should| parameter is the test function from new |Audit|. function testAudioNodeOptions(should, context, nodeName, expectedNodeOptions) { if (expectedNodeOptions === undefined) expectedNodeOptions = {}; let node; // Test that we can set channelCount and that errors are thrown for // invalid values let testChannelCount = 17; if (expectedNodeOptions.channelCount) { testChannelCount = expectedNodeOptions.channelCount.value; } should( () => { node = new window[nodeName]( context, Object.assign({}, expectedNodeOptions.additionalOptions, { channelCount: testChannelCount })); }, 'new ' + nodeName + '(c, {channelCount: ' + testChannelCount + '}}') .notThrow(); should(node.channelCount, 'node.channelCount').beEqualTo(testChannelCount); if (expectedNodeOptions.channelCount && expectedNodeOptions.channelCount.isFixed) { // The channel count is fixed. Verify that we throw an error if // we try to change it. Arbitrarily set the count to be one more // than the expected value. testChannelCount = expectedNodeOptions.channelCount.value + 1; should( () => { node = new window[nodeName]( context, Object.assign( {}, expectedNodeOptions.additionalOptions, {channelCount: testChannelCount})); }, 'new ' + nodeName + '(c, {channelCount: ' + testChannelCount + '}}') .throw(expectedNodeOptions.channelCount.errorType || TypeError); } else { // The channel count is not fixed. Try to set the count to invalid // values and make sure an error is thrown. [0, 99].forEach(testValue => { should(() => { node = new window[nodeName]( context, Object.assign({}, expectedNodeOptions.additionalOptions, { channelCount: testValue })); }, `new ${nodeName}(c, {channelCount: ${testValue}})`) .throw(DOMException, 'NotSupportedError'); }); } // Test channelCountMode let testChannelCountMode = 'max'; if (expectedNodeOptions.channelCountMode) { testChannelCountMode = expectedNodeOptions.channelCountMode.value; } should( () => { node = new window[nodeName]( context, Object.assign({}, expectedNodeOptions.additionalOptions, { channelCountMode: testChannelCountMode })); }, 'new ' + nodeName + '(c, {channelCountMode: "' + testChannelCountMode + '"}') .notThrow(); should(node.channelCountMode, 'node.channelCountMode') .beEqualTo(testChannelCountMode); if (expectedNodeOptions.channelCountMode && expectedNodeOptions.channelCountMode.isFixed) { // Channel count mode is fixed. Test setting to something else throws. ['max', 'clamped-max', 'explicit'].forEach(testValue => { if (testValue !== expectedNodeOptions.channelCountMode.value) { should( () => { node = new window[nodeName]( context, Object.assign( {}, expectedNodeOptions.additionalOptions, {channelCountMode: testValue})); }, `new ${nodeName}(c, {channelCountMode: "${testValue}"})`) .throw(expectedNodeOptions.channelCountMode.errorType); } }); } else { // Mode is not fixed. Verify that we can set the mode to all valid // values, and that we throw for invalid values. let testValues = ['max', 'clamped-max', 'explicit']; testValues.forEach(testValue => { should(() => { node = new window[nodeName]( context, Object.assign({}, expectedNodeOptions.additionalOptions, { channelCountMode: testValue })); }, `new ${nodeName}(c, {channelCountMode: "${testValue}"})`).notThrow(); should( node.channelCountMode, 'node.channelCountMode after valid setter') .beEqualTo(testValue); }); should( () => { node = new window[nodeName]( context, Object.assign( {}, expectedNodeOptions.additionalOptions, {channelCountMode: 'foobar'})); }, 'new ' + nodeName + '(c, {channelCountMode: "foobar"}') .throw(TypeError); should(node.channelCountMode, 'node.channelCountMode after invalid setter') .beEqualTo(testValues[testValues.length - 1]); } // Test channelInterpretation if (expectedNodeOptions.channelInterpretation && expectedNodeOptions.channelInterpretation.isFixed) { // The channel interpretation is fixed. Verify that we throw an // error if we try to change it. ['speakers', 'discrete'].forEach(testValue => { if (testValue !== expectedNodeOptions.channelInterpretation.value) { should( () => { node = new window[nodeName]( context, Object.assign( {}, expectedNodeOptions.additionOptions, {channelInterpretation: testValue})); }, `new ${nodeName}(c, {channelInterpretation: "${testValue}"})`) .throw(expectedNodeOptions.channelInterpretation.errorType); } }); } else { // Channel interpretation is not fixed. Verify that we can set it // to all possible values. should( () => { node = new window[nodeName]( context, Object.assign( {}, expectedNodeOptions.additionalOptions, {channelInterpretation: 'speakers'})); }, 'new ' + nodeName + '(c, {channelInterpretation: "speakers"})') .notThrow(); should(node.channelInterpretation, 'node.channelInterpretation') .beEqualTo('speakers'); should( () => { node = new window[nodeName]( context, Object.assign( {}, expectedNodeOptions.additionalOptions, {channelInterpretation: 'discrete'})); }, 'new ' + nodeName + '(c, {channelInterpretation: "discrete"})') .notThrow(); should(node.channelInterpretation, 'node.channelInterpretation') .beEqualTo('discrete'); should( () => { node = new window[nodeName]( context, Object.assign( {}, expectedNodeOptions.additionalOptions, {channelInterpretation: 'foobar'})); }, 'new ' + nodeName + '(c, {channelInterpretation: "foobar"})') .throw(TypeError); should( node.channelInterpretation, 'node.channelInterpretation after invalid setter') .beEqualTo('discrete'); } } function initializeContext(should) { let c; should(() => { c = new OfflineAudioContext(1, 1, 48000); }, 'context = new OfflineAudioContext(...)').notThrow(); return c; } function testInvalidConstructor(should, name, context) { should(() => { new window[name](); }, 'new ' + name + '()').throw(TypeError); should(() => { new window[name](1); }, 'new ' + name + '(1)').throw(TypeError); should(() => { new window[name](context, 42); }, 'new ' + name + '(context, 42)').throw(TypeError); } function testDefaultConstructor(should, name, context, options) { let node; let message = options.prefix + ' = new ' + name + '(context'; if (options.constructorOptions) message += ', ' + JSON.stringify(options.constructorOptions); message += ')' should(() => { node = new window[name](context, options.constructorOptions); }, message).notThrow(); should(node instanceof window[name], options.prefix + ' instanceof ' + name) .beEqualTo(true); should(node.numberOfInputs, options.prefix + '.numberOfInputs') .beEqualTo(options.numberOfInputs); should(node.numberOfOutputs, options.prefix + '.numberOfOutputs') .beEqualTo(options.numberOfOutputs); should(node.channelCount, options.prefix + '.channelCount') .beEqualTo(options.channelCount); should(node.channelCountMode, options.prefix + '.channelCountMode') .beEqualTo(options.channelCountMode); should(node.channelInterpretation, options.prefix + '.channelInterpretation') .beEqualTo(options.channelInterpretation); return node; } function testDefaultAttributes(should, node, prefix, items) { items.forEach((item) => { let attr = node[item.name]; if (attr instanceof AudioParam) { should(attr.value, prefix + '.' + item.name + '.value') .beEqualTo(item.value); } else { should(attr, prefix + '.' + item.name).beEqualTo(item.value); } }); }
scheib/chromium
third_party/blink/web_tests/webaudio/resources/audionodeoptions.js
JavaScript
bsd-3-clause
8,919
package org.motechproject.odk.domain; import org.motechproject.mds.annotations.Entity; import org.motechproject.mds.annotations.Field; /** * Domain object relating to a form receipt failure event */ @Entity public class FormFailure { @Field private String configName; @Field private String formTitle; @Field private String message; @Field private String exception; @Field(type = "TEXT") private String jsonContent; public FormFailure(String configName, String formTitle, String message, String exception, String jsonContent) { this.configName = configName; this.formTitle = formTitle; this.message = message; this.exception = exception; this.jsonContent = jsonContent; } public String getConfigName() { return configName; } public void setConfigName(String configName) { this.configName = configName; } public String getFormTitle() { return formTitle; } public void setFormTitle(String formTitle) { this.formTitle = formTitle; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getException() { return exception; } public void setException(String exception) { this.exception = exception; } public String getJsonContent() { return jsonContent; } public void setJsonContent(String jsonContent) { this.jsonContent = jsonContent; } }
koshalt/modules
odk/src/main/java/org/motechproject/odk/domain/FormFailure.java
Java
bsd-3-clause
1,577
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Config * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @category Zend * @package Zend_Config * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_Config_Writer { /** * Option keys to skip when calling setOptions() * * @var array */ protected $_skipOptions = array( 'options' ); /** * Config object to write * * @var Zend_Config */ protected $_config = null; /** * Create a new adapter * * $options can only be passed as array or be omitted * * @param null|array $options */ public function __construct(array $options = null) { if (is_array($options)) { $this->setOptions($options); } } /** * Set options via a Zend_Config instance * * @param Zend_Config $config * @return Zend_Config_Writer */ public function setConfig(Zend_Config $config) { $this->_config = $config; return $this; } /** * Set options via an array * * @param array $options * @return Zend_Config_Writer */ public function setOptions(array $options) { foreach ($options as $key => $value) { if (in_array(strtolower($key), $this->_skipOptions)) { continue; } $method = 'set' . ucfirst($key); if (method_exists($this, $method)) { $this->$method($value); } } return $this; } /** * Write a Zend_Config object to it's target * * @return void */ abstract public function write(); }
jupeter/zf1
library/Zend/Config/Writer.php
PHP
bsd-3-clause
2,431
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2007 * the Initial Developer. All Rights Reserved. * * Contributor(s): Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ //----------------------------------------------------------------------------- var BUGNUMBER = 392308; var summary = 'StopIteration should be catchable'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); function testStop() { function yielder() { actual += 'before, '; yield; actual += 'after, '; } expect = 'before, after, iteration terminated normally'; try { var gen = yielder(); result = gen.next(); gen.send(result); } catch (x if x instanceof StopIteration) { actual += 'iteration terminated normally'; } catch (x2) { actual += 'unexpected throw: ' + x2; } } testStop(); reportCompare(expect, actual, summary); exitFunc ('test'); }
darkrsw/safe
tests/browser_extensions/js1_7/extensions/XXXregress-392308.js
JavaScript
bsd-3-clause
2,774
/** * @license * Copyright The Closure Library Authors. * SPDX-License-Identifier: Apache-2.0 */ goog.module('goog.dom.SavedCaretRangeTest'); goog.setTestOnly(); const Range = goog.require('goog.dom.Range'); const SavedCaretRange = goog.require('goog.dom.SavedCaretRange'); const dom = goog.require('goog.dom'); const testSuite = goog.require('goog.testing.testSuite'); const testingDom = goog.require('goog.testing.dom'); const userAgent = goog.require('goog.userAgent'); /* TODO(user): Look into why removeCarets test doesn't pass. function testRemoveCarets() { var def = goog.dom.getElement('def'); var jkl = goog.dom.getElement('jkl'); var range = goog.dom.Range.createFromNodes( def.firstChild, 1, jkl.firstChild, 2); range.select(); var saved = range.saveUsingCarets(); assertHTMLEquals( "d<span id="" + saved.startCaretId_ + ""></span>ef", def.innerHTML); assertHTMLEquals( "jk<span id="" + saved.endCaretId_ + ""></span>l", jkl.innerHTML); saved.removeCarets(); assertHTMLEquals("def", def.innerHTML); assertHTMLEquals("jkl", jkl.innerHTML); var selection = goog.dom.Range.createFromWindow(window); assertEquals('Wrong start node', def.firstChild, selection.getStartNode()); assertEquals('Wrong end node', jkl.firstChild, selection.getEndNode()); assertEquals('Wrong start offset', 1, selection.getStartOffset()); assertEquals('Wrong end offset', 2, selection.getEndOffset()); } */ /** * Clear the selection by re-parsing the DOM. Then restore the saved * selection. * @param {Node} parent The node containing the current selection. * @param {dom.SavedRange} saved The saved range. * @return {dom.AbstractRange} Restored range. */ function clearSelectionAndRestoreSaved(parent, saved) { Range.clearSelection(); assertFalse(Range.hasSelection(window)); const range = saved.restore(); assertTrue(Range.hasSelection(window)); return range; } testSuite({ setUp() { document.body.normalize(); }, /** @bug 1480638 */ testSavedCaretRangeDoesntChangeSelection() { // NOTE(nicksantos): We cannot detect this bug programatically. The only // way to detect it is to run this test manually and look at the selection // when it ends. const div = dom.getElement('bug1480638'); const range = Range.createFromNodes(div.firstChild, 0, div.lastChild, 1); range.select(); // Observe visible selection. Then move to next line and see it change. // If the bug exists, it starts with "foo" selected and ends with // it not selected. // debugger; const saved = range.saveUsingCarets(); }, /** @suppress {strictMissingProperties} suppression added to enable type checking */ testSavedCaretRange() { if (userAgent.IE && !userAgent.isDocumentModeOrHigher(8)) { // testSavedCaretRange fails in IE7 unless the source files are loaded in // a certain order. Adding goog.require('goog.dom.classes') to dom.js or // goog.require('goog.array') to savedcaretrange_test.js after the // goog.require('goog.dom') line fixes the test, but it's better to not // rely on such hacks without understanding the reason of the failure. return; } const parent = dom.getElement('caretRangeTest'); let def = dom.getElement('def'); let jkl = dom.getElement('jkl'); const range = Range.createFromNodes(def.firstChild, 1, jkl.firstChild, 2); assertFalse(range.isReversed()); range.select(); const saved = range.saveUsingCarets(); assertHTMLEquals( 'd<span id="' + saved.startCaretId_ + '"></span>ef', def.innerHTML); assertHTMLEquals( 'jk<span id="' + saved.endCaretId_ + '"></span>l', jkl.innerHTML); testingDom.assertRangeEquals( def.childNodes[1], 0, jkl.childNodes[1], 0, saved.toAbstractRange()); def = dom.getElement('def'); jkl = dom.getElement('jkl'); const restoredRange = clearSelectionAndRestoreSaved(parent, saved); assertFalse(restoredRange.isReversed()); testingDom.assertRangeEquals(def, 1, jkl, 1, restoredRange); const selection = Range.createFromWindow(window); assertHTMLEquals('def', def.innerHTML); assertHTMLEquals('jkl', jkl.innerHTML); // def and jkl now contain fragmented text nodes. const endNode = selection.getEndNode(); if (endNode == jkl.childNodes[0]) { // Webkit (up to Chrome 57) and IE < 9. testingDom.assertRangeEquals( def.childNodes[1], 0, jkl.childNodes[0], 2, selection); } else if (endNode == jkl.childNodes[1]) { // Opera testingDom.assertRangeEquals( def.childNodes[1], 0, jkl.childNodes[1], 0, selection); } else { // Gecko, newer Chromes testingDom.assertRangeEquals(def, 1, jkl, 1, selection); } }, testReversedSavedCaretRange() { const parent = dom.getElement('caretRangeTest'); const def = dom.getElement('def-5'); const jkl = dom.getElement('jkl-5'); const range = Range.createFromNodes(jkl.firstChild, 1, def.firstChild, 2); assertTrue(range.isReversed()); range.select(); const saved = range.saveUsingCarets(); const restoredRange = clearSelectionAndRestoreSaved(parent, saved); assertTrue(restoredRange.isReversed()); testingDom.assertRangeEquals(def, 1, jkl, 1, restoredRange); }, testRemoveContents() { const def = dom.getElement('def-4'); const jkl = dom.getElement('jkl-4'); // Sanity check. const container = dom.getElement('removeContentsTest'); assertEquals(7, container.childNodes.length); assertEquals('def', def.innerHTML); assertEquals('jkl', jkl.innerHTML); const range = Range.createFromNodes(def.firstChild, 1, jkl.firstChild, 2); range.select(); const saved = range.saveUsingCarets(); const restored = saved.restore(); restored.removeContents(); assertEquals(6, container.childNodes.length); assertEquals('d', def.innerHTML); assertEquals('l', jkl.innerHTML); }, testHtmlEqual() { const parent = dom.getElement('caretRangeTest-2'); const def = dom.getElement('def-2'); const jkl = dom.getElement('jkl-2'); const range = Range.createFromNodes(def.firstChild, 1, jkl.firstChild, 2); range.select(); const saved = range.saveUsingCarets(); const html1 = parent.innerHTML; saved.removeCarets(); const saved2 = range.saveUsingCarets(); const html2 = parent.innerHTML; saved2.removeCarets(); assertNotEquals( 'Same selection with different saved caret range carets ' + 'must have different html.', html1, html2); assertTrue( 'Same selection with different saved caret range carets must ' + 'be considered equal by htmlEqual', SavedCaretRange.htmlEqual(html1, html2)); saved.dispose(); saved2.dispose(); }, testStartCaretIsAtEndOfParent() { const parent = dom.getElement('caretRangeTest-3'); const def = dom.getElement('def-3'); const jkl = dom.getElement('jkl-3'); let range = Range.createFromNodes(def, 1, jkl, 1); range.select(); const saved = range.saveUsingCarets(); clearSelectionAndRestoreSaved(parent, saved); range = Range.createFromWindow(); assertEquals('ghijkl', range.getText().replace(/\s/g, '')); }, });
nwjs/chromium.src
third_party/google-closure-library/closure/goog/dom/savedcaretrange_test.js
JavaScript
bsd-3-clause
7,324
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>PayPal Merchant SDK - MassPay</title> <link rel="stylesheet" href="../Common/sdk.css"/> <script type="text/javascript" src="../Common/sdk.js"></script> </head> <body> <div id="wrapper"> <img src="https://devtools-paypal.com/image/bdg_payments_by_pp_2line.png"> <div id="header"> <h3>MassPay</h3> <div id="apidetails">MassPay API operation makes a payment to one or more PayPal account holders.</div> </div> <form method="POST" action="MassPay.php"> <div id="request_form"> <div class="params"> <div class="param_name">Receiver Info Code Type</div> <div class="param_value"> <select name=receiverInfoCode> <option value=EmailAddress>Email</option> <option value=UserID>UserID</option> <option value=PhoneNumber>Phone</option> </select> </div> </div> <table class="params"> <tr> <th class="param_name">Mail</th> <th class="param_name">UserID</th> <th class="param_name">Phone Number</th> <th class="param_name">Amount</th> <th class="param_name">Currency Code</th> </tr> <tr> <td class="param_value"><input type="text" name="mail[]" value="enduser_biz@gmail.com" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="id[]" value="" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="phone[]" value="" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="amount[]" value="3.00" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="currencyCode[]" value="USD" size="25" maxlength="260" /></td> </tr> <tr> <td class="param_value"><input type="text" name="mail[]" value="sdk-three@paypal.com" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="id[]" value="" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="phone[]" value="" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="amount[]" value="3.00" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="currencyCode[]" value="USD" size="25" maxlength="260" /></td> </tr> <tr> <td class="param_value"><input type="text" name="mail[]" value="jb-us-seller@paypal.com" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="id[]" value="" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="phone[]" value="" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="amount[]" value="3.00" size="25" maxlength="260" /></td> <td class="param_value"><input type="text" name="currencyCode[]" value="USD" size="25" maxlength="260" /></td> </tr> </table> <?php include('../Permissions/Permission.html.php'); ?> <input type="submit" name="MassPayBtn" value="MassPay" /><br /> </div> <a href="../index.php">Home</a> </form> </div> </body> </html>
olegkaliuga/yii
vendor/paypal/work/merchant-sdk-php/samples/MassPay/MassPay.html.php
PHP
bsd-3-clause
3,396
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.media; import android.content.Context; import android.graphics.ImageFormat; import android.hardware.display.DisplayManager; import android.view.Display; import android.view.Surface; import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Video Capture Device base class, defines a set of methods that native code * needs to use to configure, start capture, and to be reached by callbacks and * provides some necessary data type(s) with accessors. **/ @JNINamespace("media") public abstract class VideoCapture { /** * Common class for storing a framerate range. Values should be multiplied by 1000. */ protected static class FramerateRange { public int min; public int max; public FramerateRange(int min, int max) { this.min = min; this.max = max; } } // The angle (0, 90, 180, 270) that the image needs to be rotated to show in // the display's native orientation. protected int mCameraNativeOrientation; // In some occasions we need to invert the device rotation readings, see the // individual implementations. protected boolean mInvertDeviceOrientationReadings; protected VideoCaptureFormat mCaptureFormat; protected final int mId; // Native callback context variable. protected final long mNativeVideoCaptureDeviceAndroid; protected boolean mUseBackgroundThreadForTesting; VideoCapture(int id, long nativeVideoCaptureDeviceAndroid) { mId = id; mNativeVideoCaptureDeviceAndroid = nativeVideoCaptureDeviceAndroid; } // Allocate necessary resources for capture. @CalledByNative public abstract boolean allocate( int width, int height, int frameRate, boolean enableFaceDetection); // Success is indicated by returning true and a callback to // VideoCaptureJni.get().onStarted(, VideoCapture.this), which may occur synchronously or // asynchronously. Failure can be indicated by one of the following: // * Returning false. In this case no callback to VideoCaptureJni.get().onStarted() is made. // * Returning true, and asynchronously invoking VideoCaptureJni.get().onError. In this case // also no callback to VideoCaptureJni.get().onStarted() is made. @CalledByNative public abstract boolean startCaptureMaybeAsync(); // Blocks until it is guaranteed that no more frames are sent. @CalledByNative public abstract boolean stopCaptureAndBlockUntilStopped(); // Replies by calling VideoCaptureJni.get().onGetPhotoCapabilitiesReply(). Will pass |null| // for parameter |result| to indicate failure. @CalledByNative public abstract void getPhotoCapabilitiesAsync(long callbackId); /** * @param zoom Zoom level, should be ignored if 0. * @param focusMode Focus mode following AndroidMeteringMode enum. * @param focusDistance Desired distance to plane of sharpest focus. * @param exposureMode Exposure mode following AndroidMeteringMode enum. * @param pointsOfInterest2D 2D normalized points of interest, marshalled with * x coordinate first followed by the y coordinate. * @param hasExposureCompensation Indicates if |exposureCompensation| is set. * @param exposureCompensation Adjustment to auto exposure. 0 means not adjusted. * @param exposureTime Duration each pixel is exposed to light (in nanoseconds). * @param whiteBalanceMode White Balance mode following AndroidMeteringMode enum. * @param iso Sensitivity to light. 0, which would be invalid, means ignore. * @param hasRedEyeReduction Indicates if |redEyeReduction| is set. * @param redEyeReduction Value of red eye reduction for the auto flash setting. * @param fillLightMode Flash setting, following AndroidFillLightMode enum. * @param colorTemperature White Balance reference temperature, valid if whiteBalanceMode is * manual, and its value is larger than 0. * @param torch Torch setting, true meaning on. */ @CalledByNative public abstract void setPhotoOptions(double zoom, int focusMode, double focusDistance, int exposureMode, double width, double height, double[] pointsOfInterest2D, boolean hasExposureCompensation, double exposureCompensation, double exposureTime, int whiteBalanceMode, double iso, boolean hasRedEyeReduction, boolean redEyeReduction, int fillLightMode, boolean hasTorch, boolean torch, double colorTemperature); // Replies by calling VideoCaptureJni.get().onPhotoTaken(). @CalledByNative public abstract void takePhotoAsync(long callbackId); @CalledByNative public abstract void deallocate(); @CalledByNative public final int queryWidth() { return mCaptureFormat.mWidth; } @CalledByNative public final int queryHeight() { return mCaptureFormat.mHeight; } @CalledByNative public final int queryFrameRate() { return mCaptureFormat.mFramerate; } @CalledByNative public final int getColorspace() { switch (mCaptureFormat.mPixelFormat) { case ImageFormat.YV12: return AndroidImageFormat.YV12; case ImageFormat.YUV_420_888: return AndroidImageFormat.YUV_420_888; case ImageFormat.NV21: return AndroidImageFormat.NV21; case ImageFormat.UNKNOWN: default: return AndroidImageFormat.UNKNOWN; } } @CalledByNative public final void setTestMode() { mUseBackgroundThreadForTesting = true; } protected final int getCameraRotation() { int rotation = mInvertDeviceOrientationReadings ? (360 - getDeviceRotation()) : getDeviceRotation(); return (mCameraNativeOrientation + rotation) % 360; } protected final int getDeviceRotation() { final int orientation; DisplayManager dm = (DisplayManager) ContextUtils.getApplicationContext().getSystemService( Context.DISPLAY_SERVICE); switch (dm.getDisplay(Display.DEFAULT_DISPLAY).getRotation()) { case Surface.ROTATION_90: orientation = 90; break; case Surface.ROTATION_180: orientation = 180; break; case Surface.ROTATION_270: orientation = 270; break; case Surface.ROTATION_0: default: orientation = 0; break; } return orientation; } // {@link VideoCaptureJni.get().onPhotoTaken()} needs to be called back if there's any // problem after {@link takePhotoAsync()} has returned true. protected void notifyTakePhotoError(long callbackId) { VideoCaptureJni.get().onPhotoTaken( mNativeVideoCaptureDeviceAndroid, VideoCapture.this, callbackId, null); } /** * Finds the framerate range matching |targetFramerate|. Tries to find a range with as low of a * minimum value as possible to allow the camera adjust based on the lighting conditions. * Assumes that all framerate values are multiplied by 1000. * * This code is mostly copied from WebRTC: * CameraEnumerationAndroid.getClosestSupportedFramerateRange * in webrtc/api/android/java/src/org/webrtc/CameraEnumerationAndroid.java */ protected static FramerateRange getClosestFramerateRange( final List<FramerateRange> framerateRanges, final int targetFramerate) { return Collections.min(framerateRanges, new Comparator<FramerateRange>() { // Threshold and penalty weights if the upper bound is further away than // |MAX_FPS_DIFF_THRESHOLD| from requested. private static final int MAX_FPS_DIFF_THRESHOLD = 5000; private static final int MAX_FPS_LOW_DIFF_WEIGHT = 1; private static final int MAX_FPS_HIGH_DIFF_WEIGHT = 3; // Threshold and penalty weights if the lower bound is bigger than |MIN_FPS_THRESHOLD|. private static final int MIN_FPS_THRESHOLD = 8000; private static final int MIN_FPS_LOW_VALUE_WEIGHT = 1; private static final int MIN_FPS_HIGH_VALUE_WEIGHT = 4; // Use one weight for small |value| less than |threshold|, and another weight above. private int progressivePenalty( int value, int threshold, int lowWeight, int highWeight) { return (value < threshold) ? value * lowWeight : threshold * lowWeight + (value - threshold) * highWeight; } int diff(FramerateRange range) { final int minFpsError = progressivePenalty(range.min, MIN_FPS_THRESHOLD, MIN_FPS_LOW_VALUE_WEIGHT, MIN_FPS_HIGH_VALUE_WEIGHT); final int maxFpsError = progressivePenalty(Math.abs(targetFramerate - range.max), MAX_FPS_DIFF_THRESHOLD, MAX_FPS_LOW_DIFF_WEIGHT, MAX_FPS_HIGH_DIFF_WEIGHT); return minFpsError + maxFpsError; } @Override public int compare(FramerateRange range1, FramerateRange range2) { return diff(range1) - diff(range2); } }); } protected static int[] integerArrayListToArray(ArrayList<Integer> intArrayList) { int[] intArray = new int[intArrayList.size()]; for (int i = 0; i < intArrayList.size(); i++) { intArray[i] = intArrayList.get(i).intValue(); } return intArray; } @NativeMethods interface Natives { // Method for VideoCapture implementations to call back native code. void onFrameAvailable(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, byte[] data, int length, int rotation); void onI420FrameAvailable(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, ByteBuffer yBuffer, int yStride, ByteBuffer uBuffer, ByteBuffer vBuffer, int uvRowStride, int uvPixelStride, int width, int height, int rotation, long timestamp); // Method for VideoCapture implementations to signal an asynchronous error. void onError(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, int androidVideoCaptureError, String message); // Method for VideoCapture implementations to signal that a frame was dropped. void onFrameDropped(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, int androidVideoCaptureFrameDropReason); void onGetPhotoCapabilitiesReply(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, long callbackId, PhotoCapabilities result); // Callback for calls to takePhoto(). This can indicate both success and // failure. Failure is indicated by |data| being null. void onPhotoTaken(long nativeVideoCaptureDeviceAndroid, VideoCapture caller, long callbackId, byte[] data); // Method for VideoCapture implementations to report device started event. void onStarted(long nativeVideoCaptureDeviceAndroid, VideoCapture caller); void dCheckCurrentlyOnIncomingTaskRunner( long nativeVideoCaptureDeviceAndroid, VideoCapture caller); } }
youtube/cobalt
third_party/chromium/media/capture/video/android/java/src/org/chromium/media/VideoCapture.java
Java
bsd-3-clause
11,938
// This file was generated by the _js_query_arg_file Skylark rule defined in // maps/vectortown/performance/script/build_defs.bzl. var testConfig = "overridePixelRatio=1&title=chrome_smoothness_performancetest_config&nobudget=false&nodraw=false&noprefetch=true&viewport=basic&wait=true";
scheib/chromium
tools/perf/page_sets/maps_perf_test/config.js
JavaScript
bsd-3-clause
289
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/app_list/search/history.h" #include <stddef.h> #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "ui/app_list/search/history_data.h" #include "ui/app_list/search/history_data_store.h" #include "ui/app_list/search/tokenized_string.h" namespace app_list { namespace { // Normalize the given string by joining all its tokens with a space. std::string NormalizeString(const std::string& utf8) { TokenizedString tokenized(base::UTF8ToUTF16(utf8)); return base::UTF16ToUTF8( base::JoinString(tokenized.tokens(), base::ASCIIToUTF16(" "))); } } // namespace History::History(scoped_refptr<HistoryDataStore> store) : store_(store), data_loaded_(false) { const size_t kMaxQueryEntries = 1000; const size_t kMaxSecondaryQueries = 5; data_.reset( new HistoryData(store_.get(), kMaxQueryEntries, kMaxSecondaryQueries)); data_->AddObserver(this); } History::~History() { data_->RemoveObserver(this); } bool History::IsReady() const { return data_loaded_; } void History::AddLaunchEvent(const std::string& query, const std::string& result_id) { DCHECK(IsReady()); data_->Add(NormalizeString(query), result_id); } scoped_ptr<KnownResults> History::GetKnownResults( const std::string& query) const { DCHECK(IsReady()); return data_->GetKnownResults(NormalizeString(query)); } void History::OnHistoryDataLoadedFromStore() { data_loaded_ = true; } } // namespace app_list
hujiajie/chromium-crosswalk
ui/app_list/search/history.cc
C++
bsd-3-clause
1,669
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.indices.rollover; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.support.ActiveShardCount; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.master.AcknowledgedRequest; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.ParseFieldMatcherSupplier; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.ObjectParser; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import static org.elasticsearch.action.ValidateActions.addValidationError; /** * Request class to swap index under an alias upon satisfying conditions */ public class RolloverRequest extends AcknowledgedRequest<RolloverRequest> implements IndicesRequest { public static ObjectParser<RolloverRequest, ParseFieldMatcherSupplier> PARSER = new ObjectParser<>("conditions", null); static { PARSER.declareField((parser, request, parseFieldMatcherSupplier) -> Condition.PARSER.parse(parser, request.conditions, parseFieldMatcherSupplier), new ParseField("conditions"), ObjectParser.ValueType.OBJECT); PARSER.declareField((parser, request, parseFieldMatcherSupplier) -> request.createIndexRequest.settings(parser.map()), new ParseField("settings"), ObjectParser.ValueType.OBJECT); PARSER.declareField((parser, request, parseFieldMatcherSupplier) -> { for (Map.Entry<String, Object> mappingsEntry : parser.map().entrySet()) { request.createIndexRequest.mapping(mappingsEntry.getKey(), (Map<String, Object>) mappingsEntry.getValue()); } }, new ParseField("mappings"), ObjectParser.ValueType.OBJECT); PARSER.declareField((parser, request, parseFieldMatcherSupplier) -> request.createIndexRequest.aliases(parser.map()), new ParseField("aliases"), ObjectParser.ValueType.OBJECT); } private String alias; private String newIndexName; private boolean dryRun; private Set<Condition> conditions = new HashSet<>(2); private CreateIndexRequest createIndexRequest = new CreateIndexRequest("_na_"); RolloverRequest() {} public RolloverRequest(String alias, String newIndexName) { this.alias = alias; this.newIndexName = newIndexName; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = createIndexRequest == null ? null : createIndexRequest.validate(); if (alias == null) { validationException = addValidationError("index alias is missing", validationException); } if (createIndexRequest == null) { validationException = addValidationError("create index request is missing", validationException); } return validationException; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); alias = in.readString(); newIndexName = in.readOptionalString(); dryRun = in.readBoolean(); int size = in.readVInt(); for (int i = 0; i < size; i++) { this.conditions.add(in.readNamedWriteable(Condition.class)); } createIndexRequest = new CreateIndexRequest(); createIndexRequest.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(alias); out.writeOptionalString(newIndexName); out.writeBoolean(dryRun); out.writeVInt(conditions.size()); for (Condition condition : conditions) { out.writeNamedWriteable(condition); } createIndexRequest.writeTo(out); } @Override public String[] indices() { return new String[] {alias}; } @Override public IndicesOptions indicesOptions() { return IndicesOptions.strictSingleIndexNoExpandForbidClosed(); } /** * Sets the alias to rollover to another index */ public void setAlias(String alias) { this.alias = alias; } /** * Sets the alias to rollover to another index */ public void setNewIndexName(String newIndexName) { this.newIndexName = newIndexName; } /** * Sets if the rollover should not be executed when conditions are met */ public void dryRun(boolean dryRun) { this.dryRun = dryRun; } /** * Adds condition to check if the index is at least <code>age</code> old */ public void addMaxIndexAgeCondition(TimeValue age) { this.conditions.add(new MaxAgeCondition(age)); } /** * Adds condition to check if the index has at least <code>numDocs</code> */ public void addMaxIndexDocsCondition(long numDocs) { this.conditions.add(new MaxDocsCondition(numDocs)); } /** * Sets rollover index creation request to override index settings when * the rolled over index has to be created */ public void setCreateIndexRequest(CreateIndexRequest createIndexRequest) { this.createIndexRequest = Objects.requireNonNull(createIndexRequest, "create index request must not be null");; } boolean isDryRun() { return dryRun; } Set<Condition> getConditions() { return conditions; } String getAlias() { return alias; } String getNewIndexName() { return newIndexName; } CreateIndexRequest getCreateIndexRequest() { return createIndexRequest; } public void source(BytesReference source) { XContentType xContentType = XContentFactory.xContentType(source); if (xContentType != null) { try (XContentParser parser = XContentFactory.xContent(xContentType).createParser(source)) { PARSER.parse(parser, this, () -> ParseFieldMatcher.EMPTY); } catch (IOException e) { throw new ElasticsearchParseException("failed to parse source for rollover index", e); } } else { throw new ElasticsearchParseException("failed to parse content type for rollover index source"); } } /** * Sets the number of shard copies that should be active for creation of the * new rollover index to return. Defaults to {@link ActiveShardCount#DEFAULT}, which will * wait for one shard copy (the primary) to become active. Set this value to * {@link ActiveShardCount#ALL} to wait for all shards (primary and all replicas) to be active * before returning. Otherwise, use {@link ActiveShardCount#from(int)} to set this value to any * non-negative integer, up to the number of copies per shard (number of replicas + 1), * to wait for the desired amount of shard copies to become active before returning. * Index creation will only wait up until the timeout value for the number of shard copies * to be active before returning. Check {@link RolloverResponse#isShardsAcked()} to * determine if the requisite shard copies were all started before returning or timing out. * * @param waitForActiveShards number of active shard copies to wait on */ public void setWaitForActiveShards(ActiveShardCount waitForActiveShards) { this.createIndexRequest.waitForActiveShards(waitForActiveShards); } /** * A shortcut for {@link #setWaitForActiveShards(ActiveShardCount)} where the numerical * shard count is passed in, instead of having to first call {@link ActiveShardCount#from(int)} * to get the ActiveShardCount. */ public void setWaitForActiveShards(final int waitForActiveShards) { setWaitForActiveShards(ActiveShardCount.from(waitForActiveShards)); } }
strahanjen/strahanjen.github.io
elasticsearch-master/core/src/main/java/org/elasticsearch/action/admin/indices/rollover/RolloverRequest.java
Java
bsd-3-clause
9,336
var assert = require('assert'); var appHelper = require('./helpers/appHelper'); var path = require('path'); var fs = require('fs'); describe('Configs', function() { this.timeout(30000); var appName = 'testApp'; var config; var sailsserver; var up = false; describe('in production env', function () { before(function(done) { // build app appHelper.build(function(err) { if (err) return done(err); process.chdir(appName); // Start sails and pass it command line arguments require(path.resolve('./../lib')).lift({ // Override memorystore with `{session:{adapter: null}}` session: { adapter: null } }, function(err, sails) { if (err) return done(err); up = true; config = sails.config; sailsserver = sails; done(); }); }); }); after(function() { sailsserver.lower(function() { // Not sure why this runs multiple times, but checking "up" makes // sure we only do chdir once sailsserver.removeAllListeners(); if (up === true) { up = false; process.chdir('../'); appHelper.teardown(); } }); }); it('should retain legacy `config.adapters` for backwards compat.', function() { var legacyConfig = config.adapters; assert(legacyConfig.custom && legacyConfig.custom.module === 'sails-disk'); assert(legacyConfig.sqlite.module === 'sails-sqlite'); assert(legacyConfig.sqlite.host === 'sqliteHOST'); assert(legacyConfig.sqlite.user === 'sqliteUSER'); }); // it('should load connection configs', function() { // var connectionsConfig = config.connections; // assert(config.model.adapter === 'sails-disk'); // assert(connectionsConfig.custom && connectionsConfig.custom.module === 'sails-disk'); // assert(connectionsConfig.sqlite.module === 'sails-sqlite'); // assert(connectionsConfig.sqlite.host === 'sqliteHOST'); // assert(connectionsConfig.sqlite.user === 'sqliteUSER'); // }); it('should load application configs', function() { assert(config.port === 1702); assert(config.host === 'localhost'); // this should have been overriden by the local conf file assert(config.appName === 'portal2'); assert(config.environment === 'production'); assert(config.cache.maxAge === 9001); assert(config.globals._ === false); }); it('should load the controllers configs', function() { var conf = config.controllers; assert(conf.routes.actions === false); assert(conf.routes.prefix === 'Z'); assert(conf.routes.expectIntegerId === true); assert(conf.csrf === true); }); it('should load the io configs', function() { var conf = config.sockets; assert(conf.adapter === 'disk'); assert(conf.transports[0] === 'websocket'); assert(conf.origins === '*:1337'); assert(conf.heartbeats === false); assert(conf['close timeout'] === 10); assert(conf.authorization === false); assert(conf['log level'] === 'error'); assert(conf['log colors'] === true); assert(conf.static === false); assert(conf.resource === '/all/the/sockets'); }); it('should override configs with locals config', function() { assert(config.appName === 'portal2'); }); it('should load the log configs', function() { assert(config.log.level === 'error'); }); it('should load the poly configs', function() { assert(config.policies['*'] === false); }); it('should load the routes configs', function() { assert(typeof config.routes['/'] === 'function'); }); it('should load the session configs', function() { assert(config.session.secret === '1234567'); assert(config.session.key === 'sails.sid'); }); it('should load the views config', function() { var conf = config.views; assert(conf.engine.ext === 'ejs'); assert(conf.blueprints === false); assert(conf.layout === false); }); }); });
BlueHotDog/sails-migrations
test/fixtures/sample_apps/0.9.8/node_modules/sails/test/config/integration/load.test.js
JavaScript
mit
3,853
testTransport = function(transports) { var prefix = "socketio - " + transports + ": "; connect = function(transports) { // Force transport io.transports = transports; deepEqual(io.transports, transports, "Force transports"); var options = { 'force new connection': true } return io.connect('/test', options); } asyncTest(prefix + "Connect", function() { expect(4); test = connect(transports); test.on('connect', function () { ok( true, "Connected with transport: " + test.socket.transport.name ); test.disconnect(); }); test.on('disconnect', function (reason) { ok( true, "Disconnected - " + reason ); test.socket.disconnect(); start(); }); test.on('connect_failed', function () { ok( false, "Connection failed"); start(); }); }); asyncTest(prefix + "Emit with ack", function() { expect(3); test = connect(transports); test.emit('requestack', 1, function (val1, val2) { equal(val1, 1); equal(val2, "ack"); test.disconnect(); test.socket.disconnect(); start(); }); }); asyncTest(prefix + "Emit with ack one return value", function() { expect(2); test = connect(transports); test.emit('requestackonevalue', 1, function (val1) { equal(val1, 1); test.disconnect(); test.socket.disconnect(); start(); }); }); } transports = [io.transports]; // Validate individual transports for(t in io.transports) { if(io.Transport[io.transports[t]].check()) { transports.push([io.transports[t]]); } } for(t in transports) { testTransport(transports[t]) }
grokcore/dev.lexycross
wordsmithed/src/gevent-socketio/tests/jstests/tests/suite.js
JavaScript
mit
1,679
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // using Microsoft.AzureStack.Management.Compute.Admin; using Microsoft.AzureStack.Management.Compute.Admin.Models; using System.Linq; using System.Net; using Xunit; namespace Compute.Tests { public class QuotaTests : ComputeTestBase { // Helper private Quota Create(int asc, int cl, int vssc, int vmc, int smds, int pmds) { var newQuota = new Quota() { AvailabilitySetCount = asc, CoresLimit = cl, VmScaleSetCount = vssc, VirtualMachineCount = vmc, MaxAllocationStandardManagedDisksAndSnapshots =smds, MaxAllocationPremiumManagedDisksAndSnapshots = pmds }; return newQuota; } private void ValidateQuota(Quota quota) { AssertValidResource(quota); Assert.NotNull(quota); Assert.NotNull(quota.AvailabilitySetCount); Assert.NotNull(quota.CoresLimit); Assert.NotNull(quota.VirtualMachineCount); Assert.NotNull(quota.VmScaleSetCount); Assert.NotNull(quota.MaxAllocationStandardManagedDisksAndSnapshots); Assert.NotNull(quota.MaxAllocationPremiumManagedDisksAndSnapshots); } private void AssertSame(Quota expected, Quota given, bool resourceToo = true) { if (resourceToo) { AssertSameResource(expected, given); } if (expected == null) { Assert.Null(given); } else { Assert.NotNull(given); Assert.Equal(expected.AvailabilitySetCount, given.AvailabilitySetCount); Assert.Equal(expected.CoresLimit, given.CoresLimit); Assert.Equal(expected.VirtualMachineCount, given.VirtualMachineCount); Assert.Equal(expected.VmScaleSetCount, given.VmScaleSetCount); Assert.Equal(expected.MaxAllocationStandardManagedDisksAndSnapshots, given.MaxAllocationStandardManagedDisksAndSnapshots); Assert.Equal(expected.MaxAllocationPremiumManagedDisksAndSnapshots, given.MaxAllocationPremiumManagedDisksAndSnapshots); } } [Fact] public void TestListQuotas() { RunTest((client) => { var quotas = client.Quotas.List("local"); Assert.NotNull(quotas); quotas.ForEach(ValidateQuota); }); } [Fact] public void TestGetQuota() { RunTest((client) => { var quota = client.Quotas.List("local").FirstOrDefault(); var result = client.Quotas.Get("local", quota.Name); AssertSame(quota, result); }); } [Fact] public void TestGetAllQuotas() { RunTest((client) => { var quotas = client.Quotas.List("local"); quotas.ForEach((quota) => { var result = client.Quotas.Get("local", quota.Name); AssertSame(quota, result); }); }); } private void ValidateAgainstData(Quota q, int[] d) { Assert.Equal(q.AvailabilitySetCount, d[0]); Assert.Equal(q.CoresLimit, d[1]); Assert.Equal(q.VmScaleSetCount, d[2]); Assert.Equal(q.VirtualMachineCount, d[3]); Assert.Equal(q.MaxAllocationStandardManagedDisksAndSnapshots, d[4]); Assert.Equal(q.MaxAllocationPremiumManagedDisksAndSnapshots, d[5]); } [Fact] public void CreateUpdateDeleteQuota() { RunTest((client) => { var location = "local"; var name = "testQuotaCreateUpdateDelete"; var data = new int[]{1,1,1,1,1,1 }; var newQuota = Create(data[0], data[1], data[2], data[3], data[4], data[5]); var quota = client.Quotas.CreateOrUpdate(location, name, newQuota); ValidateAgainstData(quota, data); AssertSame(newQuota, quota, false); quota.VirtualMachineCount += 1; quota = client.Quotas.CreateOrUpdate(location, name, quota); data[3] += 1; ValidateAgainstData(quota, data); quota.AvailabilitySetCount += 1; quota = client.Quotas.CreateOrUpdate(location, name, quota); data[0] += 1; ValidateAgainstData(quota, data); quota.VmScaleSetCount += 1; quota = client.Quotas.CreateOrUpdate(location, name, quota); data[2] += 1; ValidateAgainstData(quota, data); quota.CoresLimit+= 1; quota = client.Quotas.CreateOrUpdate(location, name, quota); data[1] += 1; ValidateAgainstData(quota, data); quota.MaxAllocationStandardManagedDisksAndSnapshots+= 1; quota = client.Quotas.CreateOrUpdate(location, name, quota); data[4] += 1; ValidateAgainstData(quota, data); quota.MaxAllocationPremiumManagedDisksAndSnapshots += 1; quota = client.Quotas.CreateOrUpdate(location, name, quota); data[5] += 1; ValidateAgainstData(quota, data); client.Quotas.Delete(location, name); }); } [Fact] public void TestCreateQuota() { RunTest((client) => { var location = "local"; var quotaNamePrefix = "testQuota"; var data = new System.Collections.Generic.List<int[]> { new [] { 0, 0, 0, 0, 0, 0, 0 }, new [] { 1, 0, 0, 0, 0, 0, 1 }, new [] { 0, 1, 0, 0, 0, 0, 2 }, new [] { 0, 0, 1, 0, 0, 0, 3 }, new [] { 0, 0, 0, 1, 0, 0, 4 }, new [] { 0, 0, 0, 0, 1, 0, 5 }, new [] { 0, 0, 0, 0, 0, 1, 6 }, new [] { 100, 100, 100, 100 ,100, 100, 7 }, new [] { 1000, 1000, 1000, 1000, 1000, 1000, 8 } }; data.ForEach((d) => { var name = quotaNamePrefix + d[6]; var newQuota = Create(d[0], d[1], d[2], d[3], d[4], d[5]); var quota = client.Quotas.CreateOrUpdate(location, name, newQuota); ValidateAgainstData(quota, d); var result = client.Quotas.Get(location, name); AssertSame(quota, result, false); }); data.ForEach((d) => { var name = quotaNamePrefix + d[6]; var list = client.Quotas.List(location); Assert.Equal(1, list.Count((q) => q.Name.Equals(name))); }); data.ForEach((d) => { var name = quotaNamePrefix + d[6]; client.Quotas.Delete(location, name); ValidateExpectedReturnCode( () => client.Quotas.Get(location, name), HttpStatusCode.NotFound ); }); }); } #region Test With Invalid data [Fact] public void TestCreateInvalidQuota() { RunTest((client) => { var name = "myQuota"; Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(-1, 1, 1, 1, 1, 1))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(1, -1, 1, 1, 1, 1))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(1, 1, -1, 1, 1, 1))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(1, 1, 1, -1, 1, 1))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(1, 1, 1, 1, -1, 1))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(1, 1, 1, 1, 1, -1))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(-1, 0, 0, 0, 0, 0))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(0, -1, 0, 0, 0, 0))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(0, 0, -1, 0, 0, 0))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(0, 0, 0, -1, 0, 0))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(0, 0, 0, 0, -1, 0))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(0, 0, 0, 0, 0, -1))); Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(-1, -1, -1, -1, -1, -1))); }); } // Invalid Locations [Fact(Skip = "CRP does not handle invalid locations correctly.")] public void TestListInvalidLocation() { RunTest((client) => { var list = client.Quotas.List("thisisnotarealplace"); Assert.Empty(list); }); } [Fact] public void TestDeleteNonExistingQuota() { RunTest((client) => { ValidateExpectedReturnCode( () => client.Quotas.Delete("local", "thisdoesnotexistandifitdoesoops"), HttpStatusCode.NotFound ); }); } [Fact(Skip = "CRP does not handle invalid locations correctly.")] public void TestCreateQuotaOnInvalidLocation() { RunTest((client) => { var location = "thislocationdoesnotexist"; var quotaNamePrefix = "testQuota"; var data = new System.Collections.Generic.List<int[]> { new [] { 0, 0, 0, 0, 0, 0, 0 }, new [] { 1, 0, 0, 0, 0, 0, 1 }, new [] { 0, 1, 0, 0, 0, 0, 2 }, new [] { 0, 0, 1, 0, 0, 0, 3 }, new [] { 0, 0, 0, 1, 0, 0, 4 }, new [] { 0, 0, 0, 0, 1, 0, 5 }, new [] { 0, 0, 0, 0, 0, 1, 6 }, new [] { 100, 100, 100, 100 ,100, 100, 7 }, new [] { 1000, 1000, 1000, 1000, 1000, 1000, 8 } }; data.ForEach((d) => { var name = quotaNamePrefix + d[6]; var newQuota = Create(d[0], d[1], d[2], d[3], d[4], d[5]); var quota = client.Quotas.CreateOrUpdate(location, name, newQuota); var result = client.Quotas.Get(location, name); Assert.Null(quota); Assert.Null(result); }); data.ForEach((d) => { var name = quotaNamePrefix + d[6]; var list = client.Quotas.List(location); Assert.Equal(0, list.Count((q) => q.Name.Equals(name))); }); }); } #endregion } }
shahabhijeet/azure-sdk-for-net
src/AzureStack/Admin/ComputeAdmin/Compute.Admin.Tests/src/QuotaTests.cs
C#
mit
11,692
<?php namespace SMW\Tests\DataValues; use SMW\DataValues\ImportValue; /** * @covers \SMW\DataValues\ImportValue * * @group semantic-mediawiki * * @license GNU GPL v2+ * @since 2.2 * * @author mwjames */ class ImportValueTest extends \PHPUnit_Framework_TestCase { public function testCanConstruct() { $this->assertInstanceOf( '\SMW\DataValues\ImportValue', new ImportValue( '__imp' ) ); // FIXME Legacy naming remove in 3.x $this->assertInstanceOf( '\SMWImportValue', new ImportValue( '__imp' ) ); } public function testErrorForInvalidUserValue() { $instance = new ImportValue( '__imp' ); $instance->setUserValue( 'FooBar' ); $this->assertEquals( 'FooBar', $instance->getWikiValue() ); $this->assertNotEmpty( $instance->getErrors() ); } }
owen-kellie-smith/mediawiki
wiki/extensions/SemanticMediaWiki/tests/phpunit/includes/DataValues/ImportValueTest.php
PHP
mit
805
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Security.Policy.Hash.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Security.Policy { sealed public partial class Hash : EvidenceBase, System.Runtime.Serialization.ISerializable { #region Methods and constructors public override EvidenceBase Clone() { return default(EvidenceBase); } public static System.Security.Policy.Hash CreateMD5(byte[] md5) { Contract.Ensures(Contract.Result<System.Security.Policy.Hash>() != null); return default(System.Security.Policy.Hash); } public static System.Security.Policy.Hash CreateSHA1(byte[] sha1) { Contract.Ensures(Contract.Result<System.Security.Policy.Hash>() != null); return default(System.Security.Policy.Hash); } public static System.Security.Policy.Hash CreateSHA256(byte[] sha256) { Contract.Ensures(Contract.Result<System.Security.Policy.Hash>() != null); return default(System.Security.Policy.Hash); } public byte[] GenerateHash(System.Security.Cryptography.HashAlgorithm hashAlg) { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public Hash(System.Reflection.Assembly assembly) { Contract.Ensures(!assembly.IsDynamic); } public override string ToString() { return default(string); } #endregion #region Properties and indexers public byte[] MD5 { get { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } } public byte[] SHA1 { get { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } } public byte[] SHA256 { get { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } } #endregion } }
ndykman/CodeContracts
Microsoft.Research/Contracts/MsCorlib/Sources/System.Security.Policy.Hash.cs
C#
mit
3,951
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.ComponentModel.SingleConverter.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ComponentModel { public partial class SingleConverter : BaseNumberConverter { #region Methods and constructors public SingleConverter() { } #endregion } }
ndykman/CodeContracts
Microsoft.Research/Contracts/System/Sources/System.ComponentModel.SingleConverter.cs
C#
mit
2,183
<?php /** * @file * Contains \Drupal\field\Entity\FieldConfig. */ namespace Drupal\field\Entity; use Drupal\Component\Utility\SafeMarkup; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Field\FieldConfigBase; use Drupal\Core\Field\FieldException; use Drupal\field\FieldStorageConfigInterface; use Drupal\field\FieldConfigInterface; /** * Defines the Field entity. * * @ConfigEntityType( * id = "field_config", * label = @Translation("Field"), * handlers = { * "access" = "Drupal\field\FieldConfigAccessControlHandler", * "storage" = "Drupal\field\FieldConfigStorage" * }, * config_prefix = "field", * entity_keys = { * "id" = "id", * "label" = "label" * } * ) */ class FieldConfig extends FieldConfigBase implements FieldConfigInterface { /** * Flag indicating whether the field is deleted. * * The delete() method marks the field as "deleted" and removes the * corresponding entry from the config storage, but keeps its definition in * the state storage while field data is purged by a separate * garbage-collection process. * * Deleted fields stay out of the regular entity lifecycle (notably, their * values are not populated in loaded entities, and are not saved back). * * @var bool */ public $deleted = FALSE; /** * The associated FieldStorageConfig entity. * * @var \Drupal\field\Entity\FieldStorageConfig */ protected $fieldStorage; /** * Constructs a FieldConfig object. * * In most cases, Field entities are created via * entity_create('field_config', $values), where $values is the same * parameter as in this constructor. * * @param array $values * An array of field properties, keyed by property name. The * storage associated to the field can be specified either with: * - field_storage: the FieldStorageConfigInterface object, * or by referring to an existing field storage in the current configuration * with: * - field_name: The field name. * - entity_type: The entity type. * Additionally, a 'bundle' property is required to indicate the entity * bundle to which the field is attached to. Other array elements will be * used to set the corresponding properties on the class; see the class * property documentation for details. * * @see entity_create() */ public function __construct(array $values, $entity_type = 'field_config') { // Allow either an injected FieldStorageConfig object, or a field_name and // entity_type. if (isset($values['field_storage'])) { if (!$values['field_storage'] instanceof FieldStorageConfigInterface) { throw new FieldException('Attempt to create a configurable field for a non-configurable field storage.'); } $field_storage = $values['field_storage']; $values['field_name'] = $field_storage->getName(); $values['entity_type'] = $field_storage->getTargetEntityTypeId(); // The internal property is fieldStorage, not field_storage. unset($values['field_storage']); $values['fieldStorage'] = $field_storage; } else { if (empty($values['field_name'])) { throw new FieldException('Attempt to create a field without a field_name.'); } if (empty($values['entity_type'])) { throw new FieldException(SafeMarkup::format('Attempt to create a field @field_name without an entity_type.', array('@field_name' => $values['field_name']))); } } // 'bundle' is required in either case. if (empty($values['bundle'])) { throw new FieldException(SafeMarkup::format('Attempt to create a field @field_name without a bundle.', array('@field_name' => $values['field_name']))); } parent::__construct($values, $entity_type); } /** * {@inheritdoc} */ public function postCreate(EntityStorageInterface $storage) { parent::postCreate($storage); // Validate that we have a valid storage for this field. This throws an // exception if the storage is invalid. $this->getFieldStorageDefinition(); // 'Label' defaults to the field name (mostly useful for fields created in // tests). if (empty($this->label)) { $this->label = $this->getName(); } } /** * Overrides \Drupal\Core\Entity\Entity::preSave(). * * @throws \Drupal\Core\Field\FieldException * If the field definition is invalid. * @throws \Drupal\Core\Entity\EntityStorageException * In case of failures at the configuration storage level. */ public function preSave(EntityStorageInterface $storage) { $entity_manager = \Drupal::entityManager(); $field_type_manager = \Drupal::service('plugin.manager.field.field_type'); $storage_definition = $this->getFieldStorageDefinition(); // Filter out unknown settings and make sure all settings are present, so // that a complete field definition is passed to the various hooks and // written to config. $default_settings = $field_type_manager->getDefaultFieldSettings($storage_definition->getType()); $this->settings = array_intersect_key($this->settings, $default_settings) + $default_settings; if ($this->isNew()) { // Notify the entity storage. $entity_manager->getStorage($this->entity_type)->onFieldDefinitionCreate($this); } else { // Some updates are always disallowed. if ($this->entity_type != $this->original->entity_type) { throw new FieldException("Cannot change an existing field's entity_type."); } if ($this->bundle != $this->original->bundle && empty($this->bundleRenameAllowed)) { throw new FieldException("Cannot change an existing field's bundle."); } if ($storage_definition->uuid() != $this->original->getFieldStorageDefinition()->uuid()) { throw new FieldException("Cannot change an existing field's storage."); } // Notify the entity storage. $entity_manager->getStorage($this->entity_type)->onFieldDefinitionUpdate($this, $this->original); } parent::preSave($storage); } /** * {@inheritdoc} */ public function calculateDependencies() { parent::calculateDependencies(); // Mark the field_storage_config as a a dependency. $this->addDependency('config', $this->getFieldStorageDefinition()->getConfigDependencyName()); return $this->dependencies; } /** * {@inheritdoc} */ public static function preDelete(EntityStorageInterface $storage, array $fields) { $state = \Drupal::state(); parent::preDelete($storage, $fields); // Keep the field definitions in the state storage so we can use them // later during field_purge_batch(). $deleted_fields = $state->get('field.field.deleted') ?: array(); foreach ($fields as $field) { if (!$field->deleted) { $config = $field->toArray(); $config['deleted'] = TRUE; $config['field_storage_uuid'] = $field->getFieldStorageDefinition()->uuid(); $deleted_fields[$field->uuid()] = $config; } } $state->set('field.field.deleted', $deleted_fields); } /** * {@inheritdoc} */ public static function postDelete(EntityStorageInterface $storage, array $fields) { // Clear the cache upfront, to refresh the results of getBundles(). \Drupal::entityManager()->clearCachedFieldDefinitions(); // Notify the entity storage. foreach ($fields as $field) { if (!$field->deleted) { \Drupal::entityManager()->getStorage($field->entity_type)->onFieldDefinitionDelete($field); } } // If this is part of a configuration synchronization then the following // configuration updates are not necessary. $entity = reset($fields); if ($entity->isSyncing()) { return; } // Delete the associated field storages if they are not used anymore and are // not persistent. $storages_to_delete = array(); foreach ($fields as $field) { $storage_definition = $field->getFieldStorageDefinition(); if (!$field->deleted && !$field->isUninstalling() && $storage_definition->isDeletable()) { // Key by field UUID to avoid deleting the same storage twice. $storages_to_delete[$storage_definition->uuid()] = $storage_definition; } } if ($storages_to_delete) { \Drupal::entityManager()->getStorage('field_storage_config')->delete($storages_to_delete); } } /** * {@inheritdoc} */ protected function linkTemplates() { $link_templates = parent::linkTemplates(); if (\Drupal::moduleHandler()->moduleExists('field_ui')) { $link_templates["{$this->entity_type}-field-edit-form"] = 'entity.field_config.' . $this->entity_type . '_field_edit_form'; $link_templates["{$this->entity_type}-storage-edit-form"] = 'entity.field_config.' . $this->entity_type . '_storage_edit_form'; $link_templates["{$this->entity_type}-field-delete-form"] = 'entity.field_config.' . $this->entity_type . '_field_delete_form'; if (isset($link_templates['config-translation-overview'])) { $link_templates["config-translation-overview.{$this->entity_type}"] = "entity.field_config.config_translation_overview.{$this->entity_type}"; } } return $link_templates; } /** * {@inheritdoc} */ protected function urlRouteParameters($rel) { $parameters = parent::urlRouteParameters($rel); $entity_type = \Drupal::entityManager()->getDefinition($this->entity_type); $parameters[$entity_type->getBundleEntityType()] = $this->bundle; return $parameters; } /** * {@inheritdoc} */ public function isDeleted() { return $this->deleted; } /** * {@inheritdoc} */ public function getFieldStorageDefinition() { if (!$this->fieldStorage) { $fields = $this->entityManager()->getFieldStorageDefinitions($this->entity_type); if (!isset($fields[$this->field_name])) { throw new FieldException(SafeMarkup::format('Attempt to create a field @field_name that does not exist on entity type @entity_type.', array('@field_name' => $this->field_name, '@entity_type' => $this->entity_type))); } if (!$fields[$this->field_name] instanceof FieldStorageConfigInterface) { throw new FieldException(SafeMarkup::format('Attempt to create a configurable field of non-configurable field storage @field_name.', array('@field_name' => $this->field_name, '@entity_type' => $this->entity_type))); } $this->fieldStorage = $fields[$this->field_name]; } return $this->fieldStorage; } /** * {@inheritdoc} */ public function isDisplayConfigurable($context) { return TRUE; } /** * {@inheritdoc} */ public function getDisplayOptions($display_context) { // Hide configurable fields by default. return array('type' => 'hidden'); } /** * {@inheritdoc} */ public function isReadOnly() { return FALSE; } /** * {@inheritdoc} */ public function isComputed() { return FALSE; } /** * Loads a field config entity based on the entity type and field name. * * @param string $entity_type_id * ID of the entity type. * @param string $bundle * Bundle name. * @param string $field_name * Name of the field. * * @return static * The field config entity if one exists for the provided field * name, otherwise NULL. */ public static function loadByName($entity_type_id, $bundle, $field_name) { return \Drupal::entityManager()->getStorage('field_config')->load($entity_type_id . '.' . $bundle . '.' . $field_name); } }
casivaagustin/drupalcon-mentoring
src/core/modules/field/src/Entity/FieldConfig.php
PHP
mit
11,622
// Type definitions for angular-file-upload 2.5 // Project: https://github.com/nervgh/angular-file-upload // Definitions by: Cyril Gandon <https://github.com/cyrilgandon> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 import * as angular from 'angular'; export interface FileUploaderFactory { new(options?: Partial<FileUploaderOptions>): FileUploader; } export interface FileUploaderOptions { /** * Path on the server to upload files * @default / */ url: string; /** * Name of the field which will contain the file, default is file * @default file */ alias: string; /** * Headers to be sent along with the files. HTML5 browsers only. * @default {} */ headers: Headers; /** * Items to be uploaded * @default [] */ queue: FileItem[]; /** * Automatically upload files after adding them to the queue * @default false */ autoUpload: boolean; /** * Remove files from the queue after uploading * @default false */ removeAfterUpload: boolean; /** * It's a request method. HTML5 browsers only. * @default POST */ method: string; /** * Filters to be applied to the files before adding them to the queue. If the filter returns true the file will be added to the queue * @default [folderFilter, queueLimitFilter] */ filters: Filter[]; /** * Data to be sent along with the files * @default [] */ formData: FormData[]; /** * Maximum count of files. * @default Number.MAX_VALUE */ queueLimit: number; /** * enable CORS. HTML5 browsers only. * @default false */ withCredentials: boolean; /** * Disable multipart. * @default false */ disableMultipart: boolean; } export interface FileUploader extends FileUploaderOptions { /** * Upload queue progress percentage. Read only. */ progress: number; /** * true if uploader is html5-uploader. Read only. */ isHTML5: boolean; /** * true if an upload is in progress. Read only. */ isUploading: boolean; // **Methods** /** * Add items to the queue */ addToQueue(files: File | HTMLInputElement | object | FileList | object[], options: object, filters: Filter[] | string): void; /** * Remove an item from the queue, where value is {FileItem} or index of item. */ removeFromQueue(value: FileItem | number): void; /** * Removes all elements from the queue. */ clearQueue(): void; /** * Uploads an item, where value is {FileItem} or index of item. */ uploadItem(value: FileItem | number): void; /** * Cancels uploading of item, where value is {FileItem} or index of item. */ cancelItem(value: FileItem | number): void; /** * Upload all pending items on the queue. */ uploadAll(): void; /** * Cancels all current uploads. */ cancelAll(): void; /** * Destroys a uploader. */ destroy(): void; /** * Returns true if value is {File}. */ isFile(value: any): boolean; /** * Returns true if value is {FileLikeObject}. */ isFileLikeObject(value: any): boolean; /** * Returns the index of the {FileItem} queue element. */ getIndexOfItem(fileItem: FileItem): number; /** * Return items are ready to upload. */ getReadyItems(): FileItem[]; /** * Return an array of all pending items on the queue */ getNotUploadedItems(): FileItem[]; // **Callbacks** /** * Fires after adding all the dragged or selected files to the queue. */ onAfterAddingAll(addedItems: FileItem[]): void; /** * When adding a file failed */ onWhenAddingFileFailed(item: FileItem, filter: Filter, options: object): void; /** * Fires after adding a single file to the queue. */ onAfterAddingFile(item: FileItem): void; /** * Fires before uploading an item. */ onBeforeUploadItem(item: FileItem): void; /** * On file upload progress. */ onProgressItem(item: FileItem, progress: number): void; /** * On file successfully uploaded */ onSuccessItem(item: FileItem, response: Response, status: number, headers: Headers): void; /** * On upload error */ onErrorItem(item: FileItem, response: Response, status: number, headers: Headers): void; /** * On cancel uploading */ onCancelItem(item: FileItem, response: Response, status: number, headers: Headers): void; /** * On file upload complete (independently of the sucess of the operation) */ onCompleteItem(item: FileItem, response: Response, status: number, headers: Headers): void; /** * On upload queue progress */ onProgressAll(progress: number): void; /** * On all loaded when uploading an entire queue, or on file loaded when uploading a single independent file */ onCompleteAll(): void; } export interface FileLikeObject { /** * Equals File.lastModifiedDate */ lastModifiedDate: any; /** * Equals File.name */ name: string; /** * Equals Blob.size, in octet */ size: number; /** * Equals Blob.type, in octet */ type: string; } export interface FileItem { // **Properties** file: FileLikeObject; /** * Path on the server in which this file will be uploaded */ url: string; /** * Name of the field which will contain the file, default is file */ alias: string; /** * Headers to be sent along with this file. HTML5 browsers only. */ headers: Headers; /** * Data to be sent along with this file */ formData: FormData[]; /** * It's a request method. By default POST. HTML5 browsers only. */ method: string; /** * enable CORS. HTML5 browsers only. */ withCredentials: boolean; /** * Remove this file from the queue after uploading */ removeAfterUpload: boolean; /** * A sequence number upload. Read only. */ index: number; /** * File upload progress percentage. Read only. */ progress: number; /** * File is ready to upload. Read only. */ isReady: boolean; /** * true if the file is being uploaded. Read only. */ isUploading: boolean; /** * true if the file was uploaded. Read only. */ isUploaded: boolean; /** * true if the file was uploaded successfully. Read only. */ isSuccess: boolean; /** * true if uploading was canceled. Read only. */ isCancel: boolean; /** * true if occurred error while file uploading. Read only. */ isError: boolean; /** * Reference to the parent Uploader object for this file. Read only. */ uploader: FileUploader; // **Methods** /** * Cancels uploading of this file */ cancel(): void; /** * Remove this file from the queue */ remove(): void; /** * Upload this file */ upload(): void; // **Callbacks** /** * Fires before uploading an item. */ onBeforeUpload(): void; /** * On file upload progress. */ onProgress(progress: number): void; /** * On file successfully uploaded */ onSuccess(response: Response, status: number, headers: Headers): void; /** * On upload error */ onError(response: Response, status: number, headers: Headers): void; /** * On cancel uploading */ onCancel(response: Response, status: number, headers: Headers): void; /** * On file upload complete (independently of the sucess of the operation) */ onComplete(response: Response, status: number, headers: Headers): void; } export type SyncFilter = (item: File | FileLikeObject, options?: object) => boolean; export type AsyncFilter = (item: File | FileLikeObject, options: object | undefined, deferred: angular.IDeferred<any>) => void; export interface Filter { name: string; fn: SyncFilter | AsyncFilter; }
benishouga/DefinitelyTyped
types/angular-file-upload/index.d.ts
TypeScript
mit
8,307
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Product\Resolver; use Doctrine\Common\Collections\Collection; use Sylius\Component\Product\Model\ProductInterface; use Sylius\Component\Product\Model\ProductOptionInterface; use Sylius\Component\Product\Model\ProductOptionValueInterface; final class AvailableProductOptionValuesResolver implements AvailableProductOptionValuesResolverInterface { public function resolve(ProductInterface $product, ProductOptionInterface $productOption): Collection { if (!$product->hasOption($productOption)) { throw new \InvalidArgumentException( sprintf( 'Cannot resolve available product option values. Option "%s" does not belong to product "%s".', $product->getCode(), $productOption->getCode() ) ); } return $productOption->getValues()->filter( static function (ProductOptionValueInterface $productOptionValue) use ($product) { foreach ($product->getEnabledVariants() as $productVariant) { if ($productVariant->hasOptionValue($productOptionValue)) { return true; } } return false; } ); } }
loic425/Sylius
src/Sylius/Component/Product/Resolver/AvailableProductOptionValuesResolver.php
PHP
mit
1,552
package polyfill import ( "os" "path/filepath" "github.com/go-git/go-billy/v5" ) // Polyfill is a helper that implements all missing method from billy.Filesystem. type Polyfill struct { billy.Basic c capabilities } type capabilities struct{ tempfile, dir, symlink, chroot bool } // New creates a new filesystem wrapping up 'fs' the intercepts all the calls // made and errors if fs doesn't implement any of the billy interfaces. func New(fs billy.Basic) billy.Filesystem { if original, ok := fs.(billy.Filesystem); ok { return original } h := &Polyfill{Basic: fs} _, h.c.tempfile = h.Basic.(billy.TempFile) _, h.c.dir = h.Basic.(billy.Dir) _, h.c.symlink = h.Basic.(billy.Symlink) _, h.c.chroot = h.Basic.(billy.Chroot) return h } func (h *Polyfill) TempFile(dir, prefix string) (billy.File, error) { if !h.c.tempfile { return nil, billy.ErrNotSupported } return h.Basic.(billy.TempFile).TempFile(dir, prefix) } func (h *Polyfill) ReadDir(path string) ([]os.FileInfo, error) { if !h.c.dir { return nil, billy.ErrNotSupported } return h.Basic.(billy.Dir).ReadDir(path) } func (h *Polyfill) MkdirAll(filename string, perm os.FileMode) error { if !h.c.dir { return billy.ErrNotSupported } return h.Basic.(billy.Dir).MkdirAll(filename, perm) } func (h *Polyfill) Symlink(target, link string) error { if !h.c.symlink { return billy.ErrNotSupported } return h.Basic.(billy.Symlink).Symlink(target, link) } func (h *Polyfill) Readlink(link string) (string, error) { if !h.c.symlink { return "", billy.ErrNotSupported } return h.Basic.(billy.Symlink).Readlink(link) } func (h *Polyfill) Lstat(path string) (os.FileInfo, error) { if !h.c.symlink { return nil, billy.ErrNotSupported } return h.Basic.(billy.Symlink).Lstat(path) } func (h *Polyfill) Chroot(path string) (billy.Filesystem, error) { if !h.c.chroot { return nil, billy.ErrNotSupported } return h.Basic.(billy.Chroot).Chroot(path) } func (h *Polyfill) Root() string { if !h.c.chroot { return string(filepath.Separator) } return h.Basic.(billy.Chroot).Root() } func (h *Polyfill) Underlying() billy.Basic { return h.Basic } // Capabilities implements the Capable interface. func (h *Polyfill) Capabilities() billy.Capability { return billy.Capabilities(h.Basic) }
cez81/gitea
vendor/github.com/go-git/go-billy/v5/helper/polyfill/polyfill.go
GO
mit
2,297
require 'webrat/core/elements/form' require 'action_dispatch/testing/integration' module Webrat Form.class_eval do def self.parse_rails_request_params(params) Rack::Utils.parse_nested_query(params) end end module Logging # Avoid RAILS_DEFAULT_LOGGER deprecation warning def logger # :nodoc: ::Rails.logger end end class RailsAdapter protected def do_request(http_method, url, data, headers) update_protocol(url) integration_session.send(http_method, normalize_url(url), params: data, headers: headers) end end end module ActionDispatch #:nodoc: IntegrationTest.class_eval do include Webrat::Methods include Webrat::Matchers end end
lrosskamp/makealist-public
vendor/cache/ruby/2.3.0/gems/devise-4.3.0/test/support/webrat/integrations/rails.rb
Ruby
mit
717
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Reflection.Metadata.Ecma335 { internal class NamespaceCache { private readonly MetadataReader _metadataReader; private readonly object _namespaceTableAndListLock = new object(); private Dictionary<NamespaceDefinitionHandle, NamespaceData> _namespaceTable; private NamespaceData _rootNamespace; private ImmutableArray<NamespaceDefinitionHandle> _namespaceList; private uint _virtualNamespaceCounter; internal NamespaceCache(MetadataReader reader) { Debug.Assert(reader != null); _metadataReader = reader; } /// <summary> /// Returns whether the namespaceTable has been created. If it hasn't, calling a GetXXX method /// on this will probably have a very high amount of overhead. /// </summary> internal bool CacheIsRealized { get { return _namespaceTable != null; } } internal string GetFullName(NamespaceDefinitionHandle handle) { Debug.Assert(!handle.HasFullName); // we should not hit the cache in this case. NamespaceData data = GetNamespaceData(handle); return data.FullName; } internal NamespaceData GetRootNamespace() { EnsureNamespaceTableIsPopulated(); Debug.Assert(_rootNamespace != null); return _rootNamespace; } internal NamespaceData GetNamespaceData(NamespaceDefinitionHandle handle) { EnsureNamespaceTableIsPopulated(); NamespaceData result; if (!_namespaceTable.TryGetValue(handle, out result)) { Throw.InvalidHandle(); } return result; } /// <summary> /// This will return a StringHandle for the simple name of a namespace name at the given segment index. /// If no segment index is passed explicitly or the "segment" index is greater than or equal to the number /// of segments, then the last segment is used. "Segment" in this context refers to part of a namespace /// name between dots. /// /// Example: Given a NamespaceDefinitionHandle to "System.Collections.Generic.Test" called 'handle': /// /// reader.GetString(GetSimpleName(handle)) == "Test" /// reader.GetString(GetSimpleName(handle, 0)) == "System" /// reader.GetString(GetSimpleName(handle, 1)) == "Collections" /// reader.GetString(GetSimpleName(handle, 2)) == "Generic" /// reader.GetString(GetSimpleName(handle, 3)) == "Test" /// reader.GetString(GetSimpleName(handle, 1000)) == "Test" /// </summary> private StringHandle GetSimpleName(NamespaceDefinitionHandle fullNamespaceHandle, int segmentIndex = Int32.MaxValue) { StringHandle handleContainingSegment = fullNamespaceHandle.GetFullName(); Debug.Assert(!handleContainingSegment.IsVirtual); int lastFoundIndex = fullNamespaceHandle.GetHeapOffset() - 1; int currentSegment = 0; while (currentSegment < segmentIndex) { int currentIndex = _metadataReader.StringHeap.IndexOfRaw(lastFoundIndex + 1, '.'); if (currentIndex == -1) { break; } lastFoundIndex = currentIndex; ++currentSegment; } Debug.Assert(lastFoundIndex >= 0 || currentSegment == 0); // + 1 because lastFoundIndex will either "point" to a '.', or will be -1. Either way, // we want the next char. int resultIndex = lastFoundIndex + 1; return StringHandle.FromOffset(resultIndex).WithDotTermination(); } /// <summary> /// Two distinct namespace handles represent the same namespace if their full names are the same. This /// method merges builders corresponding to such namespace handles. /// </summary> private void PopulateNamespaceTable() { lock (_namespaceTableAndListLock) { if (_namespaceTable != null) { return; } var namespaceBuilderTable = new Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder>(); // Make sure to add entry for root namespace. The root namespace is special in that even // though it might not have types of its own it always has an equivalent representation // as a nil handle and we don't want to handle it below as dot-terminated virtual namespace. // We use NamespaceDefinitionHandle.FromIndexOfFullName(0) instead of default(NamespaceDefinitionHandle) so // that we never hand back a handle to the user that doesn't have a typeid as that prevents // round-trip conversion to Handle and back. (We may discover other handle aliases for the // root namespace (any nil/empty string will do), but we need this one to always be there. NamespaceDefinitionHandle rootNamespace = NamespaceDefinitionHandle.FromFullNameOffset(0); namespaceBuilderTable.Add( rootNamespace, new NamespaceDataBuilder( rootNamespace, rootNamespace.GetFullName(), String.Empty)); PopulateTableWithTypeDefinitions(namespaceBuilderTable); PopulateTableWithExportedTypes(namespaceBuilderTable); Dictionary<string, NamespaceDataBuilder> stringTable; MergeDuplicateNamespaces(namespaceBuilderTable, out stringTable); List<NamespaceDataBuilder> virtualNamespaces; ResolveParentChildRelationships(stringTable, out virtualNamespaces); var namespaceTable = new Dictionary<NamespaceDefinitionHandle, NamespaceData>(); foreach (var group in namespaceBuilderTable) { // Freeze() caches the result, so any many-to-one relationships // between keys and values will be preserved and efficiently handled. namespaceTable.Add(group.Key, group.Value.Freeze()); } if (virtualNamespaces != null) { foreach (var virtualNamespace in virtualNamespaces) { namespaceTable.Add(virtualNamespace.Handle, virtualNamespace.Freeze()); } } _namespaceTable = namespaceTable; _rootNamespace = namespaceTable[rootNamespace]; } } /// <summary> /// This will take 'table' and merge all of the NamespaceData instances that point to the same /// namespace. It has to create 'stringTable' as an intermediate dictionary, so it will hand it /// back to the caller should the caller want to use it. /// </summary> private void MergeDuplicateNamespaces(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table, out Dictionary<string, NamespaceDataBuilder> stringTable) { var namespaces = new Dictionary<string, NamespaceDataBuilder>(); List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>> remaps = null; foreach (var group in table) { NamespaceDataBuilder data = group.Value; NamespaceDataBuilder existingRecord; if (namespaces.TryGetValue(data.FullName, out existingRecord)) { // Children should not exist until the next step. Debug.Assert(data.Namespaces.Count == 0); data.MergeInto(existingRecord); if (remaps == null) { remaps = new List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>>(); } remaps.Add(new KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>(group.Key, existingRecord)); } else { namespaces.Add(data.FullName, data); } } // Needs to be done outside of foreach (var group in table) to avoid modifying the dictionary while foreach'ing over it. if (remaps != null) { foreach (var tuple in remaps) { table[tuple.Key] = tuple.Value; } } stringTable = namespaces; } /// <summary> /// Creates a NamespaceDataBuilder instance that contains a synthesized NamespaceDefinitionHandle, /// as well as the name provided. /// </summary> private NamespaceDataBuilder SynthesizeNamespaceData(string fullName, NamespaceDefinitionHandle realChild) { Debug.Assert(realChild.HasFullName); int numberOfSegments = 0; foreach (char c in fullName) { if (c == '.') { numberOfSegments++; } } StringHandle simpleName = GetSimpleName(realChild, numberOfSegments); var namespaceHandle = NamespaceDefinitionHandle.FromVirtualIndex(++_virtualNamespaceCounter); return new NamespaceDataBuilder(namespaceHandle, simpleName, fullName); } /// <summary> /// Quick convenience method that handles linking together child + parent /// </summary> private void LinkChildDataToParentData(NamespaceDataBuilder child, NamespaceDataBuilder parent) { Debug.Assert(child != null && parent != null); Debug.Assert(!child.Handle.IsNil); child.Parent = parent.Handle; parent.Namespaces.Add(child.Handle); } /// <summary> /// Links a child to its parent namespace. If the parent namespace doesn't exist, this will create a /// virtual one. This will automatically link any virtual namespaces it creates up to its parents. /// </summary> private void LinkChildToParentNamespace(Dictionary<string, NamespaceDataBuilder> existingNamespaces, NamespaceDataBuilder realChild, ref List<NamespaceDataBuilder> virtualNamespaces) { Debug.Assert(realChild.Handle.HasFullName); string childName = realChild.FullName; var child = realChild; // The condition for this loop is very complex -- essentially, we keep going // until we: // A. Encounter the root namespace as 'child' // B. Find a preexisting namespace as 'parent' while (true) { int lastIndex = childName.LastIndexOf('.'); string parentName; if (lastIndex == -1) { if (childName.Length == 0) { return; } else { parentName = String.Empty; } } else { parentName = childName.Substring(0, lastIndex); } NamespaceDataBuilder parentData; if (existingNamespaces.TryGetValue(parentName, out parentData)) { LinkChildDataToParentData(child, parentData); return; } if (virtualNamespaces != null) { foreach (var data in virtualNamespaces) { if (data.FullName == parentName) { LinkChildDataToParentData(child, data); return; } } } else { virtualNamespaces = new List<NamespaceDataBuilder>(); } var virtualParent = SynthesizeNamespaceData(parentName, realChild.Handle); LinkChildDataToParentData(child, virtualParent); virtualNamespaces.Add(virtualParent); childName = virtualParent.FullName; child = virtualParent; } } /// <summary> /// This will link all parents/children in the given namespaces dictionary up to each other. /// /// In some cases, we need to synthesize namespaces that do not have any type definitions or forwarders /// of their own, but do have child namespaces. These are returned via the virtualNamespaces out /// parameter. /// </summary> private void ResolveParentChildRelationships(Dictionary<string, NamespaceDataBuilder> namespaces, out List<NamespaceDataBuilder> virtualNamespaces) { virtualNamespaces = null; foreach (var namespaceData in namespaces.Values) { LinkChildToParentNamespace(namespaces, namespaceData, ref virtualNamespaces); } } /// <summary> /// Loops through all type definitions in metadata, adding them to the given table /// </summary> private void PopulateTableWithTypeDefinitions(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table) { Debug.Assert(table != null); foreach (var typeHandle in _metadataReader.TypeDefinitions) { TypeDefinition type = _metadataReader.GetTypeDefinition(typeHandle); if (type.Attributes.IsNested()) { continue; } NamespaceDefinitionHandle namespaceHandle = _metadataReader.TypeDefTable.GetNamespaceDefinition(typeHandle); NamespaceDataBuilder builder; if (table.TryGetValue(namespaceHandle, out builder)) { builder.TypeDefinitions.Add(typeHandle); } else { StringHandle name = GetSimpleName(namespaceHandle); string fullName = _metadataReader.GetString(namespaceHandle); var newData = new NamespaceDataBuilder(namespaceHandle, name, fullName); newData.TypeDefinitions.Add(typeHandle); table.Add(namespaceHandle, newData); } } } /// <summary> /// Loops through all type forwarders in metadata, adding them to the given table /// </summary> private void PopulateTableWithExportedTypes(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table) { Debug.Assert(table != null); foreach (var exportedTypeHandle in _metadataReader.ExportedTypes) { ExportedType exportedType = _metadataReader.GetExportedType(exportedTypeHandle); if (exportedType.Implementation.Kind == HandleKind.ExportedType) { continue; // skip nested exported types. } NamespaceDefinitionHandle namespaceHandle = exportedType.NamespaceDefinition; NamespaceDataBuilder builder; if (table.TryGetValue(namespaceHandle, out builder)) { builder.ExportedTypes.Add(exportedTypeHandle); } else { Debug.Assert(namespaceHandle.HasFullName); StringHandle simpleName = GetSimpleName(namespaceHandle); string fullName = _metadataReader.GetString(namespaceHandle); var newData = new NamespaceDataBuilder(namespaceHandle, simpleName, fullName); newData.ExportedTypes.Add(exportedTypeHandle); table.Add(namespaceHandle, newData); } } } /// <summary> /// Populates namespaceList with distinct namespaces. No ordering is guaranteed. /// </summary> private void PopulateNamespaceList() { lock (_namespaceTableAndListLock) { if (_namespaceList != null) { return; } Debug.Assert(_namespaceTable != null); var namespaceNameSet = new HashSet<string>(); var namespaceListBuilder = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>(); foreach (var group in _namespaceTable) { var data = group.Value; if (namespaceNameSet.Add(data.FullName)) { namespaceListBuilder.Add(group.Key); } } _namespaceList = namespaceListBuilder.ToImmutable(); } } /// <summary> /// If the namespace table doesn't exist, populates it! /// </summary> private void EnsureNamespaceTableIsPopulated() { // PERF: Branch will rarely be taken; do work in PopulateNamespaceList() so this can be inlined easily. if (_namespaceTable == null) { PopulateNamespaceTable(); } Debug.Assert(_namespaceTable != null); } /// <summary> /// If the namespace list doesn't exist, populates it! /// </summary> private void EnsureNamespaceListIsPopulated() { if (_namespaceList == null) { PopulateNamespaceList(); } Debug.Assert(_namespaceList != null); } /// <summary> /// An intermediate class used to build NamespaceData instances. This was created because we wanted to /// use ImmutableArrays in NamespaceData, but having ArrayBuilders and ImmutableArrays that served the /// same purpose in NamespaceData got ugly. With the current design of how we create our Namespace /// dictionary, this needs to be a class because we have a many-to-one mapping between NamespaceHandles /// and NamespaceData. So, the pointer semantics must be preserved. /// /// This class assumes that the builders will not be modified in any way after the first call to /// Freeze(). /// </summary> private class NamespaceDataBuilder { public readonly NamespaceDefinitionHandle Handle; public readonly StringHandle Name; public readonly string FullName; public NamespaceDefinitionHandle Parent; public ImmutableArray<NamespaceDefinitionHandle>.Builder Namespaces; public ImmutableArray<TypeDefinitionHandle>.Builder TypeDefinitions; public ImmutableArray<ExportedTypeHandle>.Builder ExportedTypes; private NamespaceData _frozen; public NamespaceDataBuilder(NamespaceDefinitionHandle handle, StringHandle name, string fullName) { Handle = handle; Name = name; FullName = fullName; Namespaces = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>(); TypeDefinitions = ImmutableArray.CreateBuilder<TypeDefinitionHandle>(); ExportedTypes = ImmutableArray.CreateBuilder<ExportedTypeHandle>(); } /// <summary> /// Returns a NamespaceData that represents this NamespaceDataBuilder instance. After calling /// this method, it is an error to use any methods or fields except Freeze() on the target /// NamespaceDataBuilder. /// </summary> public NamespaceData Freeze() { // It is not an error to call this function multiple times. We cache the result // because it's immutable. if (_frozen == null) { var namespaces = Namespaces.ToImmutable(); Namespaces = null; var typeDefinitions = TypeDefinitions.ToImmutable(); TypeDefinitions = null; var exportedTypes = ExportedTypes.ToImmutable(); ExportedTypes = null; _frozen = new NamespaceData(Name, FullName, Parent, namespaces, typeDefinitions, exportedTypes); } return _frozen; } public void MergeInto(NamespaceDataBuilder other) { Parent = default(NamespaceDefinitionHandle); other.Namespaces.AddRange(this.Namespaces); other.TypeDefinitions.AddRange(this.TypeDefinitions); other.ExportedTypes.AddRange(this.ExportedTypes); } } } }
alphonsekurian/corefx
src/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs
C#
mit
21,688
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace PowerBIRestDemo.Results { public class ChallengeResult : IHttpActionResult { public ChallengeResult(string loginProvider, ApiController controller) { LoginProvider = loginProvider; Request = controller.Request; } public string LoginProvider { get; set; } public HttpRequestMessage Request { get; set; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { Request.GetOwinContext().Authentication.Challenge(LoginProvider); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; return Task.FromResult(response); } } }
ericleigh007/azure-stream-analytics
Samples/SensorDataAnalytics/SourceCode/Archived/PowerBIRestDemo-master/PowerBIRestDemo/Results/ChallengeResult.cs
C#
mit
964
<?php /** * EMongoGridFS.php * * PHP version 5.2+ * * @author Jose Martinez <jmartinez@ibitux.com> * @author Philippe Gaultier <pgaultier@ibitux.com> * @copyright 2010 Ibitux * @license http://www.yiiframework.com/license/ BSD license * @version SVN: $Revision: $ * @category ext * @package ext.YiiMongoDbSuite */ /** * EMongoGridFS * * Authorization management, dispatches actions and views on the system * * @author Jose Martinez <jmartinez@ibitux.com> * @author Philippe Gaultier <pgaultier@ibitux.com> * @copyright 2010 Ibitux * @license http://www.yiiframework.com/license/ BSD license * @version SVN: $Revision: $ * @category ext * @package ext.YiiMongoDbSuite * */ class MongoImage extends EMongoGridFS { public $metadata; /** * this is similar to the get tableName() method. this returns tha name of the * document for this class. this should be in all lowercase. */ public function getCollectionName() { return 'images'; } /** * Returns the static model of the specified AR class. * * @param string $className class name * * @return CompaniesDb the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } public function rules() { return array( array('filename, metadata','safe'), array('filename','required'), ); } }
vishin-pavel/quick-app
www/protected/extensions/YiiMongoDbSuite/examples/MongoImage.php
PHP
mit
1,364
<?php /** * This file is part of the Nette Framework (http://nette.org) * Copyright (c) 2004 David Grudl (http://davidgrudl.com) */ namespace Nette\Reflection; use Nette, Nette\Utils\ObjectMixin; /** * Reports information about a classes variable. * * @author David Grudl * @property-read ClassType $declaringClass * @property-read IAnnotation[][] $annotations * @property-read string $description * @property-read string $name * @property mixed $value * @property-read bool $public * @property-read bool $private * @property-read bool $protected * @property-read bool $static * @property-read bool $default * @property-read int $modifiers * @property-read string $docComment * @property-write bool $accessible */ class Property extends \ReflectionProperty { public function __toString() { return parent::getDeclaringClass()->getName() . '::$' . $this->getName(); } /********************* Reflection layer ****************d*g**/ /** * @return ClassType */ public function getDeclaringClass() { return new ClassType(parent::getDeclaringClass()->getName()); } /********************* Nette\Annotations support ****************d*g**/ /** * Has property specified annotation? * @param string * @return bool */ public function hasAnnotation($name) { $res = AnnotationsParser::getAll($this); return !empty($res[$name]); } /** * Returns an annotation value. * @param string * @return IAnnotation */ public function getAnnotation($name) { $res = AnnotationsParser::getAll($this); return isset($res[$name]) ? end($res[$name]) : NULL; } /** * Returns all annotations. * @return IAnnotation[][] */ public function getAnnotations() { return AnnotationsParser::getAll($this); } /** * Returns value of annotation 'description'. * @return string */ public function getDescription() { return $this->getAnnotation('description'); } /********************* Nette\Object behaviour ****************d*g**/ public function __call($name, $args) { return ObjectMixin::call($this, $name, $args); } public function &__get($name) { return ObjectMixin::get($this, $name); } public function __set($name, $value) { ObjectMixin::set($this, $name, $value); } public function __isset($name) { return ObjectMixin::has($this, $name); } public function __unset($name) { ObjectMixin::remove($this, $name); } }
xvadur01/BPIS
vendor/nette/reflection/src/Reflection/Property.php
PHP
mit
2,431
import Mmenu from '../../core/oncanvas/mmenu.oncanvas'; import * as DOM from '../../core/_dom'; // DEPRECATED // Will be removed in version 8.2 export default function (navbar) { // Add content var next = DOM.create('a.mm-btn.mm-btn_next.mm-navbar__btn'); navbar.append(next); // Update to opened panel var org; var _url, _txt; this.bind('openPanel:start', (panel) => { org = panel.querySelector('.' + this.conf.classNames.navbars.panelNext); _url = org ? org.getAttribute('href') : ''; _txt = org ? org.innerHTML : ''; if (_url) { next.setAttribute('href', _url); } else { next.removeAttribute('href'); } next.classList[_url || _txt ? 'remove' : 'add']('mm-hidden'); next.innerHTML = _txt; }); // Add screenreader / aria support this.bind('openPanel:start:sr-aria', (panel) => { Mmenu.sr_aria(next, 'hidden', next.matches('mm-hidden')); Mmenu.sr_aria(next, 'owns', (next.getAttribute('href') || '').slice(1)); }); }
extend1994/cdnjs
ajax/libs/jQuery.mmenu/8.2.3/addons/navbars/_navbar.next.js
JavaScript
mit
1,073
/** * Copyright (c) 2010-2016, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.io.caldav.internal; import static org.quartz.impl.matchers.GroupMatcher.jobGroupEquals; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import org.apache.commons.lang3.BooleanUtils; import org.joda.time.DateTimeZone; import org.openhab.core.service.AbstractActiveService; import org.openhab.io.caldav.CalDavEvent; import org.openhab.io.caldav.CalDavLoader; import org.openhab.io.caldav.CalDavQuery; import org.openhab.io.caldav.EventNotifier; import org.openhab.io.caldav.internal.EventStorage.CalendarRuntime; import org.openhab.io.caldav.internal.EventStorage.EventContainer; import org.openhab.io.caldav.internal.job.EventJob; import org.openhab.io.caldav.internal.job.EventJob.EventTrigger; import org.openhab.io.caldav.internal.job.EventReloaderJob; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.quartz.DateBuilder; import org.quartz.DateBuilder.IntervalUnit; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleScheduleBuilder; import org.quartz.SimpleTrigger; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.TriggerKey; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.sardine.Sardine; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.util.CompatibilityHints; /** * Loads all events from the configured calDAV servers. This is done with an * interval. All interesting events are hold in memory. * * @author Robert Delbrück * @since 1.8.0 * */ public class CalDavLoaderImpl extends AbstractActiveService implements ManagedService, CalDavLoader { private static final String JOB_NAME_EVENT_RELOADER = "event-reloader"; public static final String JOB_NAME_EVENT_START = "event-start"; public static final String JOB_NAME_EVENT_END = "event-end"; private static final String PROP_RELOAD_INTERVAL = "reloadInterval"; private static final String PROP_PRELOAD_TIME = "preloadTime"; private static final String PROP_HISTORIC_LOAD_TIME = "historicLoadTime"; private static final String PROP_URL = "url"; private static final String PROP_PASSWORD = "password"; private static final String PROP_USERNAME = "username"; private static final String PROP_TIMEZONE = "timeZone"; public static final String PROP_DISABLE_CERTIFICATE_VERIFICATION = "disableCertificateVerification"; private static final String PROP_LAST_MODIFIED_TIMESTAMP_VALID = "lastModifiedFileTimeStampValid"; public static DateTimeZone defaultTimeZone = DateTimeZone.getDefault(); private static final Logger log = LoggerFactory.getLogger(CalDavLoaderImpl.class); public static final String CACHE_PATH = "etc/caldav"; private ScheduledExecutorService execService; private List<EventNotifier> eventListenerList = new ArrayList<EventNotifier>(); private Scheduler scheduler; public static CalDavLoaderImpl instance; public CalDavLoaderImpl() { if (instance != null) { throw new IllegalStateException("something went wrong, the loader service should be singleton"); } instance = this; } @Override public void start() { super.start(); if (this.isProperlyConfigured()) { try { scheduler = new StdSchedulerFactory().getScheduler(); this.removeAllJobs(); } catch (SchedulerException e) { log.error("cannot get job-scheduler", e); throw new IllegalStateException("cannot get job-scheduler", e); } this.startLoading(); } } private void removeAllJobs() throws SchedulerException { scheduler.deleteJobs(new ArrayList<JobKey>(scheduler.getJobKeys(jobGroupEquals(JOB_NAME_EVENT_RELOADER)))); scheduler.deleteJobs(new ArrayList<JobKey>(scheduler.getJobKeys(jobGroupEquals(JOB_NAME_EVENT_START)))); scheduler.deleteJobs(new ArrayList<JobKey>(scheduler.getJobKeys(jobGroupEquals(JOB_NAME_EVENT_END)))); } @Override public void shutdown() { super.shutdown(); try { this.removeAllJobs(); } catch (SchedulerException e) { log.error("cannot remove jobs: " + e.getMessage(), e); } } @Override public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true); // just temporary Map<String, CalDavConfig> configMap = new HashMap<String, CalDavConfig>(); Enumeration<String> iter = config.keys(); while (iter.hasMoreElements()) { String key = iter.nextElement(); log.trace("configuration parameter: " + key); if (key.equals("service.pid")) { continue; } else if (key.equals(PROP_TIMEZONE)) { log.debug("overriding default timezone {} with {}", defaultTimeZone, config.get(key)); defaultTimeZone = DateTimeZone.forID(config.get(key) + ""); if (defaultTimeZone == null) { throw new ConfigurationException(PROP_TIMEZONE, "invalid timezone value: " + config.get(key)); } log.debug("found timeZone: {}", defaultTimeZone); continue; } String[] keys = key.split(":"); if (keys.length != 2) { throw new ConfigurationException(key, "unknown identifier"); } String id = keys[0]; String paramKey = keys[1]; CalDavConfig calDavConfig = configMap.get(id); if (calDavConfig == null) { calDavConfig = new CalDavConfig(); configMap.put(id, calDavConfig); } String value = config.get(key) + ""; calDavConfig.setKey(id); if (paramKey.equals(PROP_USERNAME)) { calDavConfig.setUsername(value); } else if (paramKey.equals(PROP_PASSWORD)) { calDavConfig.setPassword(value); } else if (paramKey.equals(PROP_URL)) { calDavConfig.setUrl(value); } else if (paramKey.equals(PROP_RELOAD_INTERVAL)) { calDavConfig.setReloadMinutes(Integer.parseInt(value)); } else if (paramKey.equals(PROP_PRELOAD_TIME)) { calDavConfig.setPreloadMinutes(Integer.parseInt(value)); } else if (paramKey.equals(PROP_HISTORIC_LOAD_TIME)) { calDavConfig.setHistoricLoadMinutes(Integer.parseInt(value)); } else if (paramKey.equals(PROP_LAST_MODIFIED_TIMESTAMP_VALID)) { calDavConfig.setLastModifiedFileTimeStampValid(BooleanUtils.toBoolean(value)); } else if (paramKey.equals(PROP_DISABLE_CERTIFICATE_VERIFICATION)) { calDavConfig.setDisableCertificateVerification(BooleanUtils.toBoolean(value)); } } // verify if all required parameters are set for (String id : configMap.keySet()) { if (configMap.get(id).getUrl() == null) { throw new ConfigurationException(PROP_URL, PROP_URL + " must be set"); } if (configMap.get(id).getUsername() == null) { throw new ConfigurationException(PROP_USERNAME, PROP_USERNAME + " must be set"); } if (configMap.get(id).getPassword() == null) { throw new ConfigurationException(PROP_PASSWORD, PROP_PASSWORD + " must be set"); } log.trace("config for id '{}': {}", id, configMap.get(id)); } // initialize event cache for (CalDavConfig calDavConfig : configMap.values()) { final CalendarRuntime eventRuntime = new CalendarRuntime(); eventRuntime.setConfig(calDavConfig); File cachePath = Util.getCachePath(calDavConfig.getKey()); if (!cachePath.exists() && !cachePath.mkdirs()) { log.error("cannot create directory ({}) for calendar caching (missing rights?)", cachePath.getAbsoluteFile()); continue; } EventStorage.getInstance().getEventCache().put(calDavConfig.getKey(), eventRuntime); } setProperlyConfigured(true); } } public List<EventNotifier> getEventListenerList() { return eventListenerList; } public Scheduler getScheduler() { return scheduler; } @Override public void addListener(EventNotifier notifier) { this.eventListenerList.add(notifier); // notify for missing changes for (CalendarRuntime calendarRuntime : EventStorage.getInstance().getEventCache().values()) { for (EventContainer eventContainer : calendarRuntime.getEventMap().values()) { for (CalDavEvent event : eventContainer.getEventList()) { notifier.eventLoaded(event); } } } } @Override public void removeListener(EventNotifier notifier) { this.eventListenerList.remove(notifier); } public synchronized void addEventToMap(EventContainer eventContainer, boolean createTimer) { CalendarRuntime calendarRuntime = EventStorage.getInstance().getEventCache() .get(eventContainer.getCalendarId()); ConcurrentHashMap<String, EventContainer> eventContainerMap = calendarRuntime.getEventMap(); if (eventContainerMap.containsKey(eventContainer.getEventId())) { EventContainer eventContainerOld = eventContainerMap.get(eventContainer.getEventId()); // event is already in map if (eventContainer.getLastChanged().isAfter(eventContainerOld.getLastChanged())) { log.debug("event is already in event map and newer -> delete the old one, reschedule timer"); // cancel old jobs for (String timerKey : eventContainerOld.getTimerMap()) { try { this.scheduler.deleteJob(JobKey.jobKey(timerKey)); } catch (SchedulerException e) { log.error("cannot cancel event with job-id: " + timerKey, e); } } eventContainerOld.getTimerMap().clear(); // override event eventContainerMap.put(eventContainer.getEventId(), eventContainer); for (EventNotifier notifier : eventListenerList) { for (CalDavEvent event : eventContainerOld.getEventList()) { log.trace("notify listener... {}", notifier); try { notifier.eventRemoved(event); } catch (Exception e) { log.error("error while invoking listener", e); } } } for (EventNotifier notifier : eventListenerList) { for (CalDavEvent event : eventContainer.getEventList()) { log.trace("notify listener... {}", notifier); try { notifier.eventLoaded(event); } catch (Exception e) { log.error("error while invoking listener", e); } } } if (createTimer) { int index = 0; for (CalDavEvent event : eventContainer.getEventList()) { if (event.getEnd().isAfterNow()) { try { createJob(eventContainer, event, index); } catch (SchedulerException e) { log.error("cannot create jobs for event '{}': ", event.getShortName(), e.getMessage()); } } index++; } } } else { // event is already in map and not updated, ignoring } } else { // event is new eventContainerMap.put(eventContainer.getEventId(), eventContainer); log.trace("listeners for events: {}", eventListenerList.size()); for (EventNotifier notifier : eventListenerList) { for (CalDavEvent event : eventContainer.getEventList()) { log.trace("notify listener... {}", notifier); try { notifier.eventLoaded(event); } catch (Exception e) { log.error("error while invoking listener", e); } } } if (createTimer) { int index = 0; for (CalDavEvent event : eventContainer.getEventList()) { if (event.getEnd().isAfterNow()) { try { createJob(eventContainer, event, index); } catch (SchedulerException e) { log.error("cannot create jobs for event: " + event.getShortName()); } } index++; } } } } private synchronized void createJob(final EventContainer eventContainer, final CalDavEvent event, final int index) throws SchedulerException { final String triggerStart = JOB_NAME_EVENT_START + "-" + event.getShortName() + "-" + index; final boolean startJobTriggerDeleted = this.scheduler .unscheduleJob(TriggerKey.triggerKey(triggerStart, JOB_NAME_EVENT_START)); final boolean startJobDeleted = this.scheduler.deleteJob(JobKey.jobKey(triggerStart, JOB_NAME_EVENT_START)); log.trace("old start job ({}) deleted? {}/{}", triggerStart, startJobDeleted, startJobTriggerDeleted); Date startDate = event.getStart().toDate(); JobDetail jobStart = JobBuilder.newJob().ofType(EventJob.class) .usingJobData(EventJob.KEY_CONFIG, eventContainer.getCalendarId()) .usingJobData(EventJob.KEY_EVENT, eventContainer.getEventId()) .usingJobData(EventJob.KEY_REC_INDEX, index) .usingJobData(EventJob.KEY_EVENT_TRIGGER, EventTrigger.BEGIN.name()).storeDurably(false) .withIdentity(triggerStart, JOB_NAME_EVENT_START).build(); Trigger jobTriggerStart = TriggerBuilder.newTrigger().withIdentity(triggerStart, JOB_NAME_EVENT_START) .startAt(startDate).build(); this.scheduler.scheduleJob(jobStart, jobTriggerStart); eventContainer.getTimerMap().add(triggerStart); log.debug("begin timer scheduled for event '{}' @ {}", event.getShortName(), startDate); final String triggerEnd = JOB_NAME_EVENT_END + "-" + event.getShortName() + "-" + index; final boolean endJobTriggerDeleted = this.scheduler .unscheduleJob(TriggerKey.triggerKey(triggerEnd, JOB_NAME_EVENT_END)); final boolean endJobDeleted = this.scheduler.deleteJob(JobKey.jobKey(triggerEnd, JOB_NAME_EVENT_END)); log.trace("old end job ({}) deleted? {}/{}", triggerEnd, endJobDeleted, endJobTriggerDeleted); Date endDate = event.getEnd().toDate(); JobDetail jobEnd = JobBuilder.newJob().ofType(EventJob.class) .usingJobData(EventJob.KEY_CONFIG, eventContainer.getCalendarId()) .usingJobData(EventJob.KEY_EVENT, eventContainer.getEventId()) .usingJobData(EventJob.KEY_REC_INDEX, index) .usingJobData(EventJob.KEY_EVENT_TRIGGER, EventTrigger.END.name()).storeDurably(false) .withIdentity(triggerEnd, JOB_NAME_EVENT_END).build(); Trigger jobTriggerEnd = TriggerBuilder.newTrigger().withIdentity(triggerEnd, JOB_NAME_EVENT_END) .startAt(endDate).build(); this.scheduler.scheduleJob(jobEnd, jobTriggerEnd); eventContainer.getTimerMap().add(triggerEnd); log.debug("end timer scheduled for event '{}' @ {}", event.getShortName(), endDate); } public void startLoading() { if (execService != null) { return; } log.trace("starting execution..."); int i = 0; for (final CalendarRuntime eventRuntime : EventStorage.getInstance().getEventCache().values()) { try { JobDetail job = JobBuilder.newJob().ofType(EventReloaderJob.class) .usingJobData(EventReloaderJob.KEY_CONFIG, eventRuntime.getConfig().getKey()) .withIdentity(eventRuntime.getConfig().getKey(), JOB_NAME_EVENT_RELOADER).storeDurably() .build(); this.scheduler.addJob(job, false); SimpleTrigger jobTrigger = TriggerBuilder.newTrigger().forJob(job) .withIdentity(eventRuntime.getConfig().getKey(), JOB_NAME_EVENT_RELOADER) .startAt(DateBuilder.futureDate(10 + i, IntervalUnit.SECOND)).withSchedule(SimpleScheduleBuilder .repeatMinutelyForever(eventRuntime.getConfig().getReloadMinutes())) .build(); this.scheduler.scheduleJob(jobTrigger); log.info("reload job scheduled for: {}", eventRuntime.getConfig().getKey()); } catch (SchedulerException e) { log.error("cannot schedule calendar-reloader", e); } // next event 10 seconds later i += 10; } } @Override protected void execute() { } @Override protected long getRefreshInterval() { return 1000; } @Override protected String getName() { return "CalDav Loader"; } @Override public void addEvent(CalDavEvent calDavEvent) { final CalendarRuntime calendarRuntime = EventStorage.getInstance().getEventCache() .get(calDavEvent.getCalendarId()); CalDavConfig config = calendarRuntime.getConfig(); if (config == null) { log.error("cannot find config for calendar id: {}", calDavEvent.getCalendarId()); } Sardine sardine = Util.getConnection(config); Calendar calendar = Util.createCalendar(calDavEvent, defaultTimeZone); try { final String fullIcsFile = config.getUrl() + "/" + calDavEvent.getFilename() + ".ics"; if (calendarRuntime.getEventContainerByFilename(calDavEvent.getFilename()) != null) { log.debug("event will be updated: {}", fullIcsFile); try { sardine.delete(fullIcsFile); } catch (IOException e) { log.error("cannot remove old ics file: {}", fullIcsFile); } } else { log.debug("event is new: {}", fullIcsFile); } sardine.put(fullIcsFile, calendar.toString().getBytes("UTF-8")); EventContainer eventContainer = new EventContainer(calDavEvent.getCalendarId()); eventContainer.setEventId(calDavEvent.getId()); eventContainer.setFilename(Util.getFilename(calDavEvent.getFilename())); eventContainer.getEventList().add(calDavEvent); eventContainer.setLastChanged(calDavEvent.getLastChanged()); this.addEventToMap(eventContainer, false); } catch (UnsupportedEncodingException e) { log.error("cannot write event", e); } catch (IOException e) { log.error("cannot write event", e); } } @Override public List<CalDavEvent> getEvents(final CalDavQuery query) { log.trace("quering events for filter: {}", query); final ArrayList<CalDavEvent> eventList = new ArrayList<CalDavEvent>(); if (query.getCalendarIds() != null) { for (String calendarId : query.getCalendarIds()) { final CalendarRuntime eventRuntime = EventStorage.getInstance().getEventCache().get(calendarId); if (eventRuntime == null) { log.debug("calendar id {} not found", calendarId); continue; } for (EventContainer eventContainer : eventRuntime.getEventMap().values()) { for (CalDavEvent calDavEvent : eventContainer.getEventList()) { if (query.getFrom() != null) { if (calDavEvent.getEnd().isBefore(query.getFrom())) { continue; } } if (query.getTo() != null) { if (calDavEvent.getStart().isAfter(query.getTo())) { continue; } } eventList.add(calDavEvent); } } } } if (query.getSort() != null) { Collections.sort(eventList, new Comparator<CalDavEvent>() { @Override public int compare(CalDavEvent arg0, CalDavEvent arg1) { if (query.getSort().equals(CalDavQuery.Sort.ASCENDING)) { return (arg0.getStart().compareTo(arg1.getStart())); } else if (query.getSort().equals(CalDavQuery.Sort.DESCENDING)) { return (arg1.getStart().compareTo(arg0.getStart())); } else { return 0; } } }); } log.debug("return event list for {} with {} entries", query, eventList.size()); return eventList; } }
paolodenti/openhab
bundles/io/org.openhab.io.caldav/src/main/java/org/openhab/io/caldav/internal/CalDavLoaderImpl.java
Java
epl-1.0
23,171
<?php /* * Copyright 2010 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. */ /** * Curl based implementation of apiIO. * * @author Chris Chabot <chabotc@google.com> * @author Chirag Shah <chirags@google.com> */ require_once 'apiCacheParser.php'; class apiCurlIO implements apiIO { const CONNECTION_ESTABLISHED = "HTTP/1.0 200 Connection established\r\n\r\n"; const FORM_URLENCODED = 'application/x-www-form-urlencoded'; private static $ENTITY_HTTP_METHODS = array("POST" => null, "PUT" => null); private static $HOP_BY_HOP = array( 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade'); private static $DEFAULT_CURL_PARAMS = array ( CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => 0, CURLOPT_FAILONERROR => false, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_HEADER => true, CURLOPT_VERBOSE => false, ); /** * Perform an authenticated / signed apiHttpRequest. * This function takes the apiHttpRequest, calls apiAuth->sign on it * (which can modify the request in what ever way fits the auth mechanism) * and then calls apiCurlIO::makeRequest on the signed request * * @param apiHttpRequest $request * @return apiHttpRequest The resulting HTTP response including the * responseHttpCode, responseHeaders and responseBody. */ public function authenticatedRequest(apiHttpRequest $request) { $request = apiClient::$auth->sign($request); return $this->makeRequest($request); } /** * Execute a apiHttpRequest * * @param apiHttpRequest $request the http request to be executed * @return apiHttpRequest http request with the response http code, response * headers and response body filled in * @throws apiIOException on curl or IO error */ public function makeRequest(apiHttpRequest $request) { // First, check to see if we have a valid cached version. $cached = $this->getCachedRequest($request); if ($cached !== false) { if (apiCacheParser::mustRevalidate($cached)) { $addHeaders = array(); if ($cached->getResponseHeader('etag')) { // [13.3.4] If an entity tag has been provided by the origin server, // we must use that entity tag in any cache-conditional request. $addHeaders['If-None-Match'] = $cached->getResponseHeader('etag'); } elseif ($cached->getResponseHeader('date')) { $addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date'); } $request->setRequestHeaders($addHeaders); } else { // No need to revalidate the request, return it directly return $cached; } } if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) { $request = $this->processEntityRequest($request); } $ch = curl_init(); curl_setopt_array($ch, self::$DEFAULT_CURL_PARAMS); curl_setopt($ch, CURLOPT_URL, $request->getUrl()); if ($request->getPostBody()) { curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getPostBody()); } $requestHeaders = $request->getRequestHeaders(); if ($requestHeaders && is_array($requestHeaders)) { $parsed = array(); foreach ($requestHeaders as $k => $v) { $parsed[] = "$k: $v"; } curl_setopt($ch, CURLOPT_HTTPHEADER, $parsed); } curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod()); curl_setopt($ch, CURLOPT_USERAGENT, $request->getUserAgent()); $respData = curl_exec($ch); // Retry if certificates are missing. if (curl_errno($ch) == CURLE_SSL_CACERT) { error_log('SSL certificate problem, verify that the CA cert is OK.' . ' Retrying with the CA cert bundle from google-api-php-client.'); curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem'); $respData = curl_exec($ch); } $respHeaderSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $respHttpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlErrorNum = curl_errno($ch); $curlError = curl_error($ch); curl_close($ch); if ($curlErrorNum != CURLE_OK) { throw new apiIOException("HTTP Error: ($respHttpCode) $curlError"); } // Parse out the raw response into usable bits list($responseHeaders, $responseBody) = self::parseHttpResponse($respData, $respHeaderSize); if ($respHttpCode == 304 && $cached) { // If the server responded NOT_MODIFIED, return the cached request. if (isset($responseHeaders['connection'])) { $hopByHop = array_merge( self::$HOP_BY_HOP, explode(',', $responseHeaders['connection']) ); $endToEnd = array(); foreach($hopByHop as $key) { if (isset($responseHeaders[$key])) { $endToEnd[$key] = $responseHeaders[$key]; } } $cached->setResponseHeaders($endToEnd); } return $cached; } // Fill in the apiHttpRequest with the response values $request->setResponseHttpCode($respHttpCode); $request->setResponseHeaders($responseHeaders); $request->setResponseBody($responseBody); // Store the request in cache (the function checks to see if the request // can actually be cached) $this->setCachedRequest($request); // And finally return it return $request; } /** * @visible for testing. * Cache the response to an HTTP request if it is cacheable. * @param apiHttpRequest $request * @return bool Returns true if the insertion was successful. * Otherwise, return false. */ public function setCachedRequest(apiHttpRequest $request) { // Determine if the request is cacheable. if (apiCacheParser::isResponseCacheable($request)) { apiClient::$cache->set($request->getCacheKey(), $request); return true; } return false; } /** * @visible for testing. * @param apiHttpRequest $request * @return apiHttpRequest|bool Returns the cached object or * false if the operation was unsuccessful. */ public function getCachedRequest(apiHttpRequest $request) { if (false == apiCacheParser::isRequestCacheable($request)) { false; } return apiClient::$cache->get($request->getCacheKey()); } /** * @param $respData * @param $headerSize * @return array */ public static function parseHttpResponse($respData, $headerSize) { if (stripos($respData, self::CONNECTION_ESTABLISHED) !== false) { $respData = str_ireplace(self::CONNECTION_ESTABLISHED, '', $respData); } if ($headerSize) { $responseBody = substr($respData, $headerSize); $responseHeaders = substr($respData, 0, $headerSize); } else { list($responseHeaders, $responseBody) = explode("\r\n\r\n", $respData, 2); } $responseHeaders = self::parseResponseHeaders($responseHeaders); return array($responseHeaders, $responseBody); } public static function parseResponseHeaders($rawHeaders) { $responseHeaders = array(); $responseHeaderLines = explode("\r\n", $rawHeaders); foreach ($responseHeaderLines as $headerLine) { if ($headerLine && strpos($headerLine, ':') !== false) { list($header, $value) = explode(': ', $headerLine, 2); $header = strtolower($header); if (isset($responseHeaders[$header])) { $responseHeaders[$header] .= "\n" . $value; } else { $responseHeaders[$header] = $value; } } } return $responseHeaders; } /** * @visible for testing * Process an http request that contains an enclosed entity. * @param apiHttpRequest $request * @return apiHttpRequest Processed request with the enclosed entity. */ public function processEntityRequest(apiHttpRequest $request) { $postBody = $request->getPostBody(); $contentType = $request->getRequestHeader("content-type"); // Set the default content-type as application/x-www-form-urlencoded. if (false == $contentType) { $contentType = self::FORM_URLENCODED; $request->setRequestHeaders(array('content-type' => $contentType)); } // Force the payload to match the content-type asserted in the header. if ($contentType == self::FORM_URLENCODED && is_array($postBody)) { $postBody = http_build_query($postBody, '', '&'); $request->setPostBody($postBody); } // Make sure the content-length header is set. if (!$postBody || is_string($postBody)) { $postsLength = strlen($postBody); $request->setRequestHeaders(array('content-length' => $postsLength)); } return $request; } }
mpranivong/golf-phpnuke
wp/wp-content/plugins/wordcents/src/io/apiCurlIO.php
PHP
gpl-2.0
9,202
/*************************************************************************** * Copyright (C) 2007 by Tarek Saidi * * tarek.saidi@arcor.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; version 2 of the License. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <QTreeWidget> #include <QPainter> #include <QPaintEvent> #include <QResizeEvent> #include "main.h" #include "TrashCanDlg.h" TrashCanDialog::TrashCanDialog(QWidget* parent,IDatabase* database,const QList<IEntryHandle*>& TrashItems):QDialog(parent){ setupUi(this); Entries=TrashItems; for(int i=0;i<Entries.size();i++){ QTreeWidgetItem* item=new QTreeWidgetItem(treeWidget); item->setData(0,Qt::UserRole,i); item->setText(0,Entries[i]->group()->title()); item->setText(1,Entries[i]->title()); item->setText(2,Entries[i]->username()); item->setText(3,Entries[i]->expire().dateToString(Qt::LocalDate)); item->setIcon(0,database->icon(Entries[i]->group()->image())); item->setIcon(1,database->icon(Entries[i]->image())); } connect(treeWidget,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(OnItemDoubleClicked(QTreeWidgetItem*))); connect(treeWidget,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(OnContextMenu(const QPoint&))); ContextMenu=new QMenu(this); ContextMenu->addAction(getIcon("restore"),"Restore"); ContextMenu->addAction(getIcon("deleteentry"),"Delete"); } void TrashCanDialog::paintEvent(QPaintEvent* event){ QDialog::paintEvent(event); QPainter painter(this); painter.setClipRegion(event->region()); painter.drawPixmap(QPoint(0,0),BannerPixmap); } void TrashCanDialog::resizeEvent(QResizeEvent* event){ createBanner(&BannerPixmap,getPixmap("trashcan"),tr("Recycle Bin"),width()); QDialog::resizeEvent(event); } void TrashCanDialog::OnItemDoubleClicked(QTreeWidgetItem* item){ SelectedEntry=Entries[item->data(0,Qt::UserRole).toInt()]; accept(); } void TrashCanDialog::OnContextMenu(const QPoint& pos){ if(treeWidget->itemAt(pos)){ QTreeWidgetItem* item=treeWidget->itemAt(pos); if(treeWidget->selectedItems().size()==0){ treeWidget->setItemSelected(item,true); } else{ if(!treeWidget->isItemSelected(item)){ while(treeWidget->selectedItems().size()){ treeWidget->setItemSelected(treeWidget->selectedItems()[0],false); } treeWidget->setItemSelected(item,true); } } } else { while(treeWidget->selectedItems().size()) treeWidget->setItemSelected(treeWidget->selectedItems()[0],false); } ContextMenu->popup(treeWidget->viewport()->mapToGlobal(pos)); } ///TODO 0.2.3 locale aware string/date compare for correct sorting
dwihn0r/keepassx
src/dialogs/TrashCanDlg.cpp
C++
gpl-2.0
3,752
// Copyright 2013 Dolphin Emulator Project // Licensed under GPLv2 // Refer to the license.txt file included. #include "Core/ConfigManager.h" #include "Core/HW/Sram.h" // english SRAM sram_dump = {{ 0xFF, 0x6B, 0x00, 0x91, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x40, 0x00, 0x00, 0x00, 0x2C, 0x44, 0x4F, 0x4C, 0x50, 0x48, 0x49, 0x4E, 0x53, 0x4C, 0x4F, 0x54, 0x41, 0x44, 0x4F, 0x4C, 0x50, 0x48, 0x49, 0x4E, 0x53, 0x4C, 0x4F, 0x54, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6E, 0x6D, 0x00, 0x00, 0x00, 0x00 }}; #if 0 // german SRAM sram_dump_german = {{ 0x1F, 0x66, 0xE0, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xEA, 0x19, 0x40, 0x00, 0x00, 0x01, 0x3C, 0x12, 0xD5, 0xEA, 0xD3, 0x00, 0xFA, 0x2D, 0x33, 0x13, 0x41, 0x26, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x84, 0xFF, 0x00, 0x00, 0x00, 0x00 }}; #endif void InitSRAM() { File::IOFile file(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strSRAM, "rb"); if (file) { if (!file.ReadArray(&g_SRAM, 1)) { ERROR_LOG(EXPANSIONINTERFACE, "EXI IPL-DEV: Could not read all of SRAM"); g_SRAM = sram_dump; } } else { g_SRAM = sram_dump; } } void SetCardFlashID(u8* buffer, u8 card_index) { u64 rand = Common::swap64( *(u64*)&(buffer[12])); u8 csum=0; for (int i = 0; i < 12; i++) { rand = (((rand * (u64)0x0000000041c64e6dULL) + (u64)0x0000000000003039ULL) >> 16); csum += g_SRAM.flash_id[card_index][i] = buffer[i] - ((u8)rand&0xff); rand = (((rand * (u64)0x0000000041c64e6dULL) + (u64)0x0000000000003039ULL) >> 16); rand &= (u64)0x0000000000007fffULL; } g_SRAM.flashID_chksum[card_index] = csum^0xFF; }
zhuowei/dolphin
Source/Core/Core/HW/Sram.cpp
C++
gpl-2.0
1,852
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "engines/wintermute/debugger.h" #include "engines/wintermute/wintermute.h" #include "engines/wintermute/base/base_engine.h" #include "engines/wintermute/base/base_file_manager.h" #include "engines/wintermute/base/base_game.h" namespace Wintermute { Console::Console(WintermuteEngine *vm) : GUI::Debugger(), _engineRef(vm) { registerCmd("show_fps", WRAP_METHOD(Console, Cmd_ShowFps)); registerCmd("dump_file", WRAP_METHOD(Console, Cmd_DumpFile)); } Console::~Console(void) { } bool Console::Cmd_ShowFps(int argc, const char **argv) { if (argc > 1) { if (Common::String(argv[1]) == "true") { _engineRef->_game->setShowFPS(true); } else if (Common::String(argv[1]) == "false") { _engineRef->_game->setShowFPS(false); } } return true; } bool Console::Cmd_DumpFile(int argc, const char **argv) { if (argc != 3) { debugPrintf("Usage: %s <file path> <output file name>\n", argv[0]); return true; } Common::String filePath = argv[1]; Common::String outFileName = argv[2]; BaseFileManager *fileManager = BaseEngine::instance().getFileManager(); Common::SeekableReadStream *inFile = fileManager->openFile(filePath); if (!inFile) { debugPrintf("File '%s' not found\n", argv[1]); return true; } Common::DumpFile *outFile = new Common::DumpFile(); outFile->open(outFileName); byte *data = new byte[inFile->size()]; inFile->read(data, inFile->size()); outFile->write(data, inFile->size()); outFile->finalize(); outFile->close(); delete[] data; delete outFile; delete inFile; debugPrintf("Resource file '%s' dumped to file '%s'\n", argv[1], argv[2]); return true; } } // End of namespace Wintermute
clone2727/cabal
engines/wintermute/debugger.cpp
C++
gpl-2.0
2,600
// 2005-12-01 Paolo Carlini <pcarlini@suse.de> // Copyright (C) 2005, 2009 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-do compile } #include <vector> namespace N { struct X { }; template<typename T> X operator+(T, std::size_t) { return X(); } template<typename T> X operator-(T, T) { return X(); } } int main() { std::vector<N::X> v(5); const std::vector<N::X> w(1); v[0]; w[0]; v.size(); v.capacity(); v.resize(1); v.insert(v.begin(), N::X()); v.insert(v.begin(), 1, N::X()); v.insert(v.begin(), w.begin(), w.end()); v = w; return 0; }
embecosm/avr32-gcc
libstdc++-v3/testsuite/23_containers/vector/types/1.cc
C++
gpl-2.0
1,294
<?php /* +---------------------------------------------------------------------------+ | Revive Adserver | | http://www.revive-adserver.com | | | | Copyright: See the COPYRIGHT.txt file. | | License: GPLv2 or later, see the LICENSE.txt file. | +---------------------------------------------------------------------------+ */ // Meta information $translation_readable = "Bulgarian"; $translation_maintainer = "Revive Adserver Team"; $translation_contact = "noreply@revive-adserver.com";
Tate-ad/revive-adserver
lib/max/language/bg/index.lang.php
PHP
gpl-2.0
723
require "mysql2" require File.expand_path(File.dirname(__FILE__) + "/base.rb") class ImportScripts::Kunena < ImportScripts::Base KUNENA_DB = "kunena" def initialize super @users = {} @client = Mysql2::Client.new( host: "localhost", username: "root", #password: "password", database: KUNENA_DB ) end def execute parse_users puts "creating users" create_users(@users) do |id, user| { id: id, email: user[:email], username: user[:username], created_at: user[:created_at], bio_raw: user[:bio], moderator: user[:moderator] ? true : false, admin: user[:admin] ? true : false, suspended_at: user[:suspended] ? Time.zone.now : nil, suspended_till: user[:suspended] ? 100.years.from_now : nil } end @users = nil create_categories(@client.query("SELECT id, parent, name, description, ordering FROM jos_kunena_categories ORDER BY parent, id;")) do |c| h = { id: c['id'], name: c['name'], description: c['description'], position: c['ordering'].to_i } if c['parent'].to_i > 0 h[:parent_category_id] = category_id_from_imported_category_id(c['parent']) end h end import_posts begin create_admin(email: 'neil.lalonde@discourse.org', username: UserNameSuggester.suggest('neil')) rescue => e puts '', "Failed to create admin user" puts e.message end end def parse_users # Need to merge data from joomla with kunena puts "fetching Joomla users data from mysql" results = @client.query("SELECT id, username, email, registerDate FROM jos_users;", cache_rows: false) results.each do |u| next unless u['id'].to_i > (0) && u['username'].present? && u['email'].present? username = u['username'].gsub(' ', '_').gsub(/[^A-Za-z0-9_]/, '')[0, User.username_length.end] if username.length < User.username_length.first username = username * User.username_length.first end @users[u['id'].to_i] = { id: u['id'].to_i, username: username, email: u['email'], created_at: u['registerDate'] } end puts "fetching Kunena user data from mysql" results = @client.query("SELECT userid, signature, moderator, banned FROM jos_kunena_users;", cache_rows: false) results.each do |u| next unless u['userid'].to_i > 0 user = @users[u['userid'].to_i] if user user[:bio] = u['signature'] user[:moderator] = (u['moderator'].to_i == 1) user[:suspended] = u['banned'].present? end end end def import_posts puts '', "creating topics and posts" total_count = @client.query("SELECT COUNT(*) count FROM jos_kunena_messages m;").first['count'] batch_size = 1000 batches(batch_size) do |offset| results = @client.query(" SELECT m.id id, m.thread thread, m.parent parent, m.catid catid, m.userid userid, m.subject subject, m.time time, t.message message FROM jos_kunena_messages m, jos_kunena_messages_text t WHERE m.id = t.mesid ORDER BY m.id LIMIT #{batch_size} OFFSET #{offset}; ", cache_rows: false) break if results.size < 1 next if all_records_exist? :posts, results.map { |p| p['id'].to_i } create_posts(results, total: total_count, offset: offset) do |m| skip = false mapped = {} mapped[:id] = m['id'] mapped[:user_id] = user_id_from_imported_user_id(m['userid']) || -1 mapped[:raw] = m["message"] mapped[:created_at] = Time.zone.at(m['time']) if m['id'] == m['thread'] mapped[:category] = category_id_from_imported_category_id(m['catid']) mapped[:title] = m['subject'] else parent = topic_lookup_from_imported_post_id(m['parent']) if parent mapped[:topic_id] = parent[:topic_id] mapped[:reply_to_post_number] = parent[:post_number] if parent[:post_number] > 1 else puts "Parent post #{m['parent']} doesn't exist. Skipping #{m["id"]}: #{m["subject"][0..40]}" skip = true end end skip ? nil : mapped end end end end ImportScripts::Kunena.new.perform
fabianoleittes/discourse
script/import_scripts/kunena.rb
Ruby
gpl-2.0
4,377
// SERVER-2282 $or de duping with sparse indexes t = db.jstests_org; t.drop(); t.ensureIndex( {a:1}, {sparse:true} ); t.ensureIndex( {b:1} ); t.remove(); t.save( {a:1,b:2} ); assert.eq( 1, t.count( {$or:[{a:1},{b:2}]} ) ); t.remove(); t.save( {a:null,b:2} ); assert.eq( 1, t.count( {$or:[{a:null},{b:2}]} ) ); t.remove(); t.save( {b:2} ); assert.eq( 1, t.count( {$or:[{a:null},{b:2}]} ) );
barakav/robomongo
src/third-party/mongodb/jstests/org.js
JavaScript
gpl-3.0
395
/* * This file is part of the cSploit. * * Copyleft of Massimo Dragano aka tux_mind <tux_mind@csploit.org> * * cSploit is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * cSploit is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with cSploit. If not, see <http://www.gnu.org/licenses/>. */ package org.csploit.android.tools; import org.csploit.android.core.ChildManager; import org.csploit.android.core.System; import org.csploit.android.core.Child; import org.csploit.android.core.Logger; import org.csploit.android.events.Event; import org.csploit.android.events.Host; import org.csploit.android.events.HostLost; import java.net.InetAddress; public class NetworkRadar extends Tool { public NetworkRadar() { mHandler = "network-radar"; mCmdPrefix = null; } public static abstract class HostReceiver extends Child.EventReceiver { public abstract void onHostFound(byte[] macAddress, InetAddress ipAddress, String name); public abstract void onHostLost(InetAddress ipAddress); public void onEvent(Event e) { if ( e instanceof Host ) { Host h = (Host)e; onHostFound(h.ethAddress, h.ipAddress, h.name); } else if ( e instanceof HostLost ) { onHostLost(((HostLost)e).ipAddress); } else { Logger.error("Unknown event: " + e); } } } public Child start(HostReceiver receiver) throws ChildManager.ChildNotStartedException { String ifName; ifName = System.getNetwork().getInterface().getDisplayName(); return async(ifName, receiver); } }
odin1314/android
cSploit/src/org/csploit/android/tools/NetworkRadar.java
Java
gpl-3.0
2,001
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.function.pattern; import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.blocks.BaseBlock; import static com.google.common.base.Preconditions.checkNotNull; /** * A pattern that returns the same {@link BaseBlock} each time. */ public class BlockPattern extends AbstractPattern { private BaseBlock block; /** * Create a new pattern with the given block. * * @param block the block */ public BlockPattern(BaseBlock block) { setBlock(block); } /** * Get the block. * * @return the block that is always returned */ public BaseBlock getBlock() { return block; } /** * Set the block that is returned. * * @param block the block */ public void setBlock(BaseBlock block) { checkNotNull(block); this.block = block; } @Override public BaseBlock apply(Vector position) { return block; } }
UnlimitedFreedom/UF-WorldEdit
worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/BlockPattern.java
Java
gpl-3.0
1,799
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_sql_user_info description: - Gather info for GCP User short_description: Gather info for GCP User version_added: '2.8' author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: instance: description: - The name of the Cloud SQL instance. This does not include the project ID. - 'This field represents a link to a Instance resource in GCP. It can be specified in two ways. First, you can place a dictionary with key ''name'' and value of your resource''s name Alternatively, you can add `register: name-of-resource` to a gcp_sql_instance task and then set this instance field to "{{ name-of-resource }}"' required: true type: dict project: description: - The Google Cloud Platform project to use. type: str auth_kind: description: - The type of credential used. type: str required: true choices: - application - machineaccount - serviceaccount service_account_contents: description: - The contents of a Service Account JSON file, either in a dictionary or as a JSON string that represents it. type: jsonarg service_account_file: description: - The path of a Service Account JSON file if serviceaccount is selected as type. type: path service_account_email: description: - An optional service account email address if machineaccount is selected and the user does not wish to use the default email. type: str scopes: description: - Array of scopes to be used type: list env_type: description: - Specifies which Ansible environment you're running this module within. - This should not be set unless you know what you're doing. - This only alters the User Agent string for any API requests. type: str notes: - for authentication, you can set service_account_file using the C(gcp_service_account_file) env variable. - for authentication, you can set service_account_contents using the C(GCP_SERVICE_ACCOUNT_CONTENTS) env variable. - For authentication, you can set service_account_email using the C(GCP_SERVICE_ACCOUNT_EMAIL) env variable. - For authentication, you can set auth_kind using the C(GCP_AUTH_KIND) env variable. - For authentication, you can set scopes using the C(GCP_SCOPES) env variable. - Environment variables values will only be used if the playbook values are not set. - The I(service_account_email) and I(service_account_file) options are mutually exclusive. ''' EXAMPLES = ''' - name: get info on a user gcp_sql_user_info: instance: "{{ instance }}" project: test_project auth_kind: serviceaccount service_account_file: "/tmp/auth.pem" ''' RETURN = ''' resources: description: List of resources returned: always type: complex contains: host: description: - The host name from which the user can connect. For insert operations, host defaults to an empty string. For update operations, host is specified as part of the request URL. The host name cannot be updated after insertion. returned: success type: str name: description: - The name of the user in the Cloud SQL instance. returned: success type: str instance: description: - The name of the Cloud SQL instance. This does not include the project ID. returned: success type: dict password: description: - The password for the user. returned: success type: str ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, replace_resource_dict import json ################################################################################ # Main ################################################################################ def main(): module = GcpModule(argument_spec=dict(instance=dict(required=True, type='dict'))) if not module.params['scopes']: module.params['scopes'] = ['https://www.googleapis.com/auth/sqlservice.admin'] return_value = {'resources': fetch_list(module, collection(module))} module.exit_json(**return_value) def collection(module): res = {'project': module.params['project'], 'instance': replace_resource_dict(module.params['instance'], 'name')} return "https://www.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}/users".format(**res) def fetch_list(module, link): auth = GcpSession(module, 'sql') return auth.list(link, return_if_object, array_name='items') def return_if_object(module, response): # If not found, return nothing. if response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: module.fail_json(msg="Invalid JSON response with error: %s" % inst) if navigate_hash(result, ['error', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result if __name__ == "__main__": main()
anryko/ansible
lib/ansible/modules/cloud/google/gcp_sql_user_info.py
Python
gpl-3.0
6,527
var searchData= [ ['print',['PRINT',['../_m_d___parola__lib_8h.html#a1696fc35fb931f8c876786fbc1078ac4',1,'MD_Parola_lib.h']]], ['print_5fstate',['PRINT_STATE',['../_m_d___parola__lib_8h.html#a3fda4e1a5122a16a21bd96ae5217402c',1,'MD_Parola_lib.h']]], ['prints',['PRINTS',['../_m_d___parola__lib_8h.html#ad68f35c3cfe67be8d09d1cea8e788e13',1,'MD_Parola_lib.h']]], ['printx',['PRINTX',['../_m_d___parola__lib_8h.html#abf55b44e8497cbc3addccdeb294138cc',1,'MD_Parola_lib.h']]] ];
javastraat/arduino
libraries/MD_Parola/doc/html/search/defines_70.js
JavaScript
gpl-3.0
482
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ const mapValuesByKeys = require('../../../js/lib/functional').mapValuesByKeys const _ = null const ExtensionConstants = { BROWSER_ACTION_REGISTERED: _, BROWSER_ACTION_UPDATED: _, EXTENSION_INSTALLED: _, EXTENSION_UNINSTALLED: _, EXTENSION_ENABLED: _, EXTENSION_DISABLED: _, CONTEXT_MENU_CREATED: _, CONTEXT_MENU_ALL_REMOVED: _, CONTEXT_MENU_CLICKED: _ } module.exports = mapValuesByKeys(ExtensionConstants)
timborden/browser-laptop
app/common/constants/extensionConstants.js
JavaScript
mpl-2.0
633
<?php $children = $main_article->getChildArticles(); $is_parent = in_array($main_article->getID(), $parents); $is_selected = $main_article->getID() == $article->getID() || ($main_article->isRedirect() && $main_article->getRedirectArticleName() == $article->getTitle()); $is_first = $first; $first = false; $project_key = (\thebuggenie\core\framework\Context::isProjectContext()) ? \thebuggenie\core\framework\Context::getCurrentProject()->getKey() . ':' : ''; // $article_name = (strpos(mb_strtolower($main_article->getTitle()), 'category:') !== false) ? substr($main_article->getTitle(), 9+mb_strlen($project_key)) : substr($main_article->getTitle(), mb_strlen($project_key)); ?> <li class="<?php echo (isset($level) && $level >= 1) ? 'child' : 'parent'; ?> <?php if ($is_parent && !$is_selected) echo 'parent'; ?> <?php if ($is_selected) echo 'selected'; ?> level_<?php echo $level; ?>" id="article_sidebar_link_<?php echo $article->getID(); ?>"> <?php if (isset($level) && $level >= 1) echo image_tag('icon_tree_child.png', array('class' => 'branch')); ?> <?php if ($is_first && $main_article->getArticleType() == \thebuggenie\modules\publish\entities\Article::TYPE_MANUAL): ?> <?php echo image_tag('icon-article-type-manual.small.png'); ?> <?php else: ?> <?php echo (!empty($children)) ? image_tag('icon_folder.png', array(), false, 'publish') : image_tag('icon_article.png', array(), false, 'publish'); ?> <?php endif; ?> <?php echo link_tag(make_url('publish_article', array('article_name' => $main_article->getName())), $main_article->getManualName()); ?> <?php if ($is_parent || $is_selected): ?> <ul> <?php foreach ($children as $child_article): ?> <?php include_component('publish/manualsidebarlink', array('parents' => $parents, 'first' => $first, 'article' => $article, 'main_article' => $child_article, 'level' => $level + 1)); ?> <?php endforeach; ?> </ul> <?php endif; ?> </li>
hurie/thebuggenie
modules/publish/templates/_manualsidebarlink.inc.php
PHP
mpl-2.0
2,024
/* * Copyright 2008, 2009 Google Inc. * Copyright 2006, 2007 Nintendo Co., 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. */ #include <string.h> #include <es/any.h> #include <es/endian.h> #include <es/formatter.h> #include <es/interfaceData.h> #include <es/object.h> #include <es/base/IProcess.h> #include <es/hashtable.h> #include <es/reflect.h> // TODO use proper name prefix or namespace namespace es { Reflect::Interface& getInterface(const char* iid); Object* getConstructor(const char* iid); extern unsigned char* defaultInterfaceInfo[]; extern size_t defaultInterfaceCount; } // namespace es #ifndef VERBOSE #define PRINTF(...) (__VA_ARGS__) #else #define PRINTF(...) report(__VA_ARGS__) #endif class ObjectValue; #include "interface.h" extern es::CurrentProcess* System(); namespace { const int GuidStringLength = 37; // Including terminating zero } // // invoke // typedef long long (*InterfaceMethod)(void* self, ...); static char heap[64*1024]; static Value* invoke(const char* iid, int number, InterfaceMethod** self, ListValue* list) { if (!self) { throw getErrorInstance("TypeError"); } Reflect::Interface interface = es::getInterface(iid); Reflect::Method method(interface.getMethod(number)); PRINTF("invoke %s.%s(%p)\n", interface.getName().c_str(), method.getName().c_str(), self); // Set up parameters Any argv[9]; Any* argp = argv; int ext = 0; // extra parameter count // Set this *argp++ = Any(reinterpret_cast<intptr_t>(self)); // In the following implementation, we assume no out nor inout attribute is // used for parameters. Reflect::Type returnType = method.getReturnType(); switch (returnType.getType()) { case Reflect::kAny: // Any op(void* buf, int len, ...); // FALL THROUGH case Reflect::kString: // const char* op(xxx* buf, int len, ...); *argp++ = Any(reinterpret_cast<intptr_t>(heap)); *argp++ = Any(sizeof(heap)); break; case Reflect::kSequence: // int op(xxx* buf, int len, ...); *argp++ = Any(reinterpret_cast<intptr_t>(heap)); ++ext; *argp++ = Any(static_cast<int32_t>(((*list)[0])->toNumber())); break; case Reflect::kArray: // void op(xxx[x] buf, ...); *argp++ = Any(reinterpret_cast<intptr_t>(heap)); break; } Reflect::Parameter param = method.listParameter(); for (int i = ext; param.next(); ++i, ++argp) { Reflect::Type type(param.getType()); Value* value = (*list)[i]; switch (type.getType()) { case Reflect::kAny: // Any variant, ... switch (value->getType()) { case Value::BoolType: *argp = Any(static_cast<bool>(value->toBoolean())); break; case Value::StringType: *argp = Any(value->toString().c_str()); break; case Value::NumberType: *argp = Any(static_cast<double>(value->toNumber())); break; case Value::ObjectType: if (InterfacePointerValue* unknown = dynamic_cast<InterfacePointerValue*>(value)) { *argp = Any(unknown->getObject()); } else { // XXX expose ECMAScript object *argp = Any(static_cast<Object*>(0)); } break; default: *argp = Any(); break; } argp->makeVariant(); break; case Reflect::kSequence: // xxx* buf, int len, ... // XXX Assume sequence<octet> now... *argp++ = Any(reinterpret_cast<intptr_t>(value->toString().c_str())); value = (*list)[++i]; *argp = Any(static_cast<int32_t>(value->toNumber())); break; case Reflect::kString: *argp = Any(value->toString().c_str()); break; case Reflect::kArray: // void op(xxx[x] buf, ...); // XXX expand data break; case Reflect::kObject: if (InterfacePointerValue* unknown = dynamic_cast<InterfacePointerValue*>(value)) { *argp = Any(unknown->getObject()); } else { *argp = Any(static_cast<Object*>(0)); } break; case Reflect::kBoolean: *argp = Any(static_cast<bool>(value->toBoolean())); break; case Reflect::kPointer: *argp = Any(static_cast<intptr_t>(value->toNumber())); break; case Reflect::kShort: *argp = Any(static_cast<int16_t>(value->toNumber())); break; case Reflect::kLong: *argp = Any(static_cast<int32_t>(value->toNumber())); break; case Reflect::kOctet: *argp = Any(static_cast<uint8_t>(value->toNumber())); break; case Reflect::kUnsignedShort: *argp = Any(static_cast<uint16_t>(value->toNumber())); break; case Reflect::kUnsignedLong: *argp = Any(static_cast<uint32_t>(value->toNumber())); break; case Reflect::kLongLong: *argp = Any(static_cast<int64_t>(value->toNumber())); break; case Reflect::kUnsignedLongLong: *argp = Any(static_cast<uint64_t>(value->toNumber())); break; case Reflect::kFloat: *argp = Any(static_cast<float>(value->toNumber())); break; case Reflect::kDouble: *argp = Any(static_cast<double>(value->toNumber())); break; default: break; } } // Invoke method Register<Value> value; unsigned methodNumber = interface.getInheritedMethodCount() + number; int argc = argp - argv; switch (returnType.getType()) { case Reflect::kAny: { Any result = apply(argc, argv, (Any (*)()) ((*self)[methodNumber])); switch (result.getType()) { case Any::TypeVoid: value = NullValue::getInstance(); break; case Any::TypeBool: value = BoolValue::getInstance(static_cast<bool>(result)); break; case Any::TypeOctet: value = new NumberValue(static_cast<uint8_t>(result)); break; case Any::TypeShort: value = new NumberValue(static_cast<int16_t>(result)); break; case Any::TypeUnsignedShort: value = new NumberValue(static_cast<uint16_t>(result)); break; case Any::TypeLong: value = new NumberValue(static_cast<int32_t>(result)); break; case Any::TypeUnsignedLong: value = new NumberValue(static_cast<uint32_t>(result)); break; case Any::TypeLongLong: value = new NumberValue(static_cast<int64_t>(result)); break; case Any::TypeUnsignedLongLong: value = new NumberValue(static_cast<uint64_t>(result)); break; case Any::TypeFloat: value = new NumberValue(static_cast<float>(result)); break; case Any::TypeDouble: value = new NumberValue(static_cast<double>(result)); break; case Any::TypeString: if (const char* string = static_cast<const char*>(result)) { value = new StringValue(string); } else { value = NullValue::getInstance(); } break; case Any::TypeObject: if (Object* unknown = static_cast<Object*>(result)) { ObjectValue* instance = new InterfacePointerValue(unknown); instance->setPrototype(getGlobal()->get(es::getInterface(Object::iid()).getName())->get("prototype")); // XXX Should use IID value = instance; } else { value = NullValue::getInstance(); } break; default: value = NullValue::getInstance(); break; } } break; case Reflect::kBoolean: value = BoolValue::getInstance(static_cast<bool>(apply(argc, argv, (bool (*)()) ((*self)[methodNumber])))); break; case Reflect::kOctet: value = new NumberValue(static_cast<uint8_t>(apply(argc, argv, (uint8_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kShort: value = new NumberValue(static_cast<int16_t>(apply(argc, argv, (int16_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kUnsignedShort: value = new NumberValue(static_cast<uint16_t>(apply(argc, argv, (uint16_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kLong: value = new NumberValue(static_cast<int32_t>(apply(argc, argv, (int32_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kUnsignedLong: value = new NumberValue(static_cast<uint32_t>(apply(argc, argv, (uint32_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kLongLong: value = new NumberValue(static_cast<int64_t>(apply(argc, argv, (int64_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kUnsignedLongLong: value = new NumberValue(static_cast<uint64_t>(apply(argc, argv, (uint64_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kFloat: value = new NumberValue(static_cast<float>(apply(argc, argv, (float (*)()) ((*self)[methodNumber])))); break; case Reflect::kDouble: value = new NumberValue(apply(argc, argv, (double (*)()) ((*self)[methodNumber]))); break; case Reflect::kPointer: value = new NumberValue(static_cast<intptr_t>(apply(argc, argv, (intptr_t (*)()) ((*self)[methodNumber])))); break; case Reflect::kString: { heap[0] = '\0'; Any result = apply(argc, argv, (const char* (*)()) ((*self)[methodNumber])); if (const char* string = static_cast<const char*>(result)) { value = new StringValue(string); } else { value = NullValue::getInstance(); } } break; case Reflect::kSequence: { // XXX Assume sequence<octet> now... int32_t count = apply(argc, argv, (int32_t (*)()) ((*self)[methodNumber])); if (count < 0) { count = 0; } heap[count] = '\0'; value = new StringValue(heap); } break; case Reflect::kObject: if (Object* unknown = apply(argc, argv, (Object* (*)()) ((*self)[methodNumber]))) { ObjectValue* instance = new InterfacePointerValue(unknown); // TODO: check Object and others instance->setPrototype(getGlobal()->get(es::getInterface(returnType.getQualifiedName().c_str()).getName())->get("prototype")); // XXX Should use IID value = instance; } else { value = NullValue::getInstance(); } break; case Reflect::kVoid: apply(argc, argv, (int32_t (*)()) ((*self)[methodNumber])); value = NullValue::getInstance(); break; } return value; } static Value* invoke(const char* iid, int number, InterfacePointerValue* object, ListValue* list) { InterfaceMethod** self = reinterpret_cast<InterfaceMethod**>(object->getObject()); if (!self) { throw getErrorInstance("TypeError"); } Value* value = invoke(iid, number, self, list); if (strcmp(iid, Object::iid()) == 0 && number == 2) // Object::release() { object->clearObject(); } return value; } // // AttributeValue // class AttributeValue : public ObjectValue { bool readOnly; const char* iid; int getter; // Method number int setter; // Method number public: AttributeValue(const char* iid) : readOnly(true), iid(iid), getter(0), setter(0) { } ~AttributeValue() { } void addSetter(int number) { readOnly = false; setter = number; } void addGetter(int number) { getter = number; } // Getter virtual Value* get(Value* self) { if (dynamic_cast<InterfacePointerValue*>(self)) { Register<ListValue> list = new ListValue; return invoke(iid, getter, static_cast<InterfacePointerValue*>(self), list); } else { return this; } } // Setter virtual bool put(Value* self, Value* value) { if (dynamic_cast<InterfacePointerValue*>(self) && !readOnly) { Register<ListValue> list = new ListValue; list->push(value); invoke(iid, setter, static_cast<InterfacePointerValue*>(self), list); } return true; } }; // // InterfaceMethodCode // class InterfaceMethodCode : public Code { FormalParameterList* arguments; ObjectValue* prototype; const char* iid; int number; // Method number public: InterfaceMethodCode(ObjectValue* object, const char* iid, int number) : arguments(new FormalParameterList), prototype(new ObjectValue), iid(iid), number(number) { Reflect::Interface interface = es::getInterface(iid); Reflect::Method method(interface.getMethod(number)); #if 0 // Add as many arguments as required. for (int i = 0; i < method.getParameterCount(); ++i) { Reflect::Parameter param(method.getParameter(i)); if (param.isInput()) { // Note the name "arguments" is reserved in a ECMAScript function. ASSERT(strcmp(param.getName(), "arguments") != 0); arguments->add(new Identifier(param.getName())); } } #endif object->setParameterList(arguments); object->setScope(getGlobal()); // Create Interface.prototype prototype->put("constructor", object); object->put("prototype", prototype); } ~InterfaceMethodCode() { delete arguments; } CompletionType evaluate() { InterfacePointerValue* object = dynamic_cast<InterfacePointerValue*>(getThis()); if (!object) { throw getErrorInstance("TypeError"); } ListValue* list = static_cast<ListValue*>(getScopeChain()->get("arguments")); Register<Value> value = invoke(iid, number, object, list); return CompletionType(CompletionType::Return, value, ""); } }; // // AttributeSetterValue // class AttributeSetterValue : public ObjectValue { const char* iid; int number; // Method number public: AttributeSetterValue(const char* iid, int number) : iid(iid), number(number) { } ~AttributeSetterValue() { } void put(Value* self, const std::string& name, Value* value) { Register<ListValue> list = new ListValue; Register<StringValue> ident = new StringValue(name); list->push(ident); list->push(value); invoke(iid, number, static_cast<InterfacePointerValue*>(self), list); return; } }; // // AttributeGetterValue // class AttributeGetterValue : public ObjectValue { const char* iid; int number; // Method number public: AttributeGetterValue(const char* iid, int number) : iid(iid), number(number) { } ~AttributeGetterValue() { } Value* get(Value* self, const std::string& name) { Register<ListValue> list = new ListValue; Register<StringValue> ident = new StringValue(name); list->push(ident); return invoke(iid, number, static_cast<InterfacePointerValue*>(self), list); } }; // // InterfacePrototypeValue // class InterfacePrototypeValue : public ObjectValue { enum OpObject { IndexGetter, IndexSetter, NameGetter, NameSetter, ObjectCount }; ObjectValue* opObjects[ObjectCount]; public: InterfacePrototypeValue() { for (int i = 0; i < ObjectCount; ++i) { opObjects[i] = 0; } } ~InterfacePrototypeValue() { } void setOpObject(int op, ObjectValue* object) { ASSERT(op >= 0 && op < ObjectCount); opObjects[op] = object; } ObjectValue* getOpObject(int op) { ASSERT(op >= 0 && op < ObjectCount); return opObjects[op]; } friend class InterfaceConstructor; friend class InterfacePointerValue; }; // // InterfaceConstructor // class InterfaceConstructor : public Code { ObjectValue* constructor; FormalParameterList* arguments; InterfacePrototypeValue* prototype; std::string iid; public: InterfaceConstructor(ObjectValue* object, std::string iid) : constructor(object), arguments(new FormalParameterList), prototype(new InterfacePrototypeValue), iid(iid) { arguments->add(new Identifier("object")); object->setParameterList(arguments); object->setScope(getGlobal()); Reflect::Interface interface = es::getInterface(iid.c_str()); // PRINTF("interface: %s\n", interface.getName().c_str()); for (int i = 0; i < interface.getMethodCount(); ++i) { // Construct Method object Reflect::Method method(interface.getMethod(i)); if (prototype->hasProperty(method.getName())) { if (method.isOperation()) { // XXX Currently overloaded functions are just ignored. } else { AttributeValue* attribute = static_cast<AttributeValue*>(prototype->get(method.getName())); if (method.isGetter()) { attribute->addGetter(i); } else { attribute->addSetter(i); } } } else { if (method.isOperation()) { ObjectValue* function = new ObjectValue; function->setCode(new InterfaceMethodCode(function, iid.c_str(), i)); prototype->put(method.getName(), function); #if 0 if (method.isIndexGetter()) { AttributeGetterValue* getter = new AttributeGetterValue(iid, i); prototype->setOpObject(InterfacePrototypeValue::IndexGetter, getter); } else if (method.isIndexSetter()) { AttributeSetterValue* setter = new AttributeSetterValue(iid, i); prototype->setOpObject(InterfacePrototypeValue::IndexSetter, setter); } else if (method.isNameGetter()) { AttributeGetterValue* getter = new AttributeGetterValue(iid, i); prototype->setOpObject(InterfacePrototypeValue::NameGetter, getter); } else if (method.isNameSetter()) { AttributeSetterValue* setter = new AttributeSetterValue(iid, i); prototype->setOpObject(InterfacePrototypeValue::NameSetter, setter); } #endif } else { // method is an attribute AttributeValue* attribute = new AttributeValue(iid.c_str()); if (method.isGetter()) { attribute->addGetter(i); } else { attribute->addSetter(i); } prototype->put(method.getName(), attribute); } } } if (interface.getQualifiedSuperName() == "") { prototype->setPrototype(getGlobal()->get("InterfaceStore")->getPrototype()->getPrototype()); } else { Reflect::Interface super = es::getInterface(interface.getQualifiedSuperName().c_str()); prototype->setPrototype(getGlobal()->get(super.getName())->get("prototype")); } // Create Interface.prototype prototype->put("constructor", object); object->put("prototype", prototype); } ~InterfaceConstructor() { delete arguments; } // Query interface for this interface. CompletionType evaluate() { if (constructor->hasInstance(getThis())) { // Constructor Object* constructor = es::getConstructor(iid.c_str()); if (!constructor) { throw getErrorInstance("TypeError"); } // TODO: Currently only the default constructor is supported std::string ciid = iid; ciid += "::Constructor"; Value* value = invoke(ciid.c_str(), 0, reinterpret_cast<InterfaceMethod**>(constructor), 0); return CompletionType(CompletionType::Return, value, ""); } else { // Cast InterfacePointerValue* self = dynamic_cast<InterfacePointerValue*>(getScopeChain()->get("object")); if (!self) { throw getErrorInstance("TypeError"); } Object* object; object = self->getObject(); if (!object || !(object = reinterpret_cast<Object*>(object->queryInterface(iid.c_str())))) { // We should throw an error in case called by a new expression. throw getErrorInstance("TypeError"); } ObjectValue* value = new InterfacePointerValue(object); value->setPrototype(prototype); return CompletionType(CompletionType::Return, value, ""); } } }; // // InterfaceStoreConstructor // class InterfaceStoreConstructor : public Code { FormalParameterList* arguments; ObjectValue* prototype; // Interface.prototype public: InterfaceStoreConstructor(ObjectValue* object) : arguments(new FormalParameterList), prototype(new ObjectValue) { ObjectValue* function = static_cast<ObjectValue*>(getGlobal()->get("Function")); arguments->add(new Identifier("iid")); object->setParameterList(arguments); object->setScope(getGlobal()); // Create Interface.prototype prototype->setPrototype(function->getPrototype()->getPrototype()); prototype->put("constructor", object); object->put("prototype", prototype); object->setPrototype(function->getPrototype()); } ~InterfaceStoreConstructor() { delete arguments; } CompletionType evaluate() { Value* value = getScopeChain()->get("iid"); if (!value->isString()) { throw getErrorInstance("TypeError"); } const char* iid = value->toString().c_str(); Reflect::Interface interface; try { interface = es::getInterface(iid); } catch (...) { throw getErrorInstance("TypeError"); } // Construct Interface Object ObjectValue* object = new ObjectValue; object->setCode(new InterfaceConstructor(object, iid)); object->setPrototype(prototype); return CompletionType(CompletionType::Return, object, ""); } }; static bool isIndexAccessor(const std::string& name) { const char* ptr = name.c_str(); bool hex = false; if (strncasecmp(ptr, "0x", 2) == 0) { ptr += 2; hex = true; } while(*ptr) { if (hex) { if (!isxdigit(*ptr)) { return false; } } else { if (!isdigit(*ptr)) { return false; } } ptr++; } return true; } Value* InterfacePointerValue::get(const std::string& name) { InterfacePrototypeValue* proto = static_cast<InterfacePrototypeValue*>(prototype); AttributeGetterValue* getter; if (hasProperty(name)) { return ObjectValue::get(name); } else if ((getter = static_cast<AttributeGetterValue*>(proto->getOpObject(InterfacePrototypeValue::IndexGetter))) && isIndexAccessor(name)) { return getter->get(this, name); } else if ((getter = static_cast<AttributeGetterValue*>(proto->getOpObject(InterfacePrototypeValue::NameGetter)))) { return getter->get(this, name); } else { return ObjectValue::get(name); } } void InterfacePointerValue::put(const std::string& name, Value* value, int attributes) { InterfacePrototypeValue* proto = static_cast<InterfacePrototypeValue*>(prototype); AttributeSetterValue* setter; if (!canPut(name)) { return; } if (hasProperty(name)) { ObjectValue::put(name, value, attributes); } else if ((setter = static_cast<AttributeSetterValue*>(proto->getOpObject(InterfacePrototypeValue::IndexSetter))) && isIndexAccessor(name)) { setter->put(this, name, value); } else if ((setter = static_cast<AttributeSetterValue*>(proto->getOpObject(InterfacePrototypeValue::NameSetter)))) { setter->put(this, name, value); } else { ObjectValue::put(name, value, attributes); } } ObjectValue* constructInterfaceObject() { ObjectValue* object = new ObjectValue; object->setCode(new InterfaceStoreConstructor(object)); return object; } ObjectValue* constructSystemObject(void* system) { for (es::InterfaceData* data = es::interfaceData; data->iid; ++data) { // Construct Default Interface Object Reflect::Interface interface = es::getInterface(data->iid()); PRINTF("%s\n", interface.getName().c_str()); ObjectValue* object = new ObjectValue; object->setCode(new InterfaceConstructor(object, interface.getQualifiedName())); object->setPrototype(getGlobal()->get("InterfaceStore")->getPrototype()); getGlobal()->put(interface.getName(), object); } System()->addRef(); ObjectValue* object = new InterfacePointerValue(System()); object->setPrototype(getGlobal()->get("CurrentProcess")->get("prototype")); return object; }
LambdaLord/es-operating-system
esjs/src/interface.cpp
C++
apache-2.0
28,073
/* Copyright IBM Corp. 2016 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 main import ( "fmt" "testing" "github.com/hyperledger/fabric/core/chaincode/shim" ex02 "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02" ) // chaincode_example02's hash is used here and must be updated if the example is changed var example02Url = "github.com/hyperledger/fabric/core/example/chaincode/chaincode_example02" // chaincode_example05 looks like it wanted to return a JSON response to Query() // it doesn't actually do this though, it just returns the sum value func jsonResponse(name string, value string) string { return fmt.Sprintf("jsonResponse = \"{\"Name\":\"%v\",\"Value\":\"%v\"}", name, value) } func checkInit(t *testing.T, stub *shim.MockStub, args []string) { _, err := stub.MockInit("1", "init", args) if err != nil { fmt.Println("Init failed", err) t.FailNow() } } func checkState(t *testing.T, stub *shim.MockStub, name string, expect string) { bytes := stub.State[name] if bytes == nil { fmt.Println("State", name, "failed to get value") t.FailNow() } if string(bytes) != expect { fmt.Println("State value", name, "was not", expect, "as expected") t.FailNow() } } func checkQuery(t *testing.T, stub *shim.MockStub, args []string, expect string) { bytes, err := stub.MockQuery("query", args) if err != nil { fmt.Println("Query", args, "failed", err) t.FailNow() } if bytes == nil { fmt.Println("Query", args, "failed to get result") t.FailNow() } if string(bytes) != expect { fmt.Println("Query result ", string(bytes), "was not", expect, "as expected") t.FailNow() } } func checkInvoke(t *testing.T, stub *shim.MockStub, args []string) { _, err := stub.MockInvoke("1", "query", args) if err != nil { fmt.Println("Invoke", args, "failed", err) t.FailNow() } } func TestExample04_Init(t *testing.T) { scc := new(SimpleChaincode) stub := shim.NewMockStub("ex05", scc) // Init A=123 B=234 checkInit(t, stub, []string{"sumStoreName", "432"}) checkState(t, stub, "sumStoreName", "432") } func TestExample04_Query(t *testing.T) { scc := new(SimpleChaincode) stub := shim.NewMockStub("ex05", scc) ccEx2 := new(ex02.SimpleChaincode) stubEx2 := shim.NewMockStub("ex02", ccEx2) checkInit(t, stubEx2, []string{"a", "111", "b", "222"}) stub.MockPeerChaincode(example02Url, stubEx2) checkInit(t, stub, []string{"sumStoreName", "0"}) // a + b = 111 + 222 = 333 checkQuery(t, stub, []string{example02Url, "sumStoreName"}, "333") // example05 doesn't return JSON? } func TestExample04_Invoke(t *testing.T) { scc := new(SimpleChaincode) stub := shim.NewMockStub("ex05", scc) ccEx2 := new(ex02.SimpleChaincode) stubEx2 := shim.NewMockStub("ex02", ccEx2) checkInit(t, stubEx2, []string{"a", "222", "b", "333"}) stub.MockPeerChaincode(example02Url, stubEx2) checkInit(t, stub, []string{"sumStoreName", "0"}) // a + b = 222 + 333 = 555 checkInvoke(t, stub, []string{example02Url, "sumStoreName"}) checkQuery(t, stub, []string{example02Url, "sumStoreName"}, "555") // example05 doesn't return JSON? checkQuery(t, stubEx2, []string{"a"}, "222") checkQuery(t, stubEx2, []string{"b"}, "333") // update A-=10 and B+=10 checkInvoke(t, stubEx2, []string{"a", "b", "10"}) // a + b = 212 + 343 = 555 checkInvoke(t, stub, []string{example02Url, "sumStoreName"}) checkQuery(t, stub, []string{example02Url, "sumStoreName"}, "555") // example05 doesn't return JSON? checkQuery(t, stubEx2, []string{"a"}, "212") checkQuery(t, stubEx2, []string{"b"}, "343") }
narayan2903/cc-commercialpaper
vendor/github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example05/chaincode_example05_test.go
GO
apache-2.0
4,062
/* * Copyright 2013 The Netty Project * * The Netty Project 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 io.netty.buffer; import io.netty.util.Recycler; import io.netty.util.internal.PlatformDependent; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileChannel; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; final class PooledUnsafeDirectByteBuf extends PooledByteBuf<ByteBuffer> { private static final Recycler<PooledUnsafeDirectByteBuf> RECYCLER = new Recycler<PooledUnsafeDirectByteBuf>() { @Override protected PooledUnsafeDirectByteBuf newObject(Handle<PooledUnsafeDirectByteBuf> handle) { return new PooledUnsafeDirectByteBuf(handle, 0); } }; static PooledUnsafeDirectByteBuf newInstance(int maxCapacity) { PooledUnsafeDirectByteBuf buf = RECYCLER.get(); buf.reuse(maxCapacity); return buf; } private long memoryAddress; private PooledUnsafeDirectByteBuf(Recycler.Handle<PooledUnsafeDirectByteBuf> recyclerHandle, int maxCapacity) { super(recyclerHandle, maxCapacity); } @Override void init(PoolChunk<ByteBuffer> chunk, long handle, int offset, int length, int maxLength, PoolThreadCache cache) { super.init(chunk, handle, offset, length, maxLength, cache); initMemoryAddress(); } @Override void initUnpooled(PoolChunk<ByteBuffer> chunk, int length) { super.initUnpooled(chunk, length); initMemoryAddress(); } private void initMemoryAddress() { memoryAddress = PlatformDependent.directBufferAddress(memory) + offset; } @Override protected ByteBuffer newInternalNioBuffer(ByteBuffer memory) { return memory.duplicate(); } @Override public boolean isDirect() { return true; } @Override protected byte _getByte(int index) { return UnsafeByteBufUtil.getByte(addr(index)); } @Override protected short _getShort(int index) { return UnsafeByteBufUtil.getShort(addr(index)); } @Override protected short _getShortLE(int index) { return UnsafeByteBufUtil.getShortLE(addr(index)); } @Override protected int _getUnsignedMedium(int index) { return UnsafeByteBufUtil.getUnsignedMedium(addr(index)); } @Override protected int _getUnsignedMediumLE(int index) { return UnsafeByteBufUtil.getUnsignedMediumLE(addr(index)); } @Override protected int _getInt(int index) { return UnsafeByteBufUtil.getInt(addr(index)); } @Override protected int _getIntLE(int index) { return UnsafeByteBufUtil.getIntLE(addr(index)); } @Override protected long _getLong(int index) { return UnsafeByteBufUtil.getLong(addr(index)); } @Override protected long _getLongLE(int index) { return UnsafeByteBufUtil.getLongLE(addr(index)); } @Override public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { UnsafeByteBufUtil.getBytes(this, addr(index), index, dst, dstIndex, length); return this; } @Override public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { UnsafeByteBufUtil.getBytes(this, addr(index), index, dst, dstIndex, length); return this; } @Override public ByteBuf getBytes(int index, ByteBuffer dst) { UnsafeByteBufUtil.getBytes(this, addr(index), index, dst); return this; } @Override public ByteBuf readBytes(ByteBuffer dst) { int length = dst.remaining(); checkReadableBytes(length); getBytes(readerIndex, dst); readerIndex += length; return this; } @Override public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { UnsafeByteBufUtil.getBytes(this, addr(index), index, out, length); return this; } @Override public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { return getBytes(index, out, length, false); } private int getBytes(int index, GatheringByteChannel out, int length, boolean internal) throws IOException { checkIndex(index, length); if (length == 0) { return 0; } ByteBuffer tmpBuf; if (internal) { tmpBuf = internalNioBuffer(); } else { tmpBuf = memory.duplicate(); } index = idx(index); tmpBuf.clear().position(index).limit(index + length); return out.write(tmpBuf); } @Override public int getBytes(int index, FileChannel out, long position, int length) throws IOException { return getBytes(index, out, position, length, false); } private int getBytes(int index, FileChannel out, long position, int length, boolean internal) throws IOException { checkIndex(index, length); if (length == 0) { return 0; } ByteBuffer tmpBuf = internal ? internalNioBuffer() : memory.duplicate(); index = idx(index); tmpBuf.clear().position(index).limit(index + length); return out.write(tmpBuf, position); } @Override public int readBytes(GatheringByteChannel out, int length) throws IOException { checkReadableBytes(length); int readBytes = getBytes(readerIndex, out, length, true); readerIndex += readBytes; return readBytes; } @Override public int readBytes(FileChannel out, long position, int length) throws IOException { checkReadableBytes(length); int readBytes = getBytes(readerIndex, out, position, length, true); readerIndex += readBytes; return readBytes; } @Override protected void _setByte(int index, int value) { UnsafeByteBufUtil.setByte(addr(index), (byte) value); } @Override protected void _setShort(int index, int value) { UnsafeByteBufUtil.setShort(addr(index), value); } @Override protected void _setShortLE(int index, int value) { UnsafeByteBufUtil.setShortLE(addr(index), value); } @Override protected void _setMedium(int index, int value) { UnsafeByteBufUtil.setMedium(addr(index), value); } @Override protected void _setMediumLE(int index, int value) { UnsafeByteBufUtil.setMediumLE(addr(index), value); } @Override protected void _setInt(int index, int value) { UnsafeByteBufUtil.setInt(addr(index), value); } @Override protected void _setIntLE(int index, int value) { UnsafeByteBufUtil.setIntLE(addr(index), value); } @Override protected void _setLong(int index, long value) { UnsafeByteBufUtil.setLong(addr(index), value); } @Override protected void _setLongLE(int index, long value) { UnsafeByteBufUtil.setLongLE(addr(index), value); } @Override public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { UnsafeByteBufUtil.setBytes(this, addr(index), index, src, srcIndex, length); return this; } @Override public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { UnsafeByteBufUtil.setBytes(this, addr(index), index, src, srcIndex, length); return this; } @Override public ByteBuf setBytes(int index, ByteBuffer src) { UnsafeByteBufUtil.setBytes(this, addr(index), index, src); return this; } @Override public int setBytes(int index, InputStream in, int length) throws IOException { return UnsafeByteBufUtil.setBytes(this, addr(index), index, in, length); } @Override public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { checkIndex(index, length); ByteBuffer tmpBuf = internalNioBuffer(); index = idx(index); tmpBuf.clear().position(index).limit(index + length); try { return in.read(tmpBuf); } catch (ClosedChannelException ignored) { return -1; } } @Override public int setBytes(int index, FileChannel in, long position, int length) throws IOException { checkIndex(index, length); ByteBuffer tmpBuf = internalNioBuffer(); index = idx(index); tmpBuf.clear().position(index).limit(index + length); try { return in.read(tmpBuf, position); } catch (ClosedChannelException ignored) { return -1; } } @Override public ByteBuf copy(int index, int length) { return UnsafeByteBufUtil.copy(this, addr(index), index, length); } @Override public int nioBufferCount() { return 1; } @Override public ByteBuffer[] nioBuffers(int index, int length) { return new ByteBuffer[] { nioBuffer(index, length) }; } @Override public ByteBuffer nioBuffer(int index, int length) { checkIndex(index, length); index = idx(index); return ((ByteBuffer) memory.duplicate().position(index).limit(index + length)).slice(); } @Override public ByteBuffer internalNioBuffer(int index, int length) { checkIndex(index, length); index = idx(index); return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); } @Override public boolean hasArray() { return false; } @Override public byte[] array() { throw new UnsupportedOperationException("direct buffer"); } @Override public int arrayOffset() { throw new UnsupportedOperationException("direct buffer"); } @Override public boolean hasMemoryAddress() { return true; } @Override public long memoryAddress() { ensureAccessible(); return memoryAddress; } private long addr(int index) { return memoryAddress + index; } @Override protected SwappedByteBuf newSwappedByteBuf() { if (PlatformDependent.isUnaligned()) { // Only use if unaligned access is supported otherwise there is no gain. return new UnsafeDirectSwappedByteBuf(this); } return super.newSwappedByteBuf(); } @Override public ByteBuf setZero(int index, int length) { UnsafeByteBufUtil.setZero(this, addr(index), index, length); return this; } @Override public ByteBuf writeZero(int length) { ensureWritable(length); int wIndex = writerIndex; setZero(wIndex, length); writerIndex = wIndex + length; return this; } }
mcobrien/netty
buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java
Java
apache-2.0
11,458
package org.keycloak.testsuite.broker; import org.keycloak.admin.client.resource.IdentityProviderResource; import org.keycloak.admin.client.resource.RealmResource; import org.keycloak.admin.client.resource.UserResource; import com.google.common.collect.ImmutableMap; import org.keycloak.broker.saml.mappers.AttributeToRoleMapper; import org.keycloak.broker.saml.mappers.UserAttributeMapper; import org.keycloak.dom.saml.v2.assertion.AssertionType; import org.keycloak.dom.saml.v2.assertion.AttributeStatementType; import org.keycloak.dom.saml.v2.assertion.AttributeType; import org.keycloak.dom.saml.v2.assertion.StatementAbstractType; import org.keycloak.dom.saml.v2.protocol.AuthnRequestType; import org.keycloak.dom.saml.v2.protocol.ResponseType; import org.keycloak.models.IdentityProviderMapperModel; import org.keycloak.models.IdentityProviderMapperSyncMode; import org.keycloak.representations.idm.IdentityProviderMapperRepresentation; import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.saml.common.constants.JBossSAMLURIConstants; import org.keycloak.saml.common.exceptions.ConfigurationException; import org.keycloak.saml.common.exceptions.ParsingException; import org.keycloak.saml.common.exceptions.ProcessingException; import org.keycloak.saml.processing.api.saml.v2.request.SAML2Request; import org.keycloak.saml.processing.core.parsers.saml.protocol.SAMLProtocolQNames; import org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder; import org.keycloak.testsuite.saml.AbstractSamlTest; import org.keycloak.testsuite.util.SamlClient; import org.keycloak.testsuite.util.SamlClient.Binding; import org.keycloak.testsuite.util.SamlClientBuilder; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.ws.rs.core.Response; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import static org.keycloak.testsuite.saml.RoleMapperTest.ROLE_ATTRIBUTE_NAME; import static org.keycloak.testsuite.util.Matchers.isSamlResponse; import static org.keycloak.testsuite.util.Matchers.statusCodeIsHC; import static org.keycloak.testsuite.util.SamlStreams.assertionsUnencrypted; import static org.keycloak.testsuite.util.SamlStreams.attributeStatements; import static org.keycloak.testsuite.util.SamlStreams.attributesUnecrypted; import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot; import static org.keycloak.testsuite.broker.BrokerTestTools.getProviderRoot; /** * Final class as it's not intended to be overriden. Feel free to remove "final" if you really know what you are doing. */ public final class KcSamlBrokerTest extends AbstractAdvancedBrokerTest { @Override protected BrokerConfiguration getBrokerConfiguration() { return KcSamlBrokerConfiguration.INSTANCE; } private static final String EMPTY_ATTRIBUTE_NAME = "empty.attribute.name"; @Override protected Iterable<IdentityProviderMapperRepresentation> createIdentityProviderMappers(IdentityProviderMapperSyncMode syncMode) { IdentityProviderMapperRepresentation attrMapper1 = new IdentityProviderMapperRepresentation(); attrMapper1.setName("manager-role-mapper"); attrMapper1.setIdentityProviderMapper(AttributeToRoleMapper.PROVIDER_ID); attrMapper1.setConfig(ImmutableMap.<String,String>builder() .put(IdentityProviderMapperModel.SYNC_MODE, syncMode.toString()) .put(UserAttributeMapper.ATTRIBUTE_NAME, "Role") .put(ATTRIBUTE_VALUE, ROLE_MANAGER) .put("role", ROLE_MANAGER) .build()); IdentityProviderMapperRepresentation attrMapper2 = new IdentityProviderMapperRepresentation(); attrMapper2.setName("user-role-mapper"); attrMapper2.setIdentityProviderMapper(AttributeToRoleMapper.PROVIDER_ID); attrMapper2.setConfig(ImmutableMap.<String,String>builder() .put(IdentityProviderMapperModel.SYNC_MODE, syncMode.toString()) .put(UserAttributeMapper.ATTRIBUTE_NAME, "Role") .put(ATTRIBUTE_VALUE, ROLE_USER) .put("role", ROLE_USER) .build()); IdentityProviderMapperRepresentation attrMapper3 = new IdentityProviderMapperRepresentation(); attrMapper3.setName("friendly-mapper"); attrMapper3.setIdentityProviderMapper(AttributeToRoleMapper.PROVIDER_ID); attrMapper3.setConfig(ImmutableMap.<String,String>builder() .put(IdentityProviderMapperModel.SYNC_MODE, syncMode.toString()) .put(UserAttributeMapper.ATTRIBUTE_FRIENDLY_NAME, KcSamlBrokerConfiguration.ATTRIBUTE_TO_MAP_FRIENDLY_NAME) .put(ATTRIBUTE_VALUE, ROLE_FRIENDLY_MANAGER) .put("role", ROLE_FRIENDLY_MANAGER) .build()); IdentityProviderMapperRepresentation attrMapper4 = new IdentityProviderMapperRepresentation(); attrMapper4.setName("user-role-dot-guide-mapper"); attrMapper4.setIdentityProviderMapper(AttributeToRoleMapper.PROVIDER_ID); attrMapper4.setConfig(ImmutableMap.<String,String>builder() .put(IdentityProviderMapperModel.SYNC_MODE, syncMode.toString()) .put(UserAttributeMapper.ATTRIBUTE_NAME, "Role") .put(ATTRIBUTE_VALUE, ROLE_USER_DOT_GUIDE) .put("role", ROLE_USER_DOT_GUIDE) .build()); IdentityProviderMapperRepresentation attrMapper5 = new IdentityProviderMapperRepresentation(); attrMapper5.setName("empty-attribute-to-role-mapper"); attrMapper5.setIdentityProviderMapper(AttributeToRoleMapper.PROVIDER_ID); attrMapper5.setConfig(ImmutableMap.<String,String>builder() .put(IdentityProviderMapperModel.SYNC_MODE, syncMode.toString()) .put(UserAttributeMapper.ATTRIBUTE_NAME, EMPTY_ATTRIBUTE_NAME) .put(ATTRIBUTE_VALUE, "") .put("role", EMPTY_ATTRIBUTE_ROLE) .build()); return Arrays.asList(attrMapper1, attrMapper2, attrMapper3, attrMapper4, attrMapper5 ); } protected void createAdditionalMapperWithCustomSyncMode(IdentityProviderMapperSyncMode syncMode) { IdentityProviderMapperRepresentation friendlyManagerMapper = new IdentityProviderMapperRepresentation(); friendlyManagerMapper.setName("friendly-manager-role-mapper"); friendlyManagerMapper.setIdentityProviderMapper(AttributeToRoleMapper.PROVIDER_ID); friendlyManagerMapper.setConfig(ImmutableMap.<String,String>builder() .put(IdentityProviderMapperModel.SYNC_MODE, syncMode.toString()) .put(UserAttributeMapper.ATTRIBUTE_NAME, "Role") .put(ATTRIBUTE_VALUE, ROLE_FRIENDLY_MANAGER) .put("role", ROLE_FRIENDLY_MANAGER) .build()); friendlyManagerMapper.setIdentityProviderAlias(bc.getIDPAlias()); RealmResource realm = adminClient.realm(bc.consumerRealmName()); IdentityProviderResource idpResource = realm.identityProviders().get(bc.getIDPAlias()); idpResource.addMapper(friendlyManagerMapper).close(); } @Test public void mapperUpdatesRolesOnEveryLogInForLegacyMode() { createRolesForRealm(bc.providerRealmName()); createRolesForRealm(bc.consumerRealmName()); createRoleMappersForConsumerRealm(IdentityProviderMapperSyncMode.FORCE); RoleRepresentation managerRole = adminClient.realm(bc.providerRealmName()).roles().get(ROLE_MANAGER).toRepresentation(); RoleRepresentation friendlyManagerRole = adminClient.realm(bc.providerRealmName()).roles().get(ROLE_FRIENDLY_MANAGER).toRepresentation(); RoleRepresentation userRole = adminClient.realm(bc.providerRealmName()).roles().get(ROLE_USER).toRepresentation(); UserResource userResource = adminClient.realm(bc.providerRealmName()).users().get(userId); userResource.roles().realmLevel().add(Collections.singletonList(managerRole)); logInAsUserInIDPForFirstTime(); Set<String> currentRoles = userResource.roles().realmLevel().listAll().stream() .map(RoleRepresentation::getName) .collect(Collectors.toSet()); assertThat(currentRoles, hasItems(ROLE_MANAGER)); assertThat(currentRoles, not(hasItems(ROLE_USER, ROLE_FRIENDLY_MANAGER))); logoutFromRealm(getConsumerRoot(), bc.consumerRealmName()); userResource.roles().realmLevel().add(Collections.singletonList(userRole)); userResource.roles().realmLevel().add(Collections.singletonList(friendlyManagerRole)); logInAsUserInIDP(); currentRoles = userResource.roles().realmLevel().listAll().stream() .map(RoleRepresentation::getName) .collect(Collectors.toSet()); assertThat(currentRoles, hasItems(ROLE_MANAGER, ROLE_USER, ROLE_FRIENDLY_MANAGER)); logoutFromRealm(getConsumerRoot(), bc.consumerRealmName()); userResource.roles().realmLevel().remove(Collections.singletonList(friendlyManagerRole)); logInAsUserInIDP(); currentRoles = userResource.roles().realmLevel().listAll().stream() .map(RoleRepresentation::getName) .collect(Collectors.toSet()); assertThat(currentRoles, hasItems(ROLE_MANAGER, ROLE_USER)); assertThat(currentRoles, not(hasItems(ROLE_FRIENDLY_MANAGER))); logoutFromRealm(getProviderRoot(), bc.providerRealmName()); logoutFromRealm(getConsumerRoot(), bc.consumerRealmName()); } @Test public void roleWithDots() { createRolesForRealm(bc.providerRealmName()); createRolesForRealm(bc.consumerRealmName()); createRoleMappersForConsumerRealm(); RoleRepresentation managerRole = adminClient.realm(bc.providerRealmName()).roles().get(ROLE_MANAGER).toRepresentation(); RoleRepresentation userRole = adminClient.realm(bc.providerRealmName()).roles().get(ROLE_USER).toRepresentation(); RoleRepresentation userRoleDotGuide = adminClient.realm(bc.providerRealmName()).roles().get(ROLE_USER_DOT_GUIDE).toRepresentation(); UserResource userResourceProv = adminClient.realm(bc.providerRealmName()).users().get(userId); userResourceProv.roles().realmLevel().add(Collections.singletonList(managerRole)); logInAsUserInIDPForFirstTime(); String consUserId = adminClient.realm(bc.consumerRealmName()).users().search(bc.getUserLogin()).iterator().next().getId(); UserResource userResourceCons = adminClient.realm(bc.consumerRealmName()).users().get(consUserId); Set<String> currentRoles = userResourceCons.roles().realmLevel().listAll().stream() .map(RoleRepresentation::getName) .collect(Collectors.toSet()); assertThat(currentRoles, hasItems(ROLE_MANAGER)); assertThat(currentRoles, not(hasItems(ROLE_USER, ROLE_FRIENDLY_MANAGER, ROLE_USER_DOT_GUIDE))); logoutFromRealm(getConsumerRoot(), bc.consumerRealmName()); UserRepresentation urp = userResourceProv.toRepresentation(); urp.setAttributes(new HashMap<>()); urp.getAttributes().put(KcSamlBrokerConfiguration.ATTRIBUTE_TO_MAP_FRIENDLY_NAME, Collections.singletonList(ROLE_FRIENDLY_MANAGER)); userResourceProv.update(urp); userResourceProv.roles().realmLevel().add(Collections.singletonList(userRole)); userResourceProv.roles().realmLevel().add(Collections.singletonList(userRoleDotGuide)); logInAsUserInIDP(); currentRoles = userResourceCons.roles().realmLevel().listAll().stream() .map(RoleRepresentation::getName) .collect(Collectors.toSet()); assertThat(currentRoles, hasItems(ROLE_MANAGER, ROLE_USER, ROLE_USER_DOT_GUIDE, ROLE_FRIENDLY_MANAGER)); logoutFromRealm(getConsumerRoot(), bc.consumerRealmName()); urp = userResourceProv.toRepresentation(); urp.setAttributes(new HashMap<>()); userResourceProv.update(urp); logInAsUserInIDP(); currentRoles = userResourceCons.roles().realmLevel().listAll().stream() .map(RoleRepresentation::getName) .collect(Collectors.toSet()); assertThat(currentRoles, hasItems(ROLE_MANAGER, ROLE_USER, ROLE_USER_DOT_GUIDE)); assertThat(currentRoles, not(hasItems(ROLE_FRIENDLY_MANAGER))); logoutFromRealm(getProviderRoot(), bc.providerRealmName()); logoutFromRealm(getConsumerRoot(), bc.consumerRealmName()); } // KEYCLOAK-6106 @Test public void loginClientWithDotsInName() throws Exception { AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null); Document doc = SAML2Request.convert(loginRep); SAMLDocumentHolder samlResponse = new SamlClientBuilder() .authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build() // Request to consumer IdP .login().idp(bc.getIDPAlias()).build() .processSamlResponse(Binding.POST) // AuthnRequest to producer IdP .targetAttributeSamlRequest() .build() .login().user(bc.getUserLogin(), bc.getUserPassword()).build() .processSamlResponse(Binding.POST) // Response from producer IdP .build() // first-broker flow .updateProfile().firstName("a").lastName("b").email(bc.getUserEmail()).username(bc.getUserLogin()).build() .followOneRedirect() .getSamlResponse(Binding.POST); // Response from consumer IdP Assert.assertThat(samlResponse, Matchers.notNullValue()); Assert.assertThat(samlResponse.getSamlObject(), isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS)); } @Test public void emptyAttributeToRoleMapperTest() throws ParsingException, ConfigurationException, ProcessingException { createRolesForRealm(bc.consumerRealmName()); createRoleMappersForConsumerRealm(); AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null); Document doc = SAML2Request.convert(loginRep); SAMLDocumentHolder samlResponse = new SamlClientBuilder() .authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build() // Request to consumer IdP .login().idp(bc.getIDPAlias()).build() .processSamlResponse(Binding.POST) // AuthnRequest to producer IdP .targetAttributeSamlRequest() .build() .login().user(bc.getUserLogin(), bc.getUserPassword()).build() .processSamlResponse(Binding.POST) // Response from producer IdP .transformObject(ob -> { assertThat(ob, org.keycloak.testsuite.util.Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS)); ResponseType resp = (ResponseType) ob; Set<StatementAbstractType> statements = resp.getAssertions().get(0).getAssertion().getStatements(); AttributeStatementType attributeType = (AttributeStatementType) statements.stream() .filter(statement -> statement instanceof AttributeStatementType) .findFirst().orElse(new AttributeStatementType()); AttributeType attr = new AttributeType(EMPTY_ATTRIBUTE_NAME); attr.addAttributeValue(null); attributeType.addAttribute(new AttributeStatementType.ASTChoiceType(attr)); resp.getAssertions().get(0).getAssertion().addStatement(attributeType); return ob; }) .build() // first-broker flow .updateProfile().firstName("a").lastName("b").email(bc.getUserEmail()).username(bc.getUserLogin()).build() .followOneRedirect() .getSamlResponse(Binding.POST); // Response from consumer IdP Assert.assertThat(samlResponse, Matchers.notNullValue()); Assert.assertThat(samlResponse.getSamlObject(), isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS)); Stream<AssertionType> assertionTypeStream = assertionsUnencrypted(samlResponse.getSamlObject()); Stream<AttributeType> attributeStatementTypeStream = attributesUnecrypted(attributeStatements(assertionTypeStream)); Set<String> attributeValues = attributeStatementTypeStream .filter(a -> a.getName().equals(ROLE_ATTRIBUTE_NAME)) .flatMap(a -> a.getAttributeValue().stream()) .map(Object::toString) .collect(Collectors.toSet()); assertThat(attributeValues, hasItems(EMPTY_ATTRIBUTE_ROLE)); } // KEYCLOAK-17935 @Test public void loginInResponseToMismatch() throws Exception { AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null); Document doc = SAML2Request.convert(loginRep); new SamlClientBuilder() .authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build() // Request to consumer IdP .login().idp(bc.getIDPAlias()).build() .processSamlResponse(Binding.POST) // AuthnRequest to producer IdP .targetAttributeSamlRequest() .build() .login().user(bc.getUserLogin(), bc.getUserPassword()).build() .processSamlResponse(Binding.POST) // Response from producer IdP .transformDocument(this::tamperInResponseTo) .build() .execute(hr -> assertThat(hr, statusCodeIsHC(Response.Status.BAD_REQUEST))); // Response from consumer IdP } // KEYCLOAK-17935 @Test public void loginInResponseToMissing() throws Exception { AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null); Document doc = SAML2Request.convert(loginRep); new SamlClientBuilder() .authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build() // Request to consumer IdP .login().idp(bc.getIDPAlias()).build() .processSamlResponse(Binding.POST) // AuthnRequest to producer IdP .targetAttributeSamlRequest() .build() .login().user(bc.getUserLogin(), bc.getUserPassword()).build() .processSamlResponse(Binding.POST) // Response from producer IdP .transformDocument(this::removeInResponseTo) .build() .execute(hr -> assertThat(hr, statusCodeIsHC(Response.Status.BAD_REQUEST))); // Response from consumer IdP } // KEYCLOAK-17935 @Test public void loginInResponseToEmpty() throws Exception { AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null); Document doc = SAML2Request.convert(loginRep); new SamlClientBuilder() .authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build() // Request to consumer IdP .login().idp(bc.getIDPAlias()).build() .processSamlResponse(Binding.POST) // AuthnRequest to producer IdP .targetAttributeSamlRequest() .build() .login().user(bc.getUserLogin(), bc.getUserPassword()).build() .processSamlResponse(Binding.POST) // Response from producer IdP .transformDocument(this::clearInResponseTo) .build() .execute(hr -> assertThat(hr, statusCodeIsHC(Response.Status.BAD_REQUEST))); // Response from consumer IdP } private Document tamperInResponseTo(Document orig) { Element rootElement = orig.getDocumentElement(); rootElement.setAttribute(SAMLProtocolQNames.ATTR_IN_RESPONSE_TO.getQName().getLocalPart(), "TAMPERED_" + rootElement.getAttribute("InResponseTo")); return orig; } private Document removeInResponseTo(Document orig) { Element rootElement = orig.getDocumentElement(); rootElement.removeAttribute(SAMLProtocolQNames.ATTR_IN_RESPONSE_TO.getQName().getLocalPart()); return orig; } private Document clearInResponseTo(Document orig) { Element rootElement = orig.getDocumentElement(); rootElement.setAttribute(SAMLProtocolQNames.ATTR_IN_RESPONSE_TO.getQName().getLocalPart(), ""); return orig; } }
keycloak/keycloak
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerTest.java
Java
apache-2.0
21,270
/** * 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.hadoop.ha; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.HadoopIllegalArgumentException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.util.ZKUtil.ZKAuthInfo; import org.apache.hadoop.util.StringUtils; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher.Event; import org.apache.zookeeper.ZKUtil; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.AsyncCallback.*; import org.apache.zookeeper.data.Stat; import org.apache.zookeeper.KeeperException.Code; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; /** * * This class implements a simple library to perform leader election on top of * Apache Zookeeper. Using Zookeeper as a coordination service, leader election * can be performed by atomically creating an ephemeral lock file (znode) on * Zookeeper. The service instance that successfully creates the znode becomes * active and the rest become standbys. <br/> * This election mechanism is only efficient for small number of election * candidates (order of 10's) because contention on single znode by a large * number of candidates can result in Zookeeper overload. <br/> * The elector does not guarantee fencing (protection of shared resources) among * service instances. After it has notified an instance about becoming a leader, * then that instance must ensure that it meets the service consistency * requirements. If it cannot do so, then it is recommended to quit the * election. The application implements the {@link ActiveStandbyElectorCallback} * to interact with the elector */ @InterfaceAudience.Private @InterfaceStability.Evolving public class ActiveStandbyElector implements StatCallback, StringCallback { /** * Callback interface to interact with the ActiveStandbyElector object. <br/> * The application will be notified with a callback only on state changes * (i.e. there will never be successive calls to becomeActive without an * intermediate call to enterNeutralMode). <br/> * The callbacks will be running on Zookeeper client library threads. The * application should return from these callbacks quickly so as not to impede * Zookeeper client library performance and notifications. The app will * typically remember the state change and return from the callback. It will * then proceed with implementing actions around that state change. It is * possible to be called back again while these actions are in flight and the * app should handle this scenario. */ public interface ActiveStandbyElectorCallback { /** * This method is called when the app becomes the active leader. * If the service fails to become active, it should throw * ServiceFailedException. This will cause the elector to * sleep for a short period, then re-join the election. * * Callback implementations are expected to manage their own * timeouts (e.g. when making an RPC to a remote node). */ void becomeActive() throws ServiceFailedException; /** * This method is called when the app becomes a standby */ void becomeStandby(); /** * If the elector gets disconnected from Zookeeper and does not know about * the lock state, then it will notify the service via the enterNeutralMode * interface. The service may choose to ignore this or stop doing state * changing operations. Upon reconnection, the elector verifies the leader * status and calls back on the becomeActive and becomeStandby app * interfaces. <br/> * Zookeeper disconnects can happen due to network issues or loss of * Zookeeper quorum. Thus enterNeutralMode can be used to guard against * split-brain issues. In such situations it might be prudent to call * becomeStandby too. However, such state change operations might be * expensive and enterNeutralMode can help guard against doing that for * transient issues. */ void enterNeutralMode(); /** * If there is any fatal error (e.g. wrong ACL's, unexpected Zookeeper * errors or Zookeeper persistent unavailability) then notifyFatalError is * called to notify the app about it. */ void notifyFatalError(String errorMessage); /** * If an old active has failed, rather than exited gracefully, then * the new active may need to take some fencing actions against it * before proceeding with failover. * * @param oldActiveData the application data provided by the prior active */ void fenceOldActive(byte[] oldActiveData); } /** * Name of the lock znode used by the library. Protected for access in test * classes */ @VisibleForTesting protected static final String LOCK_FILENAME = "ActiveStandbyElectorLock"; @VisibleForTesting protected static final String BREADCRUMB_FILENAME = "ActiveBreadCrumb"; public static final Log LOG = LogFactory.getLog(ActiveStandbyElector.class); private static final int SLEEP_AFTER_FAILURE_TO_BECOME_ACTIVE = 1000; private static enum ConnectionState { DISCONNECTED, CONNECTED, TERMINATED }; static enum State { INIT, ACTIVE, STANDBY, NEUTRAL }; private State state = State.INIT; private int createRetryCount = 0; private int statRetryCount = 0; private ZooKeeper zkClient; private WatcherWithClientRef watcher; private ConnectionState zkConnectionState = ConnectionState.TERMINATED; private final ActiveStandbyElectorCallback appClient; private final String zkHostPort; private final int zkSessionTimeout; private final List<ACL> zkAcl; private final List<ZKAuthInfo> zkAuthInfo; private byte[] appData; private final String zkLockFilePath; private final String zkBreadCrumbPath; private final String znodeWorkingDir; private final int maxRetryNum; private Lock sessionReestablishLockForTests = new ReentrantLock(); private boolean wantToBeInElection; /** * Create a new ActiveStandbyElector object <br/> * The elector is created by providing to it the Zookeeper configuration, the * parent znode under which to create the znode and a reference to the * callback interface. <br/> * The parent znode name must be the same for all service instances and * different across services. <br/> * After the leader has been lost, a new leader will be elected after the * session timeout expires. Hence, the app must set this parameter based on * its needs for failure response time. The session timeout must be greater * than the Zookeeper disconnect timeout and is recommended to be 3X that * value to enable Zookeeper to retry transient disconnections. Setting a very * short session timeout may result in frequent transitions between active and * standby states during issues like network outages/GS pauses. * * @param zookeeperHostPorts * ZooKeeper hostPort for all ZooKeeper servers * @param zookeeperSessionTimeout * ZooKeeper session timeout * @param parentZnodeName * znode under which to create the lock * @param acl * ZooKeeper ACL's * @param authInfo a list of authentication credentials to add to the * ZK connection * @param app * reference to callback interface object * @throws IOException * @throws HadoopIllegalArgumentException */ public ActiveStandbyElector(String zookeeperHostPorts, int zookeeperSessionTimeout, String parentZnodeName, List<ACL> acl, List<ZKAuthInfo> authInfo, ActiveStandbyElectorCallback app, int maxRetryNum) throws IOException, HadoopIllegalArgumentException, KeeperException { if (app == null || acl == null || parentZnodeName == null || zookeeperHostPorts == null || zookeeperSessionTimeout <= 0) { throw new HadoopIllegalArgumentException("Invalid argument"); } zkHostPort = zookeeperHostPorts; zkSessionTimeout = zookeeperSessionTimeout; zkAcl = acl; zkAuthInfo = authInfo; appClient = app; znodeWorkingDir = parentZnodeName; zkLockFilePath = znodeWorkingDir + "/" + LOCK_FILENAME; zkBreadCrumbPath = znodeWorkingDir + "/" + BREADCRUMB_FILENAME; this.maxRetryNum = maxRetryNum; // createConnection for future API calls createConnection(); } /** * To participate in election, the app will call joinElection. The result will * be notified by a callback on either the becomeActive or becomeStandby app * interfaces. <br/> * After this the elector will automatically monitor the leader status and * perform re-election if necessary<br/> * The app could potentially start off in standby mode and ignore the * becomeStandby call. * * @param data * to be set by the app. non-null data must be set. * @throws HadoopIllegalArgumentException * if valid data is not supplied */ public synchronized void joinElection(byte[] data) throws HadoopIllegalArgumentException { if (data == null) { throw new HadoopIllegalArgumentException("data cannot be null"); } if (wantToBeInElection) { LOG.info("Already in election. Not re-connecting."); return; } appData = new byte[data.length]; System.arraycopy(data, 0, appData, 0, data.length); LOG.debug("Attempting active election for " + this); joinElectionInternal(); } /** * @return true if the configured parent znode exists */ public synchronized boolean parentZNodeExists() throws IOException, InterruptedException { Preconditions.checkState(zkClient != null); try { return zkClient.exists(znodeWorkingDir, false) != null; } catch (KeeperException e) { throw new IOException("Couldn't determine existence of znode '" + znodeWorkingDir + "'", e); } } /** * Utility function to ensure that the configured base znode exists. * This recursively creates the znode as well as all of its parents. */ public synchronized void ensureParentZNode() throws IOException, InterruptedException { Preconditions.checkState(!wantToBeInElection, "ensureParentZNode() may not be called while in the election"); String pathParts[] = znodeWorkingDir.split("/"); Preconditions.checkArgument(pathParts.length >= 1 && pathParts[0].isEmpty(), "Invalid path: %s", znodeWorkingDir); StringBuilder sb = new StringBuilder(); for (int i = 1; i < pathParts.length; i++) { sb.append("/").append(pathParts[i]); String prefixPath = sb.toString(); LOG.debug("Ensuring existence of " + prefixPath); try { createWithRetries(prefixPath, new byte[]{}, zkAcl, CreateMode.PERSISTENT); } catch (KeeperException e) { if (isNodeExists(e.code())) { // This is OK - just ensuring existence. continue; } else { throw new IOException("Couldn't create " + prefixPath, e); } } } LOG.info("Successfully created " + znodeWorkingDir + " in ZK."); } /** * Clear all of the state held within the parent ZNode. * This recursively deletes everything within the znode as well as the * parent znode itself. It should only be used when it's certain that * no electors are currently participating in the election. */ public synchronized void clearParentZNode() throws IOException, InterruptedException { Preconditions.checkState(!wantToBeInElection, "clearParentZNode() may not be called while in the election"); try { LOG.info("Recursively deleting " + znodeWorkingDir + " from ZK..."); zkDoWithRetries(new ZKAction<Void>() { @Override public Void run() throws KeeperException, InterruptedException { ZKUtil.deleteRecursive(zkClient, znodeWorkingDir); return null; } }); } catch (KeeperException e) { throw new IOException("Couldn't clear parent znode " + znodeWorkingDir, e); } LOG.info("Successfully deleted " + znodeWorkingDir + " from ZK."); } /** * Any service instance can drop out of the election by calling quitElection. * <br/> * This will lose any leader status, if held, and stop monitoring of the lock * node. <br/> * If the instance wants to participate in election again, then it needs to * call joinElection(). <br/> * This allows service instances to take themselves out of rotation for known * impending unavailable states (e.g. long GC pause or software upgrade). * * @param needFence true if the underlying daemon may need to be fenced * if a failover occurs due to dropping out of the election. */ public synchronized void quitElection(boolean needFence) { LOG.info("Yielding from election"); if (!needFence && state == State.ACTIVE) { // If active is gracefully going back to standby mode, remove // our permanent znode so no one fences us. tryDeleteOwnBreadCrumbNode(); } reset(); wantToBeInElection = false; } /** * Exception thrown when there is no active leader */ public static class ActiveNotFoundException extends Exception { private static final long serialVersionUID = 3505396722342846462L; } /** * get data set by the active leader * * @return data set by the active instance * @throws ActiveNotFoundException * when there is no active leader * @throws KeeperException * other zookeeper operation errors * @throws InterruptedException * @throws IOException * when ZooKeeper connection could not be established */ public synchronized byte[] getActiveData() throws ActiveNotFoundException, KeeperException, InterruptedException, IOException { try { if (zkClient == null) { createConnection(); } Stat stat = new Stat(); return getDataWithRetries(zkLockFilePath, false, stat); } catch(KeeperException e) { Code code = e.code(); if (isNodeDoesNotExist(code)) { // handle the commonly expected cases that make sense for us throw new ActiveNotFoundException(); } else { throw e; } } } /** * interface implementation of Zookeeper callback for create */ @Override public synchronized void processResult(int rc, String path, Object ctx, String name) { if (isStaleClient(ctx)) return; LOG.debug("CreateNode result: " + rc + " for path: " + path + " connectionState: " + zkConnectionState + " for " + this); Code code = Code.get(rc); if (isSuccess(code)) { // we successfully created the znode. we are the leader. start monitoring if (becomeActive()) { monitorActiveStatus(); } else { reJoinElectionAfterFailureToBecomeActive(); } return; } if (isNodeExists(code)) { if (createRetryCount == 0) { // znode exists and we did not retry the operation. so a different // instance has created it. become standby and monitor lock. becomeStandby(); } // if we had retried then the znode could have been created by our first // attempt to the server (that we lost) and this node exists response is // for the second attempt. verify this case via ephemeral node owner. this // will happen on the callback for monitoring the lock. monitorActiveStatus(); return; } String errorMessage = "Received create error from Zookeeper. code:" + code.toString() + " for path " + path; LOG.debug(errorMessage); if (shouldRetry(code)) { if (createRetryCount < maxRetryNum) { LOG.debug("Retrying createNode createRetryCount: " + createRetryCount); ++createRetryCount; createLockNodeAsync(); return; } errorMessage = errorMessage + ". Not retrying further znode create connection errors."; } else if (isSessionExpired(code)) { // This isn't fatal - the client Watcher will re-join the election LOG.warn("Lock acquisition failed because session was lost"); return; } fatalError(errorMessage); } /** * interface implementation of Zookeeper callback for monitor (exists) */ @Override public synchronized void processResult(int rc, String path, Object ctx, Stat stat) { if (isStaleClient(ctx)) return; assert wantToBeInElection : "Got a StatNode result after quitting election"; LOG.debug("StatNode result: " + rc + " for path: " + path + " connectionState: " + zkConnectionState + " for " + this); Code code = Code.get(rc); if (isSuccess(code)) { // the following owner check completes verification in case the lock znode // creation was retried if (stat.getEphemeralOwner() == zkClient.getSessionId()) { // we own the lock znode. so we are the leader if (!becomeActive()) { reJoinElectionAfterFailureToBecomeActive(); } } else { // we dont own the lock znode. so we are a standby. becomeStandby(); } // the watch set by us will notify about changes return; } if (isNodeDoesNotExist(code)) { // the lock znode disappeared before we started monitoring it enterNeutralMode(); joinElectionInternal(); return; } String errorMessage = "Received stat error from Zookeeper. code:" + code.toString(); LOG.debug(errorMessage); if (shouldRetry(code)) { if (statRetryCount < maxRetryNum) { ++statRetryCount; monitorLockNodeAsync(); return; } errorMessage = errorMessage + ". Not retrying further znode monitoring connection errors."; } else if (isSessionExpired(code)) { // This isn't fatal - the client Watcher will re-join the election LOG.warn("Lock monitoring failed because session was lost"); return; } fatalError(errorMessage); } /** * We failed to become active. Re-join the election, but * sleep for a few seconds after terminating our existing * session, so that other nodes have a chance to become active. * The failure to become active is already logged inside * becomeActive(). */ private void reJoinElectionAfterFailureToBecomeActive() { reJoinElection(SLEEP_AFTER_FAILURE_TO_BECOME_ACTIVE); } /** * interface implementation of Zookeeper watch events (connection and node), * proxied by {@link WatcherWithClientRef}. */ synchronized void processWatchEvent(ZooKeeper zk, WatchedEvent event) { Event.EventType eventType = event.getType(); if (isStaleClient(zk)) return; LOG.debug("Watcher event type: " + eventType + " with state:" + event.getState() + " for path:" + event.getPath() + " connectionState: " + zkConnectionState + " for " + this); if (eventType == Event.EventType.None) { // the connection state has changed switch (event.getState()) { case SyncConnected: LOG.info("Session connected."); // if the listener was asked to move to safe state then it needs to // be undone ConnectionState prevConnectionState = zkConnectionState; zkConnectionState = ConnectionState.CONNECTED; if (prevConnectionState == ConnectionState.DISCONNECTED && wantToBeInElection) { monitorActiveStatus(); } break; case Disconnected: LOG.info("Session disconnected. Entering neutral mode..."); // ask the app to move to safe state because zookeeper connection // is not active and we dont know our state zkConnectionState = ConnectionState.DISCONNECTED; enterNeutralMode(); break; case Expired: // the connection got terminated because of session timeout // call listener to reconnect LOG.info("Session expired. Entering neutral mode and rejoining..."); enterNeutralMode(); reJoinElection(0); break; case SaslAuthenticated: LOG.info("Successfully authenticated to ZooKeeper using SASL."); break; default: fatalError("Unexpected Zookeeper watch event state: " + event.getState()); break; } return; } // a watch on lock path in zookeeper has fired. so something has changed on // the lock. ideally we should check that the path is the same as the lock // path but trusting zookeeper for now String path = event.getPath(); if (path != null) { switch (eventType) { case NodeDeleted: if (state == State.ACTIVE) { enterNeutralMode(); } joinElectionInternal(); break; case NodeDataChanged: monitorActiveStatus(); break; default: LOG.debug("Unexpected node event: " + eventType + " for path: " + path); monitorActiveStatus(); } return; } // some unexpected error has occurred fatalError("Unexpected watch error from Zookeeper"); } /** * Get a new zookeeper client instance. protected so that test class can * inherit and pass in a mock object for zookeeper * * @return new zookeeper client instance * @throws IOException * @throws KeeperException zookeeper connectionloss exception */ protected synchronized ZooKeeper getNewZooKeeper() throws IOException, KeeperException { // Unfortunately, the ZooKeeper constructor connects to ZooKeeper and // may trigger the Connected event immediately. So, if we register the // watcher after constructing ZooKeeper, we may miss that event. Instead, // we construct the watcher first, and have it block any events it receives // before we can set its ZooKeeper reference. watcher = new WatcherWithClientRef(); ZooKeeper zk = new ZooKeeper(zkHostPort, zkSessionTimeout, watcher); watcher.setZooKeeperRef(zk); // Wait for the asynchronous success/failure. This may throw an exception // if we don't connect within the session timeout. watcher.waitForZKConnectionEvent(zkSessionTimeout); for (ZKAuthInfo auth : zkAuthInfo) { zk.addAuthInfo(auth.getScheme(), auth.getAuth()); } return zk; } private void fatalError(String errorMessage) { LOG.fatal(errorMessage); reset(); appClient.notifyFatalError(errorMessage); } private void monitorActiveStatus() { assert wantToBeInElection; LOG.debug("Monitoring active leader for " + this); statRetryCount = 0; monitorLockNodeAsync(); } private void joinElectionInternal() { Preconditions.checkState(appData != null, "trying to join election without any app data"); if (zkClient == null) { if (!reEstablishSession()) { fatalError("Failed to reEstablish connection with ZooKeeper"); return; } } createRetryCount = 0; wantToBeInElection = true; createLockNodeAsync(); } private void reJoinElection(int sleepTime) { LOG.info("Trying to re-establish ZK session"); // Some of the test cases rely on expiring the ZK sessions and // ensuring that the other node takes over. But, there's a race // where the original lease holder could reconnect faster than the other // thread manages to take the lock itself. This lock allows the // tests to block the reconnection. It's a shame that this leaked // into non-test code, but the lock is only acquired here so will never // be contended. sessionReestablishLockForTests.lock(); try { terminateConnection(); sleepFor(sleepTime); // Should not join election even before the SERVICE is reported // as HEALTHY from ZKFC monitoring. if (appData != null) { joinElectionInternal(); } else { LOG.info("Not joining election since service has not yet been " + "reported as healthy."); } } finally { sessionReestablishLockForTests.unlock(); } } /** * Sleep for the given number of milliseconds. * This is non-static, and separated out, so that unit tests * can override the behavior not to sleep. */ @VisibleForTesting protected void sleepFor(int sleepMs) { if (sleepMs > 0) { try { Thread.sleep(sleepMs); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } @VisibleForTesting void preventSessionReestablishmentForTests() { sessionReestablishLockForTests.lock(); } @VisibleForTesting void allowSessionReestablishmentForTests() { sessionReestablishLockForTests.unlock(); } @VisibleForTesting synchronized long getZKSessionIdForTests() { if (zkClient != null) { return zkClient.getSessionId(); } else { return -1; } } @VisibleForTesting synchronized State getStateForTests() { return state; } private boolean reEstablishSession() { int connectionRetryCount = 0; boolean success = false; while(!success && connectionRetryCount < maxRetryNum) { LOG.debug("Establishing zookeeper connection for " + this); try { createConnection(); success = true; } catch(IOException e) { LOG.warn(e); sleepFor(5000); } catch(KeeperException e) { LOG.warn(e); sleepFor(5000); } ++connectionRetryCount; } return success; } private void createConnection() throws IOException, KeeperException { if (zkClient != null) { try { zkClient.close(); } catch (InterruptedException e) { throw new IOException("Interrupted while closing ZK", e); } zkClient = null; watcher = null; } zkClient = getNewZooKeeper(); LOG.debug("Created new connection for " + this); } @InterfaceAudience.Private public synchronized void terminateConnection() { if (zkClient == null) { return; } LOG.debug("Terminating ZK connection for " + this); ZooKeeper tempZk = zkClient; zkClient = null; watcher = null; try { tempZk.close(); } catch(InterruptedException e) { LOG.warn(e); } zkConnectionState = ConnectionState.TERMINATED; wantToBeInElection = false; } private void reset() { state = State.INIT; terminateConnection(); } private boolean becomeActive() { assert wantToBeInElection; if (state == State.ACTIVE) { // already active return true; } try { Stat oldBreadcrumbStat = fenceOldActive(); writeBreadCrumbNode(oldBreadcrumbStat); LOG.debug("Becoming active for " + this); appClient.becomeActive(); state = State.ACTIVE; return true; } catch (Exception e) { LOG.warn("Exception handling the winning of election", e); // Caller will handle quitting and rejoining the election. return false; } } /** * Write the "ActiveBreadCrumb" node, indicating that this node may need * to be fenced on failover. * @param oldBreadcrumbStat */ private void writeBreadCrumbNode(Stat oldBreadcrumbStat) throws KeeperException, InterruptedException { Preconditions.checkState(appData != null, "no appdata"); LOG.info("Writing znode " + zkBreadCrumbPath + " to indicate that the local node is the most recent active..."); if (oldBreadcrumbStat == null) { // No previous active, just create the node createWithRetries(zkBreadCrumbPath, appData, zkAcl, CreateMode.PERSISTENT); } else { // There was a previous active, update the node setDataWithRetries(zkBreadCrumbPath, appData, oldBreadcrumbStat.getVersion()); } } /** * Try to delete the "ActiveBreadCrumb" node when gracefully giving up * active status. * If this fails, it will simply warn, since the graceful release behavior * is only an optimization. */ private void tryDeleteOwnBreadCrumbNode() { assert state == State.ACTIVE; LOG.info("Deleting bread-crumb of active node..."); // Sanity check the data. This shouldn't be strictly necessary, // but better to play it safe. Stat stat = new Stat(); byte[] data = null; try { data = zkClient.getData(zkBreadCrumbPath, false, stat); if (!Arrays.equals(data, appData)) { throw new IllegalStateException( "We thought we were active, but in fact " + "the active znode had the wrong data: " + StringUtils.byteToHexString(data) + " (stat=" + stat + ")"); } deleteWithRetries(zkBreadCrumbPath, stat.getVersion()); } catch (Exception e) { LOG.warn("Unable to delete our own bread-crumb of being active at " + zkBreadCrumbPath + ": " + e.getLocalizedMessage() + ". " + "Expecting to be fenced by the next active."); } } /** * If there is a breadcrumb node indicating that another node may need * fencing, try to fence that node. * @return the Stat of the breadcrumb node that was read, or null * if no breadcrumb node existed */ private Stat fenceOldActive() throws InterruptedException, KeeperException { final Stat stat = new Stat(); byte[] data; LOG.info("Checking for any old active which needs to be fenced..."); try { data = zkDoWithRetries(new ZKAction<byte[]>() { @Override public byte[] run() throws KeeperException, InterruptedException { return zkClient.getData(zkBreadCrumbPath, false, stat); } }); } catch (KeeperException ke) { if (isNodeDoesNotExist(ke.code())) { LOG.info("No old node to fence"); return null; } // If we failed to read for any other reason, then likely we lost // our session, or we don't have permissions, etc. In any case, // we probably shouldn't become active, and failing the whole // thing is the best bet. throw ke; } LOG.info("Old node exists: " + StringUtils.byteToHexString(data)); if (Arrays.equals(data, appData)) { LOG.info("But old node has our own data, so don't need to fence it."); } else { appClient.fenceOldActive(data); } return stat; } private void becomeStandby() { if (state != State.STANDBY) { LOG.debug("Becoming standby for " + this); state = State.STANDBY; appClient.becomeStandby(); } } private void enterNeutralMode() { if (state != State.NEUTRAL) { LOG.debug("Entering neutral mode for " + this); state = State.NEUTRAL; appClient.enterNeutralMode(); } } private void createLockNodeAsync() { zkClient.create(zkLockFilePath, appData, zkAcl, CreateMode.EPHEMERAL, this, zkClient); } private void monitorLockNodeAsync() { zkClient.exists(zkLockFilePath, watcher, this, zkClient); } private String createWithRetries(final String path, final byte[] data, final List<ACL> acl, final CreateMode mode) throws InterruptedException, KeeperException { return zkDoWithRetries(new ZKAction<String>() { @Override public String run() throws KeeperException, InterruptedException { return zkClient.create(path, data, acl, mode); } }); } private byte[] getDataWithRetries(final String path, final boolean watch, final Stat stat) throws InterruptedException, KeeperException { return zkDoWithRetries(new ZKAction<byte[]>() { @Override public byte[] run() throws KeeperException, InterruptedException { return zkClient.getData(path, watch, stat); } }); } private Stat setDataWithRetries(final String path, final byte[] data, final int version) throws InterruptedException, KeeperException { return zkDoWithRetries(new ZKAction<Stat>() { @Override public Stat run() throws KeeperException, InterruptedException { return zkClient.setData(path, data, version); } }); } private void deleteWithRetries(final String path, final int version) throws KeeperException, InterruptedException { zkDoWithRetries(new ZKAction<Void>() { @Override public Void run() throws KeeperException, InterruptedException { zkClient.delete(path, version); return null; } }); } private <T> T zkDoWithRetries(ZKAction<T> action) throws KeeperException, InterruptedException { int retry = 0; while (true) { try { return action.run(); } catch (KeeperException ke) { if (shouldRetry(ke.code()) && ++retry < maxRetryNum) { continue; } throw ke; } } } private interface ZKAction<T> { T run() throws KeeperException, InterruptedException; } /** * The callbacks and watchers pass a reference to the ZK client * which made the original call. We don't want to take action * based on any callbacks from prior clients after we quit * the election. * @param ctx the ZK client passed into the watcher * @return true if it matches the current client */ private synchronized boolean isStaleClient(Object ctx) { Preconditions.checkNotNull(ctx); if (zkClient != (ZooKeeper)ctx) { LOG.warn("Ignoring stale result from old client with sessionId " + String.format("0x%08x", ((ZooKeeper)ctx).getSessionId())); return true; } return false; } /** * Watcher implementation which keeps a reference around to the * original ZK connection, and passes it back along with any * events. */ private final class WatcherWithClientRef implements Watcher { private ZooKeeper zk; /** * Latch fired whenever any event arrives. This is used in order * to wait for the Connected event when the client is first created. */ private CountDownLatch hasReceivedEvent = new CountDownLatch(1); /** * Latch used to wait until the reference to ZooKeeper is set. */ private CountDownLatch hasSetZooKeeper = new CountDownLatch(1); /** * Waits for the next event from ZooKeeper to arrive. * * @param connectionTimeoutMs zookeeper connection timeout in milliseconds * @throws KeeperException if the connection attempt times out. This will * be a ZooKeeper ConnectionLoss exception code. * @throws IOException if interrupted while connecting to ZooKeeper */ private void waitForZKConnectionEvent(int connectionTimeoutMs) throws KeeperException, IOException { try { if (!hasReceivedEvent.await(connectionTimeoutMs, TimeUnit.MILLISECONDS)) { LOG.error("Connection timed out: couldn't connect to ZooKeeper in " + connectionTimeoutMs + " milliseconds"); zk.close(); throw KeeperException.create(Code.CONNECTIONLOSS); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException( "Interrupted when connecting to zookeeper server", e); } } private void setZooKeeperRef(ZooKeeper zk) { Preconditions.checkState(this.zk == null, "zk already set -- must be set exactly once"); this.zk = zk; hasSetZooKeeper.countDown(); } @Override public void process(WatchedEvent event) { hasReceivedEvent.countDown(); try { if (!hasSetZooKeeper.await(zkSessionTimeout, TimeUnit.MILLISECONDS)) { LOG.debug("Event received with stale zk"); } ActiveStandbyElector.this.processWatchEvent( zk, event); } catch (Throwable t) { fatalError( "Failed to process watcher event " + event + ": " + StringUtils.stringifyException(t)); } } } private static boolean isSuccess(Code code) { return (code == Code.OK); } private static boolean isNodeExists(Code code) { return (code == Code.NODEEXISTS); } private static boolean isNodeDoesNotExist(Code code) { return (code == Code.NONODE); } private static boolean isSessionExpired(Code code) { return (code == Code.SESSIONEXPIRED); } private static boolean shouldRetry(Code code) { return code == Code.CONNECTIONLOSS || code == Code.OPERATIONTIMEOUT; } @Override public String toString() { return "elector id=" + System.identityHashCode(this) + " appData=" + ((appData == null) ? "null" : StringUtils.byteToHexString(appData)) + " cb=" + appClient; } }
JoeChien23/hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/ActiveStandbyElector.java
Java
apache-2.0
38,058
/* Copyright 2014 The Kubernetes 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 cmd import ( "fmt" "io" "io/ioutil" "os" "path/filepath" "github.com/spf13/cobra" "github.com/golang/glog" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/kubectl/cmd/templates" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/kubectl/util/i18n" ) var ( replaceLong = templates.LongDesc(i18n.T(` Replace a resource by filename or stdin. JSON and YAML formats are accepted. If replacing an existing resource, the complete resource spec must be provided. This can be obtained by $ kubectl get TYPE NAME -o yaml Please refer to the models in https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html to find if a field is mutable.`)) replaceExample = templates.Examples(i18n.T(` # Replace a pod using the data in pod.json. kubectl replace -f ./pod.json # Replace a pod based on the JSON passed into stdin. cat pod.json | kubectl replace -f - # Update a single-container pod's image version (tag) to v4 kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f - # Force replace, delete and then re-create the resource kubectl replace --force -f ./pod.json`)) ) func NewCmdReplace(f cmdutil.Factory, out io.Writer) *cobra.Command { options := &resource.FilenameOptions{} cmd := &cobra.Command{ Use: "replace -f FILENAME", DisableFlagsInUseLine: true, Short: i18n.T("Replace a resource by filename or stdin"), Long: replaceLong, Example: replaceExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) err := RunReplace(f, out, cmd, args, options) cmdutil.CheckErr(err) }, } usage := "to use to replace the resource." cmdutil.AddFilenameOptionFlags(cmd, options, usage) cmd.MarkFlagRequired("filename") cmd.Flags().Bool("force", false, "Delete and re-create the specified resource") cmd.Flags().Bool("cascade", false, "Only relevant during a force replace. If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController).") cmd.Flags().Int("grace-period", -1, "Only relevant during a force replace. Period of time in seconds given to the old resource to terminate gracefully. Ignored if negative.") cmd.Flags().Duration("timeout", 0, "Only relevant during a force replace. The length of time to wait before giving up on a delete of the old resource, zero means determine a timeout from the size of the object. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).") cmdutil.AddValidateFlags(cmd) cmdutil.AddOutputFlagsForMutation(cmd) cmdutil.AddApplyAnnotationFlags(cmd) cmdutil.AddRecordFlag(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) return cmd } func RunReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *resource.FilenameOptions) error { schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate")) if err != nil { return err } cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } force := cmdutil.GetFlagBool(cmd, "force") if cmdutil.IsFilenameSliceEmpty(options.Filenames) { return cmdutil.UsageErrorf(cmd, "Must specify --filename to replace") } shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" if force { return forceReplace(f, out, cmd, args, shortOutput, options) } if cmdutil.GetFlagInt(cmd, "grace-period") >= 0 { return fmt.Errorf("--grace-period must have --force specified") } if cmdutil.GetFlagDuration(cmd, "timeout") != 0 { return fmt.Errorf("--timeout must have --force specified") } r := f.NewBuilder(). Unstructured(). Schema(schema). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, options). Flatten(). Do() if err := r.Err(); err != nil { return err } return r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil { return cmdutil.AddSourceToErr("replacing", info.Source, err) } if cmdutil.ShouldRecord(cmd, info) { if err := cmdutil.RecordChangeCause(info.Object, f.Command(cmd, false)); err != nil { return cmdutil.AddSourceToErr("replacing", info.Source, err) } } // Serialize the object with the annotation applied. obj, err := resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, true, info.Object) if err != nil { return cmdutil.AddSourceToErr("replacing", info.Source, err) } info.Refresh(obj, true) f.PrintObjectSpecificMessage(obj, out) f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, false, "replaced") return nil }) } func forceReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool, options *resource.FilenameOptions) error { schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate")) if err != nil { return err } cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } for i, filename := range options.Filenames { if filename == "-" { tempDir, err := ioutil.TempDir("", "kubectl_replace_") if err != nil { return err } defer os.RemoveAll(tempDir) tempFilename := filepath.Join(tempDir, "resource.stdin") err = cmdutil.DumpReaderToFile(os.Stdin, tempFilename) if err != nil { return err } options.Filenames[i] = tempFilename } } r := f.NewBuilder(). Unstructured(). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, options). ResourceTypeOrNameArgs(false, args...).RequireObject(false). Flatten(). Do() if err := r.Err(); err != nil { return err } mapper := r.Mapper().RESTMapper //Replace will create a resource if it doesn't exist already, so ignore not found error ignoreNotFound := true timeout := cmdutil.GetFlagDuration(cmd, "timeout") gracePeriod := cmdutil.GetFlagInt(cmd, "grace-period") waitForDeletion := false if gracePeriod == 0 { // To preserve backwards compatibility, but prevent accidental data loss, we convert --grace-period=0 // into --grace-period=1 and wait until the object is successfully deleted. gracePeriod = 1 waitForDeletion = true } // By default use a reaper to delete all related resources. if cmdutil.GetFlagBool(cmd, "cascade") { glog.Warningf("\"cascade\" is set, kubectl will delete and re-create all resources managed by this resource (e.g. Pods created by a ReplicationController). Consider using \"kubectl rolling-update\" if you want to update a ReplicationController together with its Pods.") err = ReapResult(r, f, out, cmdutil.GetFlagBool(cmd, "cascade"), ignoreNotFound, timeout, gracePeriod, waitForDeletion, shortOutput, mapper, false) } else { err = DeleteResult(r, f, out, ignoreNotFound, gracePeriod, shortOutput, mapper) } if err != nil { return err } if timeout == 0 { timeout = kubectl.Timeout } err = r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } return wait.PollImmediate(kubectl.Interval, timeout, func() (bool, error) { if err := info.Get(); !errors.IsNotFound(err) { return false, err } return true, nil }) }) if err != nil { return err } r = f.NewBuilder(). Unstructured(). Schema(schema). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, options). Flatten(). Do() err = r.Err() if err != nil { return err } count := 0 err = r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil { return err } if cmdutil.ShouldRecord(cmd, info) { if err := cmdutil.RecordChangeCause(info.Object, f.Command(cmd, false)); err != nil { return cmdutil.AddSourceToErr("replacing", info.Source, err) } } obj, err := resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, true, info.Object) if err != nil { return err } count++ info.Refresh(obj, true) f.PrintObjectSpecificMessage(obj, out) f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, false, "replaced") return nil }) if err != nil { return err } if count == 0 { return fmt.Errorf("no objects passed to replace") } return nil }
humblec/external-storage
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/replace.go
GO
apache-2.0
9,290
/* Copyright 2016 The Kubernetes 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 plugins import ( "fmt" "k8s.io/test-infra/velodrome/sql" "github.com/spf13/cobra" ) // TypeFilterWrapperPlugin allows ignoring either PR or issues from processing type TypeFilterWrapperPlugin struct { pullRequests bool issues bool plugin Plugin // List of issues that we should ignore pass map[string]bool } var _ Plugin = &TypeFilterWrapperPlugin{} // NewTypeFilterWrapperPlugin is the constructor of TypeFilterWrapperPlugin func NewTypeFilterWrapperPlugin(plugin Plugin) *TypeFilterWrapperPlugin { return &TypeFilterWrapperPlugin{ plugin: plugin, pass: map[string]bool{}, } } // AddFlags adds "no-pull-requests" and "no-issues" to the command help func (t *TypeFilterWrapperPlugin) AddFlags(cmd *cobra.Command) { cmd.Flags().BoolVar(&t.pullRequests, "no-pull-requests", false, "Ignore pull-requests") cmd.Flags().BoolVar(&t.issues, "no-issues", false, "Ignore issues") } // CheckFlags makes sure not both PR and issues are ignored func (t *TypeFilterWrapperPlugin) CheckFlags() error { if t.pullRequests && t.issues { return fmt.Errorf( "you can't ignore both pull-requests and issues") } return nil } // ReceiveIssue calls plugin.ReceiveIssue() if issues are not ignored func (t *TypeFilterWrapperPlugin) ReceiveIssue(issue sql.Issue) []Point { if issue.IsPR && t.pullRequests { return nil } else if !issue.IsPR && t.issues { return nil } else { t.pass[issue.ID] = true return t.plugin.ReceiveIssue(issue) } } // ReceiveIssueEvent calls plugin.ReceiveIssueEvent() if issues are not ignored func (t *TypeFilterWrapperPlugin) ReceiveIssueEvent(event sql.IssueEvent) []Point { if !t.pass[event.IssueID] { return nil } return t.plugin.ReceiveIssueEvent(event) } // ReceiveComment calls plugin.ReceiveComment() if issues are not ignored func (t *TypeFilterWrapperPlugin) ReceiveComment(comment sql.Comment) []Point { if !t.pass[comment.IssueID] { return nil } return t.plugin.ReceiveComment(comment) }
lavalamp/test-infra
velodrome/transform/plugins/type_filter_wrapper.go
GO
apache-2.0
2,546
/** * Copyright 2009-2015 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 org.apache.ibatis.domain.misc.generics; public abstract class GenericSubclass extends GenericAbstract<Long> { @Override public abstract Long getId(); }
macs524/mybatis_learn
src/test/java/org/apache/ibatis/domain/misc/generics/GenericSubclass.java
Java
apache-2.0
819
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" using namespace cv; using namespace cv::cuda; #if !defined (HAVE_CUDA) || defined (CUDA_DISABLER) Ptr<cv::cuda::DescriptorMatcher> cv::cuda::DescriptorMatcher::createBFMatcher(int) { throw_no_cuda(); return Ptr<cv::cuda::DescriptorMatcher>(); } #else /* !defined (HAVE_CUDA) */ namespace cv { namespace cuda { namespace device { namespace bf_match { template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, cudaStream_t stream); template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, cudaStream_t stream); template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, cudaStream_t stream); template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, cudaStream_t stream); template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, cudaStream_t stream); template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, cudaStream_t stream); } namespace bf_knnmatch { template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask, const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist, cudaStream_t stream); template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask, const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist, cudaStream_t stream); template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask, const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist, cudaStream_t stream); template <typename T> void match2L1_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance, cudaStream_t stream); template <typename T> void match2L2_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance, cudaStream_t stream); template <typename T> void match2Hamming_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance, cudaStream_t stream); } namespace bf_radius_match { template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); } }}} namespace { static void makeGpuCollection(const std::vector<GpuMat>& trainDescCollection, const std::vector<GpuMat>& masks, GpuMat& trainCollection, GpuMat& maskCollection) { if (trainDescCollection.empty()) return; if (masks.empty()) { Mat trainCollectionCPU(1, static_cast<int>(trainDescCollection.size()), CV_8UC(sizeof(PtrStepSzb))); PtrStepSzb* trainCollectionCPU_ptr = trainCollectionCPU.ptr<PtrStepSzb>(); for (size_t i = 0, size = trainDescCollection.size(); i < size; ++i, ++trainCollectionCPU_ptr) *trainCollectionCPU_ptr = trainDescCollection[i]; trainCollection.upload(trainCollectionCPU); maskCollection.release(); } else { CV_Assert( masks.size() == trainDescCollection.size() ); Mat trainCollectionCPU(1, static_cast<int>(trainDescCollection.size()), CV_8UC(sizeof(PtrStepSzb))); Mat maskCollectionCPU(1, static_cast<int>(trainDescCollection.size()), CV_8UC(sizeof(PtrStepb))); PtrStepSzb* trainCollectionCPU_ptr = trainCollectionCPU.ptr<PtrStepSzb>(); PtrStepb* maskCollectionCPU_ptr = maskCollectionCPU.ptr<PtrStepb>(); for (size_t i = 0, size = trainDescCollection.size(); i < size; ++i, ++trainCollectionCPU_ptr, ++maskCollectionCPU_ptr) { const GpuMat& train = trainDescCollection[i]; const GpuMat& mask = masks[i]; CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.cols == train.rows) ); *trainCollectionCPU_ptr = train; *maskCollectionCPU_ptr = mask; } trainCollection.upload(trainCollectionCPU); maskCollection.upload(maskCollectionCPU); } } class BFMatcher_Impl : public cv::cuda::DescriptorMatcher { public: explicit BFMatcher_Impl(int norm) : norm_(norm) { CV_Assert( norm == NORM_L1 || norm == NORM_L2 || norm == NORM_HAMMING ); } virtual bool isMaskSupported() const { return true; } virtual void add(const std::vector<GpuMat>& descriptors) { trainDescCollection_.insert(trainDescCollection_.end(), descriptors.begin(), descriptors.end()); } virtual const std::vector<GpuMat>& getTrainDescriptors() const { return trainDescCollection_; } virtual void clear() { trainDescCollection_.clear(); } virtual bool empty() const { return trainDescCollection_.empty(); } virtual void train() { } virtual void match(InputArray queryDescriptors, InputArray trainDescriptors, std::vector<DMatch>& matches, InputArray mask = noArray()); virtual void match(InputArray queryDescriptors, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>()); virtual void matchAsync(InputArray queryDescriptors, InputArray trainDescriptors, OutputArray matches, InputArray mask = noArray(), Stream& stream = Stream::Null()); virtual void matchAsync(InputArray queryDescriptors, OutputArray matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null()); virtual void matchConvert(InputArray gpu_matches, std::vector<DMatch>& matches); virtual void knnMatch(InputArray queryDescriptors, InputArray trainDescriptors, std::vector<std::vector<DMatch> >& matches, int k, InputArray mask = noArray(), bool compactResult = false); virtual void knnMatch(InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false); virtual void knnMatchAsync(InputArray queryDescriptors, InputArray trainDescriptors, OutputArray matches, int k, InputArray mask = noArray(), Stream& stream = Stream::Null()); virtual void knnMatchAsync(InputArray queryDescriptors, OutputArray matches, int k, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null()); virtual void knnMatchConvert(InputArray gpu_matches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); virtual void radiusMatch(InputArray queryDescriptors, InputArray trainDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance, InputArray mask = noArray(), bool compactResult = false); virtual void radiusMatch(InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false); virtual void radiusMatchAsync(InputArray queryDescriptors, InputArray trainDescriptors, OutputArray matches, float maxDistance, InputArray mask = noArray(), Stream& stream = Stream::Null()); virtual void radiusMatchAsync(InputArray queryDescriptors, OutputArray matches, float maxDistance, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null()); virtual void radiusMatchConvert(InputArray gpu_matches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); private: int norm_; std::vector<GpuMat> trainDescCollection_; }; // // 1 to 1 match // void BFMatcher_Impl::match(InputArray _queryDescriptors, InputArray _trainDescriptors, std::vector<DMatch>& matches, InputArray _mask) { GpuMat d_matches; matchAsync(_queryDescriptors, _trainDescriptors, d_matches, _mask); matchConvert(d_matches, matches); } void BFMatcher_Impl::match(InputArray _queryDescriptors, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks) { GpuMat d_matches; matchAsync(_queryDescriptors, d_matches, masks); matchConvert(d_matches, matches); } void BFMatcher_Impl::matchAsync(InputArray _queryDescriptors, InputArray _trainDescriptors, OutputArray _matches, InputArray _mask, Stream& stream) { using namespace cv::cuda::device::bf_match; const GpuMat query = _queryDescriptors.getGpuMat(); const GpuMat train = _trainDescriptors.getGpuMat(); const GpuMat mask = _mask.getGpuMat(); if (query.empty() || train.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); CV_Assert( train.cols == query.cols && train.type() == query.type() ); CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.rows == query.rows && mask.cols == train.rows) ); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, cudaStream_t stream); static const caller_t callersL1[] = { matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/, matchL1_gpu<unsigned short>, matchL1_gpu<short>, matchL1_gpu<int>, matchL1_gpu<float> }; static const caller_t callersL2[] = { 0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/, 0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/, 0/*matchL2_gpu<int>*/, matchL2_gpu<float> }; static const caller_t callersHamming[] = { matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/, matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/, matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; _matches.create(2, nQuery, CV_32SC1); GpuMat matches = _matches.getGpuMat(); GpuMat trainIdx(1, nQuery, CV_32SC1, matches.ptr(0)); GpuMat distance(1, nQuery, CV_32FC1, matches.ptr(1)); func(query, train, mask, trainIdx, distance, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::matchAsync(InputArray _queryDescriptors, OutputArray _matches, const std::vector<GpuMat>& masks, Stream& stream) { using namespace cv::cuda::device::bf_match; const GpuMat query = _queryDescriptors.getGpuMat(); if (query.empty() || trainDescCollection_.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); GpuMat trainCollection, maskCollection; makeGpuCollection(trainDescCollection_, masks, trainCollection, maskCollection); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, cudaStream_t stream); static const caller_t callersL1[] = { matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/, matchL1_gpu<unsigned short>, matchL1_gpu<short>, matchL1_gpu<int>, matchL1_gpu<float> }; static const caller_t callersL2[] = { 0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/, 0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/, 0/*matchL2_gpu<int>*/, matchL2_gpu<float> }; static const caller_t callersHamming[] = { matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/, matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/, matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; _matches.create(3, nQuery, CV_32SC1); GpuMat matches = _matches.getGpuMat(); GpuMat trainIdx(1, nQuery, CV_32SC1, matches.ptr(0)); GpuMat imgIdx(1, nQuery, CV_32SC1, matches.ptr(1)); GpuMat distance(1, nQuery, CV_32FC1, matches.ptr(2)); func(query, trainCollection, maskCollection, trainIdx, imgIdx, distance, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::matchConvert(InputArray _gpu_matches, std::vector<DMatch>& matches) { Mat gpu_matches; if (_gpu_matches.kind() == _InputArray::CUDA_GPU_MAT) { _gpu_matches.getGpuMat().download(gpu_matches); } else { gpu_matches = _gpu_matches.getMat(); } if (gpu_matches.empty()) { matches.clear(); return; } CV_Assert( (gpu_matches.type() == CV_32SC1) && (gpu_matches.rows == 2 || gpu_matches.rows == 3) ); const int nQuery = gpu_matches.cols; matches.clear(); matches.reserve(nQuery); const int* trainIdxPtr = NULL; const int* imgIdxPtr = NULL; const float* distancePtr = NULL; if (gpu_matches.rows == 2) { trainIdxPtr = gpu_matches.ptr<int>(0); distancePtr = gpu_matches.ptr<float>(1); } else { trainIdxPtr = gpu_matches.ptr<int>(0); imgIdxPtr = gpu_matches.ptr<int>(1); distancePtr = gpu_matches.ptr<float>(2); } for (int queryIdx = 0; queryIdx < nQuery; ++queryIdx) { const int trainIdx = trainIdxPtr[queryIdx]; if (trainIdx == -1) continue; const int imgIdx = imgIdxPtr ? imgIdxPtr[queryIdx] : 0; const float distance = distancePtr[queryIdx]; DMatch m(queryIdx, trainIdx, imgIdx, distance); matches.push_back(m); } } // // knn match // void BFMatcher_Impl::knnMatch(InputArray _queryDescriptors, InputArray _trainDescriptors, std::vector<std::vector<DMatch> >& matches, int k, InputArray _mask, bool compactResult) { GpuMat d_matches; knnMatchAsync(_queryDescriptors, _trainDescriptors, d_matches, k, _mask); knnMatchConvert(d_matches, matches, compactResult); } void BFMatcher_Impl::knnMatch(InputArray _queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k, const std::vector<GpuMat>& masks, bool compactResult) { if (k == 2) { GpuMat d_matches; knnMatchAsync(_queryDescriptors, d_matches, k, masks); knnMatchConvert(d_matches, matches, compactResult); } else { const GpuMat query = _queryDescriptors.getGpuMat(); if (query.empty() || trainDescCollection_.empty()) { matches.clear(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); std::vector< std::vector<DMatch> > curMatches; std::vector<DMatch> temp; temp.reserve(2 * k); matches.resize(query.rows); for (size_t i = 0; i < matches.size(); ++i) matches[i].reserve(k); for (size_t imgIdx = 0; imgIdx < trainDescCollection_.size(); ++imgIdx) { knnMatch(query, trainDescCollection_[imgIdx], curMatches, k, masks.empty() ? GpuMat() : masks[imgIdx]); for (int queryIdx = 0; queryIdx < query.rows; ++queryIdx) { std::vector<DMatch>& localMatch = curMatches[queryIdx]; std::vector<DMatch>& globalMatch = matches[queryIdx]; for (size_t i = 0; i < localMatch.size(); ++i) localMatch[i].imgIdx = imgIdx; temp.clear(); std::merge(globalMatch.begin(), globalMatch.end(), localMatch.begin(), localMatch.end(), std::back_inserter(temp)); globalMatch.clear(); const size_t count = std::min(static_cast<size_t>(k), temp.size()); std::copy(temp.begin(), temp.begin() + count, std::back_inserter(globalMatch)); } } if (compactResult) { std::vector< std::vector<DMatch> >::iterator new_end = std::remove_if(matches.begin(), matches.end(), std::mem_fun_ref(&std::vector<DMatch>::empty)); matches.erase(new_end, matches.end()); } } } void BFMatcher_Impl::knnMatchAsync(InputArray _queryDescriptors, InputArray _trainDescriptors, OutputArray _matches, int k, InputArray _mask, Stream& stream) { using namespace cv::cuda::device::bf_knnmatch; const GpuMat query = _queryDescriptors.getGpuMat(); const GpuMat train = _trainDescriptors.getGpuMat(); const GpuMat mask = _mask.getGpuMat(); if (query.empty() || train.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); CV_Assert( train.cols == query.cols && train.type() == query.type() ); CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.rows == query.rows && mask.cols == train.rows) ); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask, const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist, cudaStream_t stream); static const caller_t callersL1[] = { matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/, matchL1_gpu<unsigned short>, matchL1_gpu<short>, matchL1_gpu<int>, matchL1_gpu<float> }; static const caller_t callersL2[] = { 0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/, 0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/, 0/*matchL2_gpu<int>*/, matchL2_gpu<float> }; static const caller_t callersHamming[] = { matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/, matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/, matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; const int nTrain = train.rows; GpuMat trainIdx, distance, allDist; if (k == 2) { _matches.create(2, nQuery, CV_32SC2); GpuMat matches = _matches.getGpuMat(); trainIdx = GpuMat(1, nQuery, CV_32SC2, matches.ptr(0)); distance = GpuMat(1, nQuery, CV_32FC2, matches.ptr(1)); } else { _matches.create(2 * nQuery, k, CV_32SC1); GpuMat matches = _matches.getGpuMat(); trainIdx = GpuMat(nQuery, k, CV_32SC1, matches.ptr(0), matches.step); distance = GpuMat(nQuery, k, CV_32FC1, matches.ptr(nQuery), matches.step); BufferPool pool(stream); allDist = pool.getBuffer(nQuery, nTrain, CV_32FC1); } trainIdx.setTo(Scalar::all(-1), stream); func(query, train, k, mask, trainIdx, distance, allDist, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::knnMatchAsync(InputArray _queryDescriptors, OutputArray _matches, int k, const std::vector<GpuMat>& masks, Stream& stream) { using namespace cv::cuda::device::bf_knnmatch; if (k != 2) { CV_Error(Error::StsNotImplemented, "only k=2 mode is supported for now"); } const GpuMat query = _queryDescriptors.getGpuMat(); if (query.empty() || trainDescCollection_.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); GpuMat trainCollection, maskCollection; makeGpuCollection(trainDescCollection_, masks, trainCollection, maskCollection); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks, const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance, cudaStream_t stream); static const caller_t callersL1[] = { match2L1_gpu<unsigned char>, 0/*match2L1_gpu<signed char>*/, match2L1_gpu<unsigned short>, match2L1_gpu<short>, match2L1_gpu<int>, match2L1_gpu<float> }; static const caller_t callersL2[] = { 0/*match2L2_gpu<unsigned char>*/, 0/*match2L2_gpu<signed char>*/, 0/*match2L2_gpu<unsigned short>*/, 0/*match2L2_gpu<short>*/, 0/*match2L2_gpu<int>*/, match2L2_gpu<float> }; static const caller_t callersHamming[] = { match2Hamming_gpu<unsigned char>, 0/*match2Hamming_gpu<signed char>*/, match2Hamming_gpu<unsigned short>, 0/*match2Hamming_gpu<short>*/, match2Hamming_gpu<int>, 0/*match2Hamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; _matches.create(3, nQuery, CV_32SC2); GpuMat matches = _matches.getGpuMat(); GpuMat trainIdx(1, nQuery, CV_32SC2, matches.ptr(0)); GpuMat imgIdx(1, nQuery, CV_32SC2, matches.ptr(1)); GpuMat distance(1, nQuery, CV_32FC2, matches.ptr(2)); trainIdx.setTo(Scalar::all(-1), stream); func(query, trainCollection, maskCollection, trainIdx, imgIdx, distance, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::knnMatchConvert(InputArray _gpu_matches, std::vector< std::vector<DMatch> >& matches, bool compactResult) { Mat gpu_matches; if (_gpu_matches.kind() == _InputArray::CUDA_GPU_MAT) { _gpu_matches.getGpuMat().download(gpu_matches); } else { gpu_matches = _gpu_matches.getMat(); } if (gpu_matches.empty()) { matches.clear(); return; } CV_Assert( ((gpu_matches.type() == CV_32SC2) && (gpu_matches.rows == 2 || gpu_matches.rows == 3)) || (gpu_matches.type() == CV_32SC1) ); int nQuery = -1, k = -1; const int* trainIdxPtr = NULL; const int* imgIdxPtr = NULL; const float* distancePtr = NULL; if (gpu_matches.type() == CV_32SC2) { nQuery = gpu_matches.cols; k = 2; if (gpu_matches.rows == 2) { trainIdxPtr = gpu_matches.ptr<int>(0); distancePtr = gpu_matches.ptr<float>(1); } else { trainIdxPtr = gpu_matches.ptr<int>(0); imgIdxPtr = gpu_matches.ptr<int>(1); distancePtr = gpu_matches.ptr<float>(2); } } else { nQuery = gpu_matches.rows / 2; k = gpu_matches.cols; trainIdxPtr = gpu_matches.ptr<int>(0); distancePtr = gpu_matches.ptr<float>(nQuery); } matches.clear(); matches.reserve(nQuery); for (int queryIdx = 0; queryIdx < nQuery; ++queryIdx) { matches.push_back(std::vector<DMatch>()); std::vector<DMatch>& curMatches = matches.back(); curMatches.reserve(k); for (int i = 0; i < k; ++i) { const int trainIdx = *trainIdxPtr; if (trainIdx == -1) continue; const int imgIdx = imgIdxPtr ? *imgIdxPtr : 0; const float distance = *distancePtr; DMatch m(queryIdx, trainIdx, imgIdx, distance); curMatches.push_back(m); ++trainIdxPtr; ++distancePtr; if (imgIdxPtr) ++imgIdxPtr; } if (compactResult && curMatches.empty()) { matches.pop_back(); } } } // // radius match // void BFMatcher_Impl::radiusMatch(InputArray _queryDescriptors, InputArray _trainDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance, InputArray _mask, bool compactResult) { GpuMat d_matches; radiusMatchAsync(_queryDescriptors, _trainDescriptors, d_matches, maxDistance, _mask); radiusMatchConvert(d_matches, matches, compactResult); } void BFMatcher_Impl::radiusMatch(InputArray _queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance, const std::vector<GpuMat>& masks, bool compactResult) { GpuMat d_matches; radiusMatchAsync(_queryDescriptors, d_matches, maxDistance, masks); radiusMatchConvert(d_matches, matches, compactResult); } void BFMatcher_Impl::radiusMatchAsync(InputArray _queryDescriptors, InputArray _trainDescriptors, OutputArray _matches, float maxDistance, InputArray _mask, Stream& stream) { using namespace cv::cuda::device::bf_radius_match; const GpuMat query = _queryDescriptors.getGpuMat(); const GpuMat train = _trainDescriptors.getGpuMat(); const GpuMat mask = _mask.getGpuMat(); if (query.empty() || train.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); CV_Assert( train.cols == query.cols && train.type() == query.type() ); CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.rows == query.rows && mask.cols == train.rows) ); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask, const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); static const caller_t callersL1[] = { matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/, matchL1_gpu<unsigned short>, matchL1_gpu<short>, matchL1_gpu<int>, matchL1_gpu<float> }; static const caller_t callersL2[] = { 0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/, 0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/, 0/*matchL2_gpu<int>*/, matchL2_gpu<float> }; static const caller_t callersHamming[] = { matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/, matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/, matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; const int nTrain = train.rows; const int cols = std::max((nTrain / 100), nQuery); _matches.create(2 * nQuery + 1, cols, CV_32SC1); GpuMat matches = _matches.getGpuMat(); GpuMat trainIdx(nQuery, cols, CV_32SC1, matches.ptr(0), matches.step); GpuMat distance(nQuery, cols, CV_32FC1, matches.ptr(nQuery), matches.step); GpuMat nMatches(1, nQuery, CV_32SC1, matches.ptr(2 * nQuery)); nMatches.setTo(Scalar::all(0), stream); func(query, train, maxDistance, mask, trainIdx, distance, nMatches, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::radiusMatchAsync(InputArray _queryDescriptors, OutputArray _matches, float maxDistance, const std::vector<GpuMat>& masks, Stream& stream) { using namespace cv::cuda::device::bf_radius_match; const GpuMat query = _queryDescriptors.getGpuMat(); if (query.empty() || trainDescCollection_.empty()) { _matches.release(); return; } CV_Assert( query.channels() == 1 && query.depth() < CV_64F ); GpuMat trainCollection, maskCollection; makeGpuCollection(trainDescCollection_, masks, trainCollection, maskCollection); typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks, const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches, cudaStream_t stream); static const caller_t callersL1[] = { matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/, matchL1_gpu<unsigned short>, matchL1_gpu<short>, matchL1_gpu<int>, matchL1_gpu<float> }; static const caller_t callersL2[] = { 0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/, 0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/, 0/*matchL2_gpu<int>*/, matchL2_gpu<float> }; static const caller_t callersHamming[] = { matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/, matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/, matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/ }; const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming; const caller_t func = callers[query.depth()]; if (func == 0) { CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm"); } const int nQuery = query.rows; _matches.create(3 * nQuery + 1, nQuery, CV_32FC1); GpuMat matches = _matches.getGpuMat(); GpuMat trainIdx(nQuery, nQuery, CV_32SC1, matches.ptr(0), matches.step); GpuMat imgIdx(nQuery, nQuery, CV_32SC1, matches.ptr(nQuery), matches.step); GpuMat distance(nQuery, nQuery, CV_32FC1, matches.ptr(2 * nQuery), matches.step); GpuMat nMatches(1, nQuery, CV_32SC1, matches.ptr(3 * nQuery)); nMatches.setTo(Scalar::all(0), stream); std::vector<PtrStepSzb> trains_(trainDescCollection_.begin(), trainDescCollection_.end()); std::vector<PtrStepSzb> masks_(masks.begin(), masks.end()); func(query, &trains_[0], static_cast<int>(trains_.size()), maxDistance, masks_.size() == 0 ? 0 : &masks_[0], trainIdx, imgIdx, distance, nMatches, StreamAccessor::getStream(stream)); } void BFMatcher_Impl::radiusMatchConvert(InputArray _gpu_matches, std::vector< std::vector<DMatch> >& matches, bool compactResult) { Mat gpu_matches; if (_gpu_matches.kind() == _InputArray::CUDA_GPU_MAT) { _gpu_matches.getGpuMat().download(gpu_matches); } else { gpu_matches = _gpu_matches.getMat(); } if (gpu_matches.empty()) { matches.clear(); return; } CV_Assert( gpu_matches.type() == CV_32SC1 || gpu_matches.type() == CV_32FC1 ); int nQuery = -1; const int* trainIdxPtr = NULL; const int* imgIdxPtr = NULL; const float* distancePtr = NULL; const int* nMatchesPtr = NULL; if (gpu_matches.type() == CV_32SC1) { nQuery = (gpu_matches.rows - 1) / 2; trainIdxPtr = gpu_matches.ptr<int>(0); distancePtr = gpu_matches.ptr<float>(nQuery); nMatchesPtr = gpu_matches.ptr<int>(2 * nQuery); } else { nQuery = (gpu_matches.rows - 1) / 3; trainIdxPtr = gpu_matches.ptr<int>(0); imgIdxPtr = gpu_matches.ptr<int>(nQuery); distancePtr = gpu_matches.ptr<float>(2 * nQuery); nMatchesPtr = gpu_matches.ptr<int>(3 * nQuery); } matches.clear(); matches.reserve(nQuery); for (int queryIdx = 0; queryIdx < nQuery; ++queryIdx) { const int nMatched = std::min(nMatchesPtr[queryIdx], gpu_matches.cols); if (nMatched == 0) { if (!compactResult) { matches.push_back(std::vector<DMatch>()); } } else { matches.push_back(std::vector<DMatch>(nMatched)); std::vector<DMatch>& curMatches = matches.back(); for (int i = 0; i < nMatched; ++i) { const int trainIdx = trainIdxPtr[i]; const int imgIdx = imgIdxPtr ? imgIdxPtr[i] : 0; const float distance = distancePtr[i]; DMatch m(queryIdx, trainIdx, imgIdx, distance); curMatches[i] = m; } std::sort(curMatches.begin(), curMatches.end()); } trainIdxPtr += gpu_matches.cols; distancePtr += gpu_matches.cols; if (imgIdxPtr) imgIdxPtr += gpu_matches.cols; } } } Ptr<cv::cuda::DescriptorMatcher> cv::cuda::DescriptorMatcher::createBFMatcher(int norm) { return makePtr<BFMatcher_Impl>(norm); } #endif /* !defined (HAVE_CUDA) */
DamianPilot382/Rubiks-Cube-Solver
opencv/sources/modules/cudafeatures2d/src/brute_force_matcher.cpp
C++
apache-2.0
43,804
/* * 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.facebook.presto.operator.aggregation; import com.facebook.presto.ExceededMemoryLimitException; import com.facebook.presto.bytecode.DynamicClassLoader; import com.facebook.presto.metadata.BoundVariables; import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.metadata.SqlAggregationFunction; import com.facebook.presto.operator.aggregation.state.KeyValuePairStateSerializer; import com.facebook.presto.operator.aggregation.state.KeyValuePairsState; import com.facebook.presto.operator.aggregation.state.KeyValuePairsStateFactory; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeManager; import com.facebook.presto.type.ArrayType; import com.facebook.presto.type.MapType; import com.google.common.collect.ImmutableList; import java.lang.invoke.MethodHandle; import java.util.List; import static com.facebook.presto.metadata.Signature.comparableTypeParameter; import static com.facebook.presto.metadata.Signature.typeVariable; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INDEX; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INPUT_CHANNEL; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.NULLABLE_BLOCK_INPUT_CHANNEL; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.STATE; import static com.facebook.presto.operator.aggregation.AggregationUtils.generateAggregationName; import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.util.ImmutableCollectors.toImmutableList; import static com.facebook.presto.util.Reflection.methodHandle; import static java.lang.String.format; public class MultimapAggregationFunction extends SqlAggregationFunction { public static final MultimapAggregationFunction MULTIMAP_AGG = new MultimapAggregationFunction(); public static final String NAME = "multimap_agg"; private static final MethodHandle OUTPUT_FUNCTION = methodHandle(MultimapAggregationFunction.class, "output", KeyValuePairsState.class, BlockBuilder.class); private static final MethodHandle INPUT_FUNCTION = methodHandle(MultimapAggregationFunction.class, "input", KeyValuePairsState.class, Block.class, Block.class, int.class); private static final MethodHandle COMBINE_FUNCTION = methodHandle(MultimapAggregationFunction.class, "combine", KeyValuePairsState.class, KeyValuePairsState.class); public MultimapAggregationFunction() { super(NAME, ImmutableList.of(comparableTypeParameter("K"), typeVariable("V")), ImmutableList.of(), parseTypeSignature("map(K,array(V))"), ImmutableList.of(parseTypeSignature("K"), parseTypeSignature("V"))); } @Override public String getDescription() { return "Aggregates all the rows (key/value pairs) into a single multimap"; } @Override public InternalAggregationFunction specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { Type keyType = boundVariables.getTypeVariable("K"); Type valueType = boundVariables.getTypeVariable("V"); return generateAggregation(keyType, valueType); } private static InternalAggregationFunction generateAggregation(Type keyType, Type valueType) { DynamicClassLoader classLoader = new DynamicClassLoader(MultimapAggregationFunction.class.getClassLoader()); List<Type> inputTypes = ImmutableList.of(keyType, valueType); Type outputType = new MapType(keyType, new ArrayType(valueType)); KeyValuePairStateSerializer stateSerializer = new KeyValuePairStateSerializer(keyType, valueType, true); Type intermediateType = stateSerializer.getSerializedType(); AggregationMetadata metadata = new AggregationMetadata( generateAggregationName(NAME, outputType.getTypeSignature(), inputTypes.stream().map(Type::getTypeSignature).collect(toImmutableList())), createInputParameterMetadata(keyType, valueType), INPUT_FUNCTION, COMBINE_FUNCTION, OUTPUT_FUNCTION, KeyValuePairsState.class, stateSerializer, new KeyValuePairsStateFactory(keyType, valueType), outputType); GenericAccumulatorFactoryBinder factory = AccumulatorCompiler.generateAccumulatorFactoryBinder(metadata, classLoader); return new InternalAggregationFunction(NAME, inputTypes, intermediateType, outputType, true, factory); } private static List<ParameterMetadata> createInputParameterMetadata(Type keyType, Type valueType) { return ImmutableList.of(new ParameterMetadata(STATE), new ParameterMetadata(BLOCK_INPUT_CHANNEL, keyType), new ParameterMetadata(NULLABLE_BLOCK_INPUT_CHANNEL, valueType), new ParameterMetadata(BLOCK_INDEX)); } public static void input(KeyValuePairsState state, Block key, Block value, int position) { KeyValuePairs pairs = state.get(); if (pairs == null) { pairs = new KeyValuePairs(state.getKeyType(), state.getValueType(), true); state.set(pairs); } long startSize = pairs.estimatedInMemorySize(); try { pairs.add(key, value, position, position); } catch (ExceededMemoryLimitException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("The result of map_agg may not exceed %s", e.getMaxMemory())); } state.addMemoryUsage(pairs.estimatedInMemorySize() - startSize); } public static void combine(KeyValuePairsState state, KeyValuePairsState otherState) { if (state.get() != null && otherState.get() != null) { Block keys = otherState.get().getKeys(); Block values = otherState.get().getValues(); KeyValuePairs pairs = state.get(); long startSize = pairs.estimatedInMemorySize(); for (int i = 0; i < keys.getPositionCount(); i++) { try { pairs.add(keys, values, i, i); } catch (ExceededMemoryLimitException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("The result of map_agg may not exceed %s", e.getMaxMemory())); } } state.addMemoryUsage(pairs.estimatedInMemorySize() - startSize); } else if (state.get() == null) { state.set(otherState.get()); } } public static void output(KeyValuePairsState state, BlockBuilder out) { KeyValuePairs pairs = state.get(); if (pairs == null) { out.appendNull(); } else { Block block = pairs.toMultimapNativeEncoding(); out.writeObject(block); out.closeEntry(); } } }
marsorp/blog
presto166/presto-main/src/main/java/com/facebook/presto/operator/aggregation/MultimapAggregationFunction.java
Java
apache-2.0
8,045
import { __platform_browser_private__ as r } from '@angular/platform-browser'; export var getDOM = r.getDOM; //# sourceMappingURL=platform_browser_private.js.map
evandor/skysail-webconsole
webconsole.client/client/dist/lib/@angular/platform-browser-dynamic/esm/platform_browser_private.js
JavaScript
apache-2.0
161
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.krad.devtools.datadictionary; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.net.URL; import java.util.LinkedList; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.zip.CRC32; import java.util.zip.CheckedInputStream; /** * This is a description of what this class does - gilesp don't forget to fill this in. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ public class URLMonitor { private static final Log LOG = LogFactory.getLog(URLMonitor.class); private final LinkedList<URLContentChangedListener> listeners = new LinkedList<URLContentChangedListener>(); private final Map<URL, Long> resourceMap = new ConcurrentHashMap(); private final int reloadIntervalMilliseconds; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public URLMonitor(int reloadIntervalMilliseconds) { this.reloadIntervalMilliseconds = reloadIntervalMilliseconds; } public void shutdownScheduler() { scheduler.shutdown(); } public synchronized void addListener(URLContentChangedListener listener) { listeners.add(listener); if (listeners.size() == 1) { scheduler.scheduleAtFixedRate(urlPoller, reloadIntervalMilliseconds, reloadIntervalMilliseconds, TimeUnit.MILLISECONDS); } } public void addURI(URL zipUrl) { resourceMap.put(zipUrl, getCRC(zipUrl)); } private Long getCRC(URL zipUrl) { Long result = -1l; try { CRC32 crc = new CRC32(); CheckedInputStream cis = new CheckedInputStream(zipUrl.openStream(), crc); byte[] buffer = new byte[1024]; int length; //read the entry from zip file and extract it to disk while( (length = cis.read(buffer)) > 0); cis.close(); result = crc.getValue(); } catch (IOException e) { LOG.warn("Unable to calculate CRC, resource doesn't exist?", e); } return result; } private final Runnable urlPoller = new Runnable() { @Override public void run() { for (Map.Entry<URL, Long> entry : resourceMap.entrySet()) { Long crc = getCRC(entry.getKey()); if (!entry.getValue().equals(crc)) { entry.setValue(crc); for (URLContentChangedListener listener : listeners) { listener.urlContentChanged(entry.getKey()); } } } } }; public static interface URLContentChangedListener { public void urlContentChanged(URL url); } }
bhutchinson/rice
rice-framework/krad-development-tools/src/main/java/org/kuali/rice/krad/devtools/datadictionary/URLMonitor.java
Java
apache-2.0
3,664
/* * 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.facebook.presto.accumulo; import com.facebook.presto.accumulo.conf.AccumuloConfig; import com.facebook.presto.accumulo.conf.AccumuloTableProperties; import com.facebook.presto.accumulo.index.ColumnCardinalityCache; import com.facebook.presto.accumulo.index.IndexLookup; import com.facebook.presto.accumulo.metadata.AccumuloTable; import com.facebook.presto.accumulo.metadata.ZooKeeperMetadataManager; import com.facebook.presto.spi.ColumnMetadata; import com.facebook.presto.spi.ConnectorTableMetadata; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.type.TypeRegistry; import com.google.common.collect.ImmutableList; import org.apache.accumulo.core.client.Connector; import org.testng.annotations.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static org.testng.Assert.assertNotNull; public class TestAccumuloClient { private final AccumuloClient client; private final ZooKeeperMetadataManager zooKeeperMetadataManager; public TestAccumuloClient() throws Exception { AccumuloConfig config = new AccumuloConfig() .setUsername("root") .setPassword("secret"); Connector connector = AccumuloQueryRunner.getAccumuloConnector(); config.setZooKeepers(connector.getInstance().getZooKeepers()); zooKeeperMetadataManager = new ZooKeeperMetadataManager(config, new TypeRegistry()); client = new AccumuloClient(connector, config, zooKeeperMetadataManager, new AccumuloTableManager(connector), new IndexLookup(connector, new ColumnCardinalityCache(connector, config))); } @Test public void testCreateTableEmptyAccumuloColumn() throws Exception { SchemaTableName tableName = new SchemaTableName("default", "test_create_table_empty_accumulo_column"); try { List<ColumnMetadata> columns = ImmutableList.of( new ColumnMetadata("id", BIGINT), new ColumnMetadata("a", BIGINT), new ColumnMetadata("b", BIGINT), new ColumnMetadata("c", BIGINT), new ColumnMetadata("d", BIGINT)); Map<String, Object> properties = new HashMap<>(); new AccumuloTableProperties().getTableProperties().forEach(meta -> properties.put(meta.getName(), meta.getDefaultValue())); properties.put("external", true); properties.put("column_mapping", "a:a:a,b::b,c:c:,d::"); client.createTable(new ConnectorTableMetadata(tableName, columns, properties)); assertNotNull(client.getTable(tableName)); } finally { AccumuloTable table = zooKeeperMetadataManager.getTable(tableName); if (table != null) { client.dropTable(table); } } } }
svstanev/presto
presto-accumulo/src/test/java/com/facebook/presto/accumulo/TestAccumuloClient.java
Java
apache-2.0
3,498
package j_credential // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" "github.com/go-openapi/swag" strfmt "github.com/go-openapi/strfmt" "koding/remoteapi/models" ) // PostRemoteAPIJCredentialFetchUsersIDReader is a Reader for the PostRemoteAPIJCredentialFetchUsersID structure. type PostRemoteAPIJCredentialFetchUsersIDReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *PostRemoteAPIJCredentialFetchUsersIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewPostRemoteAPIJCredentialFetchUsersIDOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: return nil, runtime.NewAPIError("unknown error", response, response.Code()) } } // NewPostRemoteAPIJCredentialFetchUsersIDOK creates a PostRemoteAPIJCredentialFetchUsersIDOK with default headers values func NewPostRemoteAPIJCredentialFetchUsersIDOK() *PostRemoteAPIJCredentialFetchUsersIDOK { return &PostRemoteAPIJCredentialFetchUsersIDOK{} } /*PostRemoteAPIJCredentialFetchUsersIDOK handles this case with default header values. OK */ type PostRemoteAPIJCredentialFetchUsersIDOK struct { Payload PostRemoteAPIJCredentialFetchUsersIDOKBody } func (o *PostRemoteAPIJCredentialFetchUsersIDOK) Error() string { return fmt.Sprintf("[POST /remote.api/JCredential.fetchUsers/{id}][%d] postRemoteApiJCredentialFetchUsersIdOK %+v", 200, o.Payload) } func (o *PostRemoteAPIJCredentialFetchUsersIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { // response payload if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { return err } return nil } /*PostRemoteAPIJCredentialFetchUsersIDOKBody post remote API j credential fetch users ID o k body swagger:model PostRemoteAPIJCredentialFetchUsersIDOKBody */ type PostRemoteAPIJCredentialFetchUsersIDOKBody struct { models.JCredential models.DefaultResponse } // UnmarshalJSON unmarshals this object from a JSON structure func (o *PostRemoteAPIJCredentialFetchUsersIDOKBody) UnmarshalJSON(raw []byte) error { var postRemoteAPIJCredentialFetchUsersIDOKBodyAO0 models.JCredential if err := swag.ReadJSON(raw, &postRemoteAPIJCredentialFetchUsersIDOKBodyAO0); err != nil { return err } o.JCredential = postRemoteAPIJCredentialFetchUsersIDOKBodyAO0 var postRemoteAPIJCredentialFetchUsersIDOKBodyAO1 models.DefaultResponse if err := swag.ReadJSON(raw, &postRemoteAPIJCredentialFetchUsersIDOKBodyAO1); err != nil { return err } o.DefaultResponse = postRemoteAPIJCredentialFetchUsersIDOKBodyAO1 return nil } // MarshalJSON marshals this object to a JSON structure func (o PostRemoteAPIJCredentialFetchUsersIDOKBody) MarshalJSON() ([]byte, error) { var _parts [][]byte postRemoteAPIJCredentialFetchUsersIDOKBodyAO0, err := swag.WriteJSON(o.JCredential) if err != nil { return nil, err } _parts = append(_parts, postRemoteAPIJCredentialFetchUsersIDOKBodyAO0) postRemoteAPIJCredentialFetchUsersIDOKBodyAO1, err := swag.WriteJSON(o.DefaultResponse) if err != nil { return nil, err } _parts = append(_parts, postRemoteAPIJCredentialFetchUsersIDOKBodyAO1) return swag.ConcatJSON(_parts...), nil } // Validate validates this post remote API j credential fetch users ID o k body func (o *PostRemoteAPIJCredentialFetchUsersIDOKBody) Validate(formats strfmt.Registry) error { var res []error if err := o.JCredential.Validate(formats); err != nil { res = append(res, err) } if err := o.DefaultResponse.Validate(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
drewsetski/koding
go/src/koding/remoteapi/client/j_credential/post_remote_api_j_credential_fetch_users_id_responses.go
GO
apache-2.0
4,007
/* * 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.flink.streaming.api.operators.collect; import org.apache.flink.core.memory.DataInputViewStreamWrapper; import org.apache.flink.core.memory.DataOutputViewStreamWrapper; import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.runtime.operators.coordination.CoordinationRequest; import org.apache.flink.runtime.operators.coordination.CoordinationRequestHandler; import org.apache.flink.runtime.operators.coordination.CoordinationResponse; import org.apache.flink.runtime.operators.coordination.OperatorCoordinator; import org.apache.flink.runtime.operators.coordination.OperatorEvent; import org.apache.flink.util.Preconditions; import org.apache.flink.util.concurrent.ExecutorThreadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.util.Collections; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * {@link OperatorCoordinator} for {@link CollectSinkFunction}. * * <p>This coordinator only forwards requests and responses from clients and sinks and it does not * store any results in itself. */ public class CollectSinkOperatorCoordinator implements OperatorCoordinator, CoordinationRequestHandler { private static final Logger LOG = LoggerFactory.getLogger(CollectSinkOperatorCoordinator.class); private final int socketTimeout; private InetSocketAddress address; private Socket socket; private DataInputViewStreamWrapper inStream; private DataOutputViewStreamWrapper outStream; private ExecutorService executorService; public CollectSinkOperatorCoordinator(int socketTimeout) { this.socketTimeout = socketTimeout; } @Override public void start() throws Exception { this.executorService = Executors.newSingleThreadExecutor( new ExecutorThreadFactory( "collect-sink-operator-coordinator-executor-thread-pool")); } @Override public void close() throws Exception { closeConnection(); this.executorService.shutdown(); } @Override public void handleEventFromOperator(int subtask, OperatorEvent event) throws Exception { Preconditions.checkArgument( event instanceof CollectSinkAddressEvent, "Operator event must be a CollectSinkAddressEvent"); address = ((CollectSinkAddressEvent) event).getAddress(); LOG.info("Received sink socket server address: " + address); } @Override public CompletableFuture<CoordinationResponse> handleCoordinationRequest( CoordinationRequest request) { Preconditions.checkArgument( request instanceof CollectCoordinationRequest, "Coordination request must be a CollectCoordinationRequest"); CollectCoordinationRequest collectRequest = (CollectCoordinationRequest) request; CompletableFuture<CoordinationResponse> responseFuture = new CompletableFuture<>(); if (address == null) { completeWithEmptyResponse(collectRequest, responseFuture); return responseFuture; } executorService.submit(() -> handleRequestImpl(collectRequest, responseFuture, address)); return responseFuture; } private void handleRequestImpl( CollectCoordinationRequest request, CompletableFuture<CoordinationResponse> responseFuture, InetSocketAddress sinkAddress) { if (sinkAddress == null) { closeConnection(); completeWithEmptyResponse(request, responseFuture); return; } try { if (socket == null) { socket = new Socket(); socket.setSoTimeout(socketTimeout); socket.setKeepAlive(true); socket.setTcpNoDelay(true); socket.connect(sinkAddress); inStream = new DataInputViewStreamWrapper(socket.getInputStream()); outStream = new DataOutputViewStreamWrapper(socket.getOutputStream()); LOG.info("Sink connection established"); } // send version and offset to sink server if (LOG.isDebugEnabled()) { LOG.debug("Forwarding request to sink socket server"); } request.serialize(outStream); // fetch back serialized results if (LOG.isDebugEnabled()) { LOG.debug("Fetching serialized result from sink socket server"); } responseFuture.complete(new CollectCoordinationResponse(inStream)); } catch (Exception e) { // request failed, close current connection and send back empty results // we catch every exception here because socket might suddenly becomes null if the sink // fails // and we do not want the coordinator to fail if (LOG.isDebugEnabled()) { // this is normal when sink restarts or job ends, so we print a debug log LOG.debug("Collect sink coordinator encounters an exception", e); } closeConnection(); completeWithEmptyResponse(request, responseFuture); } } private void completeWithEmptyResponse( CollectCoordinationRequest request, CompletableFuture<CoordinationResponse> future) { future.complete( new CollectCoordinationResponse( request.getVersion(), // this lastCheckpointedOffset is OK // because client will only expose results to the users when the // checkpointed offset increases -1, Collections.emptyList())); } private void closeConnection() { if (socket != null) { try { socket.close(); } catch (IOException e) { LOG.warn("Failed to close sink socket server connection", e); } } socket = null; } @Override public void subtaskFailed(int subtask, @Nullable Throwable reason) { // subtask failed, the socket server does not exist anymore address = null; } @Override public void subtaskReset(int subtask, long checkpointId) { // nothing to do here, connections are re-created lazily } @Override public void subtaskReady(int subtask, SubtaskGateway gateway) { // nothing to do here, connections are re-created lazily } @Override public void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> result) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(address); result.complete(baos.toByteArray()); } @Override public void notifyCheckpointComplete(long checkpointId) {} @Override public void resetToCheckpoint(long checkpointId, @Nullable byte[] checkpointData) throws Exception { if (checkpointData == null) { // restore before any checkpoint completed closeConnection(); } else { ByteArrayInputStream bais = new ByteArrayInputStream(checkpointData); ObjectInputStream ois = new ObjectInputStream(bais); address = (InetSocketAddress) ois.readObject(); } } /** Provider for {@link CollectSinkOperatorCoordinator}. */ public static class Provider implements OperatorCoordinator.Provider { private final OperatorID operatorId; private final int socketTimeout; public Provider(OperatorID operatorId, int socketTimeout) { this.operatorId = operatorId; this.socketTimeout = socketTimeout; } @Override public OperatorID getOperatorId() { return operatorId; } @Override public OperatorCoordinator create(Context context) { // we do not send operator event so we don't need a context return new CollectSinkOperatorCoordinator(socketTimeout); } } }
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/collect/CollectSinkOperatorCoordinator.java
Java
apache-2.0
9,405
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "glog/logging.h" #include "NvInferPlugin.h" #include "logger.h" #include "test_settings.h" #include "loadgen.h" #include "numpy.hpp" #include "qsl.hpp" #include "dlrm_server.h" #include "dlrm_qsl.hpp" #include "utils.hpp" #include "cuda_profiler_api.h" #include <dlfcn.h> DEFINE_string(gpu_engines, "", "Engine"); DEFINE_string(plugins, "", "Comma-separated list of shared objects for plugins"); DEFINE_string(scenario, "Offline", "Scenario to run for Loadgen (Offline, SingleStream, Server)"); DEFINE_string(test_mode, "PerformanceOnly", "Testing mode for Loadgen"); DEFINE_string(model, "dlrm", "Model name"); DEFINE_uint32(gpu_batch_size, 16384, "Max Batch size to use for all devices and engines"); DEFINE_bool(use_graphs, false, "Enable cudaGraphs for TensorRT engines"); // TODO: Enable support for Cuda Graphs DEFINE_bool(verbose, false, "Use verbose logging"); DEFINE_uint32(gpu_copy_streams, 1, "[CURRENTLY NOT USED] Number of copy streams"); DEFINE_uint32(gpu_num_bundles, 2, "Number of event-buffer bundles per GPU"); DEFINE_uint32(complete_threads, 1, "Number of threads per device for sending responses"); DEFINE_uint32(gpu_inference_streams, 1, "Number of inference streams"); DEFINE_double(warmup_duration, 1.0, "Minimum duration to run warmup for"); // configuration files DEFINE_string(mlperf_conf_path, "", "Path to mlperf.conf"); DEFINE_string(user_conf_path, "", "Path to user.conf"); DEFINE_uint64(single_stream_expected_latency_ns, 100000, "Inverse of desired target QPS"); // Loadgen logging settings DEFINE_string(logfile_outdir, "", "Specify the existing output directory for the LoadGen logs"); DEFINE_string(logfile_prefix, "", "Specify the filename prefix for the LoadGen log files"); DEFINE_string(logfile_suffix, "", "Specify the filename suffix for the LoadGen log files"); DEFINE_bool(logfile_prefix_with_datetime, false, "Prefix filenames for LoadGen log files"); DEFINE_bool(log_copy_detail_to_stdout, false, "Copy LoadGen detailed logging to stdout"); DEFINE_bool(disable_log_copy_summary_to_stdout, false, "Disable copy LoadGen summary logging to stdout"); DEFINE_string(log_mode, "AsyncPoll", "Logging mode for Loadgen"); DEFINE_uint64(log_mode_async_poll_interval_ms, 1000, "Specify the poll interval for asynchrounous logging"); DEFINE_bool(log_enable_trace, false, "Enable trace logging"); // QSL arguments DEFINE_string(map_path, "", "Path to map file for samples"); DEFINE_string(sample_partition_path, "", "Path to sample partition file in npy format."); DEFINE_string(tensor_path, "", "Path to preprocessed samples in npy format (<full_image_name>.npy). Comma-separated list if there are more than one input."); DEFINE_uint64(performance_sample_count, 0, "Number of samples to load in performance set. 0=use default"); DEFINE_bool(start_from_device, false, "Assuming that inputs start from device memory in QSL"); // Dataset arguments DEFINE_uint32(min_sample_size, 100, "Minimum number of pairs a sample can contain."); DEFINE_uint32(max_sample_size, 700, "Maximum number of pairs a sample can contain."); // BatchMaker arguments DEFINE_uint32(num_staging_threads, 8, "Number of staging threads in DLRM BatchMaker"); DEFINE_uint32(num_staging_batches, 4, "Number of staging batches in DLRM BatchMaker"); DEFINE_uint32(max_pairs_per_staging_thread, 0, "Maximum pairs to copy in one BatchMaker staging thread (0 = use default"); DEFINE_bool(check_contiguity, false, "Whether to use contiguity checking in BatchMaker (default: false, recommended: true for Offline)"); DEFINE_string(numa_config, "", "NUMA settings: cpu cores for each GPU, assuming each GPU corresponds to one NUMA node"); /* Define a map to convert test mode input string into its corresponding enum value */ std::map<std::string, mlperf::TestScenario> scenarioMap = { {"Offline", mlperf::TestScenario::Offline}, {"SingleStream", mlperf::TestScenario::SingleStream}, {"Server", mlperf::TestScenario::Server}, }; /* Define a map to convert test mode input string into its corresponding enum value */ std::map<std::string, mlperf::TestMode> testModeMap = { {"SubmissionRun", mlperf::TestMode::SubmissionRun}, {"AccuracyOnly", mlperf::TestMode::AccuracyOnly}, {"PerformanceOnly", mlperf::TestMode::PerformanceOnly} }; /* Define a map to convert logging mode input string into its corresponding enum value */ std::map<std::string, mlperf::LoggingMode> logModeMap = { {"AsyncPoll", mlperf::LoggingMode::AsyncPoll}, {"EndOfTestOnly", mlperf::LoggingMode::EndOfTestOnly}, {"Synchronous", mlperf::LoggingMode::Synchronous} }; // Example of the format: "0-63,64-127" for 2 GPUs (one per NUMA node). NumaConfig parseNumaConfig(const std::string& s) { NumaConfig config; if (!s.empty()) { auto nodes = splitString(s, ","); for (const auto& node : nodes) { auto cpuRange = splitString(node, "-"); CHECK(cpuRange.size() == 2) << "Invalid numa_config setting."; int start = std::stoi(cpuRange[0]); int last = std::stoi(cpuRange[1]); CHECK(start <= last) << "Invalid numa_config setting."; std::vector<int> cpus(last - start + 1); for (int i = start; i <= last; ++i) { cpus[i - start] = i; } config.emplace_back(cpus); } } return config; } int main(int argc, char* argv[]) { FLAGS_alsologtostderr = 1; // Log to console ::google::InitGoogleLogging("TensorRT mlperf"); ::google::ParseCommandLineFlags(&argc, &argv, true); const std::string gSampleName = "DLRM_HARNESS"; auto sampleTest = gLogger.defineTest(gSampleName, argc, const_cast<const char**>(argv)); if (FLAGS_verbose) { setReportableSeverity(Severity::kVERBOSE); } gLogger.reportTestStart(sampleTest); initLibNvInferPlugins(&gLogger.getTRTLogger(), ""); // Load all the needed shared objects for plugins. std::vector<std::string> plugin_files = splitString(FLAGS_plugins, ","); for (auto& s : plugin_files) { void* dlh = dlopen(s.c_str(), RTLD_LAZY); if (nullptr == dlh) { gLogError << "Error loading plugin library " << s << std::endl; return 1; } } // Scope to force all smart objects destruction before CUDA context resets { int num_gpu; cudaGetDeviceCount(&num_gpu); LOG(INFO) << "Found " << num_gpu << " GPUs"; // Configure the test settings mlperf::TestSettings testSettings; testSettings.scenario = scenarioMap[FLAGS_scenario]; testSettings.mode = testModeMap[FLAGS_test_mode]; testSettings.FromConfig(FLAGS_mlperf_conf_path, FLAGS_model, FLAGS_scenario); testSettings.FromConfig(FLAGS_user_conf_path, FLAGS_model, FLAGS_scenario); testSettings.single_stream_expected_latency_ns = FLAGS_single_stream_expected_latency_ns; testSettings.server_coalesce_queries = true; // Configure the logging settings mlperf::LogSettings logSettings; logSettings.log_output.outdir = FLAGS_logfile_outdir; logSettings.log_output.prefix = FLAGS_logfile_prefix; logSettings.log_output.suffix = FLAGS_logfile_suffix; logSettings.log_output.prefix_with_datetime = FLAGS_logfile_prefix_with_datetime; logSettings.log_output.copy_detail_to_stdout = FLAGS_log_copy_detail_to_stdout; logSettings.log_output.copy_summary_to_stdout = !FLAGS_disable_log_copy_summary_to_stdout; logSettings.log_mode = logModeMap[FLAGS_log_mode]; logSettings.log_mode_async_poll_interval_ms = FLAGS_log_mode_async_poll_interval_ms; logSettings.enable_trace = FLAGS_log_enable_trace; std::vector<int> gpus(num_gpu); std::iota(gpus.begin(), gpus.end(), 0); // Load the sample partition. We do this here to calculate the performance sample count of the underlying // LWIS QSL, since the super constructor must be in the constructor initialization list. std::vector<int> originalPartition; // Scope to automatically close the file { npy::NpyFile samplePartitionFile(FLAGS_sample_partition_path); CHECK_EQ(samplePartitionFile.getDims().size(), 1); // For now we do not allow numPartitions == FLAGS_performance_sample_count, since the TotalSampleCount // is determined at runtime in the underlying LWIS QSL. size_t numPartitions = samplePartitionFile.getDims()[0]; CHECK_EQ(numPartitions > FLAGS_performance_sample_count, true); std::vector<char> tmp(samplePartitionFile.getTensorSize()); samplePartitionFile.loadAll(tmp); originalPartition.resize(numPartitions); memcpy(originalPartition.data(), tmp.data(), tmp.size()); LOG(INFO) << "Loaded " << originalPartition.size() - 1 << " sample partitions. (" << tmp.size() << ") bytes."; } // Force underlying QSL to load all samples, since we want to be able to grab any partition given the sample // index. size_t perfPairCount = originalPartition.back(); auto qsl = std::make_shared<DLRMSampleLibrary>( "DLRM QSL", FLAGS_map_path, splitString(FLAGS_tensor_path, ","), originalPartition, FLAGS_performance_sample_count, perfPairCount, 0, true, FLAGS_start_from_device); auto dlrm_server = std::make_shared<DLRMServer>( "DLRM SERVER", FLAGS_gpu_engines, qsl, gpus, FLAGS_gpu_batch_size, FLAGS_gpu_num_bundles, FLAGS_complete_threads, FLAGS_gpu_inference_streams, FLAGS_warmup_duration, FLAGS_num_staging_threads, FLAGS_num_staging_batches, FLAGS_max_pairs_per_staging_thread, FLAGS_check_contiguity, FLAGS_start_from_device, parseNumaConfig(FLAGS_numa_config)); LOG(INFO) << "Starting running actual test."; cudaProfilerStart(); StartTest(dlrm_server.get(), qsl.get(), testSettings, logSettings); cudaProfilerStop(); LOG(INFO) << "Finished running actual test."; } return 0; }
mlperf/inference_results_v0.7
open/Inspur/code/harness/harness_dlrm/main_dlrm.cc
C++
apache-2.0
11,024
cask :v1 => 'font-lohit-tamil-classical' do version '2.5.3' sha256 '325ea1496bb2ae4f77552c268190251a5155717dccda64d497da4388d17c2432' url "https://fedorahosted.org/releases/l/o/lohit/lohit-tamil-classical-ttf-#{version}.tar.gz" homepage 'https://fedorahosted.org/lohit/' license :unknown font "lohit-tamil-classical-ttf-#{version}/Lohit-Tamil-Classical.ttf" end
elmariofredo/homebrew-fonts
Casks/font-lohit-tamil-classical.rb
Ruby
bsd-2-clause
376
class AddPlaneIdToNodes < ActiveRecord::Migration def change add_column :nodes, :plane_id, :integer add_index :nodes, :plane_id end end
irubi/rabel
db/migrate/20111209080432_add_plane_id_to_nodes.rb
Ruby
bsd-3-clause
148
/** * The MIT License * Copyright (c) 2014 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.front.controller; /** * * Command for archers. * */ public class ArcherCommand implements Command { @Override public void process() { new ArcherView().display(); } }
WeRockStar/java-design-patterns
front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java
Java
mit
1,344
module ActiveAdmin module ViewHelpers module AutoLinkHelper # Automatically links objects to their resource controllers. If # the resource has not been registered, a string representation of # the object is returned. # # The default content in the link is returned from ActiveAdmin::ViewHelpers::DisplayHelper#display_name # # You can pass in the content to display # eg: auto_link(@post, "My Link") # def auto_link(resource, content = display_name(resource)) if url = auto_url_for(resource) link_to content, url else content end end # Like `auto_link`, except that it only returns a URL instead of a full <a> tag def auto_url_for(resource) config = active_admin_resource_for(resource.class) return unless config if config.controller.action_methods.include?("show") && authorized?(ActiveAdmin::Auth::READ, resource) url_for config.route_instance_path resource, url_options elsif config.controller.action_methods.include?("edit") && authorized?(ActiveAdmin::Auth::UPDATE, resource) url_for config.route_edit_instance_path resource, url_options end end # Returns the ActiveAdmin::Resource instance for a class def active_admin_resource_for(klass) if respond_to? :active_admin_namespace active_admin_namespace.resource_for klass end end end end end
vraravam/activeadmin
lib/active_admin/view_helpers/auto_link_helper.rb
Ruby
mit
1,517
/** * The MIT License * Copyright (c) 2014 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.iterator; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; /** * Date: 12/14/15 - 2:58 PM * * @author Jeroen Meulemeester */ @RunWith(Parameterized.class) public class TreasureChestTest { /** * Create a list of all expected items in the chest. * * @return The set of all expected items in the chest */ @Parameterized.Parameters public static List<Object[]> data() { final List<Object[]> parameters = new ArrayList<>(); parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of courage")}); parameters.add(new Object[]{new Item(ItemType.RING, "Ring of shadows")}); parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of wisdom")}); parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of blood")}); parameters.add(new Object[]{new Item(ItemType.WEAPON, "Sword of silver +1")}); parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of rust")}); parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of healing")}); parameters.add(new Object[]{new Item(ItemType.RING, "Ring of armor")}); parameters.add(new Object[]{new Item(ItemType.WEAPON, "Steel halberd")}); parameters.add(new Object[]{new Item(ItemType.WEAPON, "Dagger of poison")}); return parameters; } /** * One of the expected items in the chest */ private final Item expectedItem; /** * Create a new test instance, test if the given expected item can be retrieved from the chest * * @param expectedItem One of the items that should be in the chest */ public TreasureChestTest(final Item expectedItem) { this.expectedItem = expectedItem; } /** * Test if the expected item can be retrieved from the chest using the {@link ItemIterator} */ @Test public void testIterator() { final TreasureChest chest = new TreasureChest(); final ItemIterator iterator = chest.iterator(expectedItem.getType()); assertNotNull(iterator); while (iterator.hasNext()) { final Item item = iterator.next(); assertNotNull(item); assertEquals(this.expectedItem.getType(), item.getType()); final String name = item.toString(); assertNotNull(name); if (this.expectedItem.toString().equals(name)) { return; } } fail("Expected to find item [" + this.expectedItem + "] using iterator, but we didn't."); } /** * Test if the expected item can be retrieved from the chest using the {@link * TreasureChest#getItems()} method */ @Test public void testGetItems() throws Exception { final TreasureChest chest = new TreasureChest(); final List<Item> items = chest.getItems(); assertNotNull(items); for (final Item item : items) { assertNotNull(item); assertNotNull(item.getType()); assertNotNull(item.toString()); final boolean sameType = this.expectedItem.getType() == item.getType(); final boolean sameName = this.expectedItem.toString().equals(item.toString()); if (sameType && sameName) { return; } } fail("Expected to find item [" + this.expectedItem + "] in the item list, but we didn't."); } }
WeRockStar/java-design-patterns
iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java
Java
mit
4,546
exports.x = "d";
g0ddish/webpack
test/cases/parsing/harmony-duplicate-export/d.js
JavaScript
mit
17
var test = require("tap").test var server = require("./lib/server.js") var common = require("./lib/common.js") var client = common.freshClient() var cache = require("./fixtures/underscore/cache.json") function nop () {} var URI = "https://npm.registry:8043/rewrite" var STARRED = true var USERNAME = "username" var PASSWORD = "%1234@asdf%" var EMAIL = "i@izs.me" var AUTH = { username : USERNAME, password : PASSWORD, email : EMAIL } var PARAMS = { starred : STARRED, auth : AUTH } test("star call contract", function (t) { t.throws(function () { client.star(undefined, PARAMS, nop) }, "requires a URI") t.throws(function () { client.star([], PARAMS, nop) }, "requires URI to be a string") t.throws(function () { client.star(URI, undefined, nop) }, "requires params object") t.throws(function () { client.star(URI, "", nop) }, "params must be object") t.throws(function () { client.star(URI, PARAMS, undefined) }, "requires callback") t.throws(function () { client.star(URI, PARAMS, "callback") }, "callback must be function") t.throws( function () { var params = { starred : STARRED } client.star(URI, params, nop) }, { name : "AssertionError", message : "must pass auth to star" }, "params must include auth" ) t.test("token auth disallowed in star", function (t) { var params = { auth : { token : "lol" } } client.star(URI, params, function (err) { t.equal( err && err.message, "This operation is unsupported for token-based auth", "star doesn't support token-based auth" ) t.end() }) }) t.end() }) test("star a package", function (t) { server.expect("GET", "/underscore?write=true", function (req, res) { t.equal(req.method, "GET") res.json(cache) }) server.expect("PUT", "/underscore", function (req, res) { t.equal(req.method, "PUT") var b = "" req.setEncoding("utf8") req.on("data", function (d) { b += d }) req.on("end", function () { var updated = JSON.parse(b) var already = [ "vesln", "mvolkmann", "lancehunt", "mikl", "linus", "vasc", "bat", "dmalam", "mbrevoort", "danielr", "rsimoes", "thlorenz" ] for (var i = 0; i < already.length; i++) { var current = already[i] t.ok( updated.users[current], current + " still likes this package" ) } t.ok(updated.users[USERNAME], "user is in the starred list") res.statusCode = 201 res.json({starred:true}) }) }) var params = { starred : STARRED, auth : AUTH } client.star("http://localhost:1337/underscore", params, function (error, data) { t.ifError(error, "no errors") t.ok(data.starred, "was starred") t.end() }) })
lwthatcher/Compass
web/node_modules/npm/node_modules/npm-registry-client/test/star.js
JavaScript
mit
2,885
/** * The MIT License * Copyright (c) 2014 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.facade; /** * * The Facade design pattern is often used when a system is very complex or difficult to understand * because the system has a large number of interdependent classes or its source code is * unavailable. This pattern hides the complexities of the larger system and provides a simpler * interface to the client. It typically involves a single wrapper class which contains a set of * members required by client. These members access the system on behalf of the facade client and * hide the implementation details. * <p> * In this example the Facade is ({@link DwarvenGoldmineFacade}) and it provides a simpler interface * to the goldmine subsystem. * */ public class App { /** * Program entry point * * @param args command line args */ public static void main(String[] args) { DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade(); facade.startNewDay(); facade.digOutGold(); facade.endDay(); } }
DevFactory/java-design-patterns
facade/src/main/java/com/iluwatar/facade/App.java
Java
mit
2,123
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Graph.RBAC.Models { using Microsoft.Azure; using Microsoft.Azure.Graph; using Microsoft.Azure.Graph.RBAC; using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Request parameters for creating a new service principal. /// </summary> public partial class ServicePrincipalCreateParameters { /// <summary> /// Initializes a new instance of the ServicePrincipalCreateParameters /// class. /// </summary> public ServicePrincipalCreateParameters() { CustomInit(); } /// <summary> /// Initializes a new instance of the ServicePrincipalCreateParameters /// class. /// </summary> /// <param name="appId">application Id</param> /// <param name="accountEnabled">Whether the account is enabled</param> /// <param name="keyCredentials">A collection of KeyCredential /// objects.</param> /// <param name="passwordCredentials">A collection of /// PasswordCredential objects</param> public ServicePrincipalCreateParameters(string appId, bool accountEnabled, IList<KeyCredential> keyCredentials = default(IList<KeyCredential>), IList<PasswordCredential> passwordCredentials = default(IList<PasswordCredential>)) { AppId = appId; AccountEnabled = accountEnabled; KeyCredentials = keyCredentials; PasswordCredentials = passwordCredentials; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets application Id /// </summary> [JsonProperty(PropertyName = "appId")] public string AppId { get; set; } /// <summary> /// Gets or sets whether the account is enabled /// </summary> [JsonProperty(PropertyName = "accountEnabled")] public bool AccountEnabled { get; set; } /// <summary> /// Gets or sets a collection of KeyCredential objects. /// </summary> [JsonProperty(PropertyName = "keyCredentials")] public IList<KeyCredential> KeyCredentials { get; set; } /// <summary> /// Gets or sets a collection of PasswordCredential objects /// </summary> [JsonProperty(PropertyName = "passwordCredentials")] public IList<PasswordCredential> PasswordCredentials { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (AppId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "AppId"); } } } }
ScottHolden/azure-sdk-for-net
src/SDKs/Graph.RBAC/Graph.RBAC/Generated/Models/ServicePrincipalCreateParameters.cs
C#
mit
3,231
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsLro { using Fixtures.Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// LRORetrysOperations operations. /// </summary> internal partial class LRORetrysOperations : IServiceOperations<AutoRestLongRunningOperationTestService>, ILRORetrysOperations { /// <summary> /// Initializes a new instance of the LRORetrysOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LRORetrysOperations(AutoRestLongRunningOperationTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestLongRunningOperationTestService /// </summary> public AutoRestLongRunningOperationTestService Client { get; private set; } /// <summary> /// Long running put request, service returns a 500, then a 201 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Polls /// return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='product'> /// Product to put /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ProductInner>> Put201CreatingSucceeded200WithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<ProductInner> _response = await BeginPut201CreatingSucceeded200WithHttpMessagesAsync(product, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Long running put request, service returns a 500, then a 200 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='product'> /// Product to put /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ProductInner,LRORetrysPutAsyncRelativeRetrySucceededHeadersInner>> PutAsyncRelativeRetrySucceededWithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<ProductInner,LRORetrysPutAsyncRelativeRetrySucceededHeadersInner> _response = await BeginPutAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request, with an entity that contains ProvisioningState=’Accepted’. /// Polls return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ProductInner,LRORetrysDeleteProvisioning202Accepted200SucceededHeadersInner>> DeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<ProductInner,LRORetrysDeleteProvisioning202Accepted200SucceededHeadersInner> _response = await BeginDeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Polls return this value until the last poll returns a /// ‘200’ with ProvisioningState=’Succeeded’ /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationHeaderResponse<LRORetrysDelete202Retry200HeadersInner>> Delete202Retry200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationHeaderResponse<LRORetrysDelete202Retry200HeadersInner> _response = await BeginDelete202Retry200WithHttpMessagesAsync(customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Poll the endpoint indicated in the Azure-AsyncOperation /// header for operation status /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner>> DeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner> _response = await BeginDeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with /// a response body after success /// </summary> /// <param name='product'> /// Product to put /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationHeaderResponse<LRORetrysPost202Retry200HeadersInner>> Post202Retry200WithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationHeaderResponse<LRORetrysPost202Retry200HeadersInner> _response = await BeginPost202Retry200WithHttpMessagesAsync(product, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='product'> /// Product to put /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner>> PostAsyncRelativeRetrySucceededWithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner> _response = await BeginPostAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Long running put request, service returns a 500, then a 201 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Polls /// return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='product'> /// Product to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ProductInner>> BeginPut201CreatingSucceeded200WithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginPut201CreatingSucceeded200", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/put/201/creating/succeeded/200").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ProductInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProductInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProductInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Long running put request, service returns a 500, then a 200 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='product'> /// Product to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ProductInner,LRORetrysPutAsyncRelativeRetrySucceededHeadersInner>> BeginPutAsyncRelativeRetrySucceededWithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginPutAsyncRelativeRetrySucceeded", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/putasync/retry/succeeded").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ProductInner,LRORetrysPutAsyncRelativeRetrySucceededHeadersInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProductInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysPutAsyncRelativeRetrySucceededHeadersInner>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request, with an entity that contains ProvisioningState=’Accepted’. /// Polls return this value until the last poll returns a ‘200’ with /// ProvisioningState=’Succeeded’ /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ProductInner,LRORetrysDeleteProvisioning202Accepted200SucceededHeadersInner>> BeginDeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDeleteProvisioning202Accepted200Succeeded", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/delete/provisioning/202/accepted/200/succeeded").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ProductInner,LRORetrysDeleteProvisioning202Accepted200SucceededHeadersInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProductInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProductInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysDeleteProvisioning202Accepted200SucceededHeadersInner>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Polls return this value until the last poll returns a /// ‘200’ with ProvisioningState=’Succeeded’ /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationHeaderResponse<LRORetrysDelete202Retry200HeadersInner>> BeginDelete202Retry200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete202Retry200", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/delete/202/retry/200").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationHeaderResponse<LRORetrysDelete202Retry200HeadersInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysDelete202Retry200HeadersInner>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Long running delete request, service returns a 500, then a 202 to the /// initial request. Poll the endpoint indicated in the Azure-AsyncOperation /// header for operation status /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner>> BeginDeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDeleteAsyncRelativeRetrySucceeded", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/deleteasync/retry/succeeded").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with /// a response body after success /// </summary> /// <param name='product'> /// Product to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationHeaderResponse<LRORetrysPost202Retry200HeadersInner>> BeginPost202Retry200WithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginPost202Retry200", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/post/202/retry/200").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationHeaderResponse<LRORetrysPost202Retry200HeadersInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysPost202Retry200HeadersInner>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Long running post request, service returns a 500, then a 202 to the initial /// request, with an entity that contains ProvisioningState=’Creating’. Poll /// the endpoint indicated in the Azure-AsyncOperation header for operation /// status /// </summary> /// <param name='product'> /// Product to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner>> BeginPostAsyncRelativeRetrySucceededWithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginPostAsyncRelativeRetrySucceeded", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/postasync/retry/succeeded").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(product != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
sergey-shandar/autorest
src/generator/AutoRest.CSharp.Azure.Fluent.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperations.cs
C#
mit
67,705
import * as React from "react"; import { shallow, mount, render, ShallowWrapper, ReactWrapper, configure, EnzymeAdapter, ShallowRendererProps, ComponentClass as EnzymeComponentClass } from "enzyme"; import { Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent } from "react"; // Help classes/interfaces interface MyComponentProps { stringProp: string; numberProp: number; } interface AnotherComponentProps { anotherStringProp?: string; anotherNumberProp?: number; } interface StatelessProps { stateless: string; } interface AnotherStatelessProps { anotherStateless: string; } interface MyComponentState { stateProperty: string; } class MyComponent extends Component<MyComponentProps, MyComponentState> { setState(...args: any[]) { console.log(args); } } class AnotherComponent extends Component<AnotherComponentProps> { setState(...args: any[]) { console.log(args); } } const MyStatelessComponent = (props: StatelessProps) => <span />; const AnotherStatelessComponent = (props: AnotherStatelessProps) => <span />; // Enzyme.configure function configureTest() { const configureAdapter: { adapter: EnzymeAdapter } = { adapter: {} }; configure(configureAdapter); const configureAdapterAndDisableLifecycle: typeof configureAdapter & Pick<ShallowRendererProps, "disableLifecycleMethods"> = { adapter: {}, disableLifecycleMethods: true, }; configure(configureAdapterAndDisableLifecycle); } // ShallowWrapper function ShallowWrapperTest() { let shallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState> = shallow<MyComponentProps, MyComponentState>(<MyComponent stringProp="value" numberProp={1} />); let reactElement: ReactElement<any>; let reactElements: Array<ReactElement<any>>; let domElement: Element; let boolVal: boolean; let stringVal: string; let numOrStringVal: number | string | undefined; let elementWrapper: ShallowWrapper<HTMLAttributes<{}>>; let anotherStatelessWrapper: ShallowWrapper<AnotherStatelessProps, never>; let anotherComponentWrapper: ShallowWrapper<AnotherComponentProps, any>; function test_props_state_inferring() { let wrapper: ShallowWrapper<MyComponentProps, MyComponentState>; wrapper = shallow(<MyComponent stringProp="value" numberProp={1} />); wrapper.state().stateProperty; wrapper.props().stringProp.toUpperCase(); } function test_shallow_options() { shallow(<MyComponent stringProp="1" numberProp={1} />, { context: { test: "a", }, lifecycleExperimental: true, disableLifecycleMethods: true }); } function test_find() { anotherComponentWrapper = shallowWrapper.find(AnotherComponent); anotherStatelessWrapper = shallowWrapper.find(AnotherStatelessComponent); shallowWrapper = shallowWrapper.find({ prop: 'value' }); elementWrapper = shallowWrapper.find('.selector'); // Since AnotherComponent does not have a constructor, it cannot match the // previous selector overload of ComponentClass { new(props?, contenxt? ) } const s1: EnzymeComponentClass<AnotherComponentProps> = AnotherComponent; } function test_findWhere() { shallowWrapper = shallowWrapper.findWhere((aShallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState>) => true); } function test_filter() { anotherComponentWrapper = shallowWrapper.filter(AnotherComponent); anotherStatelessWrapper = shallowWrapper.filter(AnotherStatelessComponent); // NOTE: The following calls to filter do not narrow down the possible type of the result based // on the type of the param, so the return type should not be different than the original // "this". This is a special case for "filter" vs other methods like "find", because "filter" // is guaranteed to return only a subset of the existing list of components/elements without // finding/adding more. shallowWrapper = shallowWrapper.filter({ numberProp: 12 }); shallowWrapper = shallowWrapper.filter('.selector'); } function test_filterWhere() { shallowWrapper = shallowWrapper.filterWhere(wrapper => { wrapper.props().stringProp; return true; }); } function test_contains() { boolVal = shallowWrapper.contains(<div className="foo bar" />); } function test_containsMatchingElement() { boolVal = shallowWrapper.contains(<div className="foo bar" />); } function test_containsAllMatchingElements() { boolVal = shallowWrapper.containsAllMatchingElements([<div className="foo bar" />]); } function test_containsAnyMatchingElement() { boolVal = shallowWrapper.containsAnyMatchingElements([<div className="foo bar" />]); } function test_dive() { interface TmpProps { foo: any; } interface TmpState { bar: any; } const diveWrapper: ShallowWrapper<TmpProps, TmpState> = shallowWrapper.dive<TmpProps, TmpState>({ context: { foobar: 'barfoo' } }); } function test_hostNodes() { shallowWrapper.hostNodes(); } function test_equals() { boolVal = shallowWrapper.equals(<div className="foo bar" />); } function test_matchesElement() { boolVal = shallowWrapper.matchesElement(<div className="foo bar" />); } function test_hasClass() { boolVal = shallowWrapper.find('.my-button').hasClass('disabled'); } function test_is() { boolVal = shallowWrapper.is('.some-class'); } function test_isEmpty() { boolVal = shallowWrapper.isEmpty(); } function test_exists() { boolVal = shallowWrapper.exists(); } function test_not() { elementWrapper = shallowWrapper.find('.foo').not('.bar'); } function test_children() { shallowWrapper = shallowWrapper.children(); anotherComponentWrapper = shallowWrapper.children(AnotherComponent); anotherStatelessWrapper = shallowWrapper.children(AnotherStatelessComponent); shallowWrapper = shallowWrapper.children({ prop: 'value' }); elementWrapper = shallowWrapper.children('.selector'); } function test_childAt() { const childWrapper: ShallowWrapper<any, any> = shallowWrapper.childAt(0); interface TmpType1 { foo: any; } interface TmpType2 { bar: any; } const childWrapper2: ShallowWrapper<TmpType1, TmpType2> = shallowWrapper.childAt<TmpType1, TmpType2>(0); } function test_parents() { shallowWrapper = shallowWrapper.parents(); anotherComponentWrapper = shallowWrapper.parents(AnotherComponent); anotherStatelessWrapper = shallowWrapper.parents(AnotherStatelessComponent); shallowWrapper = shallowWrapper.parents({ prop: 'myprop' }); elementWrapper = shallowWrapper.parents('.selector'); } function test_parent() { shallowWrapper = shallowWrapper.parent(); } function test_closest() { anotherComponentWrapper = shallowWrapper.closest(AnotherComponent); anotherStatelessWrapper = shallowWrapper.closest(AnotherStatelessComponent); shallowWrapper = shallowWrapper.closest({ prop: 'myprop' }); elementWrapper = shallowWrapper.closest('.selector'); } function test_shallow() { shallowWrapper = shallowWrapper.shallow(); } function test_unmount() { shallowWrapper = shallowWrapper.unmount(); } function test_text() { stringVal = shallowWrapper.text(); } function test_html() { stringVal = shallowWrapper.html(); } function test_get() { reactElement = shallowWrapper.get(1); } function test_getNode() { reactElement = shallowWrapper.getNode(); } function test_getNodes() { reactElements = shallowWrapper.getNodes(); } function test_getElement() { reactElement = shallowWrapper.getElement(); } function test_getElements() { reactElements = shallowWrapper.getElements(); } function test_getDOMNode() { domElement = shallowWrapper.getDOMNode(); } function test_at() { shallowWrapper = shallowWrapper.at(1); } function test_first() { shallowWrapper = shallowWrapper.first(); } function test_last() { shallowWrapper = shallowWrapper.last(); } function test_slice() { shallowWrapper = shallowWrapper.slice(1); shallowWrapper = shallowWrapper.slice(1, 3); } function test_tap() { shallowWrapper.tap((intercepter) => { }); } function test_state() { const state: MyComponentState = shallowWrapper.state(); const prop: string = shallowWrapper.state('stateProperty'); const prop2: number = shallowWrapper.state<number>('key'); const prop3 = shallowWrapper.state('key'); } function test_context() { shallowWrapper.context(); shallowWrapper.context('key'); const tmp: string = shallowWrapper.context<string>('key'); } function test_props() { const props: MyComponentProps = shallowWrapper.props(); const props2: AnotherComponentProps = shallowWrapper.find(AnotherComponent).props(); const props3: AnotherStatelessProps = shallowWrapper.find(AnotherStatelessComponent).props(); const props4: HTMLAttributes<any> = shallowWrapper.find('.selector').props(); } function test_prop() { const tmp: number = shallowWrapper.prop('numberProp'); const tmp2: string = shallowWrapper.prop<string>('key'); const tmp3 = shallowWrapper.prop('key'); } function test_key() { stringVal = shallowWrapper.key(); } function test_simulate(...args: any[]) { shallowWrapper.simulate('click'); shallowWrapper.simulate('click', args); } function test_setState() { shallowWrapper = shallowWrapper.setState({ stateProperty: 'state' }, () => console.log('state updated')); } function test_setProps() { shallowWrapper = shallowWrapper.setProps({ stringProp: 'foo' }); } function test_setContext() { shallowWrapper = shallowWrapper.setContext({ name: 'baz' }); } function test_instance() { const myComponent: MyComponent = shallowWrapper.instance(); } function test_update() { shallowWrapper = shallowWrapper.update(); } function test_debug() { stringVal = shallowWrapper.debug(); } function test_type() { const type: string | StatelessComponent<MyComponentProps> | ComponentClass<MyComponentProps> = shallowWrapper.type(); } function test_name() { stringVal = shallowWrapper.name(); } function test_forEach() { shallowWrapper = shallowWrapper.forEach(wrapper => wrapper.shallow().props().stringProp); } function test_map() { const arrayNumbers: number[] = shallowWrapper.map(wrapper => wrapper.props().numberProp); } function test_reduce() { const total: number = shallowWrapper.reduce( (amount: number, n: ShallowWrapper<MyComponentProps, MyComponentState>) => amount + n.props().numberProp ); } function test_reduceRight() { const total: number = shallowWrapper.reduceRight<number>( (amount: number, n: ShallowWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('numberProp') ); } function test_some() { boolVal = shallowWrapper.some(AnotherComponent); boolVal = shallowWrapper.some(AnotherStatelessComponent); boolVal = shallowWrapper.some({ prop: 'myprop' }); boolVal = shallowWrapper.some('.selector'); } function test_someWhere() { boolVal = shallowWrapper.someWhere((aShallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState>) => true); } function test_every() { boolVal = shallowWrapper.every(AnotherComponent); boolVal = shallowWrapper.every(AnotherStatelessComponent); boolVal = shallowWrapper.every({ prop: 'myprop' }); boolVal = shallowWrapper.every('.selector'); } function test_everyWhere() { boolVal = shallowWrapper.everyWhere((aShallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState>) => true); } function test_isEmptyRender() { boolVal = shallowWrapper.isEmptyRender(); } function test_svg() { numOrStringVal = shallowWrapper.find('svg').props().strokeWidth; } function test_constructor() { let anyWrapper: ShallowWrapper; anyWrapper = new ShallowWrapper(<MyComponent stringProp="1" numberProp={1} />); shallowWrapper = new ShallowWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />); shallowWrapper = new ShallowWrapper<MyComponentProps, MyComponentState>([<MyComponent stringProp="1" numberProp={1} />, <MyComponent stringProp="1" numberProp={1} />]); shallowWrapper = new ShallowWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, shallowWrapper); shallowWrapper = new ShallowWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, undefined, { lifecycleExperimental: true }); shallowWrapper = new ShallowWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, shallowWrapper, { lifecycleExperimental: true }); } } // ReactWrapper function ReactWrapperTest() { let reactWrapper: ReactWrapper<MyComponentProps, MyComponentState> = mount<MyComponentProps, MyComponentState>(<MyComponent stringProp="value" numberProp={1} />); let reactElement: ReactElement<any>; let reactElements: Array<ReactElement<any>>; let domElement: Element; let boolVal: boolean; let stringVal: string; let elementWrapper: ReactWrapper<HTMLAttributes<{}>>; let anotherStatelessWrapper: ReactWrapper<AnotherStatelessProps, never>; let anotherComponentWrapper: ReactWrapper<AnotherComponentProps, any>; function test_prop_state_inferring() { let wrapper: ReactWrapper<MyComponentProps, MyComponentState>; wrapper = mount(<MyComponent stringProp="value" numberProp={1} />); wrapper.state().stateProperty; wrapper.props().stringProp.toUpperCase(); } function test_unmount() { reactWrapper = reactWrapper.unmount(); } function test_mount() { reactWrapper = reactWrapper.mount(); mount(<MyComponent stringProp='1' numberProp={1} />, { attachTo: document.getElementById('test'), context: { a: "b" } }); } function test_ref() { reactWrapper = reactWrapper.ref('refName'); interface TmpType1 { foo: string; } interface TmpType2 { bar: string; } const tmp: ReactWrapper<TmpType1, TmpType2> = reactWrapper.ref<TmpType1, TmpType2>('refName'); } function test_detach() { reactWrapper.detach(); } function test_hostNodes() { reactWrapper.hostNodes(); } function test_find() { elementWrapper = reactWrapper.find('.selector'); anotherComponentWrapper = reactWrapper.find(AnotherComponent); anotherStatelessWrapper = reactWrapper.find(AnotherStatelessComponent); reactWrapper = reactWrapper.find({ prop: 'myprop' }); } function test_findWhere() { reactWrapper = reactWrapper.findWhere((aReactWrapper: ReactWrapper<MyComponentProps, MyComponentState>) => true); } function test_filter() { anotherComponentWrapper = reactWrapper.filter(AnotherComponent); anotherStatelessWrapper = reactWrapper.filter(AnotherStatelessComponent); // NOTE: The following calls to filter do not narrow down the possible type of the result based // on the type of the param, so the return type should not be different than the original // "this". This is a special case for "filter" vs other methods like "find", because "filter" // is guaranteed to return only a subset of the existing list of components/elements without // finding/adding more. reactWrapper = reactWrapper.filter({ numberProp: 12 }); reactWrapper = reactWrapper.filter('.selector'); } function test_filterWhere() { reactWrapper = reactWrapper.filterWhere(wrapper => { wrapper.props().stringProp; return true; }); } function test_contains() { boolVal = reactWrapper.contains(<div className="foo bar" />); } function test_containsMatchingElement() { boolVal = reactWrapper.contains(<div className="foo bar" />); } function test_containsAllMatchingElements() { boolVal = reactWrapper.containsAllMatchingElements([<div className="foo bar" />]); } function test_containsAnyMatchingElement() { boolVal = reactWrapper.containsAnyMatchingElements([<div className="foo bar" />]); } function test_equals() { boolVal = reactWrapper.equals(<div className="foo bar" />); } function test_matchesElement() { boolVal = reactWrapper.matchesElement(<div className="foo bar" />); } function test_hasClass() { boolVal = reactWrapper.find('.my-button').hasClass('disabled'); } function test_is() { boolVal = reactWrapper.is('.some-class'); } function test_isEmpty() { boolVal = reactWrapper.isEmpty(); } function test_not() { elementWrapper = reactWrapper.find('.foo').not('.bar'); } function test_children() { reactWrapper = reactWrapper.children(); anotherComponentWrapper = reactWrapper.children(AnotherComponent); anotherStatelessWrapper = reactWrapper.children(AnotherStatelessComponent); reactWrapper = reactWrapper.children({ prop: 'myprop' }); elementWrapper = reactWrapper.children('.selector'); } function test_childAt() { const childWrapper: ReactWrapper<any, any> = reactWrapper.childAt(0); interface TmpType1 { foo: any; } interface TmpType2 { bar: any; } const childWrapper2: ReactWrapper<TmpType1, TmpType2> = reactWrapper.childAt<TmpType1, TmpType2>(0); } function test_parents() { reactWrapper = reactWrapper.parents(); anotherComponentWrapper = reactWrapper.parents(AnotherComponent); anotherStatelessWrapper = reactWrapper.parents(AnotherStatelessComponent); reactWrapper = reactWrapper.parents({ prop: 'myprop' }); elementWrapper = reactWrapper.parents('.selector'); } function test_parent() { reactWrapper = reactWrapper.parent(); } function test_closest() { anotherComponentWrapper = reactWrapper.closest(AnotherComponent); anotherStatelessWrapper = reactWrapper.closest(AnotherStatelessComponent); reactWrapper = reactWrapper.closest({ prop: 'myprop' }); elementWrapper = reactWrapper.closest('.selector'); } function test_text() { stringVal = reactWrapper.text(); } function test_html() { stringVal = reactWrapper.html(); } function test_get() { reactElement = reactWrapper.get(1); } function test_getNode() { reactElement = reactWrapper.getNode(); } function test_getNodes() { reactElements = reactWrapper.getNodes(); } function test_getElement() { reactElement = reactWrapper.getElement(); } function test_getElements() { reactElements = reactWrapper.getElements(); } function test_getDOMNode() { domElement = reactWrapper.getDOMNode(); } function test_at() { reactWrapper = reactWrapper.at(1); } function test_first() { reactWrapper = reactWrapper.first(); } function test_last() { reactWrapper = reactWrapper.last(); } function test_slice() { reactWrapper = reactWrapper.slice(1); reactWrapper = reactWrapper.slice(1, 3); } function test_tap() { reactWrapper.tap((intercepter) => { }); } function test_state() { const state: MyComponentState = reactWrapper.state(); const prop: string = reactWrapper.state('stateProperty'); const prop2: number = reactWrapper.state<number>('key'); const prop3 = reactWrapper.state('key'); } function test_context() { reactWrapper.context(); reactWrapper.context('key'); const tmp: string = reactWrapper.context<string>('key'); } function test_props() { const props: MyComponentProps = reactWrapper.props(); const props2: AnotherComponentProps = reactWrapper.find(AnotherComponent).props(); const props3: AnotherStatelessProps = reactWrapper.find(AnotherStatelessComponent).props(); const props4: HTMLAttributes<any> = reactWrapper.find('.selector').props(); } function test_prop() { const tmp: number = reactWrapper.prop('numberProp'); const tmp2: string = reactWrapper.prop<string>('key'); const tmp3 = reactWrapper.prop('key'); } function test_key() { stringVal = reactWrapper.key(); } function test_simulate(...args: any[]) { reactWrapper.simulate('click'); reactWrapper.simulate('click', args); } function test_setState() { reactWrapper = reactWrapper.setState({ stateProperty: 'state' }); } function test_setProps() { reactWrapper = reactWrapper.setProps({ stringProp: 'foo' }, () => { }); } function test_setContext() { reactWrapper = reactWrapper.setContext({ name: 'baz' }); } function test_instance() { const myComponent: MyComponent = reactWrapper.instance(); } function test_update() { reactWrapper = reactWrapper.update(); } function test_debug() { stringVal = reactWrapper.debug(); } function test_type() { const type: string | StatelessComponent<MyComponentProps> | ComponentClass<MyComponentProps> = reactWrapper.type(); } function test_name() { stringVal = reactWrapper.name(); } function test_forEach() { reactWrapper = reactWrapper.forEach(wrapper => wrapper.props().stringProp); } function test_map() { const arrayNumbers: number[] = reactWrapper.map(wrapper => wrapper.props().numberProp); } function test_reduce() { const total: number = reactWrapper.reduce<number>( (amount: number, n: ReactWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('numberProp') ); } function test_reduceRight() { const total: number = reactWrapper.reduceRight<number>( (amount: number, n: ReactWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('numberProp') ); } function test_some() { boolVal = reactWrapper.some(AnotherComponent); boolVal = reactWrapper.some(AnotherStatelessComponent); boolVal = reactWrapper.some({ prop: 'myprop' }); boolVal = reactWrapper.some('.selector'); } function test_someWhere() { boolVal = reactWrapper.someWhere((aReactWrapper: ReactWrapper<MyComponentProps, MyComponentState>) => true); } function test_every() { boolVal = reactWrapper.every(AnotherComponent); boolVal = reactWrapper.every(AnotherStatelessComponent); boolVal = reactWrapper.every({ prop: 'myprop' }); boolVal = reactWrapper.every('.selector'); } function test_everyWhere() { boolVal = reactWrapper.everyWhere((aReactWrapper: ReactWrapper<MyComponentProps, MyComponentState>) => true); } function test_isEmptyRender() { boolVal = reactWrapper.isEmptyRender(); } function test_constructor() { let anyWrapper: ReactWrapper; anyWrapper = new ReactWrapper(<MyComponent stringProp="1" numberProp={1} />); reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />); reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>([<MyComponent stringProp="1" numberProp={1} />, <MyComponent stringProp="1" numberProp={1} />]); reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, reactWrapper); reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, undefined, { attachTo: document.createElement('div') }); reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, reactWrapper, { attachTo: document.createElement('div') }); } } // CheerioWrapper function CheerioWrapperTest() { const wrapper: Cheerio = shallow(<div />).render() || mount(<div />).render(); wrapper.toggleClass('className'); }
rolandzwaga/DefinitelyTyped
types/enzyme/enzyme-tests.tsx
TypeScript
mit
25,738
// Type definitions for non-npm package amap-js-api 1.4 // Project: https://lbs.amap.com/api/javascript-api/summary // Definitions by: breeze9527 <https://github.com/breeze9527> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// <reference path="array-bounds.d.ts" /> /// <reference path="bounds.d.ts" /> /// <reference path="browser.d.ts" /> /// <reference path="common.d.ts" /> /// <reference path="convert-from.d.ts" /> /// <reference path="dom-util.d.ts" /> /// <reference path="event.d.ts" /> /// <reference path="geometry-util.d.ts" /> /// <reference path="lngLat.d.ts" /> /// <reference path="map.d.ts" /> /// <reference path="pixel.d.ts" /> /// <reference path="size.d.ts" /> /// <reference path="type-util.d.ts" /> /// <reference path="util.d.ts" /> /// <reference path="view2D.d.ts" /> /// <reference path="layer/building.d.ts" /> /// <reference path="layer/flexible.d.ts" /> /// <reference path="layer/labelsLayer.d.ts" /> /// <reference path="layer/layer.d.ts" /> /// <reference path="layer/layerGroup.d.ts" /> /// <reference path="layer/massMarks.d.ts" /> /// <reference path="layer/mediaLayer.d.ts" /> /// <reference path="layer/tileLayer.d.ts" /> /// <reference path="layer/wms.d.ts" /> /// <reference path="layer/wmts.d.ts" /> /// <reference path="overlay/bezierCurve.d.ts" /> /// <reference path="overlay/circle.d.ts" /> /// <reference path="overlay/circleMarker.d.ts" /> /// <reference path="overlay/contextMenu.d.ts" /> /// <reference path="overlay/ellipse.d.ts" /> /// <reference path="overlay/geoJSON.d.ts" /> /// <reference path="overlay/icon.d.ts" /> /// <reference path="overlay/infoWindow.d.ts" /> /// <reference path="overlay/labelMarker.d.ts" /> /// <reference path="overlay/marker.d.ts" /> /// <reference path="overlay/markerShape.d.ts" /> /// <reference path="overlay/overlay.d.ts" /> /// <reference path="overlay/overlayGroup.d.ts" /> /// <reference path="overlay/pathOverlay.d.ts" /> /// <reference path="overlay/polygon.d.ts" /> /// <reference path="overlay/polyline.d.ts" /> /// <reference path="overlay/rectangle.d.ts" /> /// <reference path="overlay/shapeOverlay.d.ts" /> /// <reference path="overlay/text.d.ts" />
borisyankov/DefinitelyTyped
types/amap-js-api/index.d.ts
TypeScript
mit
2,198
module.exports = { "env": { "node": true, "commonjs": true, "es6": true }, "ecmaFeatures": { "arrowFunctions": true, "binaryLiterals": false, "blockBindings": true, "classes": false, "defaultParams": true, "destructuring": true, "forOf": false, "generators": false, "modules": true, "objectLiteralComputedProperties": false, "objectLiteralDuplicateProperties": false, "objectLiteralShorthandMethods": true, "objectLiteralShorthandProperties": true, "octalLiterals": false, "regexUFlag": false, "regexYFlag": false, "restParams": true, "spread": true, "superInFunctions": true, "templateStrings": true, "unicodeCodePointEscapes": false, "globalReturns": false, "jsx": true, "experimentalObjectRestSpread": true }, "parser": "babel-eslint", "rules": { "array-bracket-spacing": [ 2, "always" ], "arrow-body-style": [ 2, "as-needed" ], "arrow-parens": [ 2, "as-needed" ], "block-scoped-var": 2, "block-spacing": [ 2, "always" ], "brace-style": [ 2, "1tbs", { "allowSingleLine": false } ], "comma-dangle": [ 2, "never" ], "comma-spacing": [ 2, { "after": true, "before": false } ], "consistent-return": 2, "consistent-this": [ 2, "self" ], "constructor-super": 2, "curly": [ 2, "all" ], "dot-location": [ 2, "property" ], "dot-notation": 2, "eol-last": 2, "indent": [ 2, 2, { "SwitchCase": 1 } ], "jsx-quotes": [ 2, "prefer-double" ], "max-len": [ 2, 125, 2, { "ignorePattern": "((^import[^;]+;$)|(^\\s*it\\())", "ignoreUrls": true } ], "new-cap": 2, "no-alert": 2, "no-confusing-arrow": 2, "no-caller": 2, "no-class-assign": 2, "no-cond-assign": [ 2, "always" ], "no-console": 1, "no-const-assign": 2, "no-constant-condition": 2, "no-control-regex": 2, "no-debugger": 1, "no-dupe-args": 2, "no-dupe-class-members": 2, "no-dupe-keys": 2, "no-duplicate-case": 2, "no-else-return": 2, "no-empty": 2, "no-empty-character-class": 2, "no-eq-null": 2, "no-eval": 2, "no-ex-assign": 2, "no-extend-native": 2, "no-extra-bind": 2, "no-extra-boolean-cast": 2, "no-extra-parens": [ 2, "functions" ], "no-extra-semi": 2, "no-func-assign": 2, "no-implicit-coercion": [ 2, { "boolean": true, "number": true, "string": true } ], "no-implied-eval": 2, "no-inner-declarations": [ 2, "both" ], "no-invalid-regexp": 2, "no-invalid-this": 2, "no-irregular-whitespace": 2, "no-lonely-if": 2, "no-negated-condition": 2, "no-negated-in-lhs": 2, "no-new": 2, "no-new-func": 2, "no-new-object": 2, "no-obj-calls": 2, "no-proto": 2, "no-redeclare": 2, "no-regex-spaces": 2, "no-return-assign": 2, "no-self-compare": 2, "no-sequences": 2, "no-sparse-arrays": 2, "no-this-before-super": 2, "no-trailing-spaces": 2, "no-undef": 2, "no-unexpected-multiline": 2, "no-unneeded-ternary": 2, "no-unreachable": 2, "no-unused-vars": [ 1, { "args": "after-used", "vars": "all", "varsIgnorePattern": "React" } ], "no-use-before-define": 2, "no-useless-call": 2, "no-useless-concat": 2, "no-var": 2, "no-warning-comments": [ 1, { "location": "anywhere", "terms": [ "todo" ] } ], "no-with": 2, "object-curly-spacing": [ 2, "always" ], "object-shorthand": 2, "one-var": [ 2, "never" ], "prefer-arrow-callback": 2, "prefer-const": 2, "prefer-spread": 2, "prefer-template": 2, "radix": 2, "semi": 2, "sort-vars": [ 2, { "ignoreCase": true } ], "keyword-spacing": 2, "space-before-blocks": [ 2, "always" ], "space-before-function-paren": [ 2, "never" ], "space-infix-ops": [ 2, { "int32Hint": false } ], "use-isnan": 2, "valid-typeof": 2, "vars-on-top": 2, "yoda": [ 2, "never" ] } };
dgilroy77/Car.ly
node_modules/eslint-plugin-jsx-a11y/.eslintrc.js
JavaScript
mit
4,092
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Validator\Constraints; class Url extends \Symfony\Component\Validator\Constraint { public $message = 'This value is not a valid URL'; public $protocols = array('http', 'https'); /** * {@inheritDoc} */ public function getTargets() { return self::PROPERTY_CONSTRAINT; } }
radzikowski/alf
vendor/symfony/src/Symfony/Component/Validator/Constraints/Url.php
PHP
mit
579
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Shared.LanguageParser; using Microsoft.Build.Tasks.Hosting; using Microsoft.Build.Tasks.InteropUtilities; using Microsoft.Build.Utilities; #if (!STANDALONEBUILD) using Microsoft.Internal.Performance; #endif namespace Microsoft.Build.Tasks { /// <summary> /// This class defines the "Csc" XMake task, which enables building assemblies from C# /// source files by invoking the C# compiler. This is the new Roslyn XMake task, /// meaning that the code is compiled by using the Roslyn compiler server, rather /// than csc.exe. The two should be functionally identical, but the compiler server /// should be significantly faster with larger projects and have a smaller memory /// footprint. /// </summary> public class Csc : ManagedCompiler { private bool _useHostCompilerIfAvailable = false; #region Properties // Please keep these alphabetized. These are the parameters specific to Csc. The // ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is // the base class. public bool AllowUnsafeBlocks { set { Bag["AllowUnsafeBlocks"] = value; } get { return GetBoolParameterWithDefault("AllowUnsafeBlocks", false); } } public string ApplicationConfiguration { set { Bag["ApplicationConfiguration"] = value; } get { return (string)Bag["ApplicationConfiguration"]; } } public string BaseAddress { set { Bag["BaseAddress"] = value; } get { return (string)Bag["BaseAddress"]; } } public bool CheckForOverflowUnderflow { set { Bag["CheckForOverflowUnderflow"] = value; } get { return GetBoolParameterWithDefault("CheckForOverflowUnderflow", false); } } public string DocumentationFile { set { Bag["DocumentationFile"] = value; } get { return (string)Bag["DocumentationFile"]; } } public string DisabledWarnings { set { Bag["DisabledWarnings"] = value; } get { return (string)Bag["DisabledWarnings"]; } } public bool ErrorEndLocation { set { Bag["ErrorEndLocation"] = value; } get { return GetBoolParameterWithDefault("ErrorEndLocation", false); } } public string ErrorReport { set { Bag["ErrorReport"] = value; } get { return (string)Bag["ErrorReport"]; } } public bool GenerateFullPaths { set { Bag["GenerateFullPaths"] = value; } get { return GetBoolParameterWithDefault("GenerateFullPaths", false); } } public string LangVersion { set { Bag["LangVersion"] = value; } get { return (string)Bag["LangVersion"]; } } public string ModuleAssemblyName { set { Bag["ModuleAssemblyName"] = value; } get { return (string)Bag["ModuleAssemblyName"]; } } public bool NoStandardLib { set { Bag["NoStandardLib"] = value; } get { return GetBoolParameterWithDefault("NoStandardLib", false); } } public string PdbFile { set { Bag["PdbFile"] = value; } get { return (string)Bag["PdbFile"]; } } /// <summary> /// Name of the language passed to "/preferreduilang" compiler option. /// </summary> /// <remarks> /// If set to null, "/preferreduilang" option is omitted, and csc.exe uses its default setting. /// Otherwise, the value is passed to "/preferreduilang" as is. /// </remarks> public string PreferredUILang { set { Bag["PreferredUILang"] = value; } get { return (string)Bag["PreferredUILang"]; } } public string VsSessionGuid { set { Bag["VsSessionGuid"] = value; } get { return (string)Bag["VsSessionGuid"]; } } public bool UseHostCompilerIfAvailable { set { _useHostCompilerIfAvailable = value; } get { return _useHostCompilerIfAvailable; } } public int WarningLevel { set { Bag["WarningLevel"] = value; } get { return GetIntParameterWithDefault("WarningLevel", 4); } } public string WarningsAsErrors { set { Bag["WarningsAsErrors"] = value; } get { return (string)Bag["WarningsAsErrors"]; } } public string WarningsNotAsErrors { set { Bag["WarningsNotAsErrors"] = value; } get { return (string)Bag["WarningsNotAsErrors"]; } } #endregion #region Tool Members /// <summary> /// Return the name of the tool to execute. /// </summary> override protected string ToolName { get { return "csc2.exe"; } } /// <summary> /// Return the path to the tool to execute. /// </summary> override protected string GenerateFullPathToTool() { string pathToTool = ToolLocationHelper.GetPathToBuildToolsFile(ToolName, ToolLocationHelper.CurrentToolsVersion); if (null == pathToTool) { pathToTool = ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.VersionLatest); if (null == pathToTool) { Log.LogErrorWithCodeFromResources("General.FrameworksFileNotFound", ToolName, ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion.VersionLatest)); } } return pathToTool; } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> override protected internal void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitchIfNotNull("/lib:", this.AdditionalLibPaths, ","); commandLine.AppendPlusOrMinusSwitch("/unsafe", this.Bag, "AllowUnsafeBlocks"); commandLine.AppendPlusOrMinusSwitch("/checked", this.Bag, "CheckForOverflowUnderflow"); commandLine.AppendSwitchWithSplitting("/nowarn:", this.DisabledWarnings, ",", ';', ','); commandLine.AppendWhenTrue("/fullpaths", this.Bag, "GenerateFullPaths"); commandLine.AppendSwitchIfNotNull("/langversion:", this.LangVersion); commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", this.ModuleAssemblyName); commandLine.AppendSwitchIfNotNull("/pdb:", this.PdbFile); commandLine.AppendPlusOrMinusSwitch("/nostdlib", this.Bag, "NoStandardLib"); commandLine.AppendSwitchIfNotNull("/platform:", this.PlatformWith32BitPreference); commandLine.AppendSwitchIfNotNull("/errorreport:", this.ErrorReport); commandLine.AppendSwitchWithInteger("/warn:", this.Bag, "WarningLevel"); commandLine.AppendSwitchIfNotNull("/doc:", this.DocumentationFile); commandLine.AppendSwitchIfNotNull("/baseaddress:", this.BaseAddress); commandLine.AppendSwitchUnquotedIfNotNull("/define:", this.GetDefineConstantsSwitch(this.DefineConstants)); commandLine.AppendSwitchIfNotNull("/win32res:", this.Win32Resource); commandLine.AppendSwitchIfNotNull("/main:", this.MainEntryPoint); commandLine.AppendSwitchIfNotNull("/appconfig:", this.ApplicationConfiguration); commandLine.AppendWhenTrue("/errorendlocation", this.Bag, "ErrorEndLocation"); commandLine.AppendSwitchIfNotNull("/preferreduilang:", this.PreferredUILang); commandLine.AppendPlusOrMinusSwitch("/highentropyva", this.Bag, "HighEntropyVA"); // If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid> bool designTime = false; if (this.HostObject != null) { var csHost = this.HostObject as ICscHostObject; designTime = csHost.IsDesignTime(); } if (!designTime) { if (!string.IsNullOrWhiteSpace(this.VsSessionGuid)) { commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", this.VsSessionGuid); } } this.AddReferencesToCommandLine(commandLine); base.AddResponseFileCommands(commandLine); // This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs). // Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line, // and then any specific warnings that should be treated as errors should be specified with // /warnaserror+:<list> after the /warnaserror- switch. The order of the switches on the command-line // does matter. // // Note that // /warnaserror+ // is just shorthand for: // /warnaserror+:<all possible warnings> // // Similarly, // /warnaserror- // is just shorthand for: // /warnaserror-:<all possible warnings> commandLine.AppendSwitchWithSplitting("/warnaserror+:", this.WarningsAsErrors, ",", ';', ','); commandLine.AppendSwitchWithSplitting("/warnaserror-:", this.WarningsNotAsErrors, ",", ';', ','); // It's a good idea for the response file to be the very last switch passed, just // from a predictability perspective. if (this.ResponseFiles != null) { foreach (ITaskItem response in this.ResponseFiles) { commandLine.AppendSwitchIfNotNull("@", response.ItemSpec); } } } #endregion /// <summary> /// The C# compiler (starting with Whidbey) supports assembly aliasing for references. /// See spec at http://devdiv/spectool/Documents/Whidbey/VCSharp/Design%20Time/M3%20DCRs/DCR%20Assembly%20aliases.doc. /// This method handles the necessary work of looking at the "Aliases" attribute on /// the incoming "References" items, and making sure to generate the correct /// command-line on csc.exe. The syntax for aliasing a reference is: /// csc.exe /reference:Foo=System.Xml.dll /// /// The "Aliases" attribute on the "References" items is actually a comma-separated /// list of aliases, and if any of the aliases specified is the string "global", /// then we add that reference to the command-line without an alias. /// </summary> /// <param name="commandLine"></param> private void AddReferencesToCommandLine ( CommandLineBuilderExtension commandLine ) { // If there were no references passed in, don't add any /reference: switches // on the command-line. if ((this.References == null) || (this.References.Length == 0)) { return; } // Loop through all the references passed in. We'll be adding separate // /reference: switches for each reference, and in some cases even multiple // /reference: switches per reference. foreach (ITaskItem reference in this.References) { // See if there was an "Alias" attribute on the reference. string aliasString = reference.GetMetadata(ItemMetadataNames.aliases); string switchName = "/reference:"; bool embed = MetadataConversionUtilities.TryConvertItemMetadataToBool ( reference, ItemMetadataNames.embedInteropTypes ); if (embed == true) { switchName = "/link:"; } if ((aliasString == null) || (aliasString.Length == 0)) { // If there was no "Alias" attribute, just add this as a global reference. commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec); } else { // If there was an "Alias" attribute, it contains a comma-separated list // of aliases to use for this reference. For each one of those aliases, // we're going to add a separate /reference: switch to the csc.exe // command-line string[] aliases = aliasString.Split(','); foreach (string alias in aliases) { // Trim whitespace. string trimmedAlias = alias.Trim(); if (alias.Length == 0) { continue; } // The alias should be a valid C# identifier. Therefore it cannot // contain comma, space, semicolon, or double-quote. Let's check for // the existence of those characters right here, and bail immediately // if any are present. There are a whole bunch of other characters // that are not allowed in a C# identifier, but we'll just let csc.exe // error out on those. The ones we're checking for here are the ones // that could seriously interfere with the command-line parsing or could // allow parameter injection. if (trimmedAlias.IndexOfAny(new char[] { ',', ' ', ';', '"' }) != -1) { ErrorUtilities.VerifyThrowArgument ( false, "Csc.AssemblyAliasContainsIllegalCharacters", reference.ItemSpec, trimmedAlias ); } // The alias called "global" is special. It means that we don't // give it an alias on the command-line. if (String.Compare("global", trimmedAlias, StringComparison.OrdinalIgnoreCase) == 0) { commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec); } else { // We have a valid (and explicit) alias for this reference. Add // it to the command-line using the syntax: // /reference:Foo=System.Xml.dll commandLine.AppendSwitchAliased(switchName, trimmedAlias, reference.ItemSpec); } } } } } /// <summary> /// Determines whether a particular string is a valid C# identifier. Legal /// identifiers must start with a letter, and all the characters must be /// letters or numbers. Underscore is considered a letter. /// </summary> private static bool IsLegalIdentifier ( string identifier ) { // Must be non-empty. if (identifier.Length == 0) { return false; } // First character must be a letter. // From 2.4.2 of the C# Language Specification // identifier-start-letter-character: if ( !TokenChar.IsLetter(identifier[0]) && (identifier[0] != '_') ) { return false; } // All the other characters must be letters or numbers. // From 2.4.2 of the C# Language Specification // identifier-part-letter-character: for (int i = 1; i < identifier.Length; i++) { char currentChar = identifier[i]; if ( !TokenChar.IsLetter(currentChar) && !TokenChar.IsDecimalDigit(currentChar) && !TokenChar.IsConnecting(currentChar) && !TokenChar.IsCombining(currentChar) && !TokenChar.IsFormatting(currentChar) ) { return false; } } return true; } /// <summary> /// Old VS projects had some pretty messed-up looking values for the /// "DefineConstants" property. It worked fine in the IDE, because it /// effectively munged up the string so that it ended up being valid for /// the compiler. We do the equivalent munging here now. /// /// Basically, we take the incoming string, and split it on comma/semicolon/space. /// Then we look at the resulting list of strings, and remove any that are /// illegal identifiers, and pass the remaining ones through to the compiler. /// /// Note that CSharp does support assigning a value to the constants ... in /// other words, a constant is either defined or not defined ... it can't have /// an actual value. /// </summary> internal string GetDefineConstantsSwitch ( string originalDefineConstants ) { if (originalDefineConstants == null) { return null; } StringBuilder finalDefineConstants = new StringBuilder(); // Split the incoming string on comma/semicolon/space. string[] allIdentifiers = originalDefineConstants.Split(new char[] { ',', ';', ' ' }); // Loop through all the parts, and for the ones that are legal C# identifiers, // add them to the outgoing string. foreach (string singleIdentifier in allIdentifiers) { if (Csc.IsLegalIdentifier(singleIdentifier)) { // Separate them with a semicolon if there's something already in // the outgoing string. if (finalDefineConstants.Length > 0) { finalDefineConstants.Append(";"); } finalDefineConstants.Append(singleIdentifier); } else if (singleIdentifier.Length > 0) { Log.LogWarningWithCodeFromResources("Csc.InvalidParameterWarning", "/define:", singleIdentifier); } } if (finalDefineConstants.Length > 0) { return finalDefineConstants.ToString(); } else { // We wouldn't want to pass in an empty /define: switch on the csc.exe command-line. return null; } } /// <summary> /// This method will initialize the host compiler object with all the switches, /// parameters, resources, references, sources, etc. /// /// It returns true if everything went according to plan. It returns false if the /// host compiler had a problem with one of the parameters that was passed in. /// /// This method also sets the "this.HostCompilerSupportsAllParameters" property /// accordingly. /// /// Example: /// If we attempted to pass in WarningLevel="9876", then this method would /// set HostCompilerSupportsAllParameters=true, but it would give a /// return value of "false". This is because the host compiler fully supports /// the WarningLevel parameter, but 9876 happens to be an illegal value. /// /// Example: /// If we attempted to pass in NoConfig=false, then this method would set /// HostCompilerSupportsAllParameters=false, because while this is a legal /// thing for csc.exe, the IDE compiler cannot support it. In this situation /// the return value will also be false. /// </summary> private bool InitializeHostCompiler ( // NOTE: For compat reasons this must remain ICscHostObject // we can dynamically test for smarter interfaces later.. ICscHostObject cscHostObject ) { bool success; this.HostCompilerSupportsAllParameters = this.UseHostCompilerIfAvailable; string param = "Unknown"; try { // Need to set these separately, because they don't require a CommitChanges to the C# compiler in the IDE. param = "LinkResources"; this.CheckHostObjectSupport(param, cscHostObject.SetLinkResources(this.LinkResources)); param = "References"; this.CheckHostObjectSupport(param, cscHostObject.SetReferences(this.References)); param = "Resources"; this.CheckHostObjectSupport(param, cscHostObject.SetResources(this.Resources)); param = "Sources"; this.CheckHostObjectSupport(param, cscHostObject.SetSources(this.Sources)); // For host objects which support it, pass the list of analyzers. IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject; if (analyzerHostObject != null) { param = "Analyzers"; this.CheckHostObjectSupport(param, analyzerHostObject.SetAnalyzers(this.Analyzers)); } } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } if (this.HostCompilerSupportsAllParameters) { // If the host compiler doesn't support everything we need, we're going to end up // shelling out to the command-line compiler anyway. That means the command-line // compiler will log the error. So here, we only log the error if we would've // tried to use the host compiler. Log.LogErrorWithCodeFromResources("General.CouldNotSetHostObjectParameter", param, e.Message); } return false; } try { param = "BeginInitialization"; cscHostObject.BeginInitialization(); param = "AdditionalLibPaths"; this.CheckHostObjectSupport(param, cscHostObject.SetAdditionalLibPaths(this.AdditionalLibPaths)); param = "AddModules"; this.CheckHostObjectSupport(param, cscHostObject.SetAddModules(this.AddModules)); param = "AllowUnsafeBlocks"; this.CheckHostObjectSupport(param, cscHostObject.SetAllowUnsafeBlocks(this.AllowUnsafeBlocks)); param = "BaseAddress"; this.CheckHostObjectSupport(param, cscHostObject.SetBaseAddress(this.BaseAddress)); param = "CheckForOverflowUnderflow"; this.CheckHostObjectSupport(param, cscHostObject.SetCheckForOverflowUnderflow(this.CheckForOverflowUnderflow)); param = "CodePage"; this.CheckHostObjectSupport(param, cscHostObject.SetCodePage(this.CodePage)); // These two -- EmitDebugInformation and DebugType -- must go together, with DebugType // getting set last, because it is more specific. param = "EmitDebugInformation"; this.CheckHostObjectSupport(param, cscHostObject.SetEmitDebugInformation(this.EmitDebugInformation)); param = "DebugType"; this.CheckHostObjectSupport(param, cscHostObject.SetDebugType(this.DebugType)); param = "DefineConstants"; this.CheckHostObjectSupport(param, cscHostObject.SetDefineConstants(this.GetDefineConstantsSwitch(this.DefineConstants))); param = "DelaySign"; this.CheckHostObjectSupport(param, cscHostObject.SetDelaySign((this.Bag["DelaySign"] != null), this.DelaySign)); param = "DisabledWarnings"; this.CheckHostObjectSupport(param, cscHostObject.SetDisabledWarnings(this.DisabledWarnings)); param = "DocumentationFile"; this.CheckHostObjectSupport(param, cscHostObject.SetDocumentationFile(this.DocumentationFile)); param = "ErrorReport"; this.CheckHostObjectSupport(param, cscHostObject.SetErrorReport(this.ErrorReport)); param = "FileAlignment"; this.CheckHostObjectSupport(param, cscHostObject.SetFileAlignment(this.FileAlignment)); param = "GenerateFullPaths"; this.CheckHostObjectSupport(param, cscHostObject.SetGenerateFullPaths(this.GenerateFullPaths)); param = "KeyContainer"; this.CheckHostObjectSupport(param, cscHostObject.SetKeyContainer(this.KeyContainer)); param = "KeyFile"; this.CheckHostObjectSupport(param, cscHostObject.SetKeyFile(this.KeyFile)); param = "LangVersion"; this.CheckHostObjectSupport(param, cscHostObject.SetLangVersion(this.LangVersion)); param = "MainEntryPoint"; this.CheckHostObjectSupport(param, cscHostObject.SetMainEntryPoint(this.TargetType, this.MainEntryPoint)); param = "ModuleAssemblyName"; this.CheckHostObjectSupport(param, cscHostObject.SetModuleAssemblyName(this.ModuleAssemblyName)); param = "NoConfig"; this.CheckHostObjectSupport(param, cscHostObject.SetNoConfig(this.NoConfig)); param = "NoStandardLib"; this.CheckHostObjectSupport(param, cscHostObject.SetNoStandardLib(this.NoStandardLib)); param = "Optimize"; this.CheckHostObjectSupport(param, cscHostObject.SetOptimize(this.Optimize)); param = "OutputAssembly"; this.CheckHostObjectSupport(param, cscHostObject.SetOutputAssembly(this.OutputAssembly.ItemSpec)); param = "PdbFile"; this.CheckHostObjectSupport(param, cscHostObject.SetPdbFile(this.PdbFile)); // For host objects which support it, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion ICscHostObject4 cscHostObject4 = cscHostObject as ICscHostObject4; if (cscHostObject4 != null) { param = "PlatformWith32BitPreference"; this.CheckHostObjectSupport(param, cscHostObject4.SetPlatformWith32BitPreference(this.PlatformWith32BitPreference)); param = "HighEntropyVA"; this.CheckHostObjectSupport(param, cscHostObject4.SetHighEntropyVA(this.HighEntropyVA)); param = "SubsystemVersion"; this.CheckHostObjectSupport(param, cscHostObject4.SetSubsystemVersion(this.SubsystemVersion)); } else { param = "Platform"; this.CheckHostObjectSupport(param, cscHostObject.SetPlatform(this.Platform)); } // For host objects which support it, set the analyzer ruleset and additional files. IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject; if (analyzerHostObject != null) { param = "CodeAnalysisRuleSet"; this.CheckHostObjectSupport(param, analyzerHostObject.SetRuleSet(this.CodeAnalysisRuleSet)); param = "AdditionalFiles"; this.CheckHostObjectSupport(param, analyzerHostObject.SetAdditionalFiles(this.AdditionalFiles)); } param = "ResponseFiles"; this.CheckHostObjectSupport(param, cscHostObject.SetResponseFiles(this.ResponseFiles)); param = "TargetType"; this.CheckHostObjectSupport(param, cscHostObject.SetTargetType(this.TargetType)); param = "TreatWarningsAsErrors"; this.CheckHostObjectSupport(param, cscHostObject.SetTreatWarningsAsErrors(this.TreatWarningsAsErrors)); param = "WarningLevel"; this.CheckHostObjectSupport(param, cscHostObject.SetWarningLevel(this.WarningLevel)); // This must come after TreatWarningsAsErrors. param = "WarningsAsErrors"; this.CheckHostObjectSupport(param, cscHostObject.SetWarningsAsErrors(this.WarningsAsErrors)); // This must come after TreatWarningsAsErrors. param = "WarningsNotAsErrors"; this.CheckHostObjectSupport(param, cscHostObject.SetWarningsNotAsErrors(this.WarningsNotAsErrors)); param = "Win32Icon"; this.CheckHostObjectSupport(param, cscHostObject.SetWin32Icon(this.Win32Icon)); // In order to maintain compatibility with previous host compilers, we must // light-up for ICscHostObject2/ICscHostObject3 if (cscHostObject is ICscHostObject2) { ICscHostObject2 cscHostObject2 = (ICscHostObject2)cscHostObject; param = "Win32Manifest"; this.CheckHostObjectSupport(param, cscHostObject2.SetWin32Manifest(this.GetWin32ManifestSwitch(this.NoWin32Manifest, this.Win32Manifest))); } else { // If we have been given a property that the host compiler doesn't support // then we need to state that we are falling back to the command line compiler if (!String.IsNullOrEmpty(Win32Manifest)) { this.CheckHostObjectSupport("Win32Manifest", false); } } // This must come after Win32Manifest param = "Win32Resource"; this.CheckHostObjectSupport(param, cscHostObject.SetWin32Resource(this.Win32Resource)); if (cscHostObject is ICscHostObject3) { ICscHostObject3 cscHostObject3 = (ICscHostObject3)cscHostObject; param = "ApplicationConfiguration"; this.CheckHostObjectSupport(param, cscHostObject3.SetApplicationConfiguration(this.ApplicationConfiguration)); } else { // If we have been given a property that the host compiler doesn't support // then we need to state that we are falling back to the command line compiler if (!String.IsNullOrEmpty(ApplicationConfiguration)) { this.CheckHostObjectSupport("ApplicationConfiguration", false); } } // If we have been given a property value that the host compiler doesn't support // then we need to state that we are falling back to the command line compiler. // Null is supported because it means that option should be omitted, and compiler default used - obviously always valid. // Explicitly specified name of current locale is also supported, since it is effectively a no-op. // Other options are not supported since in-proc compiler always uses current locale. if (!String.IsNullOrEmpty(PreferredUILang) && !String.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase)) { this.CheckHostObjectSupport("PreferredUILang", false); } } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } if (this.HostCompilerSupportsAllParameters) { // If the host compiler doesn't support everything we need, we're going to end up // shelling out to the command-line compiler anyway. That means the command-line // compiler will log the error. So here, we only log the error if we would've // tried to use the host compiler. Log.LogErrorWithCodeFromResources("General.CouldNotSetHostObjectParameter", param, e.Message); } return false; } finally { int errorCode; string errorMessage; success = cscHostObject.EndInitialization(out errorMessage, out errorCode); if (this.HostCompilerSupportsAllParameters) { // If the host compiler doesn't support everything we need, we're going to end up // shelling out to the command-line compiler anyway. That means the command-line // compiler will log the error. So here, we only log the error if we would've // tried to use the host compiler. // If EndInitialization returns false, then there was an error. If EndInitialization was // successful, but there is a valid 'errorMessage,' interpret it as a warning. if (!success) { Log.LogError(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage); } else if (errorMessage != null && errorMessage.Length > 0) { Log.LogWarning(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage); } } } return (success); } /// <summary> /// This method will get called during Execute() if a host object has been passed into the Csc /// task. Returns one of the following values to indicate what the next action should be: /// UseHostObjectToExecute Host compiler exists and was initialized. /// UseAlternateToolToExecute Host compiler doesn't exist or was not appropriate. /// NoActionReturnSuccess Host compiler was already up-to-date, and we're done. /// NoActionReturnFailure Bad parameters were passed into the task. /// </summary> override protected HostObjectInitializationStatus InitializeHostObject() { if (this.HostObject != null) { // When the host object was passed into the task, it was passed in as a generic // "Object" (because ITask interface obviously can't have any Csc-specific stuff // in it, and each task is going to want to communicate with its host in a unique // way). Now we cast it to the specific type that the Csc task expects. If the // host object does not match this type, the host passed in an invalid host object // to Csc, and we error out. // NOTE: For compat reasons this must remain ICscHostObject // we can dynamically test for smarter interfaces later.. using (RCWForCurrentContext<ICscHostObject> hostObject = new RCWForCurrentContext<ICscHostObject>(this.HostObject as ICscHostObject)) { ICscHostObject cscHostObject = hostObject.RCW; if (cscHostObject != null) { bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(cscHostObject); // If we're currently only in design-time (as opposed to build-time), // then we're done. We've initialized the host compiler as best we // can, and we certainly don't want to actually do the final compile. // So return true, saying we're done and successful. if (cscHostObject.IsDesignTime()) { // If we are design-time then we do not want to continue the build at // this time. return hostObjectSuccessfullyInitialized ? HostObjectInitializationStatus.NoActionReturnSuccess : HostObjectInitializationStatus.NoActionReturnFailure; } if (!this.HostCompilerSupportsAllParameters || UseAlternateCommandLineToolToExecute()) { // Since the host compiler has refused to take on the responsibility for this compilation, // we're about to shell out to the command-line compiler to handle it. If some of the // references don't exist on disk, we know the command-line compiler will fail, so save // the trouble, and just throw a consistent error ourselves. This allows us to give // more information than the compiler would, and also make things consistent across // Vbc / Csc / etc. // This suite behaves differently in localized builds than on English builds because // VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it. if (!CheckAllReferencesExistOnDisk()) { return HostObjectInitializationStatus.NoActionReturnFailure; } // The host compiler doesn't support some of the switches/parameters // being passed to it. Therefore, we resort to using the command-line compiler // in this case. UsedCommandLineTool = true; return HostObjectInitializationStatus.UseAlternateToolToExecute; } // Ok, by now we validated that the host object supports the necessary switches // and parameters. Last thing to check is whether the host object is up to date, // and in that case, we will inform the caller that no further action is necessary. if (hostObjectSuccessfullyInitialized) { return cscHostObject.IsUpToDate() ? HostObjectInitializationStatus.NoActionReturnSuccess : HostObjectInitializationStatus.UseHostObjectToExecute; } else { return HostObjectInitializationStatus.NoActionReturnFailure; } } else { Log.LogErrorWithCodeFromResources("General.IncorrectHostObject", "Csc", "ICscHostObject"); } } } // No appropriate host object was found. UsedCommandLineTool = true; return HostObjectInitializationStatus.UseAlternateToolToExecute; } /// <summary> /// This method will get called during Execute() if a host object has been passed into the Csc /// task. Returns true if the compilation succeeded, otherwise false. /// </summary> override protected bool CallHostObjectToExecute() { Debug.Assert(this.HostObject != null, "We should not be here if the host object has not been set."); ICscHostObject cscHostObject = this.HostObject as ICscHostObject; Debug.Assert(cscHostObject != null, "Wrong kind of host object passed in!"); try { #if (!STANDALONEBUILD) CodeMarkers.Instance.CodeMarker(CodeMarkerEvent.perfMSBuildHostCompileBegin); #endif return cscHostObject.Compile(); } finally { #if (!STANDALONEBUILD) CodeMarkers.Instance.CodeMarker(CodeMarkerEvent.perfMSBuildHostCompileEnd); #endif } } } }
MetSystem/msbuild
src/XMakeTasks/Csc.cs
C#
mit
41,306
<?php /** * Plugins administration panel. * * @package WordPress * @subpackage Administration */ /** WordPress Administration Bootstrap */ require_once( dirname( __FILE__ ) . '/admin.php' ); if ( ! current_user_can( 'activate_plugins' ) ) { wp_die( __( 'Sorry, you are not allowed to manage plugins for this site.' ) ); } $wp_list_table = _get_list_table( 'WP_Plugins_List_Table' ); $pagenum = $wp_list_table->get_pagenum(); $action = $wp_list_table->current_action(); $plugin = isset( $_REQUEST['plugin'] ) ? wp_unslash( $_REQUEST['plugin'] ) : ''; $s = isset( $_REQUEST['s'] ) ? urlencode( wp_unslash( $_REQUEST['s'] ) ) : ''; // Clean up request URI from temporary args for screen options/paging uri's to work as expected. $_SERVER['REQUEST_URI'] = remove_query_arg( array( 'error', 'deleted', 'activate', 'activate-multi', 'deactivate', 'deactivate-multi', '_error_nonce' ), $_SERVER['REQUEST_URI'] ); wp_enqueue_script( 'updates' ); if ( $action ) { switch ( $action ) { case 'activate': if ( ! current_user_can( 'activate_plugin', $plugin ) ) { wp_die( __( 'Sorry, you are not allowed to activate this plugin.' ) ); } if ( is_multisite() && ! is_network_admin() && is_network_only_plugin( $plugin ) ) { wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) ); exit; } check_admin_referer( 'activate-plugin_' . $plugin ); $result = activate_plugin( $plugin, self_admin_url( 'plugins.php?error=true&plugin=' . urlencode( $plugin ) ), is_network_admin() ); if ( is_wp_error( $result ) ) { if ( 'unexpected_output' == $result->get_error_code() ) { $redirect = self_admin_url( 'plugins.php?error=true&charsout=' . strlen( $result->get_error_data() ) . '&plugin=' . urlencode( $plugin ) . "&plugin_status=$status&paged=$page&s=$s" ); wp_redirect( add_query_arg( '_error_nonce', wp_create_nonce( 'plugin-activation-error_' . $plugin ), $redirect ) ); exit; } else { wp_die( $result ); } } if ( ! is_network_admin() ) { $recent = (array) get_option( 'recently_activated' ); unset( $recent[ $plugin ] ); update_option( 'recently_activated', $recent ); } else { $recent = (array) get_site_option( 'recently_activated' ); unset( $recent[ $plugin ] ); update_site_option( 'recently_activated', $recent ); } if ( isset( $_GET['from'] ) && 'import' == $_GET['from'] ) { wp_redirect( self_admin_url( 'import.php?import=' . str_replace( '-importer', '', dirname( $plugin ) ) ) ); // overrides the ?error=true one above and redirects to the Imports page, stripping the -importer suffix } elseif ( isset( $_GET['from'] ) && 'press-this' == $_GET['from'] ) { wp_redirect( self_admin_url( 'press-this.php' ) ); } else { wp_redirect( self_admin_url( "plugins.php?activate=true&plugin_status=$status&paged=$page&s=$s" ) ); // overrides the ?error=true one above } exit; case 'activate-selected': if ( ! current_user_can( 'activate_plugins' ) ) { wp_die( __( 'Sorry, you are not allowed to activate plugins for this site.' ) ); } check_admin_referer( 'bulk-plugins' ); $plugins = isset( $_POST['checked'] ) ? (array) wp_unslash( $_POST['checked'] ) : array(); if ( is_network_admin() ) { foreach ( $plugins as $i => $plugin ) { // Only activate plugins which are not already network activated. if ( is_plugin_active_for_network( $plugin ) ) { unset( $plugins[ $i ] ); } } } else { foreach ( $plugins as $i => $plugin ) { // Only activate plugins which are not already active and are not network-only when on Multisite. if ( is_plugin_active( $plugin ) || ( is_multisite() && is_network_only_plugin( $plugin ) ) ) { unset( $plugins[ $i ] ); } // Only activate plugins which the user can activate. if ( ! current_user_can( 'activate_plugin', $plugin ) ) { unset( $plugins[ $i ] ); } } } if ( empty( $plugins ) ) { wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) ); exit; } activate_plugins( $plugins, self_admin_url( 'plugins.php?error=true' ), is_network_admin() ); if ( ! is_network_admin() ) { $recent = (array) get_option( 'recently_activated' ); } else { $recent = (array) get_site_option( 'recently_activated' ); } foreach ( $plugins as $plugin ) { unset( $recent[ $plugin ] ); } if ( ! is_network_admin() ) { update_option( 'recently_activated', $recent ); } else { update_site_option( 'recently_activated', $recent ); } wp_redirect( self_admin_url( "plugins.php?activate-multi=true&plugin_status=$status&paged=$page&s=$s" ) ); exit; case 'update-selected': check_admin_referer( 'bulk-plugins' ); if ( isset( $_GET['plugins'] ) ) { $plugins = explode( ',', wp_unslash( $_GET['plugins'] ) ); } elseif ( isset( $_POST['checked'] ) ) { $plugins = (array) wp_unslash( $_POST['checked'] ); } else { $plugins = array(); } $title = __( 'Update Plugins' ); $parent_file = 'plugins.php'; wp_enqueue_script( 'updates' ); require_once( ABSPATH . 'wp-admin/admin-header.php' ); echo '<div class="wrap">'; echo '<h1>' . esc_html( $title ) . '</h1>'; $url = self_admin_url( 'update.php?action=update-selected&amp;plugins=' . urlencode( join( ',', $plugins ) ) ); $url = wp_nonce_url( $url, 'bulk-update-plugins' ); echo "<iframe src='$url' style='width: 100%; height:100%; min-height:850px;'></iframe>"; echo '</div>'; require_once( ABSPATH . 'wp-admin/admin-footer.php' ); exit; case 'error_scrape': if ( ! current_user_can( 'activate_plugin', $plugin ) ) { wp_die( __( 'Sorry, you are not allowed to activate this plugin.' ) ); } check_admin_referer( 'plugin-activation-error_' . $plugin ); $valid = validate_plugin( $plugin ); if ( is_wp_error( $valid ) ) { wp_die( $valid ); } if ( ! WP_DEBUG ) { error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR ); } ini_set( 'display_errors', true ); //Ensure that Fatal errors are displayed. // Go back to "sandbox" scope so we get the same errors as before plugin_sandbox_scrape( $plugin ); /** This action is documented in wp-admin/includes/plugin.php */ do_action( "activate_{$plugin}" ); exit; case 'deactivate': if ( ! current_user_can( 'deactivate_plugin', $plugin ) ) { wp_die( __( 'Sorry, you are not allowed to deactivate this plugin.' ) ); } check_admin_referer( 'deactivate-plugin_' . $plugin ); if ( ! is_network_admin() && is_plugin_active_for_network( $plugin ) ) { wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) ); exit; } deactivate_plugins( $plugin, false, is_network_admin() ); if ( ! is_network_admin() ) { update_option( 'recently_activated', array( $plugin => time() ) + (array) get_option( 'recently_activated' ) ); } else { update_site_option( 'recently_activated', array( $plugin => time() ) + (array) get_site_option( 'recently_activated' ) ); } if ( headers_sent() ) { echo "<meta http-equiv='refresh' content='" . esc_attr( "0;url=plugins.php?deactivate=true&plugin_status=$status&paged=$page&s=$s" ) . "' />"; } else { wp_redirect( self_admin_url( "plugins.php?deactivate=true&plugin_status=$status&paged=$page&s=$s" ) ); } exit; case 'deactivate-selected': if ( ! current_user_can( 'deactivate_plugins' ) ) { wp_die( __( 'Sorry, you are not allowed to deactivate plugins for this site.' ) ); } check_admin_referer( 'bulk-plugins' ); $plugins = isset( $_POST['checked'] ) ? (array) wp_unslash( $_POST['checked'] ) : array(); // Do not deactivate plugins which are already deactivated. if ( is_network_admin() ) { $plugins = array_filter( $plugins, 'is_plugin_active_for_network' ); } else { $plugins = array_filter( $plugins, 'is_plugin_active' ); $plugins = array_diff( $plugins, array_filter( $plugins, 'is_plugin_active_for_network' ) ); foreach ( $plugins as $i => $plugin ) { // Only deactivate plugins which the user can deactivate. if ( ! current_user_can( 'deactivate_plugin', $plugin ) ) { unset( $plugins[ $i ] ); } } } if ( empty( $plugins ) ) { wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) ); exit; } deactivate_plugins( $plugins, false, is_network_admin() ); $deactivated = array(); foreach ( $plugins as $plugin ) { $deactivated[ $plugin ] = time(); } if ( ! is_network_admin() ) { update_option( 'recently_activated', $deactivated + (array) get_option( 'recently_activated' ) ); } else { update_site_option( 'recently_activated', $deactivated + (array) get_site_option( 'recently_activated' ) ); } wp_redirect( self_admin_url( "plugins.php?deactivate-multi=true&plugin_status=$status&paged=$page&s=$s" ) ); exit; case 'delete-selected': if ( ! current_user_can( 'delete_plugins' ) ) { wp_die( __( 'Sorry, you are not allowed to delete plugins for this site.' ) ); } check_admin_referer( 'bulk-plugins' ); //$_POST = from the plugin form; $_GET = from the FTP details screen. $plugins = isset( $_REQUEST['checked'] ) ? (array) wp_unslash( $_REQUEST['checked'] ) : array(); if ( empty( $plugins ) ) { wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) ); exit; } $plugins = array_filter( $plugins, 'is_plugin_inactive' ); // Do not allow to delete Activated plugins. if ( empty( $plugins ) ) { wp_redirect( self_admin_url( "plugins.php?error=true&main=true&plugin_status=$status&paged=$page&s=$s" ) ); exit; } // Bail on all if any paths are invalid. // validate_file() returns truthy for invalid files $invalid_plugin_files = array_filter( $plugins, 'validate_file' ); if ( $invalid_plugin_files ) { wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) ); exit; } include( ABSPATH . 'wp-admin/update.php' ); $parent_file = 'plugins.php'; if ( ! isset( $_REQUEST['verify-delete'] ) ) { wp_enqueue_script( 'jquery' ); require_once( ABSPATH . 'wp-admin/admin-header.php' ); ?> <div class="wrap"> <?php $plugin_info = array(); $have_non_network_plugins = false; foreach ( (array) $plugins as $plugin ) { $plugin_slug = dirname( $plugin ); if ( '.' == $plugin_slug ) { $data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin ); if ( $data ) { $plugin_info[ $plugin ] = $data; $plugin_info[ $plugin ]['is_uninstallable'] = is_uninstallable_plugin( $plugin ); if ( ! $plugin_info[ $plugin ]['Network'] ) { $have_non_network_plugins = true; } } } else { // Get plugins list from that folder. $folder_plugins = get_plugins( '/' . $plugin_slug ); if ( $folder_plugins ) { foreach ( $folder_plugins as $plugin_file => $data ) { $plugin_info[ $plugin_file ] = _get_plugin_data_markup_translate( $plugin_file, $data ); $plugin_info[ $plugin_file ]['is_uninstallable'] = is_uninstallable_plugin( $plugin ); if ( ! $plugin_info[ $plugin_file ]['Network'] ) { $have_non_network_plugins = true; } } } } } $plugins_to_delete = count( $plugin_info ); ?> <?php if ( 1 == $plugins_to_delete ) : ?> <h1><?php _e( 'Delete Plugin' ); ?></h1> <?php if ( $have_non_network_plugins && is_network_admin() ) : ?> <div class="error"><p><strong><?php _e( 'Caution:' ); ?></strong> <?php _e( 'This plugin may be active on other sites in the network.' ); ?></p></div> <?php endif; ?> <p><?php _e( 'You are about to remove the following plugin:' ); ?></p> <?php else : ?> <h1><?php _e( 'Delete Plugins' ); ?></h1> <?php if ( $have_non_network_plugins && is_network_admin() ) : ?> <div class="error"><p><strong><?php _e( 'Caution:' ); ?></strong> <?php _e( 'These plugins may be active on other sites in the network.' ); ?></p></div> <?php endif; ?> <p><?php _e( 'You are about to remove the following plugins:' ); ?></p> <?php endif; ?> <ul class="ul-disc"> <?php $data_to_delete = false; foreach ( $plugin_info as $plugin ) { if ( $plugin['is_uninstallable'] ) { /* translators: 1: Plugin name, 2: Plugin author. */ echo '<li>', sprintf( __( '%1$s by %2$s (will also <strong>delete its data</strong>)' ), '<strong>' . $plugin['Name'] . '</strong>', '<em>' . $plugin['AuthorName'] . '</em>' ), '</li>'; $data_to_delete = true; } else { /* translators: 1: Plugin name, 2: Plugin author. */ echo '<li>', sprintf( _x( '%1$s by %2$s', 'plugin' ), '<strong>' . $plugin['Name'] . '</strong>', '<em>' . $plugin['AuthorName'] ) . '</em>', '</li>'; } } ?> </ul> <p> <?php if ( $data_to_delete ) { _e( 'Are you sure you want to delete these files and data?' ); } else { _e( 'Are you sure you want to delete these files?' ); } ?> </p> <form method="post" action="<?php echo esc_url( $_SERVER['REQUEST_URI'] ); ?>" style="display:inline;"> <input type="hidden" name="verify-delete" value="1" /> <input type="hidden" name="action" value="delete-selected" /> <?php foreach ( (array) $plugins as $plugin ) { echo '<input type="hidden" name="checked[]" value="' . esc_attr( $plugin ) . '" />'; } ?> <?php wp_nonce_field( 'bulk-plugins' ); ?> <?php submit_button( $data_to_delete ? __( 'Yes, delete these files and data' ) : __( 'Yes, delete these files' ), '', 'submit', false ); ?> </form> <?php $referer = wp_get_referer(); ?> <form method="post" action="<?php echo $referer ? esc_url( $referer ) : ''; ?>" style="display:inline;"> <?php submit_button( __( 'No, return me to the plugin list' ), '', 'submit', false ); ?> </form> </div> <?php require_once( ABSPATH . 'wp-admin/admin-footer.php' ); exit; } else { $plugins_to_delete = count( $plugins ); } // endif verify-delete $delete_result = delete_plugins( $plugins ); set_transient( 'plugins_delete_result_' . $user_ID, $delete_result ); //Store the result in a cache rather than a URL param due to object type & length wp_redirect( self_admin_url( "plugins.php?deleted=$plugins_to_delete&plugin_status=$status&paged=$page&s=$s" ) ); exit; case 'clear-recent-list': if ( ! is_network_admin() ) { update_option( 'recently_activated', array() ); } else { update_site_option( 'recently_activated', array() ); } break; case 'resume': if ( is_multisite() ) { return; } if ( ! current_user_can( 'resume_plugin', $plugin ) ) { wp_die( __( 'Sorry, you are not allowed to resume this plugin.' ) ); } check_admin_referer( 'resume-plugin_' . $plugin ); $result = resume_plugin( $plugin, self_admin_url( "plugins.php?error=resuming&plugin_status=$status&paged=$page&s=$s" ) ); if ( is_wp_error( $result ) ) { wp_die( $result ); } wp_redirect( self_admin_url( "plugins.php?resume=true&plugin_status=$status&paged=$page&s=$s" ) ); exit; default: if ( isset( $_POST['checked'] ) ) { check_admin_referer( 'bulk-plugins' ); $plugins = isset( $_POST['checked'] ) ? (array) wp_unslash( $_POST['checked'] ) : array(); $sendback = wp_get_referer(); /** This action is documented in wp-admin/edit-comments.php */ $sendback = apply_filters( 'handle_bulk_actions-' . get_current_screen()->id, $sendback, $action, $plugins ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores wp_safe_redirect( $sendback ); exit; } break; } } $wp_list_table->prepare_items(); wp_enqueue_script( 'plugin-install' ); add_thickbox(); add_screen_option( 'per_page', array( 'default' => 999 ) ); get_current_screen()->add_help_tab( array( 'id' => 'overview', 'title' => __( 'Overview' ), 'content' => '<p>' . __( 'Plugins extend and expand the functionality of WordPress. Once a plugin is installed, you may activate it or deactivate it here.' ) . '</p>' . '<p>' . __( 'The search for installed plugins will search for terms in their name, description, or author.' ) . ' <span id="live-search-desc" class="hide-if-no-js">' . __( 'The search results will be updated as you type.' ) . '</span></p>' . '<p>' . sprintf( /* translators: %s: WordPress Plugin Directory URL. */ __( 'If you would like to see more plugins to choose from, click on the &#8220;Add New&#8221; button and you will be able to browse or search for additional plugins from the <a href="%s">WordPress Plugin Directory</a>. Plugins in the WordPress Plugin Directory are designed and developed by third parties, and are compatible with the license WordPress uses. Oh, and they&#8217;re free!' ), __( 'https://wordpress.org/plugins/' ) ) . '</p>', ) ); get_current_screen()->add_help_tab( array( 'id' => 'compatibility-problems', 'title' => __( 'Troubleshooting' ), 'content' => '<p>' . __( 'Most of the time, plugins play nicely with the core of WordPress and with other plugins. Sometimes, though, a plugin&#8217;s code will get in the way of another plugin, causing compatibility issues. If your site starts doing strange things, this may be the problem. Try deactivating all your plugins and re-activating them in various combinations until you isolate which one(s) caused the issue.' ) . '</p>' . '<p>' . sprintf( /* translators: WP_PLUGIN_DIR constant value. */ __( 'If something goes wrong with a plugin and you can&#8217;t use WordPress, delete or rename that file in the %s directory and it will be automatically deactivated.' ), '<code>' . WP_PLUGIN_DIR . '</code>' ) . '</p>', ) ); get_current_screen()->set_help_sidebar( '<p><strong>' . __( 'For more information:' ) . '</strong></p>' . '<p>' . __( '<a href="https://wordpress.org/support/article/managing-plugins/">Documentation on Managing Plugins</a>' ) . '</p>' . '<p>' . __( '<a href="https://wordpress.org/support/">Support</a>' ) . '</p>' ); get_current_screen()->set_screen_reader_content( array( 'heading_views' => __( 'Filter plugins list' ), 'heading_pagination' => __( 'Plugins list navigation' ), 'heading_list' => __( 'Plugins list' ), ) ); $title = __( 'Plugins' ); $parent_file = 'plugins.php'; require_once( ABSPATH . 'wp-admin/admin-header.php' ); $invalid = validate_active_plugins(); if ( ! empty( $invalid ) ) { foreach ( $invalid as $plugin_file => $error ) { echo '<div id="message" class="error"><p>'; printf( /* translators: 1: Plugin file, 2: Error message. */ __( 'The plugin %1$s has been deactivated due to an error: %2$s' ), '<code>' . esc_html( $plugin_file ) . '</code>', $error->get_error_message() ); echo '</p></div>'; } } ?> <?php if ( isset( $_GET['error'] ) ) : if ( isset( $_GET['main'] ) ) { $errmsg = __( 'You cannot delete a plugin while it is active on the main site.' ); } elseif ( isset( $_GET['charsout'] ) ) { $errmsg = sprintf( /* translators: %d: Number of characters. */ _n( 'The plugin generated %d character of <strong>unexpected output</strong> during activation.', 'The plugin generated %d characters of <strong>unexpected output</strong> during activation.', $_GET['charsout'] ), $_GET['charsout'] ); $errmsg .= ' ' . __( 'If you notice &#8220;headers already sent&#8221; messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.' ); } elseif ( 'resuming' === $_GET['error'] ) { $errmsg = __( 'Plugin could not be resumed because it triggered a <strong>fatal error</strong>.' ); } else { $errmsg = __( 'Plugin could not be activated because it triggered a <strong>fatal error</strong>.' ); } ?> <div id="message" class="error"><p><?php echo $errmsg; ?></p> <?php if ( ! isset( $_GET['main'] ) && ! isset( $_GET['charsout'] ) && wp_verify_nonce( $_GET['_error_nonce'], 'plugin-activation-error_' . $plugin ) ) { $iframe_url = add_query_arg( array( 'action' => 'error_scrape', 'plugin' => urlencode( $plugin ), '_wpnonce' => urlencode( $_GET['_error_nonce'] ), ), admin_url( 'plugins.php' ) ); ?> <iframe style="border:0" width="100%" height="70px" src="<?php echo esc_url( $iframe_url ); ?>"></iframe> <?php } ?> </div> <?php elseif ( isset( $_GET['deleted'] ) ) : $delete_result = get_transient( 'plugins_delete_result_' . $user_ID ); // Delete it once we're done. delete_transient( 'plugins_delete_result_' . $user_ID ); if ( is_wp_error( $delete_result ) ) : ?> <div id="message" class="error notice is-dismissible"> <p> <?php printf( /* translators: %s: Error message. */ __( 'Plugin could not be deleted due to an error: %s' ), $delete_result->get_error_message() ); ?> </p> </div> <?php else : ?> <div id="message" class="updated notice is-dismissible"> <p> <?php if ( 1 == (int) $_GET['deleted'] ) { _e( 'The selected plugin has been deleted.' ); } else { _e( 'The selected plugins have been deleted.' ); } ?> </p> </div> <?php endif; ?> <?php elseif ( isset( $_GET['activate'] ) ) : ?> <div id="message" class="updated notice is-dismissible"><p><?php _e( 'Plugin activated.' ); ?></p></div> <?php elseif ( isset( $_GET['activate-multi'] ) ) : ?> <div id="message" class="updated notice is-dismissible"><p><?php _e( 'Selected plugins activated.' ); ?></p></div> <?php elseif ( isset( $_GET['deactivate'] ) ) : ?> <div id="message" class="updated notice is-dismissible"><p><?php _e( 'Plugin deactivated.' ); ?></p></div> <?php elseif ( isset( $_GET['deactivate-multi'] ) ) : ?> <div id="message" class="updated notice is-dismissible"><p><?php _e( 'Selected plugins deactivated.' ); ?></p></div> <?php elseif ( 'update-selected' == $action ) : ?> <div id="message" class="updated notice is-dismissible"><p><?php _e( 'All selected plugins are up to date.' ); ?></p></div> <?php elseif ( isset( $_GET['resume'] ) ) : ?> <div id="message" class="updated notice is-dismissible"><p><?php _e( 'Plugin resumed.' ); ?></p></div> <?php endif; ?> <div class="wrap"> <h1 class="wp-heading-inline"> <?php echo esc_html( $title ); ?> </h1> <?php if ( ( ! is_multisite() || is_network_admin() ) && current_user_can( 'install_plugins' ) ) { ?> <a href="<?php echo self_admin_url( 'plugin-install.php' ); ?>" class="page-title-action"><?php echo esc_html_x( 'Add New', 'plugin' ); ?></a> <?php } if ( strlen( $s ) ) { /* translators: %s: Search query. */ printf( '<span class="subtitle">' . __( 'Search results for &#8220;%s&#8221;' ) . '</span>', esc_html( urldecode( $s ) ) ); } ?> <hr class="wp-header-end"> <?php /** * Fires before the plugins list table is rendered. * * This hook also fires before the plugins list table is rendered in the Network Admin. * * Please note: The 'active' portion of the hook name does not refer to whether the current * view is for active plugins, but rather all plugins actively-installed. * * @since 3.0.0 * * @param array[] $plugins_all An array of arrays containing information on all installed plugins. */ do_action( 'pre_current_active_plugins', $plugins['all'] ); ?> <?php $wp_list_table->views(); ?> <form class="search-form search-plugins" method="get"> <?php $wp_list_table->search_box( __( 'Search Installed Plugins' ), 'plugin' ); ?> </form> <form method="post" id="bulk-action-form"> <input type="hidden" name="plugin_status" value="<?php echo esc_attr( $status ); ?>" /> <input type="hidden" name="paged" value="<?php echo esc_attr( $page ); ?>" /> <?php $wp_list_table->display(); ?> </form> <span class="spinner"></span> </div> <?php wp_print_request_filesystem_credentials_modal(); wp_print_admin_notice_templates(); wp_print_update_row_templates(); include( ABSPATH . 'wp-admin/admin-footer.php' );
kirsley/repobase
wp-admin/plugins.php
PHP
gpl-2.0
24,347
<?php /* * Post relationship class. * * $HeadURL: http://plugins.svn.wordpress.org/types/tags/1.6.5.1/embedded/classes/relationship.php $ * $LastChangedDate: 2015-01-16 14:28:15 +0000 (Fri, 16 Jan 2015) $ * $LastChangedRevision: 1069430 $ * $LastChangedBy: iworks $ * */ /** * Post relationship class * * @since Types 1.2 * @package Types * @subpackage Classes * @version 0.1 * @category Relationship * @author srdjan <srdjan@icanlocalize.com> * */ class WPCF_Relationship { /** * Custom field * * @var type */ var $cf = array(); var $data = array(); /** * Settings * * @var type */ var $settings = array(); var $items_per_page = 5; var $items_per_page_option_name = '_wpcf_relationship_items_per_page'; var $child_form = null; /** * Construct function. */ function __construct() { $this->cf = new WPCF_Field; $this->settings = get_option( 'wpcf_post_relationship', array() ); add_action( 'wp_ajax_add-types_reltax_add', array($this, 'ajaxAddTax') ); } /** * Sets current data. * * @param type $parent * @param type $child * @param type $field * @param type $data */ function set( $parent, $child, $data = array() ) { return $this->_set( $parent, $child, $data ); } /** * Sets current data. * * @param type $parent * @param type $child * @param type $field * @param type $data */ function _set( $parent, $child, $data = array() ) { $this->parent = $parent; $this->child = $child; $this->cf = new WPCF_Field; // TODO Revise usage $this->data = $data; } /** * Meta box form on post edit page. * * @param type $parent Parent post * @param type $post_type Child post type * @return type string HTML formatted form table */ function child_meta_form($parent, $post_type) { if ( is_integer( $parent ) ) { $parent = get_post( $parent ); } $output = ''; require_once dirname( __FILE__ ) . '/relationship/form-child.php'; $this->child_form = new WPCF_Relationship_Child_Form( $parent, $post_type, $this->settings( $parent->post_type, $post_type ) ); $output .= $this->child_form->render(); return $output; } /** * Child row rendered on AJAX 'Add New Child' call. * * @param type $parent_id * @param type $child_id * @return type */ function child_row($parent_id, $child_id) { $parent = get_post( intval( $parent_id ) ); $child = get_post( intval( $child_id ) ); if ( empty( $parent ) || empty( $child ) ) { return new WP_Error( 'wpcf-relationship-save-child', 'no parent/child post' ); } $output = ''; $this->child_form = $this->_get_child_form( $parent, $child ); $output .= $this->child_form->child_row( $child ); return $output; } /** * Returns HTML formatted form. * * @param type $parent * @param type $child * @return \WPCF_Relationship_Child_Form */ function _get_child_form($parent, $child) { require_once dirname( __FILE__ ) . '/relationship/form-child.php'; return new WPCF_Relationship_Child_Form( $parent, $child->post_type, $this->settings( $parent->post_type, $child->post_type ) ); } function get_child() { $r = $this->child; $r->parent = $this->parent; $r->form = $this->_get_child_form( $r->parent, $this->child ); return $r; } /** * Save items_per_page settings. * * @param type $parent * @param type $child * @param int $num */ function save_items_per_page($parent, $child, $num) { if ( post_type_exists( $parent ) && post_type_exists( $child ) ) { $option_name = $this->items_per_page_option_name . '_' . $parent . '_' . $child; if ( $num == 'all' ) { $num = 9999999999999999; } update_option( $option_name, intval( $num ) ); } } /** * Return items_per_page settings * * @param type $parent * @param type $child * @return type */ function get_items_per_page($parent, $child) { $per_page = get_option( $this->items_per_page_option_name . '_' . $parent . '_' . $child, $this->items_per_page ); return empty( $per_page ) ? $this->items_per_page : $per_page; } /** * Adjusts post name when saving. * * @todo Revise (not used?) * @param type $post * @return type */ function get_insert_post_name($post) { if ( empty( $post->post_title ) ) { return $post->post_type . '-' . $post->ID; } return $post->post_title; } /** * Bulk saving children. * * @param type $parent_id * @param type $children */ function save_children($parent_id, $children) { foreach ( $children as $child_id => $fields ) { $this->save_child( $parent_id, $child_id, $fields ); } } /** * Unified save child function. * * @param type $child_id * @param type $parent_id */ function save_child( $parent_id, $child_id, $save_fields = array() ) { global $wpdb; $parent = get_post( intval( $parent_id ) ); $child = get_post( intval( $child_id ) ); $post_data = array(); if ( empty( $parent ) || empty( $child ) ) { return new WP_Error( 'wpcf-relationship-save-child', 'no parent/child post' ); } // Save relationship update_post_meta( $child->ID, '_wpcf_belongs_' . $parent->post_type . '_id', $parent->ID ); // Check if added via AJAX $check = get_post_meta( $child->ID, '_wpcf_relationship_new', true ); $new = !empty( $check ); delete_post_meta( $child->ID, '_wpcf_relationship_new' ); // Set post data $post_data['ID'] = $child->ID; // Title needs to be checked if submitted at all if ( !isset( $save_fields['_wp_title'] ) ) { // If not submitted that means it is not offered to be edited if ( !empty( $child->post_title ) ) { $post_title = $child->post_title; } else { // DO NOT LET IT BE EMPTY $post_title = $child->post_type . ' ' . $child->ID; } } else { $post_title = $save_fields['_wp_title']; } $post_data['post_title'] = $post_title; $post_data['post_content'] = isset( $save_fields['_wp_body'] ) ? $save_fields['_wp_body'] : $child->post_content; $post_data['post_type'] = $child->post_type; // Check post status - if new, convert to 'publish' else keep remaining if ( $new ) { $post_data['post_status'] = 'publish'; } else { $post_data['post_status'] = get_post_status( $child->ID ); } /* * * * * * * * UPDATE POST */ $cf = new WPCF_Field; if ( isset( $_POST['wpcf_post_relationship'][$parent_id]) && isset( $_POST['wpcf_post_relationship'][$parent_id][$child_id] ) ) { $_POST['wpcf'] = array(); foreach( $_POST['wpcf_post_relationship'][$parent_id][$child_id] as $slug => $value ) { $_POST['wpcf'][$cf->__get_slug_no_prefix( $slug )] = $value; $_POST['wpcf'][$slug] = $value; } } unset($cf); $updated_id = wp_update_post( $post_data ); if ( empty( $updated_id ) ) { return new WP_Error( 'relationship-update-post-failed', 'Updating post failed' ); } // Save parents if ( !empty( $save_fields['parents'] ) ) { foreach ( $save_fields['parents'] as $parent_post_type => $parent_post_id ) { update_post_meta( $child->ID, '_wpcf_belongs_' . $parent_post_type . '_id', $parent_post_id ); } } // Update taxonomies if ( !empty( $save_fields['taxonomies'] ) && is_array( $save_fields['taxonomies'] ) ) { $_save_data = array(); foreach ( $save_fields['taxonomies'] as $taxonomy => $t ) { if ( !is_taxonomy_hierarchical( $taxonomy ) ) { $_save_data[$taxonomy] = strval( $t ); continue; } foreach ( $t as $term_id ) { if ( $term_id != '-1' ) { $term = get_term( $term_id, $taxonomy ); if ( empty( $term ) ) { continue; } $_save_data[$taxonomy][] = $term_id; } } } wp_delete_object_term_relationships( $child->ID, array_keys( $save_fields['taxonomies'] ) ); foreach ( $_save_data as $_taxonomy => $_terms ) { wp_set_post_terms( $child->ID, $_terms, $_taxonomy, $append = false ); } } // Unset non-types unset( $save_fields['_wp_title'], $save_fields['_wp_body'], $save_fields['parents'], $save_fields['taxonomies'] ); /* * * * * * * * UPDATE Loop over fields */ foreach ( $save_fields as $slug => $value ) { if ( defined( 'WPTOOLSET_FORMS_VERSION' ) ) { // Get field by slug $field = wpcf_fields_get_field_by_slug( str_replace( WPCF_META_PREFIX, '', $slug ) ); if ( empty( $field ) ) { continue; } // Set config $config = wptoolset_form_filter_types_field( $field, $child->ID ); // Check if valid $valid = wptoolset_form_validate_field( 'post', $config, $value ); if ( is_wp_error( $valid ) ) { $errors = $valid->get_error_data(); $msg = sprintf( __( 'Child post "%s" field "%s" not updated:', 'wpcf' ), $child->post_title, $field['name'] ); wpcf_admin_message_store( $msg . ' ' . implode( ', ', $errors ), 'error' ); continue; } } $this->cf->set( $child, $field ); $this->cf->context = 'post_relationship'; $this->cf->save( $value ); } do_action( 'wpcf_relationship_save_child', $child, $parent ); clean_post_cache( $parent->ID ); clean_post_cache( $child->ID ); // Added because of caching meta 1.5.4 wp_cache_flush(); return true; } /** * Saves new child. * * @param type $parent_id * @param type $post_type * @return type */ function add_new_child($parent_id, $post_type) { global $wpdb; $parent = get_post( $parent_id ); if ( empty( $parent ) ) { return new WP_Error( 'wpcf-relationship-no-parent', 'No parent' ); } $new_post = array( 'post_title' => __('New'). ': '.$post_type, 'post_type' => $post_type, 'post_status' => 'draft', ); $id = wp_insert_post( $new_post, true ); /** * return wp_error */ if ( is_wp_error( $id ) ) { return $id; } /** * Mark that it is new post */ update_post_meta( $id, '_wpcf_relationship_new', 1 ); /** * Save relationship */ update_post_meta( $id, '_wpcf_belongs_' . $parent->post_type . '_id', $parent->ID ); /** * Fix title */ $wpdb->update( $wpdb->posts, array('post_title' => $post_type . ' ' . $id), array('ID' => $id), array('%s'), array('%d') ); do_action( 'wpcf_relationship_add_child', get_post( $id ), $parent ); wp_cache_flush(); return $id; } /** * Saved relationship settings. * * @param type $parent * @param type $child * @return type */ function settings($parent, $child) { return isset( $this->settings[$parent][$child] ) ? $this->settings[$parent][$child] : array(); } /** * Fetches submitted data. * * @param type $parent_id * @param type $child_id * @return type */ function get_submitted_data($parent_id, $child_id, $field) { if ( !is_string( $field ) ) { $_field_slug = $field->slug; } else { $_field_slug = $field; } return isset( $_POST['wpcf_post_relationship'][$parent_id][$child_id][$_field_slug] ) ? $_POST['wpcf_post_relationship'][$parent_id][$child_id][$_field_slug] : null; } /** * Gets all parents per post type. * * @param type $child * @return type */ public static function get_parents($child) { $parents = array(); $item_parents = wpcf_pr_admin_get_belongs( $child->post_type ); if ( $item_parents ) { foreach ( $item_parents as $post_type => $data ) { // Get parent ID $meta = wpcf_get_post_meta( $child->ID, '_wpcf_belongs_' . $post_type . '_id', true ); if ( !empty( $meta ) ) { $parent_post = get_post( $meta ); if ( !empty( $parent_post ) ) { $parents[$parent_post->post_type] = $parent_post; } } } } return $parents; } /** * Gets post parent by post type. * * @param type $post_id * @param type $parent_post_type * @return type */ public static function get_parent($post_id, $parent_post_type) { return wpcf_get_post_meta( $post_id, '_wpcf_belongs_' . $parent_post_type . '_id', true ); } /** * AJAX adding taxonomies */ public function ajaxAddTax() { if ( isset( $_POST['types_reltax'] ) ) { $data = array_shift( $_POST['types_reltax'] ); $tax = key( $data ); $val = array_shift( $data ); $__nonce = array_shift( $_POST['types_reltax_nonce'] ); $nonce = array_shift( $__nonce ); $_POST['action'] = 'add-' . $tax; $_POST['post_category'][$tax] = $val; $_POST['tax_input'][$tax] = $val; $_POST['new'.$tax] = $val; $_REQUEST["_ajax_nonce-add-{$tax}"] = $nonce; _wp_ajax_add_hierarchical_term(); } die(); } /** * Meta box form on post edit page. * * @param type $parent Parent post * @param type $post_type Child post type * @return type string HTML formatted list */ function child_list($parent, $post_type) { if ( is_integer( $parent ) ) { $parent = get_post( $parent ); } $output = ''; require_once dirname( __FILE__ ) . '/relationship/form-child.php'; $this->child_form = new WPCF_Relationship_Child_Form( $parent, $post_type, $this->settings( $parent->post_type, $post_type ) ); foreach($this->child_form->children as $child) { $output .= sprintf( '<li>%s</li>', apply_filters('post_title', $child->post_title) ); } if ( $output ) { $output = sprintf( '<ul>%s</ul>', $output ); } else { $output = sprintf( '<p class="info">%s</p>', $this->child_form->child_post_type_object->labels->not_found ); } return $output; } }
cgb37/umlib-wp.local
wp-content/plugins/types/embedded/classes/relationship.php
PHP
gpl-2.0
16,640
/* * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.util.locale.provider; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.spi.DateFormatProvider; import java.util.Calendar; import java.util.Locale; import java.util.MissingResourceException; import java.util.Set; import java.util.TimeZone; /** * Concrete implementation of the {@link java.text.spi.DateFormatProvider * DateFormatProvider} class for the JRE LocaleProviderAdapter. * * @author Naoto Sato * @author Masayoshi Okutsu */ public class DateFormatProviderImpl extends DateFormatProvider implements AvailableLanguageTags { private final LocaleProviderAdapter.Type type; private final Set<String> langtags; public DateFormatProviderImpl(LocaleProviderAdapter.Type type, Set<String> langtags) { this.type = type; this.langtags = langtags; } /** * Returns an array of all locales for which this locale service provider * can provide localized objects or names. * * @return An array of all locales for which this locale service provider * can provide localized objects or names. */ @Override public Locale[] getAvailableLocales() { return LocaleProviderAdapter.toLocaleArray(langtags); } @Override public boolean isSupportedLocale(Locale locale) { return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags); } /** * Returns a new <code>DateFormat</code> instance which formats time * with the given formatting style for the specified locale. * @param style the given formatting style. Either one of * {@link java.text.DateFormat#SHORT DateFormat.SHORT}, * {@link java.text.DateFormat#MEDIUM DateFormat.MEDIUM}, * {@link java.text.DateFormat#LONG DateFormat.LONG}, or * {@link java.text.DateFormat#FULL DateFormat.FULL}. * @param locale the desired locale. * @exception IllegalArgumentException if <code>style</code> is invalid, * or if <code>locale</code> isn't * one of the locales returned from * {@link java.util.spi.LocaleServiceProvider#getAvailableLocales() * getAvailableLocales()}. * @exception NullPointerException if <code>locale</code> is null * @return a time formatter. * @see java.text.DateFormat#getTimeInstance(int, java.util.Locale) */ @Override public DateFormat getTimeInstance(int style, Locale locale) { return getInstance(-1, style, locale); } /** * Returns a new <code>DateFormat</code> instance which formats date * with the given formatting style for the specified locale. * @param style the given formatting style. Either one of * {@link java.text.DateFormat#SHORT DateFormat.SHORT}, * {@link java.text.DateFormat#MEDIUM DateFormat.MEDIUM}, * {@link java.text.DateFormat#LONG DateFormat.LONG}, or * {@link java.text.DateFormat#FULL DateFormat.FULL}. * @param locale the desired locale. * @exception IllegalArgumentException if <code>style</code> is invalid, * or if <code>locale</code> isn't * one of the locales returned from * {@link java.util.spi.LocaleServiceProvider#getAvailableLocales() * getAvailableLocales()}. * @exception NullPointerException if <code>locale</code> is null * @return a date formatter. * @see java.text.DateFormat#getDateInstance(int, java.util.Locale) */ @Override public DateFormat getDateInstance(int style, Locale locale) { return getInstance(style, -1, locale); } /** * Returns a new <code>DateFormat</code> instance which formats date and time * with the given formatting style for the specified locale. * @param dateStyle the given date formatting style. Either one of * {@link java.text.DateFormat#SHORT DateFormat.SHORT}, * {@link java.text.DateFormat#MEDIUM DateFormat.MEDIUM}, * {@link java.text.DateFormat#LONG DateFormat.LONG}, or * {@link java.text.DateFormat#FULL DateFormat.FULL}. * @param timeStyle the given time formatting style. Either one of * {@link java.text.DateFormat#SHORT DateFormat.SHORT}, * {@link java.text.DateFormat#MEDIUM DateFormat.MEDIUM}, * {@link java.text.DateFormat#LONG DateFormat.LONG}, or * {@link java.text.DateFormat#FULL DateFormat.FULL}. * @param locale the desired locale. * @exception IllegalArgumentException if <code>dateStyle</code> or * <code>timeStyle</code> is invalid, * or if <code>locale</code> isn't * one of the locales returned from * {@link java.util.spi.LocaleServiceProvider#getAvailableLocales() * getAvailableLocales()}. * @exception NullPointerException if <code>locale</code> is null * @return a date/time formatter. * @see java.text.DateFormat#getDateTimeInstance(int, int, java.util.Locale) */ @Override public DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale locale) { return getInstance(dateStyle, timeStyle, locale); } private DateFormat getInstance(int dateStyle, int timeStyle, Locale locale) { if (locale == null) { throw new NullPointerException(); } // Check for region override Locale rg = CalendarDataUtility.findRegionOverride(locale); SimpleDateFormat sdf = new SimpleDateFormat("", rg); Calendar cal = sdf.getCalendar(); try { String pattern = LocaleProviderAdapter.forType(type) .getLocaleResources(rg).getDateTimePattern(timeStyle, dateStyle, cal); sdf.applyPattern(pattern); } catch (MissingResourceException mre) { // Specify the fallback pattern sdf.applyPattern("M/d/yy h:mm a"); } // Check for timezone override String tz = locale.getUnicodeLocaleType("tz"); if (tz != null) { sdf.setTimeZone( TimeZoneNameUtility.convertLDMLShortID(tz) .map(TimeZone::getTimeZone) .orElseGet(sdf::getTimeZone)); } return sdf; } @Override public Set<String> getAvailableLanguageTags() { return langtags; } }
md-5/jdk10
src/java.base/share/classes/sun/util/locale/provider/DateFormatProviderImpl.java
Java
gpl-2.0
7,634
/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.ws.config.metro.dev; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; /** * Parses a XML fragment and is expected to return a corresponding WebServiceFeature. * * @author Fabian Ritzmann */ public interface FeatureReader<T extends WebServiceFeature> { public static final QName ENABLED_ATTRIBUTE_NAME = new QName("enabled"); /** * Parse an XML stream and return the corresponding WebServiceFeature instance. */ public T parse(XMLEventReader reader) throws WebServiceException; }
FauxFaux/jdk9-jaxws
src/java.xml.ws/share/classes/com/sun/xml/internal/ws/config/metro/dev/FeatureReader.java
Java
gpl-2.0
1,858