repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
lindong28/kafka
streams/src/main/java/org/apache/kafka/streams/processor/Processor.java
2612
/* * 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.kafka.streams.processor; import java.time.Duration; /** * A processor of key-value pair records. * * @param <K> the type of keys * @param <V> the type of values * @deprecated Since 3.0. Use {@link org.apache.kafka.streams.processor.api.Processor} instead. */ @Deprecated public interface Processor<K, V> { /** * Initialize this processor with the given context. The framework ensures this is called once per processor when the topology * that contains it is initialized. When the framework is done with the processor, {@link #close()} will be called on it; the * framework may later re-use the processor by calling {@code #init()} again. * <p> * The provided {@link ProcessorContext context} can be used to access topology and record meta data, to * {@link ProcessorContext#schedule(Duration, PunctuationType, Punctuator) schedule} a method to be * {@link Punctuator#punctuate(long) called periodically} and to access attached {@link StateStore}s. * * @param context the context; may not be null */ void init(ProcessorContext context); /** * Process the record with the given key and value. * * @param key the key for the record * @param value the value for the record */ void process(K key, V value); /** * Close this processor and clean up any resources. Be aware that {@code #close()} is called after an internal cleanup. * Thus, it is not possible to write anything to Kafka as underlying clients are already closed. The framework may * later re-use this processor by calling {@code #init()} on it again. * <p> * Note: Do not close any streams managed resources, like {@link StateStore}s here, as they are managed by the library. */ void close(); }
apache-2.0
flaminc/olingo-odata4
fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/CustomerCollectionComposableInvoker.java
1294
/* * 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.olingo.fit.proxy.staticservice.microsoft.test.odata.services.odatawcfservice.types; // CHECKSTYLE:OFF (Maven checkstyle) public interface CustomerCollectionComposableInvoker extends org.apache.olingo.ext.proxy.api.StructuredCollectionComposableInvoker<CustomerCollection, CustomerCollection.Operations> { @Override CustomerCollectionComposableInvoker select(String... select); @Override CustomerCollectionComposableInvoker expand(String... expand); }
apache-2.0
lshain-android-source/tools-idea
java/compiler/impl/src/com/intellij/compiler/options/CompilerOptionsManager.java
1718
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.compiler.options; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; /** * Compiler settings page (Project Settings | Compiler) offers number of controls. However, there is a possible case that * some of them should be 'frozen' at particular environment (e.g. there is no point in disable external compiler * in case of AndroidStudio). * <p/> * This interface defines api which allows extensions to control compiler options availability. * * @author Denis Zhdanov * @since 7/18/13 12:40 PM */ public interface CompilerOptionsManager { ExtensionPointName<CompilerOptionsManager> EP_NAME = ExtensionPointName.create("com.intellij.compiler.optionsManager"); enum Setting { RESOURCE_PATTERNS, CLEAR_OUTPUT_DIR_ON_REBUILD, ADD_NOT_NULL_ASSERTIONS, AUTO_SHOW_FIRST_ERROR_IN_EDITOR, EXTERNAL_BUILD, AUTO_MAKE, PARALLEL_COMPILATION, REBUILD_MODULE_ON_DEPENDENCY_CHANGE, HEAP_SIZE, COMPILER_VM_OPTIONS } boolean isAvailable(@NotNull Setting setting, @NotNull Project project); }
apache-2.0
alanch-ms/PTVS
Python/Product/PythonTools/PythonTools/WebProject/PythonWebLauncherOptions.cs
6675
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Windows.Forms; using Microsoft.PythonTools; using Microsoft.PythonTools.Project; using Microsoft.VisualStudioTools.Project; namespace Microsoft.PythonTools.Project.Web { public partial class PythonWebLauncherOptions : UserControl, IPythonLauncherOptions { private readonly Dictionary<string, TextBox> _textBoxMap; private readonly Dictionary<string, ComboBox> _comboBoxMap; private readonly HashSet<string> _multilineProps; private readonly IPythonProject _properties; private bool _loadingSettings; public PythonWebLauncherOptions() { InitializeComponent(); _textBoxMap = new Dictionary<string, TextBox> { { PythonConstants.SearchPathSetting, _searchPaths }, { PythonConstants.CommandLineArgumentsSetting, _arguments }, { PythonConstants.InterpreterPathSetting, _interpreterPath }, { PythonConstants.InterpreterArgumentsSetting, _interpArgs }, { PythonConstants.WebBrowserUrlSetting, _launchUrl }, { PythonConstants.WebBrowserPortSetting, _portNumber }, { PythonConstants.EnvironmentSetting, _environment }, { PythonWebLauncher.RunWebServerTargetProperty, _runServerTarget }, { PythonWebLauncher.RunWebServerArgumentsProperty, _runServerArguments }, { PythonWebLauncher.RunWebServerEnvironmentProperty, _runServerEnvironment }, { PythonWebLauncher.DebugWebServerTargetProperty, _debugServerTarget }, { PythonWebLauncher.DebugWebServerArgumentsProperty, _debugServerArguments }, { PythonWebLauncher.DebugWebServerEnvironmentProperty, _debugServerEnvironment } }; _comboBoxMap = new Dictionary<string, ComboBox> { { PythonWebLauncher.RunWebServerTargetTypeProperty, _runServerTargetType }, { PythonWebLauncher.DebugWebServerTargetTypeProperty, _debugServerTargetType } }; _multilineProps = new HashSet<string> { PythonConstants.EnvironmentSetting, PythonWebLauncher.RunWebServerEnvironmentProperty, PythonWebLauncher.DebugWebServerEnvironmentProperty }; } public PythonWebLauncherOptions(IPythonProject properties) : this() { _properties = properties; } #region ILauncherOptions Members public void SaveSettings() { foreach (var propTextBox in _textBoxMap) { _properties.SetProperty(propTextBox.Key, propTextBox.Value.Text); } foreach (var propComboBox in _comboBoxMap) { var value = propComboBox.Value.SelectedItem as string; if (value != null) { _properties.SetProperty(propComboBox.Key, value); } } RaiseIsSaved(); } public void LoadSettings() { _loadingSettings = true; foreach (var propTextBox in _textBoxMap) { string value = _properties.GetUnevaluatedProperty(propTextBox.Key); if (_multilineProps.Contains(propTextBox.Key)) { value = FixLineEndings(value); } propTextBox.Value.Text = value; } foreach (var propComboBox in _comboBoxMap) { int index = propComboBox.Value.FindString(_properties.GetUnevaluatedProperty(propComboBox.Key)); propComboBox.Value.SelectedIndex = index >= 0 ? index : 0; } _loadingSettings = false; } public void ReloadSetting(string settingName) { TextBox textBox; ComboBox comboBox; if (_textBoxMap.TryGetValue(settingName, out textBox)) { string value = _properties.GetUnevaluatedProperty(settingName); if (_multilineProps.Contains(settingName)) { value = FixLineEndings(value); } textBox.Text = value; } else if (_comboBoxMap.TryGetValue(settingName, out comboBox)) { int index = comboBox.FindString(_properties.GetUnevaluatedProperty(settingName)); comboBox.SelectedIndex = index >= 0 ? index : 0; } } public event EventHandler<DirtyChangedEventArgs> DirtyChanged; Control IPythonLauncherOptions.Control { get { return this; } } #endregion private static Regex lfToCrLfRegex = new Regex(@"(?<!\r)\n"); private static string FixLineEndings(string value) { // TextBox requires \r\n for line separators, but XML can have either \n or \r\n, and we should treat those equally. // (It will always have \r\n when we write it out, but users can edit it by other means.) return lfToCrLfRegex.Replace(value ?? String.Empty, "\r\n"); } private void RaiseIsSaved() { var isDirty = DirtyChanged; if (isDirty != null) { DirtyChanged(this, DirtyChangedEventArgs.SavedValue); } } private void Setting_TextChanged(object sender, EventArgs e) { if (!_loadingSettings) { var isDirty = DirtyChanged; if (isDirty != null) { DirtyChanged(this, DirtyChangedEventArgs.DirtyValue); } } } private void Setting_SelectedValueChanged(object sender, EventArgs e) { if (!_loadingSettings) { var isDirty = DirtyChanged; if (isDirty != null) { DirtyChanged(this, DirtyChangedEventArgs.DirtyValue); } } } } }
apache-2.0
robertojrojas/go-qemu
examples/hypervisor_domain_list/main.go
1716
// Copyright 2016 The go-qemu 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 main import ( "flag" "fmt" "log" "net" "time" hypervisor "github.com/digitalocean/go-qemu/hypervisor" ) var ( network = flag.String("network", "unix", `Named network used to connect on. For Unix sockets -network=unix, for TCP connections: -network=tcp`) address = flag.String("address", "/var/run/libvirt/libvirt-sock", `Address of the hypervisor. This could be in the form of Unix or TCP sockets. For TCP connections: -address="host:16509"`) timeout = flag.Duration("timeout", 2*time.Second, "Connection timeout. Another valid value could be -timeout=500ms") ) func main() { flag.Parse() fmt.Printf("\nConnecting to %s://%s\n", *network, *address) newConn := func() (net.Conn, error) { return net.DialTimeout(*network, *address, *timeout) } driver := hypervisor.NewRPCDriver(newConn) hv := hypervisor.New(driver) fmt.Printf("\n**********Domains**********\n") domains, err := hv.Domains() if err != nil { log.Fatalf("Unable to get domains from hypervisor: %v", err) } for _, dom := range domains { fmt.Printf("%s\n", dom.Name) } fmt.Printf("\n***************************\n") }
apache-2.0
jacksonic/vjlofvhjfgm
src/foam/swift/ui/DAOTableViewSource.js
4560
/** * @license * Copyright 2018 The FOAM 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. */ foam.CLASS({ package: 'foam.swift.ui', name: 'DAOTableViewSource', requires: [ 'foam.dao.ArraySink', 'foam.dao.FnSink', ], swiftImports: [ 'UIKit', ], swiftImplements: [ 'UITableViewDataSource', ], properties: [ { class: 'foam.dao.DAOProperty', name: 'dao', swiftPostSet: ` if newValue == nil { return } let findIndex = { (o: foam_core_FObject) -> Int? in let id = o.get(key: "id") return self.daoContents.firstIndex(where: { (o) -> Bool in let o = o as! foam_core_FObject return FOAM_utils.equals(id, o.get(key: "id")) }) } daoSub = try! newValue!.listen(FnSink_create([ "fn": { [weak self] str, obj, sub in if self == nil { return } if str == "add" { if let index = findIndex(obj as! foam_core_FObject) { self?.daoContents[index] = obj self?.tableView?.reloadRows(at: [IndexPath(row: index, section: 0)], with: .automatic) } else { self?.daoContents.append(obj) self?.tableView?.insertRows(at: [IndexPath(row: self!.daoContents.count - 1, section: 0)], with: .automatic) } } else if str == "remove" { if let index = findIndex(obj as! foam_core_FObject) { self?.daoContents.remove(at: index) self?.tableView?.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic) } } else { self?.onDAOUpdate() } } as (String?, Any?, ${foam.core.Detachable.model_.swiftName}?) -> Void, ]), nil) onDetach(daoSub) onDAOUpdate() ` }, { type: 'foam.core.Detachable', name: 'daoSub', swiftPostSet: `if let o = oldValue as? ${foam.core.Detachable.model_.swiftName} { o.detach() }`, }, { swiftType: 'UITableView?', swiftWeak: true, name: 'tableView', swiftPostSet: 'newValue?.dataSource = self', }, { class: 'String', name: 'reusableCellIdentifier', value: 'CellID', }, { class: 'List', name: 'daoContents', }, { swiftType: '(() -> UITableViewCell)', swiftRequiresEscaping: true, name: 'rowViewFactory', }, { swiftType: '((UITableViewCell, foam_core_FObject) -> Void)', swiftRequiresEscaping: true, name: 'rowViewPrepare', }, { swiftType: '((IndexPath, UITableViewCell) -> Void)?', name: 'rowViewRemoved', }, ], listeners: [ { name: 'onDAOUpdate', isMerged: true, swiftCode: function() {/* let sink = try? dao!.select(ArraySink_create()) as? foam_dao_ArraySink daoContents = sink?.array ?? [] tableView?.reloadData() */}, }, ], methods: [ ], swiftCode: function() {/* public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return daoContents.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reusableCellIdentifier) ?? rowViewFactory() rowViewPrepare(cell, daoContents[indexPath.row] as! foam_core_FObject) return cell } class SimpleRowView: UITableViewCell { let view: UIView init(view: UIView, style: UITableViewCell.CellStyle, reuseIdentifier: String?) { self.view = view super.init(style: style, reuseIdentifier: reuseIdentifier) let viewMap: [String:UIView] = ["v":view] for v in viewMap.values { v.translatesAutoresizingMaskIntoConstraints = false addSubview(v) } addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "H:|[v]|", options: .alignAllCenterY, metrics: nil, views: viewMap)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:|[v]|", options: .alignAllCenterY, metrics: nil, views: viewMap)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } */}, });
apache-2.0
ramtej/Qi4j.Repo.4.Sync
core/runtime/src/main/java/org/qi4j/runtime/association/NamedAssociationsModel.java
5117
/* * Copyright (c) 2011-2013, Niclas Hedhman. All Rights Reserved. * Copyright (c) 2014, Paul Merlin. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.qi4j.runtime.association; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Member; import java.util.LinkedHashMap; import java.util.Map; import org.qi4j.api.association.AssociationDescriptor; import org.qi4j.api.association.NamedAssociation; import org.qi4j.api.common.QualifiedName; import org.qi4j.functional.HierarchicalVisitor; import org.qi4j.functional.VisitableHierarchy; import org.qi4j.runtime.structure.ModuleUnitOfWork; import org.qi4j.runtime.value.ValueStateInstance; import org.qi4j.spi.entity.EntityState; /** * Model for NamedAssociations. */ public final class NamedAssociationsModel implements VisitableHierarchy<NamedAssociationsModel, NamedAssociationModel> { private final Map<AccessibleObject, NamedAssociationModel> mapAccessorAssociationModel = new LinkedHashMap<>(); public NamedAssociationsModel() { } public Iterable<NamedAssociationModel> namedAssociations() { return mapAccessorAssociationModel.values(); } public void addNamedAssociation( NamedAssociationModel model ) { mapAccessorAssociationModel.put( model.accessor(), model ); } @Override public <ThrowableType extends Throwable> boolean accept( HierarchicalVisitor<? super NamedAssociationsModel, ? super NamedAssociationModel, ThrowableType> visitor ) throws ThrowableType { if( visitor.visitEnter( this ) ) { for( NamedAssociationModel associationModel : mapAccessorAssociationModel.values() ) { if( !associationModel.accept( visitor ) ) { break; } } } return visitor.visitLeave( this ); } public <T> NamedAssociation<T> newInstance( AccessibleObject accessor, EntityState entityState, ModuleUnitOfWork uow ) { return mapAccessorAssociationModel.get( accessor ).newInstance( uow, entityState ); } public NamedAssociationModel getNamedAssociation( AccessibleObject accessor ) throws IllegalArgumentException { if( false ) { return (NamedAssociationModel) getNamedAssociationByName( QualifiedName.fromAccessor( accessor ).name() ); } NamedAssociationModel namedAssociationModel = mapAccessorAssociationModel.get( accessor ); if( namedAssociationModel == null ) { throw new IllegalArgumentException( "No named-association found with name:" + ( (Member) accessor ).getName() ); } System.out.println( "######################################################################" ); System.out.println( "GET NAMED ASSOCIATION" ); System.out.println( "\tupon: " + mapAccessorAssociationModel ); System.out.println( "\tfor: " + accessor ); System.out.println( "\treturn: "+namedAssociationModel ); System.out.println( "######################################################################" ); return namedAssociationModel; } public AssociationDescriptor getNamedAssociationByName( String name ) throws IllegalArgumentException { for( NamedAssociationModel associationModel : mapAccessorAssociationModel.values() ) { if( associationModel.qualifiedName().name().equals( name ) ) { return associationModel; } } throw new IllegalArgumentException( "No named-association found with name:" + name ); } public AssociationDescriptor getNamedAssociationByQualifiedName( QualifiedName name ) throws IllegalArgumentException { for( NamedAssociationModel associationModel : mapAccessorAssociationModel.values() ) { if( associationModel.qualifiedName().equals( name ) ) { return associationModel; } } throw new IllegalArgumentException( "No named-association found with qualified name:" + name ); } public void checkConstraints( ValueStateInstance state ) { for( NamedAssociationModel associationModel : mapAccessorAssociationModel.values() ) { associationModel.checkAssociationConstraints( state.namedAssociationFor( associationModel.accessor() ) ); } } }
apache-2.0
osuosl/omnibus-software
config/software/libossp-uuid.rb
1028
# # Copyright 2012-2014 Chef Software, 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. # name "libossp-uuid" default_version "1.6.2" version "1.6.2" do source md5: "5db0d43a9022a6ebbbc25337ae28942f" end source url: "ftp://ftp.ossp.org/pkg/lib/uuid/uuid-#{version}.tar.gz" relative_path "uuid-#{version}" build do env = with_standard_compiler_flags(with_embedded_path) command "./configure" \ " --prefix=#{install_dir}/embedded", env: env make "-j #{workers}", env: env make "install", env: env end
apache-2.0
mikelewis0/EasySRL
src/edu/uw/easysrl/rebanking/Rebanker.java
5527
package edu.uw.easysrl.rebanking; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import edu.uw.easysrl.corpora.CCGBankDependencies.CCGBankDependency; import edu.uw.easysrl.corpora.CCGBankParseReader; import edu.uw.easysrl.corpora.ParallelCorpusReader; import edu.uw.easysrl.corpora.ParallelCorpusReader.Sentence; import edu.uw.easysrl.dependencies.Coindexation; import edu.uw.easysrl.dependencies.SRLDependency; import edu.uw.easysrl.syntax.grammar.Category; import edu.uw.easysrl.syntax.grammar.SyntaxTreeNode; import edu.uw.easysrl.syntax.grammar.SyntaxTreeNode.SyntaxTreeNodeLeaf; import edu.uw.easysrl.syntax.tagger.TagDict; /** * Used to extract modified supertagger training data from CCGBank. * * @author mlewis * */ public abstract class Rebanker { public static void main(final String[] args) throws IOException { Coindexation.parseMarkedUpFile(new File("testfiles/model_rebank/markedup")); final boolean isDev = true; final File trainingFolder = new File("training/experiments/rebank_again/" + (isDev ? "dev" : "train")); trainingFolder.mkdirs(); processCorpus(isDev, trainingFolder, new DummyRebanker(), new PrepositionRebanker(), new VPadjunctRebanker(), new ExtraArgumentRebanker() ); } static class DummyRebanker extends Rebanker { @Override boolean dontUseAsTrainingExample(final Category c) { return false; } @Override boolean doRebanking(final List<SyntaxTreeNodeLeaf> result, final Sentence sentence) { return false; } } private static void processCorpus(final boolean isDev, final File trainingFolder, final Rebanker... rebankers) throws IOException { final FileWriter fw = new FileWriter(new File(trainingFolder, "gold.stagged").getAbsoluteFile()); final BufferedWriter bw = new BufferedWriter(fw); final Multimap<String, Category> tagDict = HashMultimap.create(); getTrainingData(ParallelCorpusReader.READER.readCorpus(isDev), bw, tagDict, isDev, rebankers); TagDict.writeTagDict(tagDict.asMap(), new File(trainingFolder, "tagdict.ccgbank")); bw.flush(); } private static void getTrainingData(final Iterator<Sentence> corpus, final BufferedWriter supertaggerTrainingFile, final Multimap<String, Category> tagDictionary, final boolean isTest, final Rebanker... rebankers) throws IOException { int changed = 0; while (corpus.hasNext()) { final Sentence sentence = corpus.next(); final List<SyntaxTreeNodeLeaf> rebanked = new ArrayList<>(sentence.getCcgbankParse().getLeaves()); boolean change = false; for (final Rebanker rebanker : rebankers) { change = change || rebanker.doRebanking(rebanked, sentence); } if (change) { changed++; for (final String word : sentence.getWords()) { System.out.print(word + " "); } System.out.println(); System.out.println(sentence.getCcgbankParse().getLeaves()); System.out.println(rebanked); System.out.println(); } for (final SyntaxTreeNodeLeaf leaf : rebanked) { if (leaf.getSentencePosition() > 0) { supertaggerTrainingFile.write(" "); } tagDictionary.put(leaf.getWord(), leaf.getCategory()); if (!isTest// && dontUseAsTrainingExample(leaf.getCategory()) ) { supertaggerTrainingFile.write(leaf.getWord() + "||" + leaf.getCategory()); } else { supertaggerTrainingFile.write(makeDatapoint(leaf)); /* * if (!isTest) { allCats.add(leaf.getCategory()); } */ } } supertaggerTrainingFile.newLine(); } System.out.println("Changed: " + changed); } private static String makeDatapoint(final SyntaxTreeNodeLeaf leaf) { return leaf.getWord() + "|" + leaf.getPos() + "|" + leaf.getCategory(); } abstract boolean dontUseAsTrainingExample(Category c); public static SyntaxTreeNode getParse(final Iterator<String> autoLines) { String line = autoLines.next(); line = autoLines.next(); return CCGBankParseReader.parse(line); } abstract boolean doRebanking(List<SyntaxTreeNodeLeaf> result, Sentence sentence); void setCategory(final List<SyntaxTreeNodeLeaf> result, final int index, final Category newCategory) { final SyntaxTreeNodeLeaf leaf = result.get(index); result.set( index, new SyntaxTreeNodeLeaf(leaf.getWord(), leaf.getPos(), leaf.getNER(), newCategory, leaf .getSentencePosition())); } boolean isPropbankCoreArgument(final int predicateIndex, final int argumentNumber, final Sentence sentence, final boolean isCore) { for (final CCGBankDependency dep : sentence.getCCGBankDependencyParse().getArgument(predicateIndex, argumentNumber)) { for (final SRLDependency srl : sentence.getSrlParse().getDependenciesAtPredicateIndex(predicateIndex)) { if (srl.getArgumentPositions().contains(dep.getSentencePositionOfArgument()) && srl.isCoreArgument() == isCore) { return true; } } } return false; } boolean isPredicate(final Sentence sentence, final SyntaxTreeNodeLeaf node) { if (!sentence.getSrlParse().getPredicatePositions().contains(node.getHeadIndex())) { return false; } // Propbank only annotates adjuncts, not arguments, of "have to" for (final SRLDependency dep : sentence.getSrlParse().getDependenciesAtPredicateIndex(node.getHeadIndex())) { if (dep.isCoreArgument()) { return true; } } return false; } }
apache-2.0
brix-cms/brix-cms
brix-core/src/main/java/org/brixcms/plugin/site/resource/admin/ViewPropertiesTab.java
3917
/** * 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.brixcms.plugin.site.resource.admin; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.brixcms.auth.Action.Context; import org.brixcms.jcr.wrapper.BrixFileNode; import org.brixcms.jcr.wrapper.BrixNode; import org.brixcms.jcr.wrapper.BrixNode.Protocol; import org.brixcms.plugin.site.SitePlugin; import org.brixcms.plugin.site.resource.ResourceNodeHandler; import org.brixcms.web.generic.BrixGenericPanel; public class ViewPropertiesTab extends BrixGenericPanel<BrixNode> { public ViewPropertiesTab(String id, final IModel<BrixNode> nodeModel) { super(id, nodeModel); add(new Label("mimeType", new Model<String>() { @Override public String getObject() { BrixFileNode node = (BrixFileNode) nodeModel.getObject(); return node.getMimeType(); } })); add(new Label("size", new Model<String>() { @Override public String getObject() { BrixFileNode node = (BrixFileNode) nodeModel.getObject(); return node.getContentLength() + " bytes"; } })); add(new Label("requiredProtocol", new Model<String>() { @Override public String getObject() { Protocol protocol = nodeModel.getObject().getRequiredProtocol(); return getString(protocol.toString()); } })); add(new Link<Void>("download") { @Override public void onClick() { getRequestCycle().scheduleRequestHandlerAfterCurrent(new ResourceNodeHandler(nodeModel, true)); } }); add(new Link<Void>("edit") { @Override public void onClick() { EditPropertiesPanel panel = new EditPropertiesPanel(ViewPropertiesTab.this.getId(), ViewPropertiesTab.this.getModel()) { @Override void goBack() { replaceWith(ViewPropertiesTab.this); } }; ViewPropertiesTab.this.replaceWith(panel); } @Override public boolean isVisible() { return hasEditPermission(ViewPropertiesTab.this.getModel()); } }); /* * List<Protocol> protocols = Arrays.asList(Protocol.values()); * * final ModelBuffer model = new ModelBuffer(nodeModel); Form<?> form = * new Form<Void>("form"); * * IModel<Protocol> protocolModel = * model.forProperty("requiredProtocol"); form.add(new DropDownChoice<Protocol>("protocol", * protocolModel, protocols).setNullValid(false)); * * form.add(new Button<Void>("save") { @Override public void onSubmit() { * BrixNode node = nodeModel.getObject(); node.checkout(); * model.apply(); node.checkin(); node.save(); } }); * * add(form); */ } private static boolean hasEditPermission(IModel<BrixNode> model) { return SitePlugin.get().canEditNode(model.getObject(), Context.ADMINISTRATION); } }
apache-2.0
stanojevic/beer
src/beer/data/judgments/WMT11.scala
4018
package beer.data.judgments import java.io.File import scala.io.Source import scala.collection.mutable.{Map => MutableMap} private class WMT11 (dir:String) { val csv = dir+"/wmt11-maneval-indivsystems.RNK_results.csv" val references_dir = dir+"/wmt11-data/plain/references/" // newstest2011-ref.$lang val system_dir = dir+"/wmt11-data/plain/system-outputs/newstest2011/" // lang pairs dirs val langs = List("cs", "de", "es", "fr", "en") val lang_pairs = List("cs-en", "de-en", "es-en", "fr-en", "en-cs", "en-de", "en-es", "en-fr") type LangPair = String type Lang = String type System = String val system_sents = MutableMap[LangPair, MutableMap[System, Array[String]]]() val ref_sents = MutableMap[LangPair, Array[String]]() var judgments = List[Judgment]() def load() : Unit = { load_system_translations(); load_references(); load_csv("wmt11", csv); } private def load_csv(dataset_name:String, csv_fn:String) : Unit = { var line_id = 0 val file_iterator = Source.fromFile(csv_fn).getLines() file_iterator.next() // skip_first line for(line <- file_iterator){ val fields = line.split(",") val src_lang_long = fields(0) val tgt_lang_long = fields(1) val src_lang_short = WMT11.long_to_short(src_lang_long) val tgt_lang_short = WMT11.long_to_short(tgt_lang_long) val sys_names = List(fields(7), fields(9), fields(11), fields(13), fields(15)) val rankings = List(fields(16).toInt, fields(17).toInt, fields(18).toInt, fields(19).toInt, fields(20).toInt); val sentId = fields(2).toInt-1 val lp = s"$src_lang_short-$tgt_lang_short" val sents : List[String] = sys_names.map{ sys => if(sys equals "_ref"){ ref_sents(lp)(sentId) }else{ val long_sys_name = "newstest2011."+(lp.replace("cs", "cz"))+"."+(sys.replace("uedin","udein")) system_sents(lp)(long_sys_name)(sentId) } } val ref : String = ref_sents(lp)(sentId) judgments ::= new Judgment(dataset_name, src_lang_short, tgt_lang_short, sentId, sys_names, rankings, sents, ref) } } private def load_system_translations() : Unit = { for(lp <- lang_pairs){ val system_sents = scala.collection.mutable.Map[String, Array[String]]() val lp_real = lp.replace("cs","cz") for(file <- WMT11.getListOfFiles(system_dir+"/"+lp_real)){ val system = file.getName system_sents(system) = WMT11.loadContent(file) } this.system_sents(lp) = system_sents } } private def load_references():Unit={ for(lang <- langs){ val lang_really = if(lang eq "cs") "cz" else lang val fn = references_dir+"/newstest2011-ref."+lang_really val content = WMT11.loadContent(new File(fn)) for(lp <- lang_pairs){ if(lp matches s".*-$lang"){ ref_sents(lp) = content } } } } } object WMT11 { def loadJudgments(dir:String) : List[Judgment] = { val loader = new WMT11(dir) loader.load() loader.judgments } private def loadContent(file:File) : Array[String] = { Source.fromFile(file, "UTF-8").getLines().toArray } private def getListOfFiles(dir: String):List[File] = { val d = new File(dir) if (d.exists && d.isDirectory) { d.listFiles.filter(_.isFile).toList } else { List[File]() } } private def long_to_short(lang:String) : String = { lang match { case "English" => "en" case "Hindi" => "hi" case "Czech" => "cs" case "Russian" => "ru" case "Spanish" => "es" case "French" => "fr" case "German" => "de" } } private def short_to_long(lang:String) : String = { lang match { case "en" => "English" case "hi" => "Hindi" case "cs"|"cz" => "Czech" case "ru" => "Russian" case "es" => "Spanish" case "fr" => "French" case "de" => "German" } } }
apache-2.0
ntt-sic/neutron
neutron/db/migration/alembic_migrations/versions/e197124d4b9_add_unique_constrain.py
1778
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """add unique constraint to members Revision ID: e197124d4b9 Revises: havana Create Date: 2013-11-17 10:09:37.728903 """ # revision identifiers, used by Alembic. revision = 'e197124d4b9' down_revision = 'havana' # Change to ['*'] if this migration applies to all plugins migration_for_plugins = [ 'neutron.services.loadbalancer.plugin.LoadBalancerPlugin', 'neutron.plugins.nicira.NeutronServicePlugin.NvpAdvancedPlugin', ] from alembic import op from neutron.db import migration CONSTRAINT_NAME = 'uniq_member0pool_id0address0port' TABLE_NAME = 'members' def upgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.create_unique_constraint( name=CONSTRAINT_NAME, source=TABLE_NAME, local_cols=['pool_id', 'address', 'protocol_port'] ) def downgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.drop_constraint( name=CONSTRAINT_NAME, tablename=TABLE_NAME, type='unique' )
apache-2.0
GAIPS-INESC-ID/FAtiMA-Emotional-Appraisal
Components/Utilities/DataStructures/IOpenSet.cs
612
using System.Collections.Generic; namespace Utilities.DataStructures { public interface IOpenSet<T> where T : class { void Initialize(); void Replace(NodeRecord<T> nodeToBeReplaced, NodeRecord<T> nodeToReplace); NodeRecord<T> GetBestAndRemove(); NodeRecord<T> PeekBest(); void AddToOpen(NodeRecord<T> nodeRecord); void RemoveFromOpen(NodeRecord<T> nodeRecord); //should return null if the node is not found NodeRecord<T> SearchInOpen(NodeRecord<T> nodeRecord); ICollection<NodeRecord<T>> All(); int CountOpen(); } }
apache-2.0
awhitford/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/data/nuget/XPathMSBuildProjectParser.java
3319
/* * This file is part of dependency-check-core. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (c) 2018 Paul Irwin. All Rights Reserved. */ package org.owasp.dependencycheck.data.nuget; import org.owasp.dependencycheck.utils.XmlUtils; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * Parses a MSBuild project file for NuGet references using XPath. * * @author paulirwin */ public class XPathMSBuildProjectParser implements MSBuildProjectParser { /** * Parses the given stream for MSBuild PackageReference elements. * * @param stream the input stream to parse * @return a collection of discovered NuGet package references * @throws MSBuildProjectParseException if an exception occurs */ @Override public List<NugetPackageReference> parse(InputStream stream) throws MSBuildProjectParseException { try { final DocumentBuilder db = XmlUtils.buildSecureDocumentBuilder(); final Document d = db.parse(stream); final XPath xpath = XPathFactory.newInstance().newXPath(); final List<NugetPackageReference> packages = new ArrayList<>(); final NodeList nodeList = (NodeList) xpath.evaluate("//PackageReference", d, XPathConstants.NODESET); if (nodeList == null) { throw new MSBuildProjectParseException("Unable to parse MSBuild project file"); } for (int i = 0; i < nodeList.getLength(); i++) { final Node node = nodeList.item(i); final NamedNodeMap attrs = node.getAttributes(); final Node include = attrs.getNamedItem("Include"); final Node version = attrs.getNamedItem("Version"); if (include != null && version != null) { final NugetPackageReference npr = new NugetPackageReference(); npr.setId(include.getNodeValue()); npr.setVersion(version.getNodeValue()); packages.add(npr); } } return packages; } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | MSBuildProjectParseException e) { throw new MSBuildProjectParseException("Unable to parse MSBuild project file", e); } } }
apache-2.0
sibok666/flowable-engine
modules/flowable5-test/src/test/java/org/activiti/standalone/history/FullHistoryTest.java
83826
/* 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.activiti.standalone.history; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.activiti.engine.impl.test.ResourceFlowableTestCase; import org.activiti.engine.impl.variable.EntityManagerSession; import org.activiti.engine.impl.variable.EntityManagerSessionFactory; import org.activiti.engine.test.api.runtime.DummySerializable; import org.activiti.engine.test.history.SerializableVariable; import org.activiti.standalone.jpa.FieldAccessJPAEntity; import org.flowable.engine.common.api.FlowableException; import org.flowable.engine.common.api.FlowableIllegalArgumentException; import org.flowable.engine.common.runtime.Clock; import org.flowable.engine.history.HistoricActivityInstance; import org.flowable.engine.history.HistoricDetail; import org.flowable.engine.history.HistoricFormProperty; import org.flowable.engine.history.HistoricProcessInstance; import org.flowable.engine.history.HistoricTaskInstance; import org.flowable.engine.history.HistoricVariableInstance; import org.flowable.engine.history.HistoricVariableInstanceQuery; import org.flowable.engine.history.HistoricVariableUpdate; import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.task.Task; import org.flowable.engine.test.Deployment; /** * @author Tom Baeyens * @author Frederik Heremans * @author Joram Barrez * @author Christian Lipphardt (camunda) */ public class FullHistoryTest extends ResourceFlowableTestCase { public FullHistoryTest() { super("org/activiti/standalone/history/fullhistory.flowable.cfg.xml"); } @Deployment public void testVariableUpdates() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("number", "one"); variables.put("character", "a"); variables.put("bytes", ":-(".getBytes()); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("receiveTask", variables); runtimeService.setVariable(processInstance.getId(), "number", "two"); runtimeService.setVariable(processInstance.getId(), "bytes", ":-)".getBytes()); // Start-task should be added to history HistoricActivityInstance historicStartEvent = historyService.createHistoricActivityInstanceQuery() .processInstanceId(processInstance.getId()) .activityId("theStart") .singleResult(); assertNotNull(historicStartEvent); HistoricActivityInstance waitStateActivity = historyService.createHistoricActivityInstanceQuery() .processInstanceId(processInstance.getId()) .activityId("waitState") .singleResult(); assertNotNull(waitStateActivity); HistoricActivityInstance serviceTaskActivity = historyService.createHistoricActivityInstanceQuery() .processInstanceId(processInstance.getId()) .activityId("serviceTask") .singleResult(); assertNotNull(serviceTaskActivity); List<HistoricDetail> historicDetails = historyService.createHistoricDetailQuery() .orderByVariableName().asc() .orderByVariableRevision().asc() .list(); assertEquals(10, historicDetails.size()); HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) historicDetails.get(0); assertEquals("bytes", historicVariableUpdate.getVariableName()); assertEquals(":-(", new String((byte[]) historicVariableUpdate.getValue())); assertEquals(0, historicVariableUpdate.getRevision()); assertEquals(historicStartEvent.getId(), historicVariableUpdate.getActivityInstanceId()); // Variable is updated when process was in waitstate historicVariableUpdate = (HistoricVariableUpdate) historicDetails.get(1); assertEquals("bytes", historicVariableUpdate.getVariableName()); assertEquals(":-)", new String((byte[]) historicVariableUpdate.getValue())); assertEquals(1, historicVariableUpdate.getRevision()); assertEquals(waitStateActivity.getId(), historicVariableUpdate.getActivityInstanceId()); historicVariableUpdate = (HistoricVariableUpdate) historicDetails.get(2); assertEquals("character", historicVariableUpdate.getVariableName()); assertEquals("a", historicVariableUpdate.getValue()); assertEquals(0, historicVariableUpdate.getRevision()); assertEquals(historicStartEvent.getId(), historicVariableUpdate.getActivityInstanceId()); historicVariableUpdate = (HistoricVariableUpdate) historicDetails.get(3); assertEquals("number", historicVariableUpdate.getVariableName()); assertEquals("one", historicVariableUpdate.getValue()); assertEquals(0, historicVariableUpdate.getRevision()); assertEquals(historicStartEvent.getId(), historicVariableUpdate.getActivityInstanceId()); // Variable is updated when process was in waitstate historicVariableUpdate = (HistoricVariableUpdate) historicDetails.get(4); assertEquals("number", historicVariableUpdate.getVariableName()); assertEquals("two", historicVariableUpdate.getValue()); assertEquals(1, historicVariableUpdate.getRevision()); assertEquals(waitStateActivity.getId(), historicVariableUpdate.getActivityInstanceId()); // Variable set from process-start execution listener historicVariableUpdate = (HistoricVariableUpdate) historicDetails.get(5); assertEquals("zVar1", historicVariableUpdate.getVariableName()); assertEquals("Event: start", historicVariableUpdate.getValue()); assertEquals(0, historicVariableUpdate.getRevision()); assertEquals(historicStartEvent.getId(), historicVariableUpdate.getActivityInstanceId()); // Variable set from transition take execution listener historicVariableUpdate = (HistoricVariableUpdate) historicDetails.get(6); assertEquals("zVar2", historicVariableUpdate.getVariableName()); assertEquals("Event: take", historicVariableUpdate.getValue()); assertEquals(0, historicVariableUpdate.getRevision()); assertNull(historicVariableUpdate.getActivityInstanceId()); // Variable set from activity start execution listener on the servicetask historicVariableUpdate = (HistoricVariableUpdate) historicDetails.get(7); assertEquals("zVar3", historicVariableUpdate.getVariableName()); assertEquals("Event: start", historicVariableUpdate.getValue()); assertEquals(0, historicVariableUpdate.getRevision()); assertEquals(serviceTaskActivity.getId(), historicVariableUpdate.getActivityInstanceId()); // Variable set from activity end execution listener on the servicetask historicVariableUpdate = (HistoricVariableUpdate) historicDetails.get(8); assertEquals("zVar4", historicVariableUpdate.getVariableName()); assertEquals("Event: end", historicVariableUpdate.getValue()); assertEquals(0, historicVariableUpdate.getRevision()); assertEquals(serviceTaskActivity.getId(), historicVariableUpdate.getActivityInstanceId()); // Variable set from service-task historicVariableUpdate = (HistoricVariableUpdate) historicDetails.get(9); assertEquals("zzz", historicVariableUpdate.getVariableName()); assertEquals(123456789L, historicVariableUpdate.getValue()); assertEquals(0, historicVariableUpdate.getRevision()); assertEquals(serviceTaskActivity.getId(), historicVariableUpdate.getActivityInstanceId()); // trigger receive task runtimeService.trigger(processInstance.getId()); assertProcessEnded(processInstance.getId()); // check for historic process variables set HistoricVariableInstanceQuery historicProcessVariableQuery = historyService .createHistoricVariableInstanceQuery() .orderByVariableName().asc(); assertEquals(8, historicProcessVariableQuery.count()); List<HistoricVariableInstance> historicVariables = historicProcessVariableQuery.list(); // Variable status when process is finished HistoricVariableInstance historicVariable = historicVariables.get(0); assertEquals("bytes", historicVariable.getVariableName()); assertEquals(":-)", new String((byte[]) historicVariable.getValue())); assertNotNull(historicVariable.getCreateTime()); assertNotNull(historicVariable.getLastUpdatedTime()); historicVariable = historicVariables.get(1); assertEquals("character", historicVariable.getVariableName()); assertEquals("a", historicVariable.getValue()); assertNotNull(historicVariable.getCreateTime()); assertNotNull(historicVariable.getLastUpdatedTime()); historicVariable = historicVariables.get(2); assertEquals("number", historicVariable.getVariableName()); assertEquals("two", historicVariable.getValue()); assertNotNull(historicVariable.getCreateTime()); assertNotNull(historicVariable.getLastUpdatedTime()); assertNotSame(historicVariable.getCreateTime(), historicVariable.getLastUpdatedTime()); historicVariable = historicVariables.get(3); assertEquals("zVar1", historicVariable.getVariableName()); assertEquals("Event: start", historicVariable.getValue()); assertNotNull(historicVariable.getCreateTime()); assertNotNull(historicVariable.getLastUpdatedTime()); historicVariable = historicVariables.get(4); assertEquals("zVar2", historicVariable.getVariableName()); assertEquals("Event: take", historicVariable.getValue()); assertNotNull(historicVariable.getCreateTime()); assertNotNull(historicVariable.getLastUpdatedTime()); historicVariable = historicVariables.get(5); assertEquals("zVar3", historicVariable.getVariableName()); assertEquals("Event: start", historicVariable.getValue()); assertNotNull(historicVariable.getCreateTime()); assertNotNull(historicVariable.getLastUpdatedTime()); historicVariable = historicVariables.get(6); assertEquals("zVar4", historicVariable.getVariableName()); assertEquals("Event: end", historicVariable.getValue()); assertNotNull(historicVariable.getCreateTime()); assertNotNull(historicVariable.getLastUpdatedTime()); historicVariable = historicVariables.get(7); assertEquals("zzz", historicVariable.getVariableName()); assertEquals(123456789L, historicVariable.getValue()); assertNotNull(historicVariable.getCreateTime()); assertNotNull(historicVariable.getLastUpdatedTime()); historicVariable = historyService.createHistoricVariableInstanceQuery().variableValueLike("number", "tw%").singleResult(); assertNotNull(historicVariable); assertEquals("number", historicVariable.getVariableName()); assertEquals("two", historicVariable.getValue()); historicVariable = historyService.createHistoricVariableInstanceQuery().variableValueLikeIgnoreCase("number", "TW%").singleResult(); assertNotNull(historicVariable); assertEquals("number", historicVariable.getVariableName()); assertEquals("two", historicVariable.getValue()); historicVariable = historyService.createHistoricVariableInstanceQuery().variableValueLikeIgnoreCase("number", "TW2%").singleResult(); assertNull(historicVariable); } @Deployment(resources = { "org/activiti/engine/test/history/oneTaskProcess.bpmn20.xml" }) public void testHistoricVariableInstanceQueryTaskVariables() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("variable", "setFromProcess"); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", variables); assertEquals(1, historyService.createHistoricVariableInstanceQuery().count()); Task activeTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertNotNull(activeTask); taskService.setVariableLocal(activeTask.getId(), "variable", "setFromTask"); // Check if additional variable is available in history, task-local assertEquals(2, historyService.createHistoricVariableInstanceQuery().count()); assertEquals(1, historyService.createHistoricVariableInstanceQuery().taskId(activeTask.getId()).count()); assertEquals("setFromTask", historyService.createHistoricVariableInstanceQuery().taskId(activeTask.getId()).singleResult().getValue()); assertEquals(activeTask.getId(), historyService.createHistoricVariableInstanceQuery().taskId(activeTask.getId()).singleResult().getTaskId()); assertEquals(1, historyService.createHistoricVariableInstanceQuery().excludeTaskVariables().count()); // Test null task-id try { historyService.createHistoricVariableInstanceQuery().taskId(null).singleResult(); fail("Exception expected"); } catch (FlowableIllegalArgumentException ae) { assertEquals("taskId is null", ae.getMessage()); } // Test invalid usage of taskId together with excludeTaskVariables try { historyService.createHistoricVariableInstanceQuery().taskId("123").excludeTaskVariables().singleResult(); fail("Exception expected"); } catch (FlowableIllegalArgumentException ae) { assertEquals("Cannot use taskId together with excludeTaskVariables", ae.getMessage()); } try { historyService.createHistoricVariableInstanceQuery().excludeTaskVariables().taskId("123").singleResult(); fail("Exception expected"); } catch (FlowableIllegalArgumentException ae) { assertEquals("Cannot use taskId together with excludeTaskVariables", ae.getMessage()); } } @Deployment(resources = "org/activiti/standalone/history/FullHistoryTest.testVariableUpdates.bpmn20.xml") public void testHistoricVariableInstanceQuery() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("process", "one"); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("receiveTask", variables); runtimeService.trigger(processInstance.getProcessInstanceId()); assertEquals(1, historyService.createHistoricVariableInstanceQuery().variableName("process").count()); assertEquals(1, historyService.createHistoricVariableInstanceQuery().variableValueEquals("process", "one").count()); Map<String, Object> variables2 = new HashMap<String, Object>(); variables2.put("process", "two"); ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("receiveTask", variables2); runtimeService.trigger(processInstance2.getProcessInstanceId()); assertEquals(2, historyService.createHistoricVariableInstanceQuery().variableName("process").count()); assertEquals(1, historyService.createHistoricVariableInstanceQuery().variableValueEquals("process", "one").count()); assertEquals(1, historyService.createHistoricVariableInstanceQuery().variableValueEquals("process", "two").count()); HistoricVariableInstance historicProcessVariable = historyService.createHistoricVariableInstanceQuery().variableValueEquals("process", "one").singleResult(); assertEquals("process", historicProcessVariable.getVariableName()); assertEquals("one", historicProcessVariable.getValue()); Map<String, Object> variables3 = new HashMap<String, Object>(); variables3.put("long", 1000l); variables3.put("double", 25.43d); ProcessInstance processInstance3 = runtimeService.startProcessInstanceByKey("receiveTask", variables3); runtimeService.trigger(processInstance3.getProcessInstanceId()); assertEquals(1, historyService.createHistoricVariableInstanceQuery().variableName("long").count()); assertEquals(1, historyService.createHistoricVariableInstanceQuery().variableValueEquals("long", 1000l).count()); assertEquals(1, historyService.createHistoricVariableInstanceQuery().variableName("double").count()); assertEquals(1, historyService.createHistoricVariableInstanceQuery().variableValueEquals("double", 25.43d).count()); } @Deployment public void testHistoricVariableUpdatesAllTypes() throws Exception { Clock clock = processEngineConfiguration.getClock(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss SSS"); Map<String, Object> variables = new HashMap<String, Object>(); variables.put("aVariable", "initial value"); Date startedDate = sdf.parse("01/01/2001 01:23:45 000"); // In the javaDelegate, the current time is manipulated Date updatedDate = sdf.parse("01/01/2001 01:23:46 000"); clock.setCurrentTime(startedDate); processEngineConfiguration.setClock(clock); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("HistoricVariableUpdateProcess", variables); List<HistoricDetail> details = historyService.createHistoricDetailQuery() .variableUpdates() .processInstanceId(processInstance.getId()) .orderByVariableName().asc() .orderByTime().asc() .list(); // 8 variable updates should be present, one performed when starting process // the other 7 are set in VariableSetter serviceTask assertEquals(9, details.size()); // Since we order by varName, first entry should be aVariable update from startTask HistoricVariableUpdate startVarUpdate = (HistoricVariableUpdate) details.get(0); assertEquals("aVariable", startVarUpdate.getVariableName()); assertEquals("initial value", startVarUpdate.getValue()); assertEquals(0, startVarUpdate.getRevision()); assertEquals(processInstance.getId(), startVarUpdate.getProcessInstanceId()); // Date should the the one set when starting assertEquals(startedDate, startVarUpdate.getTime()); HistoricVariableUpdate updatedStringVariable = (HistoricVariableUpdate) details.get(1); assertEquals("aVariable", updatedStringVariable.getVariableName()); assertEquals("updated value", updatedStringVariable.getValue()); assertEquals(processInstance.getId(), updatedStringVariable.getProcessInstanceId()); // Date should be the updated date assertEquals(updatedDate, updatedStringVariable.getTime()); HistoricVariableUpdate intVariable = (HistoricVariableUpdate) details.get(2); assertEquals("bVariable", intVariable.getVariableName()); assertEquals(123, intVariable.getValue()); assertEquals(processInstance.getId(), intVariable.getProcessInstanceId()); assertEquals(updatedDate, intVariable.getTime()); HistoricVariableUpdate longVariable = (HistoricVariableUpdate) details.get(3); assertEquals("cVariable", longVariable.getVariableName()); assertEquals(12345L, longVariable.getValue()); assertEquals(processInstance.getId(), longVariable.getProcessInstanceId()); assertEquals(updatedDate, longVariable.getTime()); HistoricVariableUpdate doubleVariable = (HistoricVariableUpdate) details.get(4); assertEquals("dVariable", doubleVariable.getVariableName()); assertEquals(1234.567, doubleVariable.getValue()); assertEquals(processInstance.getId(), doubleVariable.getProcessInstanceId()); assertEquals(updatedDate, doubleVariable.getTime()); HistoricVariableUpdate shortVariable = (HistoricVariableUpdate) details.get(5); assertEquals("eVariable", shortVariable.getVariableName()); assertEquals((short) 12, shortVariable.getValue()); assertEquals(processInstance.getId(), shortVariable.getProcessInstanceId()); assertEquals(updatedDate, shortVariable.getTime()); HistoricVariableUpdate dateVariable = (HistoricVariableUpdate) details.get(6); assertEquals("fVariable", dateVariable.getVariableName()); assertEquals(sdf.parse("01/01/2001 01:23:45 678"), dateVariable.getValue()); assertEquals(processInstance.getId(), dateVariable.getProcessInstanceId()); assertEquals(updatedDate, dateVariable.getTime()); HistoricVariableUpdate serializableVariable = (HistoricVariableUpdate) details.get(7); assertEquals("gVariable", serializableVariable.getVariableName()); assertEquals(new SerializableVariable("hello hello"), serializableVariable.getValue()); assertEquals(processInstance.getId(), serializableVariable.getProcessInstanceId()); assertEquals(updatedDate, serializableVariable.getTime()); HistoricVariableUpdate byteArrayVariable = (HistoricVariableUpdate) details.get(8); assertEquals("hVariable", byteArrayVariable.getVariableName()); assertEquals(";-)", new String((byte[]) byteArrayVariable.getValue())); assertEquals(processInstance.getId(), byteArrayVariable.getProcessInstanceId()); assertEquals(updatedDate, byteArrayVariable.getTime()); // end process instance List<Task> tasks = taskService.createTaskQuery().list(); assertEquals(1, tasks.size()); taskService.complete(tasks.get(0).getId()); assertProcessEnded(processInstance.getId()); // check for historic process variables set HistoricVariableInstanceQuery historicProcessVariableQuery = historyService .createHistoricVariableInstanceQuery() .orderByVariableName().asc(); assertEquals(8, historicProcessVariableQuery.count()); List<HistoricVariableInstance> historicVariables = historicProcessVariableQuery.list(); // Variable status when process is finished HistoricVariableInstance historicVariable = historicVariables.get(0); assertEquals("aVariable", historicVariable.getVariableName()); assertEquals("updated value", historicVariable.getValue()); assertEquals(processInstance.getId(), historicVariable.getProcessInstanceId()); historicVariable = historicVariables.get(1); assertEquals("bVariable", historicVariable.getVariableName()); assertEquals(123, historicVariable.getValue()); assertEquals(processInstance.getId(), historicVariable.getProcessInstanceId()); historicVariable = historicVariables.get(2); assertEquals("cVariable", historicVariable.getVariableName()); assertEquals(12345L, historicVariable.getValue()); assertEquals(processInstance.getId(), historicVariable.getProcessInstanceId()); historicVariable = historicVariables.get(3); assertEquals("dVariable", historicVariable.getVariableName()); assertEquals(1234.567, historicVariable.getValue()); assertEquals(processInstance.getId(), historicVariable.getProcessInstanceId()); historicVariable = historicVariables.get(4); assertEquals("eVariable", historicVariable.getVariableName()); assertEquals((short) 12, historicVariable.getValue()); assertEquals(processInstance.getId(), historicVariable.getProcessInstanceId()); historicVariable = historicVariables.get(5); assertEquals("fVariable", historicVariable.getVariableName()); assertEquals(sdf.parse("01/01/2001 01:23:45 678"), historicVariable.getValue()); assertEquals(processInstance.getId(), historicVariable.getProcessInstanceId()); historicVariable = historicVariables.get(6); assertEquals("gVariable", historicVariable.getVariableName()); assertEquals(new SerializableVariable("hello hello"), historicVariable.getValue()); assertEquals(processInstance.getId(), historicVariable.getProcessInstanceId()); historicVariable = historicVariables.get(7); assertEquals("hVariable", historicVariable.getVariableName()); assertEquals(";-)", ";-)", new String((byte[]) historicVariable.getValue())); assertEquals(processInstance.getId(), historicVariable.getProcessInstanceId()); processEngineConfiguration.resetClock(); } @Deployment public void testHistoricFormProperties() throws Exception { Clock clock = processEngineConfiguration.getClock(); Date startedDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss SSS").parse("01/01/2001 01:23:46 000"); clock.setCurrentTime(startedDate); processEngineConfiguration.setClock(clock); Map<String, String> formProperties = new HashMap<String, String>(); formProperties.put("formProp1", "Activiti rocks"); formProperties.put("formProp2", "12345"); ProcessDefinition procDef = repositoryService.createProcessDefinitionQuery().processDefinitionKey("historicFormPropertiesProcess").singleResult(); ProcessInstance processInstance = formService.submitStartFormData(procDef.getId(), formProperties); // Submit form-properties on the created task Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertNotNull(task); // Out execution only has a single activity waiting, the task List<String> activityIds = runtimeService.getActiveActivityIds(task.getExecutionId()); assertNotNull(activityIds); assertEquals(1, activityIds.size()); String taskActivityId = activityIds.get(0); // Submit form properties formProperties = new HashMap<String, String>(); formProperties.put("formProp3", "Activiti still rocks!!!"); formProperties.put("formProp4", "54321"); formService.submitTaskFormData(task.getId(), formProperties); // 4 historic form properties should be created. 2 when process started, 2 when task completed List<HistoricDetail> props = historyService.createHistoricDetailQuery() .formProperties() .processInstanceId(processInstance.getId()) .orderByFormPropertyId().asc() .list(); HistoricFormProperty historicProperty1 = (HistoricFormProperty) props.get(0); assertEquals("formProp1", historicProperty1.getPropertyId()); assertEquals("Activiti rocks", historicProperty1.getPropertyValue()); assertEquals(startedDate, historicProperty1.getTime()); assertEquals(processInstance.getId(), historicProperty1.getProcessInstanceId()); assertNull(historicProperty1.getTaskId()); assertNotNull(historicProperty1.getActivityInstanceId()); HistoricActivityInstance historicActivityInstance = historyService.createHistoricActivityInstanceQuery().activityInstanceId(historicProperty1.getActivityInstanceId()).singleResult(); assertNotNull(historicActivityInstance); assertEquals("start", historicActivityInstance.getActivityId()); HistoricFormProperty historicProperty2 = (HistoricFormProperty) props.get(1); assertEquals("formProp2", historicProperty2.getPropertyId()); assertEquals("12345", historicProperty2.getPropertyValue()); assertEquals(startedDate, historicProperty2.getTime()); assertEquals(processInstance.getId(), historicProperty2.getProcessInstanceId()); assertNull(historicProperty2.getTaskId()); assertNotNull(historicProperty2.getActivityInstanceId()); historicActivityInstance = historyService.createHistoricActivityInstanceQuery().activityInstanceId(historicProperty2.getActivityInstanceId()).singleResult(); assertNotNull(historicActivityInstance); assertEquals("start", historicActivityInstance.getActivityId()); HistoricFormProperty historicProperty3 = (HistoricFormProperty) props.get(2); assertEquals("formProp3", historicProperty3.getPropertyId()); assertEquals("Activiti still rocks!!!", historicProperty3.getPropertyValue()); assertEquals(startedDate, historicProperty3.getTime()); assertEquals(processInstance.getId(), historicProperty3.getProcessInstanceId()); String activityInstanceId = historicProperty3.getActivityInstanceId(); historicActivityInstance = historyService.createHistoricActivityInstanceQuery().activityInstanceId(activityInstanceId).singleResult(); assertNotNull(historicActivityInstance); assertEquals(taskActivityId, historicActivityInstance.getActivityId()); assertNotNull(historicProperty3.getTaskId()); HistoricFormProperty historicProperty4 = (HistoricFormProperty) props.get(3); assertEquals("formProp4", historicProperty4.getPropertyId()); assertEquals("54321", historicProperty4.getPropertyValue()); assertEquals(startedDate, historicProperty4.getTime()); assertEquals(processInstance.getId(), historicProperty4.getProcessInstanceId()); activityInstanceId = historicProperty4.getActivityInstanceId(); historicActivityInstance = historyService.createHistoricActivityInstanceQuery().activityInstanceId(activityInstanceId).singleResult(); assertNotNull(historicActivityInstance); assertEquals(taskActivityId, historicActivityInstance.getActivityId()); assertNotNull(historicProperty4.getTaskId()); assertEquals(4, props.size()); processEngineConfiguration.resetClock(); } @Deployment(resources = { "org/activiti/engine/test/history/oneTaskProcess.bpmn20.xml" }) public void testHistoricVariableQuery() throws Exception { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("stringVar", "activiti rocks!"); variables.put("longVar", 12345L); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", variables); // Query on activity-instance, activity instance null will return all vars set when starting process assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().activityInstanceId(null).count()); assertEquals(0, historyService.createHistoricDetailQuery().variableUpdates().activityInstanceId("unexisting").count()); // Query on process-instance assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId(processInstance.getId()).count()); assertEquals(0, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId("unexisting").count()); // Query both process-instance and activity-instance assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates() .activityInstanceId(null) .processInstanceId(processInstance.getId()).count()); // end process instance List<Task> tasks = taskService.createTaskQuery().list(); assertEquals(1, tasks.size()); taskService.complete(tasks.get(0).getId()); assertProcessEnded(processInstance.getId()); assertEquals(2, historyService.createHistoricVariableInstanceQuery().count()); // Query on process-instance assertEquals(2, historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).count()); assertEquals(0, historyService.createHistoricVariableInstanceQuery().processInstanceId("unexisting").count()); } @Deployment(resources = { "org/activiti/engine/test/history/oneTaskProcess.bpmn20.xml" }) public void testHistoricVariableQueryExcludeTaskRelatedDetails() throws Exception { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("stringVar", "activiti rocks!"); variables.put("longVar", 12345L); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", variables); // Set a local task-variable Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertNotNull(task); taskService.setVariableLocal(task.getId(), "taskVar", "It is I, le Variable"); // Query on process-instance assertEquals(3, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId(processInstance.getId()).count()); // Query on process-instance, excluding task-details assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId(processInstance.getId()) .excludeTaskDetails().count()); // Check task-id precedence on excluding task-details assertEquals(1, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId(processInstance.getId()) .excludeTaskDetails().taskId(task.getId()).count()); } @Deployment(resources = { "org/activiti/engine/test/history/oneTaskProcess.bpmn20.xml" }) public void testHistoricFormPropertiesQuery() throws Exception { Map<String, String> formProperties = new HashMap<String, String>(); formProperties.put("stringVar", "activiti rocks!"); formProperties.put("longVar", "12345"); ProcessDefinition procDef = repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").singleResult(); ProcessInstance processInstance = formService.submitStartFormData(procDef.getId(), formProperties); // Query on activity-instance, activity instance null will return all vars set when starting process assertEquals(2, historyService.createHistoricDetailQuery().formProperties().activityInstanceId(null).count()); assertEquals(0, historyService.createHistoricDetailQuery().formProperties().activityInstanceId("unexisting").count()); // Query on process-instance assertEquals(2, historyService.createHistoricDetailQuery().formProperties().processInstanceId(processInstance.getId()).count()); assertEquals(0, historyService.createHistoricDetailQuery().formProperties().processInstanceId("unexisting").count()); // Complete the task by submitting the task properties Task task = taskService.createTaskQuery().singleResult(); formProperties = new HashMap<String, String>(); formProperties.put("taskVar", "task form property"); formService.submitTaskFormData(task.getId(), formProperties); assertEquals(3, historyService.createHistoricDetailQuery().formProperties().processInstanceId(processInstance.getId()).count()); assertEquals(0, historyService.createHistoricDetailQuery().formProperties().processInstanceId("unexisting").count()); } @Deployment(resources = { "org/activiti/engine/test/history/oneTaskProcess.bpmn20.xml" }) public void testHistoricVariableQuerySorting() throws Exception { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("stringVar", "activiti rocks!"); variables.put("longVar", 12345L); runtimeService.startProcessInstanceByKey("oneTaskProcess", variables); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByProcessInstanceId().asc().count()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByTime().asc().count()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableName().asc().count()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableRevision().asc().count()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableType().asc().count()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByProcessInstanceId().desc().count()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByTime().desc().count()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableName().desc().count()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableRevision().desc().count()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableType().desc().count()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByProcessInstanceId().asc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByTime().asc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableName().asc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableRevision().asc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableType().asc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByProcessInstanceId().desc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByTime().desc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableName().desc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableRevision().desc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().variableUpdates().orderByVariableType().desc().list().size()); } @Deployment(resources = { "org/activiti/engine/test/history/oneTaskProcess.bpmn20.xml" }) public void testHistoricFormPropertySorting() throws Exception { Map<String, String> formProperties = new HashMap<String, String>(); formProperties.put("stringVar", "activiti rocks!"); formProperties.put("longVar", "12345"); ProcessDefinition procDef = repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").singleResult(); formService.submitStartFormData(procDef.getId(), formProperties); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByProcessInstanceId().asc().count()); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByTime().asc().count()); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByFormPropertyId().asc().count()); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByProcessInstanceId().desc().count()); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByTime().desc().count()); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByFormPropertyId().desc().count()); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByProcessInstanceId().asc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByTime().asc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByFormPropertyId().asc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByProcessInstanceId().desc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByTime().desc().list().size()); assertEquals(2, historyService.createHistoricDetailQuery().formProperties().orderByFormPropertyId().desc().list().size()); } @Deployment public void testHistoricDetailQueryMixed() throws Exception { Map<String, String> formProperties = new HashMap<String, String>(); formProperties.put("formProp1", "activiti rocks!"); formProperties.put("formProp2", "12345"); ProcessDefinition procDef = repositoryService.createProcessDefinitionQuery().processDefinitionKey("historicDetailMixed").singleResult(); ProcessInstance processInstance = formService.submitStartFormData(procDef.getId(), formProperties); List<HistoricDetail> details = historyService .createHistoricDetailQuery() .processInstanceId(processInstance.getId()) .orderByVariableName().asc() .list(); assertEquals(4, details.size()); assertTrue(details.get(0) instanceof HistoricFormProperty); HistoricFormProperty formProp1 = (HistoricFormProperty) details.get(0); assertEquals("formProp1", formProp1.getPropertyId()); assertEquals("activiti rocks!", formProp1.getPropertyValue()); assertTrue(details.get(1) instanceof HistoricFormProperty); HistoricFormProperty formProp2 = (HistoricFormProperty) details.get(1); assertEquals("formProp2", formProp2.getPropertyId()); assertEquals("12345", formProp2.getPropertyValue()); assertTrue(details.get(2) instanceof HistoricVariableUpdate); HistoricVariableUpdate varUpdate1 = (HistoricVariableUpdate) details.get(2); assertEquals("variable1", varUpdate1.getVariableName()); assertEquals("activiti rocks!", varUpdate1.getValue()); // This variable should be of type LONG since this is defined in the process-definition assertTrue(details.get(3) instanceof HistoricVariableUpdate); HistoricVariableUpdate varUpdate2 = (HistoricVariableUpdate) details.get(3); assertEquals("variable2", varUpdate2.getVariableName()); assertEquals(12345L, varUpdate2.getValue()); } public void testHistoricDetailQueryInvalidSorting() throws Exception { try { historyService.createHistoricDetailQuery().asc().list(); fail(); } catch (FlowableIllegalArgumentException e) { } try { historyService.createHistoricDetailQuery().desc().list(); fail(); } catch (FlowableIllegalArgumentException e) { } try { historyService.createHistoricDetailQuery().orderByProcessInstanceId().list(); fail(); } catch (FlowableIllegalArgumentException e) { } try { historyService.createHistoricDetailQuery().orderByTime().list(); fail(); } catch (FlowableIllegalArgumentException e) { } try { historyService.createHistoricDetailQuery().orderByVariableName().list(); fail(); } catch (FlowableIllegalArgumentException e) { } try { historyService.createHistoricDetailQuery().orderByVariableRevision().list(); fail(); } catch (FlowableIllegalArgumentException e) { } try { historyService.createHistoricDetailQuery().orderByVariableType().list(); fail(); } catch (FlowableIllegalArgumentException e) { } } @Deployment public void testHistoricTaskInstanceVariableUpdates() { String processInstanceId = runtimeService.startProcessInstanceByKey("HistoricTaskInstanceTest").getId(); String taskId = taskService.createTaskQuery().singleResult().getId(); runtimeService.setVariable(processInstanceId, "deadline", "yesterday"); taskService.setVariableLocal(taskId, "bucket", "23c"); taskService.setVariableLocal(taskId, "mop", "37i"); taskService.complete(taskId); assertEquals(1, historyService.createHistoricTaskInstanceQuery().count()); List<HistoricDetail> historicTaskVariableUpdates = historyService.createHistoricDetailQuery() .taskId(taskId) .variableUpdates() .orderByVariableName().asc() .list(); assertEquals(2, historicTaskVariableUpdates.size()); historyService.deleteHistoricTaskInstance(taskId); // Check if the variable updates have been removed as well historicTaskVariableUpdates = historyService.createHistoricDetailQuery() .taskId(taskId) .variableUpdates() .orderByVariableName().asc() .list(); assertEquals(0, historicTaskVariableUpdates.size()); } // ACT-592 @Deployment public void testSetVariableOnProcessInstanceWithTimer() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("timerVariablesProcess"); runtimeService.setVariable(processInstance.getId(), "myVar", 123456L); assertEquals(123456L, runtimeService.getVariable(processInstance.getId(), "myVar")); } @Deployment public void testDeleteHistoricProcessInstance() { // Start process-instance with some variables set Map<String, Object> vars = new HashMap<String, Object>(); vars.put("processVar", 123L); vars.put("anotherProcessVar", new DummySerializable()); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("HistoricTaskInstanceTest", vars); assertNotNull(processInstance); // Set 2 task properties Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.setVariableLocal(task.getId(), "taskVar", 45678); taskService.setVariableLocal(task.getId(), "anotherTaskVar", "value"); // Finish the task, this end the process-instance taskService.complete(task.getId()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).count()); assertEquals(3, historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).count()); assertEquals(4, historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).count()); assertEquals(4, historyService.createHistoricDetailQuery().processInstanceId(processInstance.getId()).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).count()); // Delete the historic process-instance historyService.deleteHistoricProcessInstance(processInstance.getId()); // Verify no traces are left in the history tables assertEquals(0, historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).count()); assertEquals(0, historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).count()); assertEquals(0, historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).count()); assertEquals(0, historyService.createHistoricDetailQuery().processInstanceId(processInstance.getId()).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).count()); try { // Delete the historic process-instance, which is still running historyService.deleteHistoricProcessInstance("unexisting"); fail("Exception expected when deleting process-instance that is still running"); } catch (FlowableException ae) { // Expected exception assertTextPresent("No historic process instance found with id: unexisting", ae.getMessage()); } } @Deployment public void testDeleteRunningHistoricProcessInstance() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("HistoricTaskInstanceTest"); assertNotNull(processInstance); try { // Delete the historic process-instance, which is still running historyService.deleteHistoricProcessInstance(processInstance.getId()); fail("Exception expected when deleting process-instance that is still running"); } catch (FlowableException ae) { // Expected exception assertTextPresent("Process instance is still running, cannot delete historic process instance", ae.getMessage()); } } /** * Test created to validate ACT-621 fix. */ @Deployment public void testHistoricFormPropertiesOnReEnteringActivity() { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("comeBack", Boolean.TRUE); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("HistoricFormPropertiesProcess", variables); assertNotNull(processInstance); // Submit form on task Map<String, String> data = new HashMap<String, String>(); data.put("formProp1", "Property value"); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); formService.submitTaskFormData(task.getId(), data); // Historic property should be available List<HistoricDetail> details = historyService.createHistoricDetailQuery() .formProperties() .processInstanceId(processInstance.getId()) .list(); assertNotNull(details); assertEquals(1, details.size()); // Task should be active in the same activity as the previous one task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); formService.submitTaskFormData(task.getId(), data); details = historyService.createHistoricDetailQuery() .formProperties() .processInstanceId(processInstance.getId()) .list(); assertNotNull(details); assertEquals(2, details.size()); // Should have 2 different historic activity instance ID's, with the same activityId assertNotSame(details.get(0).getActivityInstanceId(), details.get(1).getActivityInstanceId()); HistoricActivityInstance historicActInst1 = historyService.createHistoricActivityInstanceQuery() .activityInstanceId(details.get(0).getActivityInstanceId()) .singleResult(); HistoricActivityInstance historicActInst2 = historyService.createHistoricActivityInstanceQuery() .activityInstanceId(details.get(1).getActivityInstanceId()) .singleResult(); assertEquals(historicActInst1.getActivityId(), historicActInst2.getActivityId()); } @Deployment public void testHistoricTaskInstanceQueryTaskVariableValueEquals() throws Exception { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("HistoricTaskInstanceTest"); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); // Set some variables on the task Map<String, Object> variables = new HashMap<String, Object>(); variables.put("longVar", 12345L); variables.put("shortVar", (short) 123); variables.put("integerVar", 1234); variables.put("stringVar", "stringValue"); variables.put("booleanVar", true); Date date = Calendar.getInstance().getTime(); variables.put("dateVar", date); variables.put("nullVar", null); taskService.setVariablesLocal(task.getId(), variables); // Validate all variable-updates are present in DB assertEquals(7, historyService.createHistoricDetailQuery().variableUpdates().taskId(task.getId()).count()); // Query Historic task instances based on variable assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("longVar", 12345L).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("shortVar", (short) 123).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("integerVar", 1234).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("stringVar", "stringValue").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("booleanVar", true).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("dateVar", date).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("nullVar", null).count()); // Update the variables variables.put("longVar", 67890L); variables.put("shortVar", (short) 456); variables.put("integerVar", 5678); variables.put("stringVar", "updatedStringValue"); variables.put("booleanVar", false); Calendar otherCal = Calendar.getInstance(); otherCal.add(Calendar.DAY_OF_MONTH, 1); Date otherDate = otherCal.getTime(); variables.put("dateVar", otherDate); variables.put("nullVar", null); taskService.setVariablesLocal(task.getId(), variables); // Validate all variable-updates are present in DB assertEquals(14, historyService.createHistoricDetailQuery().variableUpdates().taskId(task.getId()).count()); // Previous values should NOT match assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("longVar", 12345L).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("shortVar", (short) 123).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("integerVar", 1234).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("stringVar", "stringValue").count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("booleanVar", true).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("dateVar", date).count()); // New values should match assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("longVar", 67890L).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("shortVar", (short) 456).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("integerVar", 5678).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("stringVar", "updatedStringValue").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("booleanVar", false).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("dateVar", otherDate).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals("nullVar", null).count()); } @Deployment public void testHistoricTaskInstanceQueryProcessVariableValueEquals() throws Exception { // Set some variables on the process instance Map<String, Object> variables = new HashMap<String, Object>(); variables.put("longVar", 12345L); variables.put("shortVar", (short) 123); variables.put("integerVar", 1234); variables.put("stringVar", "stringValue"); variables.put("booleanVar", true); Date date = Calendar.getInstance().getTime(); variables.put("dateVar", date); variables.put("nullVar", null); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("HistoricTaskInstanceTest", variables); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); // Validate all variable-updates are present in DB assertEquals(7, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId(processInstance.getId()).count()); // Query Historic task instances based on process variable assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("longVar", 12345L).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("shortVar", (short) 123).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("integerVar", 1234).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("stringVar", "stringValue").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("booleanVar", true).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("dateVar", date).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("nullVar", null).count()); // Update the variables variables.put("longVar", 67890L); variables.put("shortVar", (short) 456); variables.put("integerVar", 5678); variables.put("stringVar", "updatedStringValue"); variables.put("booleanVar", false); Calendar otherCal = Calendar.getInstance(); otherCal.add(Calendar.DAY_OF_MONTH, 1); Date otherDate = otherCal.getTime(); variables.put("dateVar", otherDate); variables.put("nullVar", null); runtimeService.setVariables(processInstance.getId(), variables); // Validate all variable-updates are present in DB assertEquals(14, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId(processInstance.getId()).count()); // Previous values should NOT match assertEquals(0, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("longVar", 12345L).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("shortVar", (short) 123).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("integerVar", 1234).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("stringVar", "stringValue").count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("booleanVar", true).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("dateVar", date).count()); // New values should match assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("longVar", 67890L).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("shortVar", (short) 456).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("integerVar", 5678).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("stringVar", "updatedStringValue").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("booleanVar", false).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("dateVar", otherDate).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("nullVar", null).count()); // Set a task-variables, shouldn't affect the process-variable matches taskService.setVariableLocal(task.getId(), "longVar", 9999L); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("longVar", 9999L).count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().processVariableValueEquals("longVar", 67890L).count()); } @Deployment public void testHistoricProcessInstanceVariableValueEquals() throws Exception { // Set some variables on the process instance Map<String, Object> variables = new HashMap<String, Object>(); variables.put("longVar", 12345L); variables.put("shortVar", (short) 123); variables.put("integerVar", 1234); variables.put("stringVar", "stringValue"); variables.put("booleanVar", true); Date date = Calendar.getInstance().getTime(); variables.put("dateVar", date); variables.put("nullVar", null); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("HistoricProcessInstanceTest", variables); // Validate all variable-updates are present in DB assertEquals(7, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId(processInstance.getId()).count()); // Query Historic process instances based on process variable assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("longVar", 12345L).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("shortVar", (short) 123).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("integerVar", 1234).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("stringVar", "stringValue").count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("booleanVar", true).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("dateVar", date).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("nullVar", null).count()); // Update the variables variables.put("longVar", 67890L); variables.put("shortVar", (short) 456); variables.put("integerVar", 5678); variables.put("stringVar", "updatedStringValue"); variables.put("booleanVar", false); Calendar otherCal = Calendar.getInstance(); otherCal.add(Calendar.DAY_OF_MONTH, 1); Date otherDate = otherCal.getTime(); variables.put("dateVar", otherDate); variables.put("nullVar", null); runtimeService.setVariables(processInstance.getId(), variables); // Validate all variable-updates are present in DB assertEquals(14, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId(processInstance.getId()).count()); // Previous values should NOT match assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueEquals("longVar", 12345L).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueEquals("shortVar", (short) 123).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueEquals("integerVar", 1234).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueEquals("stringVar", "stringValue").count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueEquals("booleanVar", true).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueEquals("dateVar", date).count()); // New values should match assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("longVar", 67890L).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("shortVar", (short) 456).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("integerVar", 5678).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("stringVar", "updatedStringValue").count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("booleanVar", false).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("dateVar", otherDate).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueEquals("nullVar", null).count()); } @Deployment(resources = { "org/activiti/standalone/history/FullHistoryTest.testHistoricProcessInstanceVariableValueEquals.bpmn20.xml" }) public void testHistoricProcessInstanceVariableValueNotEquals() throws Exception { // Set some variables on the process instance Map<String, Object> variables = new HashMap<String, Object>(); variables.put("longVar", 12345L); variables.put("shortVar", (short) 123); variables.put("integerVar", 1234); variables.put("stringVar", "stringValue"); variables.put("booleanVar", true); Date date = Calendar.getInstance().getTime(); Calendar otherCal = Calendar.getInstance(); otherCal.add(Calendar.DAY_OF_MONTH, 1); Date otherDate = otherCal.getTime(); variables.put("dateVar", date); variables.put("nullVar", null); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("HistoricProcessInstanceTest", variables); // Validate all variable-updates are present in DB assertEquals(7, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId(processInstance.getId()).count()); // Query Historic process instances based on process variable, shouldn't match assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("longVar", 12345L).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("shortVar", (short) 123).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("integerVar", 1234).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("stringVar", "stringValue").count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("booleanVar", true).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("dateVar", date).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("nullVar", null).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("nullVar", null).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("longVar", 67890L).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("shortVar", (short) 456).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("integerVar", 5678).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("stringVar", "updatedStringValue").count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("booleanVar", false).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("dateVar", otherDate).count()); // Update the variables variables.put("longVar", 67890L); variables.put("shortVar", (short) 456); variables.put("integerVar", 5678); variables.put("stringVar", "updatedStringValue"); variables.put("booleanVar", false); variables.put("dateVar", otherDate); variables.put("nullVar", null); runtimeService.setVariables(processInstance.getId(), variables); // Validate all variable-updates are present in DB assertEquals(14, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId(processInstance.getId()).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("longVar", 12345L).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("shortVar", (short) 123).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("integerVar", 1234).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("stringVar", "stringValue").count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("booleanVar", true).count()); assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("dateVar", date).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("longVar", 67890L).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("shortVar", (short) 456).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("integerVar", 5678).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("stringVar", "updatedStringValue").count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("booleanVar", false).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("dateVar", otherDate).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueNotEquals("nullVar", null).count()); } @Deployment(resources = { "org/activiti/standalone/history/FullHistoryTest.testHistoricProcessInstanceVariableValueEquals.bpmn20.xml" }) public void testHistoricProcessInstanceVariableValueLessThanAndGreaterThan() throws Exception { // Set some variables on the process instance Map<String, Object> variables = new HashMap<String, Object>(); variables.put("longVar", 12345L); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("HistoricProcessInstanceTest", variables); // Validate all variable-updates are present in DB assertEquals(1, historyService.createHistoricDetailQuery().variableUpdates().processInstanceId(processInstance.getId()).count()); assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueGreaterThan("longVar", 12345L).count()); // assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueGreaterThan("longVar", 12344L).count()); // assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueGreaterThanOrEqual("longVar", 12345L).count()); // assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueGreaterThanOrEqual("longVar", 12344L).count()); // assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueGreaterThanOrEqual("longVar", 12346L).count()); // // assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueLessThan("longVar", 12345L).count()); // assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueLessThan("longVar", 12346L).count()); // assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueLessThanOrEqual("longVar", 12345L).count()); // assertEquals(1, historyService.createHistoricProcessInstanceQuery().variableValueLessThanOrEqual("longVar", 12346L).count()); // assertEquals(0, historyService.createHistoricProcessInstanceQuery().variableValueLessThanOrEqual("longVar", 12344L).count()); } @Deployment(resources = { "org/activiti/standalone/history/FullHistoryTest.testVariableUpdatesAreLinkedToActivity.bpmn20.xml" }) public void testVariableUpdatesLinkedToActivity() throws Exception { ProcessInstance pi = runtimeService.startProcessInstanceByKey("ProcessWithSubProcess"); Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult(); Map<String, Object> variables = new HashMap<String, Object>(); variables.put("test", "1"); taskService.complete(task.getId(), variables); // now we are in the subprocess task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult(); variables.clear(); variables.put("test", "2"); taskService.complete(task.getId(), variables); // now we are ended assertProcessEnded(pi.getId()); // check history List<HistoricDetail> updates = historyService.createHistoricDetailQuery().variableUpdates().list(); assertEquals(2, updates.size()); Map<String, HistoricVariableUpdate> updatesMap = new HashMap<String, HistoricVariableUpdate>(); HistoricVariableUpdate update = (HistoricVariableUpdate) updates.get(0); updatesMap.put((String) update.getValue(), update); update = (HistoricVariableUpdate) updates.get(1); updatesMap.put((String) update.getValue(), update); HistoricVariableUpdate update1 = updatesMap.get("1"); HistoricVariableUpdate update2 = updatesMap.get("2"); assertNotNull(update1.getActivityInstanceId()); assertNotNull(update1.getExecutionId()); HistoricActivityInstance historicActivityInstance1 = historyService.createHistoricActivityInstanceQuery().activityInstanceId(update1.getActivityInstanceId()).singleResult(); assertEquals(historicActivityInstance1.getExecutionId(), update1.getExecutionId()); assertEquals("usertask1", historicActivityInstance1.getActivityId()); assertNotNull(update2.getActivityInstanceId()); HistoricActivityInstance historicActivityInstance2 = historyService.createHistoricActivityInstanceQuery().activityInstanceId(update2.getActivityInstanceId()).singleResult(); assertEquals("usertask2", historicActivityInstance2.getActivityId()); /* * This is OK! The variable is set on the root execution, on a execution never run through the activity, where the process instances stands when calling the set Variable. But the ActivityId of * this flow node is used. So the execution id's doesn't have to be equal. * * execution id: On which execution it was set activity id: in which activity was the process instance when setting the variable */ assertFalse(historicActivityInstance2.getExecutionId().equals(update2.getExecutionId())); } @Deployment(resources = { "org/activiti/standalone/jpa/JPAVariableTest.testQueryJPAVariable.bpmn20.xml" }) public void testReadJpaVariableValueFromHistoricVariableUpdate() { org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl activiti5ProcessEngineConfig = (org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl) processEngineConfiguration.getFlowable5CompatibilityHandler() .getRawProcessConfiguration(); EntityManagerSessionFactory entityManagerSessionFactory = (EntityManagerSessionFactory) activiti5ProcessEngineConfig .getSessionFactories() .get(EntityManagerSession.class); EntityManagerFactory entityManagerFactory = entityManagerSessionFactory.getEntityManagerFactory(); String executionId = runtimeService.startProcessInstanceByKey("JPAVariableProcess").getProcessInstanceId(); String variableName = "name"; FieldAccessJPAEntity entity = new FieldAccessJPAEntity(); entity.setId(1L); entity.setValue("Test"); EntityManager manager = entityManagerFactory.createEntityManager(); manager.getTransaction().begin(); manager.persist(entity); manager.flush(); manager.getTransaction().commit(); manager.close(); Task task = taskService.createTaskQuery().processInstanceId(executionId).taskName("my task").singleResult(); runtimeService.setVariable(executionId, variableName, entity); taskService.complete(task.getId()); List<org.activiti.engine.history.HistoricDetail> variableUpdates = activiti5ProcessEngineConfig.getHistoryService().createHistoricDetailQuery().processInstanceId(executionId).variableUpdates().list(); assertEquals(1, variableUpdates.size()); org.activiti.engine.history.HistoricVariableUpdate update = (org.activiti.engine.history.HistoricVariableUpdate) variableUpdates.get(0); assertNotNull(update.getValue()); assertTrue(update.getValue() instanceof FieldAccessJPAEntity); assertEquals(entity.getId(), ((FieldAccessJPAEntity) update.getValue()).getId()); } /** * Test confirming fix for ACT-1731 */ @Deployment(resources = { "org/activiti/engine/test/history/oneTaskProcess.bpmn20.xml" }) public void testQueryHistoricTaskIncludeBinaryVariable() throws Exception { // Start process with a binary variable ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", Collections.singletonMap("binaryVariable", (Object) "It is I, le binary".getBytes())); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertNotNull(task); taskService.setVariableLocal(task.getId(), "binaryTaskVariable", (Object) "It is I, le binary".getBytes()); // Complete task taskService.complete(task.getId()); // Query task, including processVariables HistoricTaskInstance historicTask = historyService.createHistoricTaskInstanceQuery().taskId(task.getId()).includeProcessVariables().singleResult(); assertNotNull(historicTask); assertNotNull(historicTask.getProcessVariables()); byte[] bytes = (byte[]) historicTask.getProcessVariables().get("binaryVariable"); assertEquals("It is I, le binary", new String(bytes)); // Query task, including taskVariables historicTask = historyService.createHistoricTaskInstanceQuery().taskId(task.getId()).includeTaskLocalVariables().singleResult(); assertNotNull(historicTask); assertNotNull(historicTask.getTaskLocalVariables()); bytes = (byte[]) historicTask.getTaskLocalVariables().get("binaryTaskVariable"); assertEquals("It is I, le binary", new String(bytes)); } /** * Test confirming fix for ACT-1731 */ @Deployment(resources = { "org/activiti/engine/test/history/oneTaskProcess.bpmn20.xml" }) public void testQueryHistoricProcessInstanceIncludeBinaryVariable() throws Exception { // Start process with a binary variable ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", Collections.singletonMap("binaryVariable", (Object) "It is I, le binary".getBytes())); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertNotNull(task); // Complete task to end process taskService.complete(task.getId()); // Query task, including processVariables HistoricProcessInstance historicProcess = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).includeProcessVariables().singleResult(); assertNotNull(historicProcess); assertNotNull(historicProcess.getProcessVariables()); byte[] bytes = (byte[]) historicProcess.getProcessVariables().get("binaryVariable"); assertEquals("It is I, le binary", new String(bytes)); } // Test for https://activiti.atlassian.net/browse/ACT-2186 @Deployment(resources = { "org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml" }) public void testHistoricVariableRemovedWhenRuntimeVariableIsRemoved() { Map<String, Object> vars = new HashMap<String, Object>(); vars.put("var1", "Hello"); vars.put("var2", "World"); vars.put("var3", "!"); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", vars); // Verify runtime assertEquals(3, runtimeService.getVariables(processInstance.getId()).size()); assertEquals(3, runtimeService.getVariables(processInstance.getId(), Arrays.asList("var1", "var2", "var3")).size()); assertNotNull(runtimeService.getVariable(processInstance.getId(), "var2")); // Verify history assertEquals(3, historyService.createHistoricVariableInstanceQuery().list().size()); assertNotNull(historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).variableName("var2").singleResult()); // Verify historic details List<HistoricDetail> details = historyService.createHistoricDetailQuery().processInstanceId(processInstance.getId()).variableUpdates().orderByTime().asc().list(); assertEquals(3, details.size()); // 3 vars for (HistoricDetail historicDetail : details) { assertNotNull(((HistoricVariableUpdate) historicDetail).getValue()); } // Remove one variable runtimeService.removeVariable(processInstance.getId(), "var2"); // Verify runtime assertEquals(2, runtimeService.getVariables(processInstance.getId()).size()); assertEquals(2, runtimeService.getVariables(processInstance.getId(), Arrays.asList("var1", "var2", "var3")).size()); assertNull(runtimeService.getVariable(processInstance.getId(), "var2")); // Verify history assertEquals(2, historyService.createHistoricVariableInstanceQuery().list().size()); assertNull(historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).variableName("var2").singleResult()); // Verify historic details details = historyService.createHistoricDetailQuery().processInstanceId(processInstance.getId()).variableUpdates().orderByTime().asc().list(); assertEquals(4, details.size()); // 3 vars + 1 delete // The last entry should be the delete for (int i = 0; i < details.size(); i++) { if (i != 3) { assertNotNull(((HistoricVariableUpdate) details.get(i)).getValue()); } else if (i == 3) { assertNull(((HistoricVariableUpdate) details.get(i)).getValue()); } } } }
apache-2.0
gemxd/gemfirexd-oss
tests/core/src/main/java/com/gemstone/gemfire/management/internal/cli/domain/AbstractImpl.java
789
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package com.gemstone.gemfire.management.internal.cli.domain; public abstract class AbstractImpl implements Interface1{ }
apache-2.0
knative-sandbox/kn-plugin-func
vendor/github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1/generated_expansion.go
810
/* Copyright 2020 The Tekton 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. */ // Code generated by client-gen. DO NOT EDIT. package v1beta1 type ClusterTaskExpansion interface{} type PipelineExpansion interface{} type PipelineRunExpansion interface{} type TaskExpansion interface{} type TaskRunExpansion interface{}
apache-2.0
sergeyevstifeev/docker
integration-cli/docker_cli_exec_test.go
18839
// +build !test_no_exec package main import ( "bufio" "fmt" "os" "os/exec" "path/filepath" "reflect" "sort" "strings" "sync" "testing" "time" ) func TestExec(t *testing.T) { defer deleteAllContainers() runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top") if out, _, _, err := runCommandWithStdoutStderr(runCmd); err != nil { t.Fatal(out, err) } execCmd := exec.Command(dockerBinary, "exec", "testing", "cat", "/tmp/file") out, _, err := runCommandWithOutput(execCmd) if err != nil { t.Fatal(out, err) } out = strings.Trim(out, "\r\n") if expected := "test"; out != expected { t.Errorf("container exec should've printed %q but printed %q", expected, out) } logDone("exec - basic test") } func TestExecInteractiveStdinClose(t *testing.T) { defer deleteAllContainers() out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-itd", "busybox", "/bin/cat")) if err != nil { t.Fatal(err) } contId := strings.TrimSpace(out) returnchan := make(chan struct{}) go func() { var err error cmd := exec.Command(dockerBinary, "exec", "-i", contId, "/bin/ls", "/") cmd.Stdin = os.Stdin if err != nil { t.Fatal(err) } out, err := cmd.CombinedOutput() if err != nil { t.Fatal(err, string(out)) } if string(out) == "" { t.Fatalf("Output was empty, likely blocked by standard input") } returnchan <- struct{}{} }() select { case <-returnchan: case <-time.After(10 * time.Second): t.Fatal("timed out running docker exec") } logDone("exec - interactive mode closes stdin after execution") } func TestExecInteractive(t *testing.T) { defer deleteAllContainers() runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top") if out, _, _, err := runCommandWithStdoutStderr(runCmd); err != nil { t.Fatal(out, err) } execCmd := exec.Command(dockerBinary, "exec", "-i", "testing", "sh") stdin, err := execCmd.StdinPipe() if err != nil { t.Fatal(err) } stdout, err := execCmd.StdoutPipe() if err != nil { t.Fatal(err) } if err := execCmd.Start(); err != nil { t.Fatal(err) } if _, err := stdin.Write([]byte("cat /tmp/file\n")); err != nil { t.Fatal(err) } r := bufio.NewReader(stdout) line, err := r.ReadString('\n') if err != nil { t.Fatal(err) } line = strings.TrimSpace(line) if line != "test" { t.Fatalf("Output should be 'test', got '%q'", line) } if err := stdin.Close(); err != nil { t.Fatal(err) } finish := make(chan struct{}) go func() { if err := execCmd.Wait(); err != nil { t.Fatal(err) } close(finish) }() select { case <-finish: case <-time.After(1 * time.Second): t.Fatal("docker exec failed to exit on stdin close") } logDone("exec - Interactive test") } func TestExecAfterContainerRestart(t *testing.T) { defer deleteAllContainers() runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top") out, _, err := runCommandWithOutput(runCmd) if err != nil { t.Fatal(out, err) } cleanedContainerID := strings.TrimSpace(out) runCmd = exec.Command(dockerBinary, "restart", cleanedContainerID) if out, _, err = runCommandWithOutput(runCmd); err != nil { t.Fatal(out, err) } runCmd = exec.Command(dockerBinary, "exec", cleanedContainerID, "echo", "hello") out, _, err = runCommandWithOutput(runCmd) if err != nil { t.Fatal(out, err) } outStr := strings.TrimSpace(out) if outStr != "hello" { t.Errorf("container should've printed hello, instead printed %q", outStr) } logDone("exec - exec running container after container restart") } func TestExecAfterDaemonRestart(t *testing.T) { testRequires(t, SameHostDaemon) defer deleteAllContainers() d := NewDaemon(t) if err := d.StartWithBusybox(); err != nil { t.Fatalf("Could not start daemon with busybox: %v", err) } defer d.Stop() if out, err := d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil { t.Fatalf("Could not run top: err=%v\n%s", err, out) } if err := d.Restart(); err != nil { t.Fatalf("Could not restart daemon: %v", err) } if out, err := d.Cmd("start", "top"); err != nil { t.Fatalf("Could not start top after daemon restart: err=%v\n%s", err, out) } out, err := d.Cmd("exec", "top", "echo", "hello") if err != nil { t.Fatalf("Could not exec on container top: err=%v\n%s", err, out) } outStr := strings.TrimSpace(string(out)) if outStr != "hello" { t.Errorf("container should've printed hello, instead printed %q", outStr) } logDone("exec - exec running container after daemon restart") } // Regression test for #9155, #9044 func TestExecEnv(t *testing.T) { defer deleteAllContainers() runCmd := exec.Command(dockerBinary, "run", "-e", "LALA=value1", "-e", "LALA=value2", "-d", "--name", "testing", "busybox", "top") if out, _, _, err := runCommandWithStdoutStderr(runCmd); err != nil { t.Fatal(out, err) } execCmd := exec.Command(dockerBinary, "exec", "testing", "env") out, _, err := runCommandWithOutput(execCmd) if err != nil { t.Fatal(out, err) } if strings.Contains(out, "LALA=value1") || !strings.Contains(out, "LALA=value2") || !strings.Contains(out, "HOME=/root") { t.Errorf("exec env(%q), expect %q, %q", out, "LALA=value2", "HOME=/root") } logDone("exec - exec inherits correct env") } func TestExecExitStatus(t *testing.T) { defer deleteAllContainers() runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "top", "busybox", "top") if out, _, _, err := runCommandWithStdoutStderr(runCmd); err != nil { t.Fatal(out, err) } // Test normal (non-detached) case first cmd := exec.Command(dockerBinary, "exec", "top", "sh", "-c", "exit 23") ec, _ := runCommand(cmd) if ec != 23 { t.Fatalf("Should have had an ExitCode of 23, not: %d", ec) } logDone("exec - exec non-zero ExitStatus") } func TestExecPausedContainer(t *testing.T) { defer deleteAllContainers() defer unpauseAllContainers() runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "testing", "busybox", "top") out, _, err := runCommandWithOutput(runCmd) if err != nil { t.Fatal(out, err) } ContainerID := strings.TrimSpace(out) pausedCmd := exec.Command(dockerBinary, "pause", "testing") out, _, _, err = runCommandWithStdoutStderr(pausedCmd) if err != nil { t.Fatal(out, err) } execCmd := exec.Command(dockerBinary, "exec", "-i", "-t", ContainerID, "echo", "hello") out, _, err = runCommandWithOutput(execCmd) if err == nil { t.Fatal("container should fail to exec new command if it is paused") } expected := ContainerID + " is paused, unpause the container before exec" if !strings.Contains(out, expected) { t.Fatal("container should not exec new command if it is paused") } logDone("exec - exec should not exec a pause container") } // regression test for #9476 func TestExecTtyCloseStdin(t *testing.T) { defer deleteAllContainers() cmd := exec.Command(dockerBinary, "run", "-d", "-it", "--name", "exec_tty_stdin", "busybox") if out, _, err := runCommandWithOutput(cmd); err != nil { t.Fatal(out, err) } cmd = exec.Command(dockerBinary, "exec", "-i", "exec_tty_stdin", "cat") stdinRw, err := cmd.StdinPipe() if err != nil { t.Fatal(err) } stdinRw.Write([]byte("test")) stdinRw.Close() if out, _, err := runCommandWithOutput(cmd); err != nil { t.Fatal(out, err) } cmd = exec.Command(dockerBinary, "top", "exec_tty_stdin") out, _, err := runCommandWithOutput(cmd) if err != nil { t.Fatal(out, err) } outArr := strings.Split(out, "\n") if len(outArr) > 3 || strings.Contains(out, "nsenter-exec") { // This is the really bad part if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "rm", "-f", "exec_tty_stdin")); err != nil { t.Fatal(out, err) } t.Fatalf("exec process left running\n\t %s", out) } logDone("exec - stdin is closed properly with tty enabled") } func TestExecTtyWithoutStdin(t *testing.T) { defer deleteAllContainers() cmd := exec.Command(dockerBinary, "run", "-d", "-ti", "busybox") out, _, err := runCommandWithOutput(cmd) if err != nil { t.Fatalf("failed to start container: %v (%v)", out, err) } id := strings.TrimSpace(out) if err := waitRun(id); err != nil { t.Fatal(err) } defer func() { cmd := exec.Command(dockerBinary, "kill", id) if out, _, err := runCommandWithOutput(cmd); err != nil { t.Fatalf("failed to kill container: %v (%v)", out, err) } }() done := make(chan struct{}) go func() { defer close(done) cmd := exec.Command(dockerBinary, "exec", "-ti", id, "true") if _, err := cmd.StdinPipe(); err != nil { t.Fatal(err) } expected := "cannot enable tty mode" if out, _, err := runCommandWithOutput(cmd); err == nil { t.Fatal("exec should have failed") } else if !strings.Contains(out, expected) { t.Fatalf("exec failed with error %q: expected %q", out, expected) } }() select { case <-done: case <-time.After(3 * time.Second): t.Fatal("exec is running but should have failed") } logDone("exec - forbid piped stdin to tty enabled container") } func TestExecParseError(t *testing.T) { defer deleteAllContainers() runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "top", "busybox", "top") if out, _, err := runCommandWithOutput(runCmd); err != nil { t.Fatal(out, err) } // Test normal (non-detached) case first cmd := exec.Command(dockerBinary, "exec", "top") if _, stderr, code, err := runCommandWithStdoutStderr(cmd); err == nil || !strings.Contains(stderr, "See '"+dockerBinary+" exec --help'") || code == 0 { t.Fatalf("Should have thrown error & point to help: %s", stderr) } logDone("exec - error on parseExec should point to help") } func TestExecStopNotHanging(t *testing.T) { defer deleteAllContainers() if out, err := exec.Command(dockerBinary, "run", "-d", "--name", "testing", "busybox", "top").CombinedOutput(); err != nil { t.Fatal(out, err) } if err := exec.Command(dockerBinary, "exec", "testing", "top").Start(); err != nil { t.Fatal(err) } wait := make(chan struct{}) go func() { if out, err := exec.Command(dockerBinary, "stop", "testing").CombinedOutput(); err != nil { t.Fatal(out, err) } close(wait) }() select { case <-time.After(3 * time.Second): t.Fatal("Container stop timed out") case <-wait: } logDone("exec - container with exec not hanging on stop") } func TestExecCgroup(t *testing.T) { defer deleteAllContainers() var cmd *exec.Cmd cmd = exec.Command(dockerBinary, "run", "-d", "--name", "testing", "busybox", "top") _, err := runCommand(cmd) if err != nil { t.Fatal(err) } cmd = exec.Command(dockerBinary, "exec", "testing", "cat", "/proc/1/cgroup") out, _, err := runCommandWithOutput(cmd) if err != nil { t.Fatal(out, err) } containerCgroups := sort.StringSlice(strings.Split(string(out), "\n")) var wg sync.WaitGroup var s sync.Mutex execCgroups := []sort.StringSlice{} // exec a few times concurrently to get consistent failure for i := 0; i < 5; i++ { wg.Add(1) go func() { cmd := exec.Command(dockerBinary, "exec", "testing", "cat", "/proc/self/cgroup") out, _, err := runCommandWithOutput(cmd) if err != nil { t.Fatal(out, err) } cg := sort.StringSlice(strings.Split(string(out), "\n")) s.Lock() execCgroups = append(execCgroups, cg) s.Unlock() wg.Done() }() } wg.Wait() for _, cg := range execCgroups { if !reflect.DeepEqual(cg, containerCgroups) { fmt.Println("exec cgroups:") for _, name := range cg { fmt.Printf(" %s\n", name) } fmt.Println("container cgroups:") for _, name := range containerCgroups { fmt.Printf(" %s\n", name) } t.Fatal("cgroups mismatched") } } logDone("exec - exec has the container cgroups") } func TestInspectExecID(t *testing.T) { defer deleteAllContainers() out, exitCode, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "busybox", "top")) if exitCode != 0 || err != nil { t.Fatalf("failed to run container: %s, %v", out, err) } id := strings.TrimSuffix(out, "\n") out, err = inspectField(id, "ExecIDs") if err != nil { t.Fatalf("failed to inspect container: %s, %v", out, err) } if out != "<no value>" { t.Fatalf("ExecIDs should be empty, got: %s", out) } exitCode, err = runCommand(exec.Command(dockerBinary, "exec", "-d", id, "ls", "/")) if exitCode != 0 || err != nil { t.Fatalf("failed to exec in container: %s, %v", out, err) } out, err = inspectField(id, "ExecIDs") if err != nil { t.Fatalf("failed to inspect container: %s, %v", out, err) } out = strings.TrimSuffix(out, "\n") if out == "[]" || out == "<no value>" { t.Fatalf("ExecIDs should not be empty, got: %s", out) } logDone("inspect - inspect a container with ExecIDs") } func TestLinksPingLinkedContainersOnRename(t *testing.T) { defer deleteAllContainers() var out string out, _ = dockerCmd(t, "run", "-d", "--name", "container1", "busybox", "top") idA := strings.TrimSpace(out) if idA == "" { t.Fatal(out, "id should not be nil") } out, _ = dockerCmd(t, "run", "-d", "--link", "container1:alias1", "--name", "container2", "busybox", "top") idB := strings.TrimSpace(out) if idB == "" { t.Fatal(out, "id should not be nil") } execCmd := exec.Command(dockerBinary, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") out, _, err := runCommandWithOutput(execCmd) if err != nil { t.Fatal(out, err) } dockerCmd(t, "rename", "container1", "container_new") execCmd = exec.Command(dockerBinary, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") out, _, err = runCommandWithOutput(execCmd) if err != nil { t.Fatal(out, err) } logDone("links - ping linked container upon rename") } func TestRunExecDir(t *testing.T) { testRequires(t, SameHostDaemon) cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top") out, _, err := runCommandWithOutput(cmd) if err != nil { t.Fatal(err, out) } id := strings.TrimSpace(out) execDir := filepath.Join(execDriverPath, id) stateFile := filepath.Join(execDir, "state.json") { fi, err := os.Stat(execDir) if err != nil { t.Fatal(err) } if !fi.IsDir() { t.Fatalf("%q must be a directory", execDir) } fi, err = os.Stat(stateFile) if err != nil { t.Fatal(err) } } stopCmd := exec.Command(dockerBinary, "stop", id) out, _, err = runCommandWithOutput(stopCmd) if err != nil { t.Fatal(err, out) } { _, err := os.Stat(execDir) if err == nil { t.Fatal(err) } if err == nil { t.Fatalf("Exec directory %q exists for removed container!", execDir) } if !os.IsNotExist(err) { t.Fatalf("Error should be about non-existing, got %s", err) } } startCmd := exec.Command(dockerBinary, "start", id) out, _, err = runCommandWithOutput(startCmd) if err != nil { t.Fatal(err, out) } { fi, err := os.Stat(execDir) if err != nil { t.Fatal(err) } if !fi.IsDir() { t.Fatalf("%q must be a directory", execDir) } fi, err = os.Stat(stateFile) if err != nil { t.Fatal(err) } } rmCmd := exec.Command(dockerBinary, "rm", "-f", id) out, _, err = runCommandWithOutput(rmCmd) if err != nil { t.Fatal(err, out) } { _, err := os.Stat(execDir) if err == nil { t.Fatal(err) } if err == nil { t.Fatalf("Exec directory %q is exists for removed container!", execDir) } if !os.IsNotExist(err) { t.Fatalf("Error should be about non-existing, got %s", err) } } logDone("run - check execdriver dir behavior") } func TestRunMutableNetworkFiles(t *testing.T) { testRequires(t, SameHostDaemon) defer deleteAllContainers() for _, fn := range []string{"resolv.conf", "hosts"} { deleteAllContainers() content, err := runCommandAndReadContainerFile(fn, exec.Command(dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", fmt.Sprintf("echo success >/etc/%s && top", fn))) if err != nil { t.Fatal(err) } if strings.TrimSpace(string(content)) != "success" { t.Fatal("Content was not what was modified in the container", string(content)) } out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "c2", "busybox", "top")) if err != nil { t.Fatal(err) } contID := strings.TrimSpace(out) netFilePath := containerStorageFile(contID, fn) f, err := os.OpenFile(netFilePath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644) if err != nil { t.Fatal(err) } if _, err := f.Seek(0, 0); err != nil { f.Close() t.Fatal(err) } if err := f.Truncate(0); err != nil { f.Close() t.Fatal(err) } if _, err := f.Write([]byte("success2\n")); err != nil { f.Close() t.Fatal(err) } f.Close() res, err := exec.Command(dockerBinary, "exec", contID, "cat", "/etc/"+fn).CombinedOutput() if err != nil { t.Fatalf("Output: %s, error: %s", res, err) } if string(res) != "success2\n" { t.Fatalf("Expected content of %s: %q, got: %q", fn, "success2\n", res) } } logDone("run - mutable network files") } func TestExecWithUser(t *testing.T) { defer deleteAllContainers() runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "parent", "busybox", "top") if out, _, err := runCommandWithOutput(runCmd); err != nil { t.Fatal(out, err) } cmd := exec.Command(dockerBinary, "exec", "-u", "1", "parent", "id") out, _, err := runCommandWithOutput(cmd) if err != nil { t.Fatal(err, out) } if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") { t.Fatalf("exec with user by id expected daemon user got %s", out) } cmd = exec.Command(dockerBinary, "exec", "-u", "root", "parent", "id") out, _, err = runCommandWithOutput(cmd) if err != nil { t.Fatal(err, out) } if !strings.Contains(out, "uid=0(root) gid=0(root)") { t.Fatalf("exec with user by root expected root user got %s", out) } logDone("exec - with user") } func TestExecWithPrivileged(t *testing.T) { defer deleteAllContainers() runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "parent", "--cap-drop=ALL", "busybox", "top") if out, _, err := runCommandWithOutput(runCmd); err != nil { t.Fatal(out, err) } cmd := exec.Command(dockerBinary, "exec", "parent", "sh", "-c", "mknod /tmp/sda b 8 0") out, _, err := runCommandWithOutput(cmd) if err == nil || !strings.Contains(out, "Operation not permitted") { t.Fatalf("exec mknod in --cap-drop=ALL container without --privileged should failed") } cmd = exec.Command(dockerBinary, "exec", "--privileged", "parent", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") out, _, err = runCommandWithOutput(cmd) if err != nil { t.Fatal(err, out) } if actual := strings.TrimSpace(out); actual != "ok" { t.Fatalf("exec mknod in --cap-drop=ALL container with --privileged failed: %v, output: %q", err, out) } logDone("exec - exec command in a container with privileged") }
apache-2.0
smithab/azure-sdk-for-net
src/ResourceManagement/Resource/Microsoft.Azure.Management.ResourceManager/Generated/IPolicyAssignmentsOperations.cs
10284
// 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 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// PolicyAssignmentsOperations operations. /// </summary> public partial interface IPolicyAssignmentsOperations { /// <summary> /// Delete policy assignment. /// </summary> /// <param name='scope'> /// Scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// Policy assignment name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<PolicyAssignment>> DeleteWithHttpMessagesAsync(string scope, string policyAssignmentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create policy assignment. /// </summary> /// <param name='scope'> /// Scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// Policy assignment name. /// </param> /// <param name='parameters'> /// Policy assignment. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<PolicyAssignment>> CreateWithHttpMessagesAsync(string scope, string policyAssignmentName, PolicyAssignment parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get single policy assignment. /// </summary> /// <param name='scope'> /// Scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// Policy assignment name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<PolicyAssignment>> GetWithHttpMessagesAsync(string scope, string policyAssignmentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets policy assignments of the resource group. /// </summary> /// <param name='resourceGroupName'> /// Resource group name. /// </param> /// <param name='filter'> /// The filter to apply on the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<PolicyAssignment>>> ListForResourceGroupWithHttpMessagesAsync(string resourceGroupName, string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets policy assignments of the resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// The resource provider namespace. /// </param> /// <param name='parentResourcePath'> /// The parent resource path. /// </param> /// <param name='resourceType'> /// The resource type. /// </param> /// <param name='resourceName'> /// The resource name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<PolicyAssignment>>> ListForResourceWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, ODataQuery<PolicyAssignment> odataQuery = default(ODataQuery<PolicyAssignment>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the policy assignments of a subscription. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<PolicyAssignment>>> ListWithHttpMessagesAsync(ODataQuery<PolicyAssignment> odataQuery = default(ODataQuery<PolicyAssignment>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete policy assignment. /// </summary> /// <param name='policyAssignmentId'> /// Policy assignment Id /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<PolicyAssignment>> DeleteByIdWithHttpMessagesAsync(string policyAssignmentId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create policy assignment by Id. /// </summary> /// <param name='policyAssignmentId'> /// Policy assignment Id /// </param> /// <param name='parameters'> /// Policy assignment. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<PolicyAssignment>> CreateByIdWithHttpMessagesAsync(string policyAssignmentId, PolicyAssignment parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get single policy assignment. /// </summary> /// <param name='policyAssignmentId'> /// Policy assignment Id /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<PolicyAssignment>> GetByIdWithHttpMessagesAsync(string policyAssignmentId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets policy assignments of the resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<PolicyAssignment>>> ListForResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets policy assignments of the resource. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<PolicyAssignment>>> ListForResourceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the policy assignments of a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<PolicyAssignment>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
apache-2.0
IgnacioDomingo/rome-modules
src/main/java/com/rometools/modules/opensearch/impl/OpenSearchModuleImpl.java
4207
/* * 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.rometools.modules.opensearch.impl; import java.io.Serializable; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rometools.modules.opensearch.OpenSearchModule; import com.rometools.modules.opensearch.entity.OSQuery; import com.rometools.rome.feed.CopyFrom; import com.rometools.rome.feed.atom.Link; import com.rometools.rome.feed.module.ModuleImpl; /** * @author Michael W. Nassif (enrouteinc@gmail.com) OpenSearch Module implementation */ public class OpenSearchModuleImpl extends ModuleImpl implements OpenSearchModule, Serializable { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(OpenSearchModuleImpl.class); private int totalResults = -1; private int startIndex = 1; private int itemsPerPage = -1; private Link link; private List<OSQuery> queries; public OpenSearchModuleImpl() { super(OpenSearchModuleImpl.class, OpenSearchModule.URI); } /** * @return Returns the itemsPerPage. */ @Override public int getItemsPerPage() { return itemsPerPage; } /** * @param itemsPerPage The itemsPerPage to set. */ @Override public void setItemsPerPage(final int itemsPerPage) { this.itemsPerPage = itemsPerPage; } /** * @return Returns the link. */ @Override public Link getLink() { return link; } /** * @param link The link to set. */ @Override public void setLink(final Link link) { this.link = link; } /** * @return Returns the queries. */ @Override public List<OSQuery> getQueries() { if (queries == null) { queries = new LinkedList<OSQuery>(); } return queries; } /** * @param queries The queries to set. */ @Override public void setQueries(final List<OSQuery> queries) { this.queries = queries; } @Override public void addQuery(final OSQuery query) { getQueries().add(query); } /** * @return Returns the startIndex. */ @Override public int getStartIndex() { return startIndex; } /** * @param startIndex The startIndex to set. */ @Override public void setStartIndex(final int startIndex) { this.startIndex = startIndex; } /** * @return Returns the totalResults. */ @Override public int getTotalResults() { return totalResults; } /** * @param totalResults The totalResults to set. */ @Override public void setTotalResults(final int totalResults) { this.totalResults = totalResults; } /* * (non-Javadoc) * * @see com.rometools.rome.feed.CopyFrom#copyFrom(java.lang.Object) */ @Override public void copyFrom(final CopyFrom obj) { final OpenSearchModule osm = (OpenSearchModule) obj; setTotalResults(osm.getTotalResults()); setItemsPerPage(osm.getItemsPerPage()); setStartIndex(osm.getStartIndex()); setLink(osm.getLink()); for (final OSQuery q : osm.getQueries()) { try { getQueries().add((OSQuery) q.clone()); } catch (final CloneNotSupportedException e) { LOG.error("Error", e); } } } /* * (non-Javadoc) * * @see com.rometools.rome.feed.CopyFrom#getInterface() */ @Override public Class<OpenSearchModule> getInterface() { return OpenSearchModule.class; } }
apache-2.0
lrytz/scala
test/files/neg/t10296-after/UnusedMacro_1.scala
200
import scala.reflect.macros.whitebox.Context object UnusedMacro { def macroImpl(c: Context)(body: c.Expr[Int]): c.Tree = { import c.universe._ val _ = body Literal(Constant(42)) } }
apache-2.0
PaycoinFoundation/paycoinj
core/src/main/java/io/xpydev/paycoinj/net/NioClient.java
3915
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * 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 io.xpydev.paycoinj.net; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; /** * Creates a simple connection to a server using a {@link StreamParser} to process data. */ public class NioClient implements MessageWriteTarget { private final Handler handler; private final NioClientManager manager = new NioClientManager(); class Handler extends AbstractTimeoutHandler implements StreamParser { private final StreamParser upstreamParser; private MessageWriteTarget writeTarget; private boolean closeOnOpen = false; private boolean closeCalled = false; Handler(StreamParser upstreamParser, int connectTimeoutMillis) { this.upstreamParser = upstreamParser; setSocketTimeout(connectTimeoutMillis); setTimeoutEnabled(true); } @Override protected synchronized void timeoutOccurred() { closeOnOpen = true; connectionClosed(); } @Override public synchronized void connectionClosed() { manager.stopAsync(); if (!closeCalled) { closeCalled = true; upstreamParser.connectionClosed(); } } @Override public synchronized void connectionOpened() { if (!closeOnOpen) upstreamParser.connectionOpened(); } @Override public int receiveBytes(ByteBuffer buff) throws Exception { return upstreamParser.receiveBytes(buff); } @Override public synchronized void setWriteTarget(MessageWriteTarget writeTarget) { if (closeOnOpen) writeTarget.closeConnection(); else { setTimeoutEnabled(false); this.writeTarget = writeTarget; upstreamParser.setWriteTarget(writeTarget); } } @Override public int getMaxMessageSize() { return upstreamParser.getMaxMessageSize(); } } /** * <p>Creates a new client to the given server address using the given {@link StreamParser} to decode the data. * The given parser <b>MUST</b> be unique to this object. This does not block while waiting for the connection to * open, but will call either the {@link StreamParser#connectionOpened()} or * {@link StreamParser#connectionClosed()} callback on the created network event processing thread.</p> * * @param connectTimeoutMillis The connect timeout set on the connection (in milliseconds). 0 is interpreted as no * timeout. */ public NioClient(final SocketAddress serverAddress, final StreamParser parser, final int connectTimeoutMillis) throws IOException { manager.startAsync(); manager.awaitRunning(); handler = new Handler(parser, connectTimeoutMillis); manager.openConnection(serverAddress, handler); } @Override public void closeConnection() { handler.writeTarget.closeConnection(); } @Override public synchronized void writeBytes(byte[] message) throws IOException { handler.writeTarget.writeBytes(message); } }
apache-2.0
goodwinnk/intellij-community
python/testSrc/com/jetbrains/python/PythonHighlightingTest.java
11442
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.jetbrains.python.documentation.PyDocumentationSettings; import com.jetbrains.python.documentation.docstrings.DocStringFormat; import com.jetbrains.python.fixtures.PyTestCase; import com.jetbrains.python.psi.LanguageLevel; import org.jetbrains.annotations.NotNull; import java.awt.*; /** * Test highlighting added by annotators. * * @author yole */ public class PythonHighlightingTest extends PyTestCase { public void testBuiltins() { EditorColorsScheme scheme = createTemporaryColorScheme(); TextAttributesKey xKey; TextAttributes xAttributes; xKey = TextAttributesKey.find("PY.BUILTIN_NAME"); xAttributes = new TextAttributes(Color.green, Color.black, Color.white, EffectType.BOXED, Font.BOLD); scheme.setAttributes(xKey, xAttributes); xKey = TextAttributesKey.find("PY.PREDEFINED_USAGE"); xAttributes = new TextAttributes(Color.yellow, Color.black, Color.white, EffectType.BOXED, Font.BOLD); scheme.setAttributes(xKey, xAttributes); doTest(); } public void testDeclarations() { EditorColorsScheme scheme = createTemporaryColorScheme(); TextAttributesKey xKey = TextAttributesKey.find("PY.CLASS_DEFINITION"); TextAttributes xAttributes = new TextAttributes(Color.blue, Color.black, Color.white, EffectType.BOXED, Font.BOLD); scheme.setAttributes(xKey, xAttributes); xKey = TextAttributesKey.find("PY.FUNC_DEFINITION"); xAttributes = new TextAttributes(Color.red, Color.black, Color.white, EffectType.BOXED, Font.BOLD); scheme.setAttributes(xKey, xAttributes); xKey = TextAttributesKey.find("PY.PREDEFINED_DEFINITION"); xAttributes = new TextAttributes(Color.green, Color.black, Color.white, EffectType.BOXED, Font.BOLD); scheme.setAttributes(xKey, xAttributes); doTest(); } public void testAssignmentTargets() { runWithLanguageLevel(LanguageLevel.PYTHON26, () -> doTest(true, false)); } public void testAssignmentTargetWith() { // PY-7529 runWithLanguageLevel(LanguageLevel.PYTHON27, () -> doTest(true, false)); } public void testAssignmentTargets3K() { doTest(LanguageLevel.PYTHON34, true, false); } public void testBreakOutsideOfLoop() { doTest(true, false); } public void testReturnOutsideOfFunction() { doTest(); } public void testContinueOutsideOfLoop() { doTest(false, false); } public void testReturnWithArgumentsInGenerator() { doTest(); } public void testYieldOutsideOfFunction() { doTest(LanguageLevel.PYTHON27, true, true); } public void testYieldInDefaultValue() { doTest(LanguageLevel.PYTHON34, true, false); } // PY-11663 public void testYieldInLambda() { doTest(); } public void testImportStarAtTopLevel() { doTest(true, false); } public void testMalformedStringUnterminated() { doTest(); } public void testMalformedStringEscaped() { doTest(false, false); } /* public void testStringEscapedOK() { doTest(); } */ public void testStringMixedSeparatorsOK() { // PY-299 doTest(); } public void testStringBytesLiteralOK() { doTest(LanguageLevel.PYTHON26, true, true); } public void testArgumentList() { doTest(true, false); } public void testRegularAfterVarArgs() { doTest(LanguageLevel.PYTHON34, true, false); } public void testKeywordOnlyArguments() { doTest(LanguageLevel.PYTHON34, true, false); } public void testMalformedStringTripleQuoteUnterminated() { doTest(); } public void testMixedTripleQuotes() { // PY-2806 doTest(); } public void testOddNumberOfQuotes() { // PY-2802 doTest(true, false); } public void testEscapedBackslash() { // PY-2994 doTest(true, false); } public void testMultipleEscapedBackslashes() { doTest(true, false); } public void testUnsupportedFeaturesInPython3() { doTest(LanguageLevel.PYTHON34, true, false); } // PY-6703 public void testUnicode33() { doTest(LanguageLevel.PYTHON34, true, false); } public void testParenthesizedGenerator() { doTest(false, false); } public void testStarInGenerator() { // PY-10177 doTest(LanguageLevel.PYTHON34, false, false); } public void testStarArgs() { // PY-6456 doTest(LanguageLevel.PYTHON34, true, false); } public void testDocstring() { // PY-8025 PyDocumentationSettings documentationSettings = PyDocumentationSettings.getInstance(myFixture.getModule()); documentationSettings.setFormat(DocStringFormat.REST); try { doTest(false, true); } finally { documentationSettings.setFormat(DocStringFormat.PLAIN); } } public void testYieldInNestedFunction() { // highlight func declaration first, lest we get an "Extra fragment highlighted" error. EditorColorsScheme scheme = createTemporaryColorScheme(); TextAttributesKey xKey = TextAttributesKey.find("PY.FUNC_DEFINITION"); TextAttributes xAttributes = new TextAttributes(Color.red, Color.black, Color.white, EffectType.BOXED, Font.BOLD); scheme.setAttributes(xKey, xAttributes); doTest(); } public void testAsync() { doTest(LanguageLevel.PYTHON35, true, true); } public void testAwait() { doTest(LanguageLevel.PYTHON35, true, true); } // PY-19679 public void testAwaitInListPy35() { doTest(LanguageLevel.PYTHON35, true, false); } public void testAwaitInTuple() { doTest(LanguageLevel.PYTHON35, true, false); } public void testAwaitInGenerator() { doTest(LanguageLevel.PYTHON35, true, false); } public void testAwaitInSetPy35() { doTest(LanguageLevel.PYTHON35, true, false); } public void testAwaitInDictPy35() { doTest(LanguageLevel.PYTHON35, true, false); } // PY-20770 public void testAwaitInListPy36() { doTest(LanguageLevel.PYTHON36, true, false); } // PY-20770 public void testAwaitInSetPy36() { doTest(LanguageLevel.PYTHON36, true, false); } // PY-20770 public void testAwaitInDictPy36() { doTest(LanguageLevel.PYTHON36, true, false); } public void testYieldInsideAsyncDefPy35() { doTest(LanguageLevel.PYTHON35, false, false); } // PY-20770 public void testYieldInsideAsyncDefPy36() { doTest(LanguageLevel.PYTHON36, true, false); } public void testUnpackingStar() { doTest(LanguageLevel.PYTHON35, false, false); } // PY-19927 public void testMagicMethods() { EditorColorsScheme scheme = createTemporaryColorScheme(); TextAttributesKey xKey = TextAttributesKey.find("PY.PREDEFINED_DEFINITION"); TextAttributes xAttributes = new TextAttributes(Color.green, Color.black, Color.white, EffectType.BOXED, Font.BOLD); scheme.setAttributes(xKey, xAttributes); doTest(); } // PY-19775 public void testAsyncBuiltinMethods() { doTest(LanguageLevel.PYTHON35, true, false); } // PY-28017 public void testAsyncModuleBuiltinMethods() { doTest(LanguageLevel.PYTHON37, true, false); } // PY-28017 public void testModuleBuiltinMethods() { doTest(LanguageLevel.PYTHON37, false, true); } public void testImplicitOctLongInteger() { doTest(LanguageLevel.PYTHON35, true, false); } public void testUnderscoresInNumericLiterals() { doTest(LanguageLevel.PYTHON35, true, false); } public void testVariableAnnotations() { doTest(LanguageLevel.PYTHON35, true, false); } public void testIllegalVariableAnnotationTarget() { doTest(LanguageLevel.PYTHON36, true, false); } public void testFStringLiterals() { doTest(); } // PY-20770 public void testAsyncComprehensionsPy35() { doTest(LanguageLevel.PYTHON35, true, false); } // PY-20770 public void testAsyncComprehensionsPy36() { doTest(LanguageLevel.PYTHON36, true, false); } // PY-20775 public void testFStringMissingRightBrace() { runWithLanguageLevel(LanguageLevel.PYTHON36, () -> doTest(true, false)); } // PY-20776 public void testFStringEmptyExpressions() { runWithLanguageLevel(LanguageLevel.PYTHON36, () -> doTest(true, false)); } // PY-20778 public void testFStringIllegalConversionCharacter() { runWithLanguageLevel(LanguageLevel.PYTHON36, () -> doTest(true, false)); } // PY-20773 public void testFStringHashSigns() { runWithLanguageLevel(LanguageLevel.PYTHON36, () -> doTest(true, false)); } // PY-20844 public void testFStringBackslashes() { runWithLanguageLevel(LanguageLevel.PYTHON36, () -> doTest(true, false)); } // PY-20897 public void testFStringSingleRightBraces() { runWithLanguageLevel(LanguageLevel.PYTHON36, () -> doTest(true, false)); } // PY-20901 public void testFStringTooDeeplyNestedExpressionFragments() { runWithLanguageLevel(LanguageLevel.PYTHON36, () -> doTest(true, false)); } // PY-12634 public void testSpaceBetweenAtAndDecorator() { doTest(true, true); } // PY-25381 public void testBuiltinDecorator() { doTest(true, true); } // PY-11418 public void testFunctionCalls() { doTest(); } // PY-20401 public void testAnnotations() { runWithLanguageLevel(LanguageLevel.PYTHON36, this::doTest); } // PY-22729 public void testParametersWithAnnotationsAndDefaults() { runWithLanguageLevel(LanguageLevel.PYTHON34, this::doTest); } // PY-26491 public void testMultiplePositionalContainers() { doTest(LanguageLevel.PYTHON35, true, false); } // PY-26491 public void testMultipleKeywordContainers() { doTest(LanguageLevel.PYTHON35, true, false); } // PY-26510 public void testEmptyRaise() { doTest(false, false); } // PY-28247 public void testAsyncAndAwaitAsIdentifiersIn37() { doTest(LanguageLevel.PYTHON37, false, false); } // PY-27913 public void testDunderClassGetItem() { doTest(LanguageLevel.PYTHON37, false, true); } // PY-28313 public void testVarargs() { doTest(); } // PY-28313 public void testKwargs() { doTest(); } // PY-20530 public void testUnparsedTypeHints() { doTest(LanguageLevel.PYTHON36, false, false); } @NotNull private static EditorColorsScheme createTemporaryColorScheme() { EditorColorsManager manager = EditorColorsManager.getInstance(); EditorColorsScheme scheme = (EditorColorsScheme)manager.getGlobalScheme().clone(); manager.addColorsScheme(scheme); EditorColorsManager.getInstance().setGlobalScheme(scheme); return scheme; } // --- private void doTest(final LanguageLevel languageLevel, final boolean checkWarnings, final boolean checkInfos) { runWithLanguageLevel(languageLevel, () -> doTest(checkWarnings, checkInfos)); } private void doTest() { doTest(true, true); } private void doTest(boolean checkWarnings, boolean checkInfos) { myFixture.testHighlighting(checkWarnings, checkInfos, false, getTestName(true) + PyNames.DOT_PY); } @Override protected String getTestDataPath() { return super.getTestDataPath() + "/highlighting/"; } }
apache-2.0
alibaba/fastjson
src/test/java/com/alibaba/json/bvt/serializer/features/WriteNonStringValueAsStringTestIntegerField.java
935
package com.alibaba.json.bvt.serializer.features; import org.junit.Assert; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import junit.framework.TestCase; public class WriteNonStringValueAsStringTestIntegerField extends TestCase { public void test_0() throws Exception { VO vo = new VO(); vo.id = 100; String text = JSON.toJSONString(vo, SerializerFeature.WriteNonStringValueAsString); Assert.assertEquals("{\"id\":\"100\"}", text); } public void test_1() throws Exception { V1 vo = new V1(); vo.id = 100; String text = JSON.toJSONString(vo, SerializerFeature.WriteNonStringValueAsString); Assert.assertEquals("{\"id\":\"100\"}", text); } public static class VO { public Integer id; } private static class V1 { public Integer id; } }
apache-2.0
zstackorg/zstack
core/src/main/java/org/zstack/core/ansible/SshYamlChecker.java
2980
package org.zstack.core.ansible; import org.apache.logging.log4j.util.Strings; import org.zstack.utils.Utils; import org.zstack.utils.logging.CLogger; import org.zstack.utils.ssh.Ssh; import org.zstack.utils.ssh.SshResult; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; /** * Created by MaJin on 2019/12/14. */ public class SshYamlChecker implements AnsibleChecker { private static final CLogger logger = Utils.getLogger(SshYamlChecker.class); private String yamlFilePath; private String username; private String password; private String privateKey; private String targetIp; private int sshPort = 22; private Map<String, String> expectConfigs = new HashMap<>(); @Override public boolean needDeploy() { if (Strings.isEmpty(yamlFilePath) || expectConfigs.isEmpty()) { return false; } Ssh ssh = new Ssh(); ssh.setUsername(username).setPrivateKey(privateKey) .setPassword(password).setPort(sshPort) .setHostname(targetIp); try { ssh.command(String.format("grep -o '%s' %s | uniq | wc -l", getGrepArgs(), yamlFilePath)); SshResult ret = ssh.run(); if (ret.getReturnCode() != 0) { return true; } String out = ret.getStdout(); if (Strings.isEmpty(out) || !out.trim().equals(String.valueOf(expectConfigs.size()))) { return true; } ssh.reset(); } finally { ssh.close(); } return false; } @Override public void deleteDestFile() { // do nothing. } public SshYamlChecker expectConfig(String key, String value) { expectConfigs.put(key, value); return this; } private String getGrepArgs() { return expectConfigs.entrySet().stream().map(it -> it.getKey() + "\\s*:\\s*" + it.getValue()) .collect(Collectors.joining("\\|")); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public int getSshPort() { return sshPort; } public void setSshPort(int sshPort) { this.sshPort = sshPort; } public String getTargetIp() { return targetIp; } public void setTargetIp(String targetIp) { this.targetIp = targetIp; } public String getYamlFilePath() { return yamlFilePath; } public void setYamlFilePath(String yamlFilePath) { this.yamlFilePath = yamlFilePath; } }
apache-2.0
salyh/javamailspec
geronimo-ejb_3.1_spec/src/main/java/javax/ejb/TimerService.java
2771
/* * 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. */ // // This source code implements specifications defined by the Java // Community Process. In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package javax.ejb; import java.io.Serializable; import java.util.Collection; import java.util.Date; /** * @version $Rev$ $Date$ */ public interface TimerService { Timer createTimer(Date initialExpiration, long intervalDuration, Serializable info) throws IllegalArgumentException, IllegalStateException, EJBException; Timer createTimer(Date expiration, Serializable info) throws IllegalArgumentException, IllegalStateException, EJBException; Timer createTimer(long initialDuration, long intervalDuration, Serializable info) throws IllegalArgumentException, IllegalStateException, EJBException; Timer createTimer(long duration, Serializable info) throws IllegalArgumentException, IllegalStateException, EJBException; Collection<Timer> getTimers() throws IllegalStateException, EJBException; Timer createSingleActionTimer(long duration, TimerConfig timerConfig) throws IllegalArgumentException, IllegalStateException, EJBException; Timer createSingleActionTimer(java.util.Date expiration, TimerConfig timerConfig) throws IllegalArgumentException, IllegalStateException, EJBException; Timer createIntervalTimer(long initialDuration, long intervalDuration, TimerConfig timerConfig) throws IllegalArgumentException, IllegalStateException, EJBException; Timer createIntervalTimer(java.util.Date initialExpiration, long intervalDuration, TimerConfig timerConfig) throws IllegalArgumentException, IllegalStateException, EJBException; Timer createCalendarTimer(ScheduleExpression schedule) throws IllegalArgumentException, IllegalStateException, EJBException; Timer createCalendarTimer(ScheduleExpression schedule, TimerConfig timerConfig) throws IllegalArgumentException, IllegalStateException, EJBException; }
apache-2.0
AArnott/roslyn
src/VisualStudio/Core/Next/Remote/ServiceHubRemoteHostClient.cs
6067
// 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.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Execution; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Remote; using Microsoft.ServiceHub.Client; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Roslyn.Utilities; using StreamJsonRpc; namespace Microsoft.VisualStudio.LanguageServices.Remote { using Workspace = Microsoft.CodeAnalysis.Workspace; internal partial class ServiceHubRemoteHostClient : RemoteHostClient { private readonly HubClient _hubClient; private readonly JsonRpc _rpc; private readonly string _hostGroup; public static async Task<RemoteHostClient> CreateAsync( Workspace workspace, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.ServiceHubRemoteHostClient_CreateAsync, cancellationToken)) { var primary = new HubClient("ManagedLanguage.IDE.RemoteHostClient"); var current = $"VS ({Process.GetCurrentProcess().Id})"; var remoteHostStream = await RequestServiceAsync(primary, WellKnownRemoteHostServices.RemoteHostService, current, cancellationToken).ConfigureAwait(false); var instance = new ServiceHubRemoteHostClient(workspace, primary, current, remoteHostStream); // make sure connection is done right var host = await instance._rpc.InvokeAsync<string>(WellKnownRemoteHostServices.RemoteHostService_Connect, current).ConfigureAwait(false); // TODO: change this to non fatal watson and make VS to use inproc implementation Contract.ThrowIfFalse(host == current.ToString()); instance.Connected(); // Create a workspace host to hear about workspace changes. We'll // remote those changes over to the remote side when they happen. RegisterWorkspaceHost(workspace, instance); // return instance return instance; } } private static void RegisterWorkspaceHost(Workspace workspace, RemoteHostClient client) { var vsWorkspace = workspace as VisualStudioWorkspaceImpl; if (vsWorkspace == null) { return; } vsWorkspace.ProjectTracker.RegisterWorkspaceHost( new WorkspaceHost(vsWorkspace, client)); } private ServiceHubRemoteHostClient( Workspace workspace, HubClient hubClient, string hostGroup, Stream stream) : base(workspace) { _hubClient = hubClient; _hostGroup = hostGroup; _rpc = JsonRpc.Attach(stream, target: this); // handle disconnected situation _rpc.Disconnected += OnRpcDisconnected; } protected override async Task<Session> CreateServiceSessionAsync(string serviceName, PinnedRemotableDataScope snapshot, object callbackTarget, CancellationToken cancellationToken) { // get stream from service hub to communicate snapshot/asset related information // this is the back channel the system uses to move data between VS and remote host var snapshotStream = await RequestServiceAsync(_hubClient, WellKnownServiceHubServices.SnapshotService, _hostGroup, cancellationToken).ConfigureAwait(false); // get stream from service hub to communicate service specific information // this is what consumer actually use to communicate information var serviceStream = await RequestServiceAsync(_hubClient, serviceName, _hostGroup, cancellationToken).ConfigureAwait(false); return await JsonRpcSession.CreateAsync(snapshot, snapshotStream, callbackTarget, serviceStream, cancellationToken).ConfigureAwait(false); } protected override void OnConnected() { } protected override void OnDisconnected() { _rpc.Dispose(); } private void OnRpcDisconnected(object sender, JsonRpcDisconnectedEventArgs e) { Disconnected(); } private static async Task<Stream> RequestServiceAsync(HubClient client, string serviceName, string hostGroup, CancellationToken cancellationToken = default(CancellationToken)) { const int max_retry = 10; const int retry_delayInMS = 50; // call to get service can fail due to this bug - devdiv#288961 // until root cause is fixed, we decide to have retry rather than fail right away for (var i = 0; i < max_retry; i++) { cancellationToken.ThrowIfCancellationRequested(); try { var descriptor = new ServiceDescriptor(serviceName) { HostGroup = new HostGroup(hostGroup) }; return await client.RequestServiceAsync(descriptor, cancellationToken).ConfigureAwait(false); } catch (RemoteInvocationException ex) { // RequestServiceAsync should never fail unless service itself is actually broken. // right now, we know only 1 case where it can randomly fail. but there might be more cases so // adding non fatal watson here. FatalError.ReportWithoutCrash(ex); } // wait for retry_delayInMS before next try await Task.Delay(retry_delayInMS, cancellationToken).ConfigureAwait(false); } return Contract.FailWithReturn<Stream>("Fail to get service. look FatalError.s_reportedException for more detail"); } } }
apache-2.0
qiuxin2012/BigDL
spark/dl/src/main/scala/com/intel/analytics/bigdl/utils/tf/loaders/Conv2DBackpropFilter.scala
2406
/* * Copyright 2016 The BigDL Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intel.analytics.bigdl.utils.tf.loaders import java.nio.ByteOrder import com.intel.analytics.bigdl.Module import com.intel.analytics.bigdl.nn.Identity import com.intel.analytics.bigdl.nn.abstractnn.{AbstractModule, Activity, DataFormat} import com.intel.analytics.bigdl.nn.ops.Conv2DBackFilter import com.intel.analytics.bigdl.tensor.Tensor import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric import com.intel.analytics.bigdl.utils.tf.Context import org.tensorflow.framework.NodeDef import scala.reflect.ClassTag class Conv2DBackpropFilter extends TensorflowOpsLoader { import Utils._ override def build[T: ClassTag](nodeDef: NodeDef, byteOrder: ByteOrder, context: Context[T])(implicit ev: TensorNumeric[T]): Module[T] = { val attributes = nodeDef.getAttrMap val (pW, pH) = if (getString(attributes, "padding") == "SAME") { (-1, -1) } else { (0, 0) } val strideList = getIntList(attributes, "strides") require(strideList.head == 1, s"not support strides on batch") val format = getString(attributes, "data_format") val convBackFilter = format match { case "NHWC" => require(strideList(3) == 1, s"not support strides on depth") val strideW = strideList(1) val strideH = strideList(2) Conv2DBackFilter[T](strideW, strideH, pW, pH, DataFormat.NHWC) case "NCHW" => require(strideList(1) == 1, s"not support strides on depth") val strideW = strideList(2) val strideH = strideList(3) Conv2DBackFilter[T](strideW, strideH, pW, pH, DataFormat.NCHW) case _ => throw new IllegalArgumentException(s"not supported data format: $format") } convBackFilter.asInstanceOf[AbstractModule[Activity, Activity, T]] } }
apache-2.0
ya7lelkom/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201405/InvalidEmailError.java
1745
package com.google.api.ads.dfp.jaxws.v201405; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * Caused by supplying a value for an email attribute that is not a valid * email address. * * * <p>Java class for InvalidEmailError complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="InvalidEmailError"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201405}ApiError"> * &lt;sequence> * &lt;element name="reason" type="{https://www.google.com/apis/ads/publisher/v201405}InvalidEmailError.Reason" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "InvalidEmailError", propOrder = { "reason" }) public class InvalidEmailError extends ApiError { @XmlSchemaType(name = "string") protected InvalidEmailErrorReason reason; /** * Gets the value of the reason property. * * @return * possible object is * {@link InvalidEmailErrorReason } * */ public InvalidEmailErrorReason getReason() { return reason; } /** * Sets the value of the reason property. * * @param value * allowed object is * {@link InvalidEmailErrorReason } * */ public void setReason(InvalidEmailErrorReason value) { this.reason = value; } }
apache-2.0
suhand/product-as
modules/integration/tests-integration/tests-ldap-userstore/src/test/java/org/wso2/appserver/integration/tests/readonlyldap/ReadOnlyLDAPUserStoreManagerTestCase.java
13436
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.appserver.integration.tests.readonlyldap; import org.apache.axis2.AxisFault; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.appserver.integration.common.utils.ASIntegrationTest; import org.wso2.carbon.automation.engine.FrameworkConstants; import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; import org.wso2.carbon.automation.engine.annotations.SetEnvironment; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.carbon.automation.test.utils.common.TestConfigurationProvider; import org.wso2.carbon.integration.common.admin.client.AuthenticatorClient; import org.wso2.carbon.integration.common.admin.client.UserManagementClient; import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; import org.wso2.carbon.user.mgt.stub.UserAdminUserAdminException; import org.wso2.carbon.user.mgt.stub.types.carbon.FlaggedName; import java.io.File; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; /** * This test class will test the Application Server with Read Only Ldap server as the primary user store */ public class ReadOnlyLDAPUserStoreManagerTestCase extends ASIntegrationTest { private ServerConfigurationManager scm; private UserManagementClient userMgtClient; private AuthenticatorClient authenticatorClient; private final String newUserName = "ReadOnlyLDAPUserName"; //https://wso2.org/jira/browse/IDENTITY-3438 - can not put upper letters as user role when permissions granted private final String newUserRole = "readonlyldapuserrole"; private final String newUserPassword = "ReadOnlyLDAPUserPass"; @SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE}) @BeforeClass(alwaysRun = true) public void configureServer() throws Exception { super.init(TestUserMode.SUPER_TENANT_ADMIN); userMgtClient = new UserManagementClient(backendURL, sessionCookie); authenticatorClient = new AuthenticatorClient(backendURL); if (userMgtClient.roleNameExists(newUserRole)) { userMgtClient.deleteRole(newUserRole); } //Populate roles and users in to ReadWrite Ldap userMgtClient.addRole(newUserRole, null, new String[]{"/permission/admin/login"}); userMgtClient.addUser(newUserName, newUserPassword, new String[]{newUserRole}, null); assertTrue(userMgtClient.roleNameExists(newUserRole), "Role name doesn't exists " + newUserRole); assertTrue(userMgtClient.userNameExists(newUserRole, newUserName), "User name doesn't exists " + newUserName); String newUserSessionCookie = authenticatorClient.login(newUserName , newUserPassword, asServer.getInstance().getHosts().get("default")); assertTrue(newUserSessionCookie.contains("JSESSIONID"), "Session Cookie not found. Login failed"); authenticatorClient.logOut(); //adding another 3 users for (int i = 1; i < 3; i++) { userMgtClient.addRole(newUserRole + i, null, new String[]{"/permission/admin/login"}); userMgtClient.addUser(newUserName + i, newUserPassword, new String[]{newUserRole + i}, null); assertTrue(userMgtClient.roleNameExists(newUserRole + i), "Role name doesn't exists"); assertTrue(userMgtClient.userNameExists(newUserRole + i, newUserName + i), "User name doesn't exists"); } File userMgtConfigFile = new File(TestConfigurationProvider.getResourceLocation("AS") + File.separator + "configs" + File.separator + "readonlyldap" + File.separator + "user-mgt.xml"); scm = new ServerConfigurationManager(asServer); //Enable ReadOnly User Store in user-mgt.xml scm.applyConfiguration(userMgtConfigFile); super.init(TestUserMode.SUPER_TENANT_ADMIN); userMgtClient = new UserManagementClient(backendURL, sessionCookie); } @Test(groups = "wso2.as", description = "Test login of a user already exist in the ReadOnly ldap") public void userLoginTest() throws Exception { String userSessionCookie = authenticatorClient.login(newUserName, newUserPassword , asServer.getInstance().getHosts().get("default")); assertTrue(userSessionCookie.contains("JSESSIONID"), "Session Cookie not found. Login failed user " + newUserName); authenticatorClient.logOut(); } @Test(groups = "wso2.as", description = "Getting users of a role") public void getUsersOfRoleTest() throws Exception { assertTrue(nameExists(userMgtClient.getUsersOfRole(newUserRole, newUserName, 10), newUserName) , "List does not contains the expected user name"); for (int i = 1; i < 3; i++) { assertTrue(nameExists(userMgtClient.getUsersOfRole(newUserRole + i, newUserName + i, 10), newUserName + i) , "List does not contains the expected user name"); } } @Test(groups = "wso2.as", description = "Get roles of a particular user") public void getRolesOfUser() throws Exception { assertTrue(nameExists(userMgtClient.getRolesOfUser(newUserName, newUserRole, 10), newUserRole) , "List does not contains the expected role name"); } @Test(groups = "wso2.as", description = "get all the roles in ldap") public void getAllRolesNamesTest() throws Exception { FlaggedName[] flaggedNames = userMgtClient.getAllRolesNames("*", 10); Assert.assertNotNull(flaggedNames, "Role list empty"); assertTrue(flaggedNames.length > 3, "No role listed in Ldap"); assertTrue(nameExists(flaggedNames, newUserRole), "User role not listed " + newUserRole); for (int i = 1; i < 3; i++) { assertTrue(nameExists(flaggedNames, newUserRole + i), "Role name not found " + newUserRole + i); } } @Test(groups = "wso2.as", description = "Check new role addition failure in readonly Ldap" , expectedExceptions = AxisFault.class , expectedExceptionsMessageRegExp = "Read only user store or Role creation is disabled") public void testAddNewRole() throws Exception { final String roleName = "addNewRole"; assertFalse(nameExists(userMgtClient.getAllRolesNames(roleName, 100), roleName) , "User Role trying to add already exist"); userMgtClient.addRole(roleName, null, new String[]{"login"}, false); assertFalse(nameExists(userMgtClient.getAllRolesNames(roleName, 100), roleName) , "Role creation success. New role must not be allowed to add in ReadOnly Ldap"); } @Test(groups = "wso2.as", description = "Check new user addition failure in readonly Ldap", expectedExceptions = UserAdminUserAdminException.class, expectedExceptionsMessageRegExp = "UserAdminUserAdminException") public void addNewUserTest() throws Exception { final String userName = "addReadOnlyUser"; userMgtClient.addUser(userName, newUserPassword, new String[]{newUserRole}, null); assertFalse(nameExists(userMgtClient.listAllUsers(userName, 10), userName), "New user must not" + " be allowed to add in ReadOnly Ldap"); } @Test(groups = "wso2.as", description = "Check update role name failure", expectedExceptions = AxisFault.class, expectedExceptionsMessageRegExp = "Read-only UserStoreManager. Roles cannot be added or modified.") public void updateRoleNameTest() throws Exception { String updatedUserRole = newUserRole + "updated"; userMgtClient.updateRoleName(newUserRole, updatedUserRole); assertFalse(nameExists(userMgtClient.getAllRolesNames(newUserRole + "1", 100), updatedUserRole) , "Role has been updated. New role must not be allowed to update in ReadOnly Ldap"); } @Test(groups = "wso2.as", description = "Check update users of role failure", expectedExceptions = UserAdminUserAdminException.class, expectedExceptionsMessageRegExp = "UserAdminUserAdminException") public void updateUsersOfRoleTest() throws Exception { String[] userList = new String[]{newUserName}; FlaggedName[] userFlagList = new FlaggedName[userList.length]; for (int i = 0; i < userFlagList.length; i++) { FlaggedName flaggedName = new FlaggedName(); flaggedName.setItemName(userList[i]); flaggedName.setSelected(true); userFlagList[i] = flaggedName; } userMgtClient.updateUsersOfRole(asServer.getSuperTenant().getTenantAdmin().getUserName(), userFlagList); fail("Roles of user must not be allowed to add in ReadOnly Ldap"); } @Test(groups = "wso2.as", description = "Check add remove roles of user failure", expectedExceptions = AxisFault.class, expectedExceptionsMessageRegExp = "Error occurred while getting" + " database type from DB connection") public void addRemoveRolesOfUserTest() throws Exception { String[] newRoles = new String[]{FrameworkConstants.ADMIN_ROLE}; String[] deletedRoles = new String[]{newUserRole}; userMgtClient.addRemoveRolesOfUser(newUserName, newRoles, deletedRoles); fail("Roles of user must not be allowed to remove in ReadOnly Ldap"); } @Test(groups = "wso2.as", description = "Check add remove users of role failure", expectedExceptions = AxisFault.class, expectedExceptionsMessageRegExp = "Read-only user store.Roles cannot be added or modified") public void addRemoveUsersOfRoleTest() throws Exception { String[] newUsers = new String[]{asServer.getSuperTenant().getTenantAdmin().getUserName()}; String[] deletedUsers = new String[]{newUserName}; //https://wso2.org/jira/browse/IDENTITY-3433 userMgtClient.addRemoveUsersOfRole(newUserRole, newUsers, deletedUsers); fail("User roles must not be allowed to remove in ReadOnly Ldap"); } @Test(groups = "wso2.as", description = "Listing all available users") public void listAllUsersTest() throws Exception { FlaggedName[] userList = userMgtClient.listAllUsers("*", 100); assertTrue(userList.length > 0, "List all users return empty list"); assertTrue(nameExists(userList, newUserName), "User Not Exist in the user list"); } @Test(groups = "wso2.as", description = "Check list users") public void listUsersTest() throws Exception { String[] usersList = userMgtClient.listUsers("*", 100); Assert.assertNotNull(usersList, "UserList null"); assertTrue(usersList.length > 0, "List users return empty list"); } @SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE}) @AfterClass(alwaysRun = true) public void restoreServer() throws Exception { scm.restoreToLastConfiguration(); super.init(TestUserMode.SUPER_TENANT_ADMIN); userMgtClient = new UserManagementClient(backendURL, sessionCookie); if (nameExists(userMgtClient.listAllUsers(newUserName, 10), newUserName)) { userMgtClient.deleteUser(newUserName); } for(int i = 0; i < 3; i++) { if (nameExists(userMgtClient.listAllUsers(newUserName + i, 10), newUserName + i)) { userMgtClient.deleteUser(newUserName + i); } } if (userMgtClient.roleNameExists(newUserRole)) { userMgtClient.deleteRole(newUserRole); } for(int i = 0; i < 3; i++) { if (userMgtClient.roleNameExists(newUserRole + i)) { userMgtClient.deleteRole(newUserRole + i); } } } /** * Check where given input is existing on FlaggedName array * * @param allNames FlaggedName array * @param inputName input string to search * @return true if input name exist, else false */ private boolean nameExists(FlaggedName[] allNames, String inputName) { boolean exists = false; for (FlaggedName flaggedName : allNames) { String name = flaggedName.getItemName(); if (name.equals(inputName)) { exists = true; break; } else { exists = false; } } return exists; } }
apache-2.0
leeyazhou/sharding-jdbc
sharding-scaling/sharding-scaling-mysql/src/test/java/org/apache/shardingsphere/shardingscaling/mysql/MySQLLogPositionManagerTest.java
3826
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.shardingscaling.mysql; import lombok.SneakyThrows; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public final class MySQLLogPositionManagerTest { private static final String LOG_FILE_NAME = "binlog-000001"; private static final long LOG_POSITION = 4L; private static final long SERVER_ID = 555555; @Mock private DataSource dataSource; @Mock private Connection connection; @Before public void setUp() throws Exception { when(dataSource.getConnection()).thenReturn(connection); PreparedStatement positionStatement = mockPositionStatement(); when(connection.prepareStatement("SHOW MASTER STATUS")).thenReturn(positionStatement); PreparedStatement serverIdStatement = mockServerIdStatement(); when(connection.prepareStatement("SHOW VARIABLES LIKE 'server_id'")).thenReturn(serverIdStatement); } @Test public void assertGetCurrentPosition() { MySQLLogPositionManager mySQLLogManager = new MySQLLogPositionManager(dataSource); BinlogPosition actual = mySQLLogManager.getCurrentPosition(); assertThat(actual.getServerId(), is(SERVER_ID)); assertThat(actual.getFilename(), is(LOG_FILE_NAME)); assertThat(actual.getPosition(), is(LOG_POSITION)); } @Test public void assertUpdateCurrentPosition() { MySQLLogPositionManager mySQLLogManager = new MySQLLogPositionManager(dataSource); BinlogPosition expected = new BinlogPosition(LOG_FILE_NAME, LOG_POSITION, SERVER_ID); mySQLLogManager.updateCurrentPosition(expected); assertThat(mySQLLogManager.getCurrentPosition(), is(expected)); } @SneakyThrows private PreparedStatement mockPositionStatement() { PreparedStatement result = mock(PreparedStatement.class); ResultSet resultSet = mock(ResultSet.class); when(result.executeQuery()).thenReturn(resultSet); when(resultSet.next()).thenReturn(true, false); when(resultSet.getString(1)).thenReturn(LOG_FILE_NAME); when(resultSet.getLong(2)).thenReturn(LOG_POSITION); return result; } @SneakyThrows private PreparedStatement mockServerIdStatement() { PreparedStatement result = mock(PreparedStatement.class); ResultSet resultSet = mock(ResultSet.class); when(result.executeQuery()).thenReturn(resultSet); when(resultSet.next()).thenReturn(true, false); when(resultSet.getLong(2)).thenReturn(SERVER_ID); return result; } }
apache-2.0
elasticjob/elastic-job
elasticjob-infra/elasticjob-infra-common/src/main/java/org/apache/shardingsphere/elasticjob/infra/exception/JobStatisticException.java
1136
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.elasticjob.infra.exception; /** * Job statistic exception. */ public final class JobStatisticException extends RuntimeException { private static final long serialVersionUID = -2502533914008085601L; public JobStatisticException(final Exception ex) { super(ex); } }
apache-2.0
jiaphuan/models
research/object_detection/inference/detection_inference.py
5505
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utility functions for detection inference.""" from __future__ import division import tensorflow as tf from object_detection.core import standard_fields def build_input(tfrecord_paths): """Builds the graph's input. Args: tfrecord_paths: List of paths to the input TFRecords Returns: serialized_example_tensor: The next serialized example. String scalar Tensor image_tensor: The decoded image of the example. Uint8 tensor, shape=[1, None, None,3] """ filename_queue = tf.train.string_input_producer( tfrecord_paths, shuffle=False, num_epochs=1) tf_record_reader = tf.TFRecordReader() _, serialized_example_tensor = tf_record_reader.read(filename_queue) features = tf.parse_single_example( serialized_example_tensor, features={ standard_fields.TfExampleFields.image_encoded: tf.FixedLenFeature([], tf.string), }) encoded_image = features[standard_fields.TfExampleFields.image_encoded] image_tensor = tf.image.decode_image(encoded_image, channels=3) image_tensor.set_shape([None, None, 3]) image_tensor = tf.expand_dims(image_tensor, 0) return serialized_example_tensor, image_tensor def build_inference_graph(image_tensor, inference_graph_path): """Loads the inference graph and connects it to the input image. Args: image_tensor: The input image. uint8 tensor, shape=[1, None, None, 3] inference_graph_path: Path to the inference graph with embedded weights Returns: detected_boxes_tensor: Detected boxes. Float tensor, shape=[num_detections, 4] detected_scores_tensor: Detected scores. Float tensor, shape=[num_detections] detected_labels_tensor: Detected labels. Int64 tensor, shape=[num_detections] """ with tf.gfile.Open(inference_graph_path, 'r') as graph_def_file: graph_content = graph_def_file.read() graph_def = tf.GraphDef() graph_def.MergeFromString(graph_content) tf.import_graph_def( graph_def, name='', input_map={'image_tensor': image_tensor}) g = tf.get_default_graph() num_detections_tensor = tf.squeeze( g.get_tensor_by_name('num_detections:0'), 0) num_detections_tensor = tf.cast(num_detections_tensor, tf.int32) detected_boxes_tensor = tf.squeeze( g.get_tensor_by_name('detection_boxes:0'), 0) detected_boxes_tensor = detected_boxes_tensor[:num_detections_tensor] detected_scores_tensor = tf.squeeze( g.get_tensor_by_name('detection_scores:0'), 0) detected_scores_tensor = detected_scores_tensor[:num_detections_tensor] detected_labels_tensor = tf.squeeze( g.get_tensor_by_name('detection_classes:0'), 0) detected_labels_tensor = tf.cast(detected_labels_tensor, tf.int64) detected_labels_tensor = detected_labels_tensor[:num_detections_tensor] return detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor def infer_detections_and_add_to_example( serialized_example_tensor, detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor, discard_image_pixels): """Runs the supplied tensors and adds the inferred detections to the example. Args: serialized_example_tensor: Serialized TF example. Scalar string tensor detected_boxes_tensor: Detected boxes. Float tensor, shape=[num_detections, 4] detected_scores_tensor: Detected scores. Float tensor, shape=[num_detections] detected_labels_tensor: Detected labels. Int64 tensor, shape=[num_detections] discard_image_pixels: If true, discards the image from the result Returns: The de-serialized TF example augmented with the inferred detections. """ tf_example = tf.train.Example() (serialized_example, detected_boxes, detected_scores, detected_classes) = tf.get_default_session().run([ serialized_example_tensor, detected_boxes_tensor, detected_scores_tensor, detected_labels_tensor ]) detected_boxes = detected_boxes.T tf_example.ParseFromString(serialized_example) feature = tf_example.features.feature feature[standard_fields.TfExampleFields. detection_score].float_list.value[:] = detected_scores feature[standard_fields.TfExampleFields. detection_bbox_ymin].float_list.value[:] = detected_boxes[0] feature[standard_fields.TfExampleFields. detection_bbox_xmin].float_list.value[:] = detected_boxes[1] feature[standard_fields.TfExampleFields. detection_bbox_ymax].float_list.value[:] = detected_boxes[2] feature[standard_fields.TfExampleFields. detection_bbox_xmax].float_list.value[:] = detected_boxes[3] feature[standard_fields.TfExampleFields. detection_class_label].int64_list.value[:] = detected_classes if discard_image_pixels: del feature[standard_fields.TfExampleFields.image_encoded] return tf_example
apache-2.0
susinda/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb/src/org/wso2/developerstudio/eclipse/gmf/esb/MQTTSubscriptionQOS.java
6087
/** * Copyright 2009-2012 WSO2, Inc. (http://wso2.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.wso2.developerstudio.eclipse.gmf.esb; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>MQTT Subscription QOS</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getMQTTSubscriptionQOS() * @model * @generated */ public enum MQTTSubscriptionQOS implements Enumerator { /** * The '<em><b>Zero</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ZERO_VALUE * @generated * @ordered */ ZERO(0, "zero", "0"), /** * The '<em><b>One</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ONE_VALUE * @generated * @ordered */ ONE(1, "one", "1"), /** * The '<em><b>Two</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #TWO_VALUE * @generated * @ordered */ TWO(2, "two", "2"); /** * The '<em><b>Zero</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Zero</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #ZERO * @model name="zero" literal="0" * @generated * @ordered */ public static final int ZERO_VALUE = 0; /** * The '<em><b>One</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>One</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #ONE * @model name="one" literal="1" * @generated * @ordered */ public static final int ONE_VALUE = 1; /** * The '<em><b>Two</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Two</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #TWO * @model name="two" literal="2" * @generated * @ordered */ public static final int TWO_VALUE = 2; /** * An array of all the '<em><b>MQTT Subscription QOS</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final MQTTSubscriptionQOS[] VALUES_ARRAY = new MQTTSubscriptionQOS[] { ZERO, ONE, TWO, }; /** * A public read-only list of all the '<em><b>MQTT Subscription QOS</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<MQTTSubscriptionQOS> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>MQTT Subscription QOS</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static MQTTSubscriptionQOS get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { MQTTSubscriptionQOS result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>MQTT Subscription QOS</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static MQTTSubscriptionQOS getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { MQTTSubscriptionQOS result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>MQTT Subscription QOS</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static MQTTSubscriptionQOS get(int value) { switch (value) { case ZERO_VALUE: return ZERO; case ONE_VALUE: return ONE; case TWO_VALUE: return TWO; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private MQTTSubscriptionQOS(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //MQTTSubscriptionQOS
apache-2.0
googleapis/google-cloud-php
AppEngineAdmin/src/V1/UpdateServiceRequest.php
9098
<?php # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/appengine/v1/appengine.proto namespace Google\Cloud\AppEngine\V1; use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** * Request message for `Services.UpdateService`. * * Generated from protobuf message <code>google.appengine.v1.UpdateServiceRequest</code> */ class UpdateServiceRequest extends \Google\Protobuf\Internal\Message { /** * Name of the resource to update. Example: `apps/myapp/services/default`. * * Generated from protobuf field <code>string name = 1;</code> */ private $name = ''; /** * A Service resource containing the updated service. Only fields set in the * field mask will be updated. * * Generated from protobuf field <code>.google.appengine.v1.Service service = 2;</code> */ private $service = null; /** * Standard field mask for the set of fields to be updated. * * Generated from protobuf field <code>.google.protobuf.FieldMask update_mask = 3;</code> */ private $update_mask = null; /** * Set to `true` to gradually shift traffic to one or more versions that you * specify. By default, traffic is shifted immediately. * For gradual traffic migration, the target versions * must be located within instances that are configured for both * [warmup requests](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#InboundServiceType) * and * [automatic scaling](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#AutomaticScaling). * You must specify the * [`shardBy`](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services#ShardBy) * field in the Service resource. Gradual traffic migration is not * supported in the App Engine flexible environment. For examples, see * [Migrating and Splitting Traffic](https://cloud.google.com/appengine/docs/admin-api/migrating-splitting-traffic). * * Generated from protobuf field <code>bool migrate_traffic = 4;</code> */ private $migrate_traffic = false; /** * Constructor. * * @param array $data { * Optional. Data for populating the Message object. * * @type string $name * Name of the resource to update. Example: `apps/myapp/services/default`. * @type \Google\Cloud\AppEngine\V1\Service $service * A Service resource containing the updated service. Only fields set in the * field mask will be updated. * @type \Google\Protobuf\FieldMask $update_mask * Standard field mask for the set of fields to be updated. * @type bool $migrate_traffic * Set to `true` to gradually shift traffic to one or more versions that you * specify. By default, traffic is shifted immediately. * For gradual traffic migration, the target versions * must be located within instances that are configured for both * [warmup requests](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#InboundServiceType) * and * [automatic scaling](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#AutomaticScaling). * You must specify the * [`shardBy`](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services#ShardBy) * field in the Service resource. Gradual traffic migration is not * supported in the App Engine flexible environment. For examples, see * [Migrating and Splitting Traffic](https://cloud.google.com/appengine/docs/admin-api/migrating-splitting-traffic). * } */ public function __construct($data = NULL) { \GPBMetadata\Google\Appengine\V1\Appengine::initOnce(); parent::__construct($data); } /** * Name of the resource to update. Example: `apps/myapp/services/default`. * * Generated from protobuf field <code>string name = 1;</code> * @return string */ public function getName() { return $this->name; } /** * Name of the resource to update. Example: `apps/myapp/services/default`. * * Generated from protobuf field <code>string name = 1;</code> * @param string $var * @return $this */ public function setName($var) { GPBUtil::checkString($var, True); $this->name = $var; return $this; } /** * A Service resource containing the updated service. Only fields set in the * field mask will be updated. * * Generated from protobuf field <code>.google.appengine.v1.Service service = 2;</code> * @return \Google\Cloud\AppEngine\V1\Service|null */ public function getService() { return $this->service; } public function hasService() { return isset($this->service); } public function clearService() { unset($this->service); } /** * A Service resource containing the updated service. Only fields set in the * field mask will be updated. * * Generated from protobuf field <code>.google.appengine.v1.Service service = 2;</code> * @param \Google\Cloud\AppEngine\V1\Service $var * @return $this */ public function setService($var) { GPBUtil::checkMessage($var, \Google\Cloud\AppEngine\V1\Service::class); $this->service = $var; return $this; } /** * Standard field mask for the set of fields to be updated. * * Generated from protobuf field <code>.google.protobuf.FieldMask update_mask = 3;</code> * @return \Google\Protobuf\FieldMask|null */ public function getUpdateMask() { return $this->update_mask; } public function hasUpdateMask() { return isset($this->update_mask); } public function clearUpdateMask() { unset($this->update_mask); } /** * Standard field mask for the set of fields to be updated. * * Generated from protobuf field <code>.google.protobuf.FieldMask update_mask = 3;</code> * @param \Google\Protobuf\FieldMask $var * @return $this */ public function setUpdateMask($var) { GPBUtil::checkMessage($var, \Google\Protobuf\FieldMask::class); $this->update_mask = $var; return $this; } /** * Set to `true` to gradually shift traffic to one or more versions that you * specify. By default, traffic is shifted immediately. * For gradual traffic migration, the target versions * must be located within instances that are configured for both * [warmup requests](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#InboundServiceType) * and * [automatic scaling](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#AutomaticScaling). * You must specify the * [`shardBy`](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services#ShardBy) * field in the Service resource. Gradual traffic migration is not * supported in the App Engine flexible environment. For examples, see * [Migrating and Splitting Traffic](https://cloud.google.com/appengine/docs/admin-api/migrating-splitting-traffic). * * Generated from protobuf field <code>bool migrate_traffic = 4;</code> * @return bool */ public function getMigrateTraffic() { return $this->migrate_traffic; } /** * Set to `true` to gradually shift traffic to one or more versions that you * specify. By default, traffic is shifted immediately. * For gradual traffic migration, the target versions * must be located within instances that are configured for both * [warmup requests](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#InboundServiceType) * and * [automatic scaling](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#AutomaticScaling). * You must specify the * [`shardBy`](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services#ShardBy) * field in the Service resource. Gradual traffic migration is not * supported in the App Engine flexible environment. For examples, see * [Migrating and Splitting Traffic](https://cloud.google.com/appengine/docs/admin-api/migrating-splitting-traffic). * * Generated from protobuf field <code>bool migrate_traffic = 4;</code> * @param bool $var * @return $this */ public function setMigrateTraffic($var) { GPBUtil::checkBool($var); $this->migrate_traffic = $var; return $this; } }
apache-2.0
mahak/vitess
go/vt/vitessdriver/rows.go
1421
/* Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package vitessdriver import ( "database/sql/driver" "io" "vitess.io/vitess/go/sqltypes" ) // rows creates a database/sql/driver compliant Row iterator // for a non-streaming QueryResult. type rows struct { convert *converter qr *sqltypes.Result index int } // newRows creates a new rows from qr. func newRows(qr *sqltypes.Result, c *converter) driver.Rows { return &rows{qr: qr, convert: c} } func (ri *rows) Columns() []string { cols := make([]string, 0, len(ri.qr.Fields)) for _, field := range ri.qr.Fields { cols = append(cols, field.Name) } return cols } func (ri *rows) Close() error { return nil } func (ri *rows) Next(dest []driver.Value) error { if ri.index == len(ri.qr.Rows) { return io.EOF } if err := ri.convert.populateRow(dest, ri.qr.Rows[ri.index]); err != nil { return err } ri.index++ return nil }
apache-2.0
mbiang/cloudformstest
Automate/CloudFormsPOC/Integration/Amazon/RDS.class/__methods__/createrdsinstance.rb
4574
begin @task = nil @service = nil # Simple logging method def log(level, msg) $evm.log(level, msg) end # Error logging convenience def log_err(err) log(:error, "#{err.class} #{err}") log(:error, "#{err.backtrace.join("\n")}") end # standard dump of $evm.root def dump_root() log(:info, "Root:<$evm.root> Begin $evm.root.attributes") $evm.root.attributes.sort.each { |k, v| log(:info, "Root:<$evm.root> Attribute - #{k}: #{v}")} log(:info, "Root:<$evm.root> End $evm.root.attributes") log(:info, "") end # convenience method to get an AWS::RDS Object using # the AWS EVM Management System def get_rds_from_management_system(ext_management_system) AWS.config( :access_key_id => ext_management_system.authentication_userid, :secret_access_key => ext_management_system.authentication_password, :region => ext_management_system.provider_region ) return AWS::RDS.new() end # Get the AWS Management System from teh various options available def get_mgt_system() aws_mgt = nil if @task if @task.get_option(:mid) aws_mgt = $evm.vmdb(:ems_amazon).find_by_id(@task.get_option(:mid)) log(:info, "Got AWS Mgt System from @task.get_option(:mid)") end elsif $evm.root['vm'] vm = $evm.root['vm'] aws_mgt = vm.ext_management_system log(:info, "Got AWS Mgt System from VM #{vm.name}") else aws_mgt = $evm.vmdb(:ems_amazon).first log(:info, "Got First Available AWS Mgt System from VMDB") end return aws_mgt end # Get the Relevant RDS Options from the available # Service Template Provisioning Task Options def get_rds_options_hash() options_regex = /^rds_(.*)/ options_hash = {} @task.options.each {|key, value| if options_regex =~ key newkey = "#{key}" newkey.sub! "rds_", "" integer_regex = /^\d+$/ options_hash[:"#{newkey}"] = value options_hash[:"#{newkey}"] = value.to_i if integer_regex =~ value log(:info, "Set :#{newkey} => #{value}") end } log(:info, "Returning Options Hash: #{options_hash.inspect}") return options_hash end # BEGIN MAIN # log(:info, "Begin Automate Method") dump_root # Get the task object from root @task = $evm.root['service_template_provision_task'] if @task # List Service Task Attributes @task.attributes.sort.each { |k, v| log(:info, "#{@method} - Task:<#{@task}> Attributes - #{k}: #{v}")} # Get destination service object @service = @task.destination log(:info,"Detected Service:<#{@service.name}> Id:<#{@service.id}>") end require 'aws-sdk' # get the AWS Management System Object aws_mgt = get_mgt_system log(:info, "AWS Mgt System is #{aws_mgt.inspect}") # Get an RDS Client Object via the AWS SDK client = get_rds_from_management_system(aws_mgt).client log(:info, "Got AWS-SDK RDS Client: #{client.inspect}") # Get the relevant RDS Options hash from the provisioning task # these will be passed unchanged to create_db_instance. It is up to # the catalog item initialization to validate and process these into # options on the task item options_hash = get_rds_options_hash log(:info, "Creating RDS Instace with options: #{options_hash.inspect}") db_instance = client.create_db_instance(options_hash) log(:info, "DB Instance Created: #{db_instance.inspect}") # The instance is now in creating state, set some attributes on the service object @service.custom_set("rds_db_instance_identifier", db_instance[:db_instance_identifier]) @service.custom_set("rds_preferred_backup_window", db_instance[:preferred_backup_window]) @service.custom_set("rds_engine", "#{db_instance[:engine]} #{db_instance[:engine_version]}") @service.custom_set("rds_db_instance_class", db_instance[:db_instance_class]) @service.custom_set("rds_publicly_accessible", db_instance[:publicly_accessible].to_s) @service.custom_set("MID", "#{aws_mgt.id}") # Make sure these options are available so they can be used for notification later # (if needed) @task.set_option(:rds_engine_version, db_instance[:engine_version]) @task.set_option(:rds_engine, db_instance[:engine]) # End this automate method log(:info, "End Automate Method") # END MAIN # rescue => err log_err(err) $evm.root['ae_result'] = "error" @task.message = "Error Provisioning RDS Instance: #{err.class} '#{err}'" @service.remove_from_vmdb if @service && @task && @task.get_option(:remove_from_vmdb_on_fail) exit MIQ_ABORT end
apache-2.0
attila-kiss-it/querydsl
querydsl-codegen-utils/src/main/java/com/querydsl/codegen/utils/MethodEvaluator.java
1886
/* * Copyright 2010, Mysema Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.querydsl.codegen.utils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; /** * @author tiwe * * @param <T> */ public final class MethodEvaluator<T> implements Evaluator<T> { private final Method method; private final Class<? extends T> projectionType; private final Object[] args; MethodEvaluator(Method method, Map<String, Object> constants, Class<? extends T> projectionType) { this.method = method; this.projectionType = projectionType; this.args = new Object[method.getParameterTypes().length]; int i = args.length - constants.size(); for (Object value : constants.values()) { args[i++] = value; } } @SuppressWarnings("unchecked") @Override public T evaluate(Object... args) { try { System.arraycopy(args, 0, this.args, 0, args.length); return (T) method.invoke(null, this.args); } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } catch (InvocationTargetException e) { throw new IllegalArgumentException(e); } } @Override public Class<? extends T> getType() { return projectionType; } }
apache-2.0
xstefank/SilverWare-Demos
demos/openalt-2015/src/main/java/io/silverware/demos/openalt/RegisterTemperature.java
1943
/* * -----------------------------------------------------------------------\ * SilverWare *   * Copyright (C) 2010 - 2013 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 io.silverware.demos.openalt; import java.util.Collections; import javax.inject.Inject; import io.silverware.microservices.annotations.Gateway; import io.silverware.microservices.annotations.Microservice; import io.silverware.microservices.annotations.MicroserviceReference; import io.silverware.microservices.providers.cdi.builtin.Storage; /** * @author <a href="mailto:marvenec@gmail.com">Martin Večeřa</a> */ @Microservice @Gateway public class RegisterTemperature { @Inject @MicroserviceReference private ValueFilter valueFilter; @Inject @MicroserviceReference private InfluxDBWriter influxDBWriter; public void temperature(final String sensorId, final int celsius) { valueFilter.change(sensorId + ".temperature", celsius, t -> { influxDBWriter.write("sensors", "temperature", Collections.singletonMap("value", t)); }); } public void humidity(final String sensorId, final int relHumidity) { valueFilter.change(sensorId + ".humidity", relHumidity, h -> { influxDBWriter.write("sensors", "humidity", Collections.singletonMap("value", h)); }); } }
apache-2.0
jwren/intellij-community
plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/NestedMemberAccess.java
16593
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.java.decompiler.main.rels; import org.jetbrains.java.decompiler.code.CodeConstants; import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; import org.jetbrains.java.decompiler.main.DecompilerContext; import org.jetbrains.java.decompiler.main.collectors.CounterContainer; import org.jetbrains.java.decompiler.main.collectors.VarNamesCollector; import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; import org.jetbrains.java.decompiler.modules.decompiler.exps.*; import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph; import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectNode; import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPair; import org.jetbrains.java.decompiler.struct.StructMethod; import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; import org.jetbrains.java.decompiler.util.InterpreterUtil; import java.util.*; public class NestedMemberAccess { private enum MethodAccess {NORMAL, FIELD_GET, FIELD_SET, METHOD, FUNCTION} private boolean noSynthFlag; private final Map<MethodWrapper, MethodAccess> mapMethodType = new HashMap<>(); public void propagateMemberAccess(ClassNode root) { if (root.nested.isEmpty()) { return; } noSynthFlag = DecompilerContext.getOption(IFernflowerPreferences.SYNTHETIC_NOT_SET); computeMethodTypes(root); eliminateStaticAccess(root); } private void computeMethodTypes(ClassNode node) { if (node.type == ClassNode.CLASS_LAMBDA) { return; } for (ClassNode nd : node.nested) { computeMethodTypes(nd); } for (MethodWrapper method : node.getWrapper().getMethods()) { computeMethodType(node, method); } } private void computeMethodType(ClassNode node, MethodWrapper method) { MethodAccess type = MethodAccess.NORMAL; if (method.root != null) { DirectGraph graph = method.getOrBuildGraph(); StructMethod mt = method.methodStruct; if ((noSynthFlag || mt.isSynthetic()) && mt.hasModifier(CodeConstants.ACC_STATIC)) { if (graph.nodes.size() == 2) { // incl. dummy exit node if (graph.first.exprents.size() == 1) { Exprent exprent = graph.first.exprents.get(0); MethodDescriptor mtdesc = MethodDescriptor.parseDescriptor(mt.getDescriptor()); int parcount = mtdesc.params.length; Exprent exprCore = exprent; if (exprent.type == Exprent.EXPRENT_EXIT) { ExitExprent exexpr = (ExitExprent)exprent; if (exexpr.getExitType() == ExitExprent.EXIT_RETURN && exexpr.getValue() != null) { exprCore = exexpr.getValue(); } } switch (exprCore.type) { case Exprent.EXPRENT_FIELD: FieldExprent fexpr = (FieldExprent)exprCore; if ((parcount == 1 && !fexpr.isStatic()) || (parcount == 0 && fexpr.isStatic())) { if (fexpr.getClassname().equals(node.classStruct.qualifiedName)) { // FIXME: check for private flag of the field if (fexpr.isStatic() || (fexpr.getInstance().type == Exprent.EXPRENT_VAR && ((VarExprent)fexpr.getInstance()).getIndex() == 0)) { type = MethodAccess.FIELD_GET; } } } break; case Exprent.EXPRENT_VAR: // qualified this if (parcount == 1) { // this or final variable if (((VarExprent)exprCore).getIndex() != 0) { type = MethodAccess.FIELD_GET; } } break; case Exprent.EXPRENT_FUNCTION: // for now detect only increment/decrement FunctionExprent functionExprent = (FunctionExprent)exprCore; if (functionExprent.getFuncType() >= FunctionExprent.FUNCTION_IMM && functionExprent.getFuncType() <= FunctionExprent.FUNCTION_PPI) { if (functionExprent.getLstOperands().get(0).type == Exprent.EXPRENT_FIELD) { type = MethodAccess.FUNCTION; } } break; case Exprent.EXPRENT_INVOCATION: type = MethodAccess.METHOD; break; case Exprent.EXPRENT_ASSIGNMENT: AssignmentExprent asexpr = (AssignmentExprent)exprCore; if (asexpr.getLeft().type == Exprent.EXPRENT_FIELD && asexpr.getRight().type == Exprent.EXPRENT_VAR) { FieldExprent fexpras = (FieldExprent)asexpr.getLeft(); if ((parcount == 2 && !fexpras.isStatic()) || (parcount == 1 && fexpras.isStatic())) { if (fexpras.getClassname().equals(node.classStruct.qualifiedName)) { // FIXME: check for private flag of the field if (fexpras.isStatic() || (fexpras.getInstance().type == Exprent.EXPRENT_VAR && ((VarExprent)fexpras.getInstance()).getIndex() == 0)) { if (((VarExprent)asexpr.getRight()).getIndex() == parcount - 1) { type = MethodAccess.FIELD_SET; } } } } } } if (type == MethodAccess.METHOD) { // FIXME: check for private flag of the method type = MethodAccess.NORMAL; InvocationExprent invexpr = (InvocationExprent)exprCore; boolean isStatic = invexpr.isStatic(); if ((isStatic && invexpr.getParameters().size() == parcount) || (!isStatic && invexpr.getInstance().type == Exprent.EXPRENT_VAR && ((VarExprent)invexpr.getInstance()).getIndex() == 0 && invexpr.getParameters().size() == parcount - 1)) { boolean equalpars = true; int index = isStatic ? 0 : 1; for (int i = 0; i < invexpr.getParameters().size(); i++) { Exprent parexpr = invexpr.getParameters().get(i); if (parexpr.type != Exprent.EXPRENT_VAR || ((VarExprent)parexpr).getIndex() != index) { equalpars = false; break; } index += mtdesc.params[i + (isStatic ? 0 : 1)].stackSize; } if (equalpars) { type = MethodAccess.METHOD; } } } } else if (graph.first.exprents.size() == 2) { Exprent exprentFirst = graph.first.exprents.get(0); Exprent exprentSecond = graph.first.exprents.get(1); if (exprentFirst.type == Exprent.EXPRENT_ASSIGNMENT && exprentSecond.type == Exprent.EXPRENT_EXIT) { MethodDescriptor mtdesc = MethodDescriptor.parseDescriptor(mt.getDescriptor()); int parcount = mtdesc.params.length; AssignmentExprent asexpr = (AssignmentExprent)exprentFirst; if (asexpr.getLeft().type == Exprent.EXPRENT_FIELD && asexpr.getRight().type == Exprent.EXPRENT_VAR) { FieldExprent fexpras = (FieldExprent)asexpr.getLeft(); if ((parcount == 2 && !fexpras.isStatic()) || (parcount == 1 && fexpras.isStatic())) { if (fexpras.getClassname().equals(node.classStruct.qualifiedName)) { // FIXME: check for private flag of the field if (fexpras.isStatic() || (fexpras.getInstance().type == Exprent.EXPRENT_VAR && ((VarExprent)fexpras.getInstance()).getIndex() == 0)) { if (((VarExprent)asexpr.getRight()).getIndex() == parcount - 1) { ExitExprent exexpr = (ExitExprent)exprentSecond; if (exexpr.getExitType() == ExitExprent.EXIT_RETURN && exexpr.getValue() != null) { if (exexpr.getValue().type == Exprent.EXPRENT_VAR && ((VarExprent)asexpr.getRight()).getIndex() == parcount - 1) { type = MethodAccess.FIELD_SET; } } } } } } } } } } } } if (type != MethodAccess.NORMAL) { mapMethodType.put(method, type); } else { mapMethodType.remove(method); } } private void eliminateStaticAccess(ClassNode node) { if (node.type == ClassNode.CLASS_LAMBDA) { return; } for (MethodWrapper meth : node.getWrapper().getMethods()) { if (meth.root != null) { boolean replaced = false; DirectGraph graph = meth.getOrBuildGraph(); HashSet<DirectNode> setVisited = new HashSet<>(); LinkedList<DirectNode> stack = new LinkedList<>(); stack.add(graph.first); while (!stack.isEmpty()) { // TODO: replace with interface iterator? DirectNode nd = stack.removeFirst(); if (setVisited.contains(nd)) { continue; } setVisited.add(nd); for (int i = 0; i < nd.exprents.size(); i++) { Exprent exprent = nd.exprents.get(i); replaced |= replaceInvocations(node, meth, exprent); if (exprent.type == Exprent.EXPRENT_INVOCATION) { Exprent ret = replaceAccessExprent(node, meth, (InvocationExprent)exprent); if (ret != null) { nd.exprents.set(i, ret); replaced = true; } } } stack.addAll(nd.successors); } if (replaced) { computeMethodType(node, meth); } } } for (ClassNode child : node.nested) { eliminateStaticAccess(child); } } private boolean replaceInvocations(ClassNode caller, MethodWrapper meth, Exprent exprent) { boolean res = false; for (Exprent expr : exprent.getAllExprents()) { res |= replaceInvocations(caller, meth, expr); } while (true) { boolean found = false; for (Exprent expr : exprent.getAllExprents()) { if (expr.type == Exprent.EXPRENT_INVOCATION) { Exprent newexpr = replaceAccessExprent(caller, meth, (InvocationExprent)expr); if (newexpr != null) { exprent.replaceExprent(expr, newexpr); found = true; res = true; break; } } } if (!found) { break; } } return res; } private static boolean sameTree(ClassNode caller, ClassNode callee) { if (caller.classStruct.qualifiedName.equals(callee.classStruct.qualifiedName)) { return false; } while (caller.parent != null) { caller = caller.parent; } while (callee.parent != null) { callee = callee.parent; } return caller == callee; } private Exprent replaceAccessExprent(ClassNode caller, MethodWrapper methdest, InvocationExprent invexpr) { ClassNode node = DecompilerContext.getClassProcessor().getMapRootClasses().get(invexpr.getClassName()); MethodWrapper methsource = null; if (node != null && node.getWrapper() != null) { methsource = node.getWrapper().getMethodWrapper(invexpr.getName(), invexpr.getStringDescriptor()); } if (methsource == null || !mapMethodType.containsKey(methsource)) { return null; } // if same method, return if (node.classStruct.qualifiedName.equals(caller.classStruct.qualifiedName) && methsource.methodStruct.getName().equals(methdest.methodStruct.getName()) && methsource.methodStruct.getDescriptor().equals(methdest.methodStruct.getDescriptor())) { // no recursive invocations permitted! return null; } MethodAccess type = mapMethodType.get(methsource); // // FIXME: impossible case. MethodAccess.NORMAL is not saved in the map // if(type == MethodAccess.NORMAL) { // return null; // } if (!sameTree(caller, node)) { return null; } DirectGraph graph = methsource.getOrBuildGraph(); Exprent source = graph.first.exprents.get(0); Exprent retexprent = null; switch (type) { case FIELD_GET: ExitExprent exsource = (ExitExprent)source; if (exsource.getValue().type == Exprent.EXPRENT_VAR) { // qualified this VarExprent var = (VarExprent)exsource.getValue(); String varname = methsource.varproc.getVarName(new VarVersionPair(var)); if (!methdest.setOuterVarNames.contains(varname)) { VarNamesCollector vnc = new VarNamesCollector(); vnc.addName(varname); methdest.varproc.refreshVarNames(vnc); methdest.setOuterVarNames.add(varname); } int index = methdest.counter.getCounterAndIncrement(CounterContainer.VAR_COUNTER); VarExprent ret = new VarExprent(index, var.getVarType(), methdest.varproc); methdest.varproc.setVarName(new VarVersionPair(index, 0), varname); retexprent = ret; } else { // field FieldExprent ret = (FieldExprent)exsource.getValue().copy(); if (!ret.isStatic()) { ret.replaceExprent(ret.getInstance(), invexpr.getParameters().get(0)); } retexprent = ret; } break; case FIELD_SET: AssignmentExprent ret; if (source.type == Exprent.EXPRENT_EXIT) { ExitExprent extex = (ExitExprent)source; ret = (AssignmentExprent)extex.getValue().copy(); } else { ret = (AssignmentExprent)source.copy(); } FieldExprent fexpr = (FieldExprent)ret.getLeft(); if (fexpr.isStatic()) { ret.replaceExprent(ret.getRight(), invexpr.getParameters().get(0)); } else { ret.replaceExprent(ret.getRight(), invexpr.getParameters().get(1)); fexpr.replaceExprent(fexpr.getInstance(), invexpr.getParameters().get(0)); } // do not use copied bytecodes ret.getLeft().bytecode = null; ret.getRight().bytecode = null; retexprent = ret; break; case FUNCTION: retexprent = replaceFunction(invexpr, source); break; case METHOD: if (source.type == Exprent.EXPRENT_EXIT) { source = ((ExitExprent)source).getValue(); } InvocationExprent invret = (InvocationExprent)source.copy(); int index = 0; if (!invret.isStatic()) { invret.replaceExprent(invret.getInstance(), invexpr.getParameters().get(0)); index = 1; } for (int i = 0; i < invret.getParameters().size(); i++) { invret.replaceExprent(invret.getParameters().get(i), invexpr.getParameters().get(i + index)); } retexprent = invret; } if (retexprent != null) { // preserve original bytecodes retexprent.bytecode = null; retexprent.addBytecodeOffsets(invexpr.bytecode); // hide synthetic access method boolean hide = true; if (node.type == ClassNode.CLASS_ROOT || (node.access & CodeConstants.ACC_STATIC) != 0) { StructMethod mt = methsource.methodStruct; if (!mt.isSynthetic()) { hide = false; } } if (hide) { node.getWrapper().getHiddenMembers().add(InterpreterUtil.makeUniqueKey(invexpr.getName(), invexpr.getStringDescriptor())); } } return retexprent; } private static Exprent replaceFunction(final InvocationExprent invexpr, final Exprent source) { FunctionExprent functionExprent = (FunctionExprent)((ExitExprent)source).getValue().copy(); List<Exprent> lstParameters = invexpr.getParameters(); FieldExprent fieldExprent = (FieldExprent)functionExprent.getLstOperands().get(0); if (fieldExprent.isStatic()) { if (!lstParameters.isEmpty()) { return null; } return functionExprent; } if (lstParameters.size() != 1) { return null; } fieldExprent.replaceExprent(fieldExprent.getInstance(), lstParameters.get(0)); return functionExprent; } }
apache-2.0
yugangw-msft/azure-sdk-for-net
sdk/insights/Azure.ResourceManager.Insights/src/Generated/Models/LogSearchRuleResourceCollection.Serialization.cs
1398
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Insights.Models { public partial class LogSearchRuleResourceCollection { internal static LogSearchRuleResourceCollection DeserializeLogSearchRuleResourceCollection(JsonElement element) { Optional<IReadOnlyList<LogSearchRuleResource>> value = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("value")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<LogSearchRuleResource> array = new List<LogSearchRuleResource>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(LogSearchRuleResource.DeserializeLogSearchRuleResource(item)); } value = array; continue; } } return new LogSearchRuleResourceCollection(Optional.ToList(value)); } } }
apache-2.0
bradtm/pulsar
pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/SimpleLoadManagerImplTest.java
26093
/** * 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.pulsar.broker.loadbalance; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.lang.reflect.Field; import java.net.InetAddress; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.apache.bookkeeper.test.PortManager; import org.apache.bookkeeper.util.ZkUtils; import org.apache.commons.lang3.SystemUtils; import org.apache.pulsar.broker.PulsarService; import org.apache.pulsar.broker.ServiceConfiguration; import org.apache.pulsar.broker.admin.AdminResource; import org.apache.pulsar.broker.cache.ResourceQuotaCache; import org.apache.pulsar.broker.loadbalance.BrokerHostUsage; import org.apache.pulsar.broker.loadbalance.LoadManager; import org.apache.pulsar.broker.loadbalance.LoadRanker; import org.apache.pulsar.broker.loadbalance.LoadReport; import org.apache.pulsar.broker.loadbalance.LoadResourceQuotaUpdaterTask; import org.apache.pulsar.broker.loadbalance.LoadSheddingTask; import org.apache.pulsar.broker.loadbalance.ResourceUnit; import org.apache.pulsar.broker.loadbalance.impl.GenericBrokerHostUsageImpl; import org.apache.pulsar.broker.loadbalance.impl.LinuxBrokerHostUsageImpl; import org.apache.pulsar.broker.loadbalance.impl.PulsarLoadReportImpl; import org.apache.pulsar.broker.loadbalance.impl.PulsarResourceDescription; import org.apache.pulsar.broker.loadbalance.impl.ResourceAvailabilityRanker; import org.apache.pulsar.broker.loadbalance.impl.SimpleLoadCalculatorImpl; import org.apache.pulsar.broker.loadbalance.impl.SimpleLoadManagerImpl; import org.apache.pulsar.broker.loadbalance.impl.SimpleResourceUnit; import org.apache.pulsar.client.admin.BrokerStats; import org.apache.pulsar.client.admin.PulsarAdmin; import org.apache.pulsar.client.api.Authentication; import org.apache.pulsar.common.naming.NamespaceBundle; import org.apache.pulsar.common.naming.NamespaceName; import org.apache.pulsar.common.policies.data.AutoFailoverPolicyData; import org.apache.pulsar.common.policies.data.AutoFailoverPolicyType; import org.apache.pulsar.common.policies.data.NamespaceIsolationData; import org.apache.pulsar.common.policies.data.ResourceQuota; import org.apache.pulsar.common.policies.impl.NamespaceIsolationPolicies; import org.apache.pulsar.common.util.ObjectMapperFactory; import org.apache.pulsar.policies.data.loadbalancer.BrokerUsage; import org.apache.pulsar.policies.data.loadbalancer.JvmUsage; import org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats; import org.apache.pulsar.policies.data.loadbalancer.ResourceUnitRanking; import org.apache.pulsar.policies.data.loadbalancer.ResourceUsage; import org.apache.pulsar.policies.data.loadbalancer.SystemResourceUsage; import org.apache.pulsar.zookeeper.LocalBookkeeperEnsemble; import org.apache.pulsar.zookeeper.LocalZooKeeperCache; import org.apache.pulsar.zookeeper.ZooKeeperChildrenCache; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Sets; import jersey.repackaged.com.google.common.collect.Maps; /** */ public class SimpleLoadManagerImplTest { LocalBookkeeperEnsemble bkEnsemble; URL url1; PulsarService pulsar1; PulsarAdmin admin1; URL url2; PulsarService pulsar2; PulsarAdmin admin2; BrokerStats brokerStatsClient1; BrokerStats brokerStatsClient2; String primaryHost; String secondaryHost; ExecutorService executor = new ThreadPoolExecutor(5, 20, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); private final int ZOOKEEPER_PORT = PortManager.nextFreePort(); private final int PRIMARY_BROKER_WEBSERVICE_PORT = PortManager.nextFreePort(); private final int SECONDARY_BROKER_WEBSERVICE_PORT = PortManager.nextFreePort(); private final int PRIMARY_BROKER_PORT = PortManager.nextFreePort(); private final int SECONDARY_BROKER_PORT = PortManager.nextFreePort(); private static final Logger log = LoggerFactory.getLogger(SimpleLoadManagerImplTest.class); static { System.setProperty("test.basePort", "16100"); } @BeforeMethod void setup() throws Exception { // Start local bookkeeper ensemble bkEnsemble = new LocalBookkeeperEnsemble(3, ZOOKEEPER_PORT, PortManager.nextFreePort()); bkEnsemble.start(); // Start broker 1 ServiceConfiguration config1 = spy(new ServiceConfiguration()); config1.setClusterName("use"); config1.setWebServicePort(PRIMARY_BROKER_WEBSERVICE_PORT); config1.setZookeeperServers("127.0.0.1" + ":" + ZOOKEEPER_PORT); config1.setBrokerServicePort(PRIMARY_BROKER_PORT); pulsar1 = new PulsarService(config1); pulsar1.start(); url1 = new URL("http://127.0.0.1" + ":" + PRIMARY_BROKER_WEBSERVICE_PORT); admin1 = new PulsarAdmin(url1, (Authentication) null); brokerStatsClient1 = admin1.brokerStats(); primaryHost = String.format("http://%s:%d", InetAddress.getLocalHost().getHostName(), PRIMARY_BROKER_WEBSERVICE_PORT); // Start broker 2 ServiceConfiguration config2 = new ServiceConfiguration(); config2.setClusterName("use"); config2.setWebServicePort(SECONDARY_BROKER_WEBSERVICE_PORT); config2.setZookeeperServers("127.0.0.1" + ":" + ZOOKEEPER_PORT); config2.setBrokerServicePort(SECONDARY_BROKER_PORT); pulsar2 = new PulsarService(config2); pulsar2.start(); url2 = new URL("http://127.0.0.1" + ":" + SECONDARY_BROKER_WEBSERVICE_PORT); admin2 = new PulsarAdmin(url2, (Authentication) null); brokerStatsClient2 = admin2.brokerStats(); secondaryHost = String.format("http://%s:%d", InetAddress.getLocalHost().getHostName(), SECONDARY_BROKER_WEBSERVICE_PORT); Thread.sleep(100); } @AfterMethod void shutdown() throws Exception { log.info("--- Shutting down ---"); executor.shutdown(); admin1.close(); admin2.close(); pulsar2.close(); pulsar1.close(); bkEnsemble.stop(); } private void createNamespacePolicies(PulsarService pulsar) throws Exception { NamespaceIsolationPolicies policies = new NamespaceIsolationPolicies(); // set up policy that use this broker as primary NamespaceIsolationData policyData = new NamespaceIsolationData(); policyData.namespaces = new ArrayList<String>(); policyData.namespaces.add("pulsar/use/primary-ns.*"); policyData.primary = new ArrayList<String>(); policyData.primary.add(pulsar1.getAdvertisedAddress() + "*"); policyData.secondary = new ArrayList<String>(); policyData.secondary.add("prod2-broker([78]).messaging.usw.example.co.*"); policyData.auto_failover_policy = new AutoFailoverPolicyData(); policyData.auto_failover_policy.policy_type = AutoFailoverPolicyType.min_available; policyData.auto_failover_policy.parameters = new HashMap<String, String>(); policyData.auto_failover_policy.parameters.put("min_limit", "1"); policyData.auto_failover_policy.parameters.put("usage_threshold", "100"); policies.setPolicy("primaryBrokerPolicy", policyData); ObjectMapper jsonMapper = ObjectMapperFactory.create(); ZooKeeper globalZk = pulsar.getGlobalZkCache().getZooKeeper(); ZkUtils.createFullPathOptimistic(globalZk, AdminResource.path("clusters", "use", "namespaceIsolationPolicies"), new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); byte[] content = jsonMapper.writeValueAsBytes(policies.getPolicies()); globalZk.setData(AdminResource.path("clusters", "use", "namespaceIsolationPolicies"), content, -1); } @Test(enabled = true) public void testBasicBrokerSelection() throws Exception { LoadManager loadManager = new SimpleLoadManagerImpl(pulsar1); PulsarResourceDescription rd = new PulsarResourceDescription(); rd.put("memory", new ResourceUsage(1024, 4096)); rd.put("cpu", new ResourceUsage(10, 100)); rd.put("bandwidthIn", new ResourceUsage(250 * 1024, 1024 * 1024)); rd.put("bandwidthOut", new ResourceUsage(550 * 1024, 1024 * 1024)); ResourceUnit ru1 = new SimpleResourceUnit("http://prod2-broker7.messaging.usw.example.com:8080", rd); Set<ResourceUnit> rus = new HashSet<ResourceUnit>(); rus.add(ru1); LoadRanker lr = new ResourceAvailabilityRanker(); AtomicReference<Map<Long, Set<ResourceUnit>>> sortedRankingsInstance = new AtomicReference<>(Maps.newTreeMap()); sortedRankingsInstance.get().put(lr.getRank(rd), rus); Field sortedRankings = SimpleLoadManagerImpl.class.getDeclaredField("sortedRankings"); sortedRankings.setAccessible(true); sortedRankings.set(loadManager, sortedRankingsInstance); ResourceUnit found = ((SimpleLoadManagerImpl) loadManager) .getLeastLoaded(new NamespaceName("pulsar/use/primary-ns.10")); // broker is not active so found should be null assertEquals(found, null, "found a broker when expected none to be found"); } private void setObjectField(Class objClass, Object objInstance, String fieldName, Object newValue) throws Exception { Field field = objClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(objInstance, newValue); } @Test(enabled = true) public void testPrimary() throws Exception { createNamespacePolicies(pulsar1); LoadManager loadManager = new SimpleLoadManagerImpl(pulsar1); PulsarResourceDescription rd = new PulsarResourceDescription(); rd.put("memory", new ResourceUsage(1024, 4096)); rd.put("cpu", new ResourceUsage(10, 100)); rd.put("bandwidthIn", new ResourceUsage(250 * 1024, 1024 * 1024)); rd.put("bandwidthOut", new ResourceUsage(550 * 1024, 1024 * 1024)); ResourceUnit ru1 = new SimpleResourceUnit( "http://" + pulsar1.getAdvertisedAddress() + ":" + pulsar1.getConfiguration().getWebServicePort(), rd); Set<ResourceUnit> rus = new HashSet<ResourceUnit>(); rus.add(ru1); LoadRanker lr = new ResourceAvailabilityRanker(); // inject the load report and rankings Map<ResourceUnit, org.apache.pulsar.policies.data.loadbalancer.LoadReport> loadReports = new HashMap<>(); org.apache.pulsar.policies.data.loadbalancer.LoadReport loadReport = new org.apache.pulsar.policies.data.loadbalancer.LoadReport(); loadReport.setSystemResourceUsage(new SystemResourceUsage()); loadReports.put(ru1, loadReport); setObjectField(SimpleLoadManagerImpl.class, loadManager, "currentLoadReports", loadReports); ResourceUnitRanking ranking = new ResourceUnitRanking(loadReport.getSystemResourceUsage(), new HashSet<String>(), new ResourceQuota(), new HashSet<String>(), new ResourceQuota()); Map<ResourceUnit, ResourceUnitRanking> rankings = new HashMap<>(); rankings.put(ru1, ranking); setObjectField(SimpleLoadManagerImpl.class, loadManager, "resourceUnitRankings", rankings); AtomicReference<Map<Long, Set<ResourceUnit>>> sortedRankingsInstance = new AtomicReference<>(Maps.newTreeMap()); sortedRankingsInstance.get().put(lr.getRank(rd), rus); setObjectField(SimpleLoadManagerImpl.class, loadManager, "sortedRankings", sortedRankingsInstance); ResourceUnit found = ((SimpleLoadManagerImpl) loadManager) .getLeastLoaded(new NamespaceName("pulsar/use/primary-ns.10")); // broker is not active so found should be null assertNotEquals(found, null, "did not find a broker when expected one to be found"); } @Test(enabled = false) public void testPrimarySecondary() throws Exception { createNamespacePolicies(pulsar1); LocalZooKeeperCache mockCache = mock(LocalZooKeeperCache.class); ZooKeeperChildrenCache zooKeeperChildrenCache = mock(ZooKeeperChildrenCache.class); Set<String> activeBrokers = Sets.newHashSet("prod2-broker7.messaging.use.example.com:8080", "prod2-broker8.messaging.use.example.com:8080", "prod2-broker9.messaging.use.example.com:8080"); when(mockCache.getChildren(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT)).thenReturn(activeBrokers); when(zooKeeperChildrenCache.get()).thenReturn(activeBrokers); when(zooKeeperChildrenCache.get(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT)).thenReturn(activeBrokers); Field zkCacheField = PulsarService.class.getDeclaredField("localZkCache"); zkCacheField.setAccessible(true); LocalZooKeeperCache originalLZK1 = (LocalZooKeeperCache) zkCacheField.get(pulsar1); LocalZooKeeperCache originalLZK2 = (LocalZooKeeperCache) zkCacheField.get(pulsar2); log.info("lzk are {} 2: {}", originalLZK1.getChildren(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT), originalLZK2.getChildren(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT)); zkCacheField.set(pulsar1, mockCache); LocalZooKeeperCache newZk = (LocalZooKeeperCache) pulsar1.getLocalZkCache(); log.info("lzk mocked are {}", newZk.getChildren(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT)); ZooKeeperChildrenCache availableActiveBrokers = new ZooKeeperChildrenCache(pulsar1.getLocalZkCache(), SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT); log.info("lzk mocked active brokers are {}", availableActiveBrokers.get(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT)); LoadManager loadManager = new SimpleLoadManagerImpl(pulsar1); PulsarResourceDescription rd = new PulsarResourceDescription(); rd.put("memory", new ResourceUsage(1024, 4096)); rd.put("cpu", new ResourceUsage(10, 100)); rd.put("bandwidthIn", new ResourceUsage(250 * 1024, 1024 * 1024)); rd.put("bandwidthOut", new ResourceUsage(550 * 1024, 1024 * 1024)); ResourceUnit ru1 = new SimpleResourceUnit("http://prod2-broker7.messaging.usw.example.com:8080", rd); Set<ResourceUnit> rus = new HashSet<ResourceUnit>(); rus.add(ru1); LoadRanker lr = new ResourceAvailabilityRanker(); AtomicReference<Map<Long, Set<ResourceUnit>>> sortedRankingsInstance = new AtomicReference<>(Maps.newTreeMap()); sortedRankingsInstance.get().put(lr.getRank(rd), rus); Field sortedRankings = SimpleLoadManagerImpl.class.getDeclaredField("sortedRankings"); sortedRankings.setAccessible(true); sortedRankings.set(loadManager, sortedRankingsInstance); ResourceUnit found = ((SimpleLoadManagerImpl) loadManager) .getLeastLoaded(new NamespaceName("pulsar/use/primary-ns.10")); assertEquals(found.getResourceId(), ru1.getResourceId()); zkCacheField.set(pulsar1, originalLZK1); } @Test public void testResourceDescription() { PulsarResourceDescription rd = new PulsarResourceDescription(); rd.put("memory", new ResourceUsage(1024, 4096)); rd.put("cpu", new ResourceUsage(10, 100)); rd.put("bandwidthIn", new ResourceUsage(250 * 1024, 1024 * 1024)); rd.put("bandwidthOut", new ResourceUsage(550 * 1024, 1024 * 1024)); PulsarResourceDescription rd1 = new PulsarResourceDescription(); rd1.put("memory", new ResourceUsage(2048, 4096)); rd1.put("cpu", new ResourceUsage(50, 100)); rd1.put("bandwidthIn", new ResourceUsage(550 * 1024, 1024 * 1024)); rd1.put("bandwidthOut", new ResourceUsage(850 * 1024, 1024 * 1024)); assertTrue(rd.compareTo(rd1) == 1); assertTrue(rd1.calculateRank() > rd.calculateRank()); SimpleLoadCalculatorImpl calc = new SimpleLoadCalculatorImpl(); calc.recaliberateResourceUsagePerServiceUnit(null); assertNull(calc.getResourceDescription(null)); } @Test public void testLoadReportParsing() throws Exception { ObjectMapper mapper = ObjectMapperFactory.create(); org.apache.pulsar.policies.data.loadbalancer.LoadReport reportData = new org.apache.pulsar.policies.data.loadbalancer.LoadReport(); reportData.setName("b1"); SystemResourceUsage resource = new SystemResourceUsage(); ResourceUsage resourceUsage = new ResourceUsage(); resource.setBandwidthIn(resourceUsage); resource.setBandwidthOut(resourceUsage); resource.setMemory(resourceUsage); resource.setCpu(resourceUsage); reportData.setSystemResourceUsage(resource); String loadReportJson = mapper.writeValueAsString(reportData); LoadReport loadReport = PulsarLoadReportImpl.parse(loadReportJson); assertEquals( loadReport.getResourceUnitDescription().getResourceUsage().get("bandwidthIn").compareTo(resourceUsage), 0); } @Test(enabled = true) public void testDoLoadShedding() throws Exception { LoadManager loadManager = spy(new SimpleLoadManagerImpl(pulsar1)); PulsarResourceDescription rd = new PulsarResourceDescription(); rd.put("memory", new ResourceUsage(1024, 4096)); rd.put("cpu", new ResourceUsage(10, 100)); rd.put("bandwidthIn", new ResourceUsage(250 * 1024, 1024 * 1024)); rd.put("bandwidthOut", new ResourceUsage(550 * 1024, 1024 * 1024)); ResourceUnit ru1 = new SimpleResourceUnit("http://pulsar-broker1.com:8080", rd); ResourceUnit ru2 = new SimpleResourceUnit("http://pulsar-broker2.com:8080", rd); Set<ResourceUnit> rus = new HashSet<ResourceUnit>(); rus.add(ru1); rus.add(ru2); LoadRanker lr = new ResourceAvailabilityRanker(); AtomicReference<Map<Long, Set<ResourceUnit>>> sortedRankingsInstance = new AtomicReference<>(Maps.newTreeMap()); sortedRankingsInstance.get().put(lr.getRank(rd), rus); Field sortedRankings = SimpleLoadManagerImpl.class.getDeclaredField("sortedRankings"); sortedRankings.setAccessible(true); sortedRankings.set(loadManager, sortedRankingsInstance); // inject the load report and rankings SystemResourceUsage systemResource = new SystemResourceUsage(); systemResource.setBandwidthIn(new ResourceUsage(90, 100)); Map<String, NamespaceBundleStats> stats = Maps.newHashMap(); NamespaceBundleStats nsb1 = new NamespaceBundleStats(); nsb1.msgRateOut = 10000; NamespaceBundleStats nsb2 = new NamespaceBundleStats(); nsb2.msgRateOut = 10000; stats.put("property/cluster/namespace1/0x00000000_0xFFFFFFFF", nsb1); stats.put("property/cluster/namespace2/0x00000000_0xFFFFFFFF", nsb2); Map<ResourceUnit, org.apache.pulsar.policies.data.loadbalancer.LoadReport> loadReports = new HashMap<>(); org.apache.pulsar.policies.data.loadbalancer.LoadReport loadReport1 = new org.apache.pulsar.policies.data.loadbalancer.LoadReport(); loadReport1.setSystemResourceUsage(systemResource); loadReport1.setBundleStats(stats); org.apache.pulsar.policies.data.loadbalancer.LoadReport loadReport2 = new org.apache.pulsar.policies.data.loadbalancer.LoadReport(); loadReport2.setSystemResourceUsage(new SystemResourceUsage()); loadReport2.setBundleStats(stats); loadReports.put(ru1, loadReport1); loadReports.put(ru2, loadReport2); setObjectField(SimpleLoadManagerImpl.class, loadManager, "currentLoadReports", loadReports); ((SimpleLoadManagerImpl) loadManager).doLoadShedding(); verify(loadManager, atLeastOnce()).doLoadShedding(); } // Test that bundles belonging to the same namespace are evenly distributed. @Test public void testEvenBundleDistribution() throws Exception { final NamespaceBundle[] bundles = LoadBalancerTestingUtils .makeBundles(pulsar1.getNamespaceService().getNamespaceBundleFactory(), "pulsar", "use", "test", 16); final ResourceQuota quota = new ResourceQuota(); final String quotaZPath = String.format("%s/%s/%s", ResourceQuotaCache.RESOURCE_QUOTA_ROOT, "namespace", bundles[0]); // Create high message rate quota for the first bundle to make it unlikely to be a coincidence of even // distribution. ZkUtils.createFullPathOptimistic(pulsar1.getZkClient(), quotaZPath, ObjectMapperFactory.getThreadLocal().writeValueAsBytes(quota), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); int numAssignedToPrimary = 0; int numAssignedToSecondary = 0; pulsar1.getConfiguration().setLoadBalancerPlacementStrategy(SimpleLoadManagerImpl.LOADBALANCER_STRATEGY_LLS); final SimpleLoadManagerImpl loadManager = (SimpleLoadManagerImpl) pulsar1.getLoadManager().get(); for (final NamespaceBundle bundle : bundles) { if (loadManager.getLeastLoaded(bundle).getResourceId().equals(primaryHost)) { ++numAssignedToPrimary; } else { ++numAssignedToSecondary; } // Check that number of assigned bundles are equivalent when an even number have been assigned. if ((numAssignedToPrimary + numAssignedToSecondary) % 2 == 0) { assert (numAssignedToPrimary == numAssignedToSecondary); } } } @Test public void testNamespaceBundleStats() { NamespaceBundleStats nsb1 = new NamespaceBundleStats(); nsb1.msgRateOut = 10000; nsb1.producerCount = 1; nsb1.consumerCount = 1; nsb1.cacheSize = 4; nsb1.msgRateIn = 500; nsb1.msgThroughputIn = 30; nsb1.msgThroughputOut = 30; NamespaceBundleStats nsb2 = new NamespaceBundleStats(); nsb2.msgRateOut = 20000; nsb2.producerCount = 300; nsb2.consumerCount = 300; nsb2.cacheSize = 110000; nsb2.msgRateIn = 5000; nsb2.msgThroughputIn = 110000.0; nsb2.msgThroughputOut = 110000.0; assertTrue(nsb1.compareTo(nsb2) == -1); assertTrue(nsb1.compareByMsgRate(nsb2) == -1); assertTrue(nsb1.compareByTopicConnections(nsb2) == -1); assertTrue(nsb1.compareByCacheSize(nsb2) == -1); assertTrue(nsb1.compareByBandwidthOut(nsb2) == -1); assertTrue(nsb1.compareByBandwidthIn(nsb2) == -1); } @Test public void testBrokerHostUsage() { BrokerHostUsage brokerUsage; if (SystemUtils.IS_OS_LINUX) { brokerUsage = new LinuxBrokerHostUsageImpl(pulsar1); } else { brokerUsage = new GenericBrokerHostUsageImpl(pulsar1); } brokerUsage.getBrokerHostUsage(); // Ok } @Test public void testTask() throws Exception { LoadManager loadManager = mock(LoadManager.class); AtomicReference<LoadManager> atomicLoadManager = new AtomicReference<>(loadManager); LoadResourceQuotaUpdaterTask task1 = new LoadResourceQuotaUpdaterTask(atomicLoadManager); task1.run(); verify(loadManager, times(1)).writeResourceQuotasToZooKeeper(); LoadSheddingTask task2 = new LoadSheddingTask(atomicLoadManager); task2.run(); verify(loadManager, times(1)).doLoadShedding(); } @Test public void testUsage() { Map<String, Object> metrics = Maps.newHashMap(); metrics.put("brk_conn_cnt", new Long(1)); metrics.put("brk_repl_conn_cnt", new Long(1)); metrics.put("jvm_thread_cnt", new Long(1)); BrokerUsage brokerUsage = BrokerUsage.populateFrom(metrics); assertEquals(brokerUsage.getConnectionCount(), 1); assertEquals(brokerUsage.getReplicationConnectionCount(), 1); JvmUsage jvmUage = JvmUsage.populateFrom(metrics); assertEquals(jvmUage.getThreadCount(), 1); SystemResourceUsage usage = new SystemResourceUsage(); double usageLimit = 10.0; usage.setBandwidthIn(new ResourceUsage(usageLimit, usageLimit)); assertEquals(usage.getBandwidthIn().usage, usageLimit); usage.reset(); assertNotEquals(usage.getBandwidthIn().usage, usageLimit); } }
apache-2.0
apache/incubator-johnzon
johnzon-jsonb/src/test/java/org/apache/johnzon/jsonb/JohnzonProviderTest.java
1184
/* * 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.johnzon.jsonb; import org.junit.Test; import javax.json.bind.spi.JsonbProvider; import static org.junit.Assert.assertNotNull; public class JohnzonProviderTest { @Test public void provider() { assertNotNull(JsonbProvider.provider()); } @Test public void create() { assertNotNull(JsonbProvider.provider().create()); } }
apache-2.0
iostackproject/IO-Bandwidth-Differentiation
swift/cli/ringbuilder.py
46849
#! /usr/bin/env python # Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from errno import EEXIST from itertools import islice, izip from operator import itemgetter from os import mkdir from os.path import basename, abspath, dirname, exists, join as pathjoin from sys import argv as sys_argv, exit, stderr, stdout from textwrap import wrap from time import time import optparse import math from swift.common import exceptions from swift.common.ring import RingBuilder, Ring from swift.common.ring.builder import MAX_BALANCE from swift.common.ring.utils import validate_args, \ validate_and_normalize_ip, build_dev_from_opts, \ parse_builder_ring_filename_args, parse_search_value, \ parse_search_values_from_opts, parse_change_values_from_opts, \ dispersion_report, validate_device_name from swift.common.utils import lock_parent_directory MAJOR_VERSION = 1 MINOR_VERSION = 3 EXIT_SUCCESS = 0 EXIT_WARNING = 1 EXIT_ERROR = 2 global argv, backup_dir, builder, builder_file, ring_file argv = backup_dir = builder = builder_file = ring_file = None def format_device(dev): """ Format a device for display. """ copy_dev = dev.copy() for key in ('ip', 'replication_ip'): if ':' in copy_dev[key]: copy_dev[key] = '[' + copy_dev[key] + ']' return ('d%(id)sr%(region)sz%(zone)s-%(ip)s:%(port)sR' '%(replication_ip)s:%(replication_port)s/%(device)s_' '"%(meta)s"' % copy_dev) def _parse_search_values(argvish): new_cmd_format, opts, args = validate_args(argvish) # We'll either parse the all-in-one-string format or the # --options format, # but not both. If both are specified, raise an error. try: search_values = {} if len(args) > 0: if new_cmd_format or len(args) != 1: print Commands.search.__doc__.strip() exit(EXIT_ERROR) search_values = parse_search_value(args[0]) else: search_values = parse_search_values_from_opts(opts) return search_values except ValueError as e: print e exit(EXIT_ERROR) def _find_parts(devs): devs = [d['id'] for d in devs] if not devs or not builder._replica2part2dev: return None partition_count = {} for replica in builder._replica2part2dev: for partition, device in enumerate(replica): if device in devs: if partition not in partition_count: partition_count[partition] = 0 partition_count[partition] += 1 # Sort by number of found replicas to keep the output format sorted_partition_count = sorted( partition_count.iteritems(), key=itemgetter(1), reverse=True) return sorted_partition_count def _parse_list_parts_values(argvish): new_cmd_format, opts, args = validate_args(argvish) # We'll either parse the all-in-one-string format or the # --options format, # but not both. If both are specified, raise an error. try: devs = [] if len(args) > 0: if new_cmd_format: print Commands.list_parts.__doc__.strip() exit(EXIT_ERROR) for arg in args: devs.extend( builder.search_devs(parse_search_value(arg)) or []) else: devs.extend(builder.search_devs( parse_search_values_from_opts(opts)) or []) return devs except ValueError as e: print e exit(EXIT_ERROR) def _parse_address(rest): if rest.startswith('['): # remove first [] for ip rest = rest.replace('[', '', 1).replace(']', '', 1) pos = 0 while (pos < len(rest) and not (rest[pos] == 'R' or rest[pos] == '/')): pos += 1 address = rest[:pos] rest = rest[pos:] port_start = address.rfind(':') if port_start == -1: raise ValueError('Invalid port in add value') ip = address[:port_start] try: port = int(address[(port_start + 1):]) except (TypeError, ValueError): raise ValueError( 'Invalid port %s in add value' % address[port_start:]) # if this is an ipv6 address then we want to convert it # to all lowercase and use its fully expanded representation # to make searches easier ip = validate_and_normalize_ip(ip) return (ip, port, rest) def _parse_add_values(argvish): """ Parse devices to add as specified on the command line. Will exit on error and spew warnings. :returns: array of device dicts """ new_cmd_format, opts, args = validate_args(argvish) # We'll either parse the all-in-one-string format or the # --options format, # but not both. If both are specified, raise an error. parsed_devs = [] if len(args) > 0: if new_cmd_format or len(args) % 2 != 0: print Commands.add.__doc__.strip() exit(EXIT_ERROR) devs_and_weights = izip(islice(args, 0, len(args), 2), islice(args, 1, len(args), 2)) for devstr, weightstr in devs_and_weights: region = 1 rest = devstr if devstr.startswith('r'): i = 1 while i < len(devstr) and devstr[i].isdigit(): i += 1 region = int(devstr[1:i]) rest = devstr[i:] else: stderr.write('WARNING: No region specified for %s. ' 'Defaulting to region 1.\n' % devstr) if not rest.startswith('z'): raise ValueError('Invalid add value: %s' % devstr) i = 1 while i < len(rest) and rest[i].isdigit(): i += 1 zone = int(rest[1:i]) rest = rest[i:] if not rest.startswith('-'): raise ValueError('Invalid add value: %s' % devstr) ip, port, rest = _parse_address(rest[1:]) replication_ip = ip replication_port = port if rest.startswith('R'): replication_ip, replication_port, rest = \ _parse_address(rest[1:]) if not rest.startswith('/'): raise ValueError( 'Invalid add value: %s' % devstr) i = 1 while i < len(rest) and rest[i] != '_': i += 1 device_name = rest[1:i] if not validate_device_name(device_name): raise ValueError('Invalid device name') rest = rest[i:] meta = '' if rest.startswith('_'): meta = rest[1:] weight = float(weightstr) if weight < 0: raise ValueError('Invalid weight value: %s' % devstr) parsed_devs.append({'region': region, 'zone': zone, 'ip': ip, 'port': port, 'device': device_name, 'replication_ip': replication_ip, 'replication_port': replication_port, 'weight': weight, 'meta': meta}) else: parsed_devs.append(build_dev_from_opts(opts)) return parsed_devs def _set_weight_values(devs, weight): if not devs: print('Search value matched 0 devices.\n' 'The on-disk ring builder is unchanged.') exit(EXIT_ERROR) if len(devs) > 1: print 'Matched more than one device:' for dev in devs: print ' %s' % format_device(dev) if raw_input('Are you sure you want to update the weight for ' 'these %s devices? (y/N) ' % len(devs)) != 'y': print 'Aborting device modifications' exit(EXIT_ERROR) for dev in devs: builder.set_dev_weight(dev['id'], weight) print '%s weight set to %s' % (format_device(dev), dev['weight']) def _parse_set_weight_values(argvish): new_cmd_format, opts, args = validate_args(argvish) # We'll either parse the all-in-one-string format or the # --options format, # but not both. If both are specified, raise an error. try: devs = [] if not new_cmd_format: if len(args) % 2 != 0: print Commands.set_weight.__doc__.strip() exit(EXIT_ERROR) devs_and_weights = izip(islice(argvish, 0, len(argvish), 2), islice(argvish, 1, len(argvish), 2)) for devstr, weightstr in devs_and_weights: devs.extend(builder.search_devs( parse_search_value(devstr)) or []) weight = float(weightstr) _set_weight_values(devs, weight) else: if len(args) != 1: print Commands.set_weight.__doc__.strip() exit(EXIT_ERROR) devs.extend(builder.search_devs( parse_search_values_from_opts(opts)) or []) weight = float(args[0]) _set_weight_values(devs, weight) except ValueError as e: print e exit(EXIT_ERROR) def _set_info_values(devs, change): if not devs: print("Search value matched 0 devices.\n" "The on-disk ring builder is unchanged.") exit(EXIT_ERROR) if len(devs) > 1: print 'Matched more than one device:' for dev in devs: print ' %s' % format_device(dev) if raw_input('Are you sure you want to update the info for ' 'these %s devices? (y/N) ' % len(devs)) != 'y': print 'Aborting device modifications' exit(EXIT_ERROR) for dev in devs: orig_dev_string = format_device(dev) test_dev = dict(dev) for key in change: test_dev[key] = change[key] for check_dev in builder.devs: if not check_dev or check_dev['id'] == test_dev['id']: continue if check_dev['ip'] == test_dev['ip'] and \ check_dev['port'] == test_dev['port'] and \ check_dev['device'] == test_dev['device']: print 'Device %d already uses %s:%d/%s.' % \ (check_dev['id'], check_dev['ip'], check_dev['port'], check_dev['device']) exit(EXIT_ERROR) for key in change: dev[key] = change[key] print 'Device %s is now %s' % (orig_dev_string, format_device(dev)) def _parse_set_info_values(argvish): new_cmd_format, opts, args = validate_args(argvish) # We'll either parse the all-in-one-string format or the # --options format, # but not both. If both are specified, raise an error. if not new_cmd_format: if len(args) % 2 != 0: print Commands.search.__doc__.strip() exit(EXIT_ERROR) searches_and_changes = izip(islice(argvish, 0, len(argvish), 2), islice(argvish, 1, len(argvish), 2)) for search_value, change_value in searches_and_changes: devs = builder.search_devs(parse_search_value(search_value)) change = {} ip = '' if len(change_value) and change_value[0].isdigit(): i = 1 while (i < len(change_value) and change_value[i] in '0123456789.'): i += 1 ip = change_value[:i] change_value = change_value[i:] elif len(change_value) and change_value[0] == '[': i = 1 while i < len(change_value) and change_value[i] != ']': i += 1 i += 1 ip = change_value[:i].lstrip('[').rstrip(']') change_value = change_value[i:] if ip: change['ip'] = validate_and_normalize_ip(ip) if change_value.startswith(':'): i = 1 while i < len(change_value) and change_value[i].isdigit(): i += 1 change['port'] = int(change_value[1:i]) change_value = change_value[i:] if change_value.startswith('R'): change_value = change_value[1:] replication_ip = '' if len(change_value) and change_value[0].isdigit(): i = 1 while (i < len(change_value) and change_value[i] in '0123456789.'): i += 1 replication_ip = change_value[:i] change_value = change_value[i:] elif len(change_value) and change_value[0] == '[': i = 1 while i < len(change_value) and change_value[i] != ']': i += 1 i += 1 replication_ip = \ change_value[:i].lstrip('[').rstrip(']') change_value = change_value[i:] if replication_ip: change['replication_ip'] = \ validate_and_normalize_ip(replication_ip) if change_value.startswith(':'): i = 1 while i < len(change_value) and change_value[i].isdigit(): i += 1 change['replication_port'] = int(change_value[1:i]) change_value = change_value[i:] if change_value.startswith('/'): i = 1 while i < len(change_value) and change_value[i] != '_': i += 1 change['device'] = change_value[1:i] change_value = change_value[i:] if change_value.startswith('_'): change['meta'] = change_value[1:] change_value = '' if change_value or not change: raise ValueError('Invalid set info change value: %s' % repr(argvish[1])) _set_info_values(devs, change) else: devs = builder.search_devs(parse_search_values_from_opts(opts)) change = parse_change_values_from_opts(opts) _set_info_values(devs, change) def _parse_remove_values(argvish): new_cmd_format, opts, args = validate_args(argvish) # We'll either parse the all-in-one-string format or the # --options format, # but not both. If both are specified, raise an error. try: devs = [] if len(args) > 0: if new_cmd_format: print Commands.remove.__doc__.strip() exit(EXIT_ERROR) for arg in args: devs.extend(builder.search_devs( parse_search_value(arg)) or []) else: devs.extend(builder.search_devs( parse_search_values_from_opts(opts))) return devs except ValueError as e: print e exit(EXIT_ERROR) class Commands(object): def unknown(): print 'Unknown command: %s' % argv[2] exit(EXIT_ERROR) def create(): """ swift-ring-builder <builder_file> create <part_power> <replicas> <min_part_hours> Creates <builder_file> with 2^<part_power> partitions and <replicas>. <min_part_hours> is number of hours to restrict moving a partition more than once. """ if len(argv) < 6: print Commands.create.__doc__.strip() exit(EXIT_ERROR) builder = RingBuilder(int(argv[3]), float(argv[4]), int(argv[5])) backup_dir = pathjoin(dirname(argv[1]), 'backups') try: mkdir(backup_dir) except OSError as err: if err.errno != EEXIST: raise builder.save(pathjoin(backup_dir, '%d.' % time() + basename(argv[1]))) builder.save(argv[1]) exit(EXIT_SUCCESS) def default(): """ swift-ring-builder <builder_file> Shows information about the ring and the devices within. """ print '%s, build version %d' % (argv[1], builder.version) regions = 0 zones = 0 balance = 0 dev_count = 0 if builder.devs: regions = len(set(d['region'] for d in builder.devs if d is not None)) zones = len(set((d['region'], d['zone']) for d in builder.devs if d is not None)) dev_count = len([dev for dev in builder.devs if dev is not None]) balance = builder.get_balance() dispersion_trailer = '' if builder.dispersion is None else ( ', %.02f dispersion' % (builder.dispersion)) print '%d partitions, %.6f replicas, %d regions, %d zones, ' \ '%d devices, %.02f balance%s' % ( builder.parts, builder.replicas, regions, zones, dev_count, balance, dispersion_trailer) print 'The minimum number of hours before a partition can be ' \ 'reassigned is %s' % builder.min_part_hours print 'The overload factor is %0.2f%% (%.6f)' % ( builder.overload * 100, builder.overload) if builder.devs: print 'Devices: id region zone ip address port ' \ 'replication ip replication port name ' \ 'weight partitions balance meta' weighted_parts = builder.parts * builder.replicas / \ sum(d['weight'] for d in builder.devs if d is not None) for dev in builder.devs: if dev is None: continue if not dev['weight']: if dev['parts']: balance = MAX_BALANCE else: balance = 0 else: balance = 100.0 * dev['parts'] / \ (dev['weight'] * weighted_parts) - 100.0 print(' %5d %7d %5d %15s %5d %15s %17d %9s %6.02f ' '%10s %7.02f %s' % (dev['id'], dev['region'], dev['zone'], dev['ip'], dev['port'], dev['replication_ip'], dev['replication_port'], dev['device'], dev['weight'], dev['parts'], balance, dev['meta'])) exit(EXIT_SUCCESS) def search(): """ swift-ring-builder <builder_file> search <search-value> or swift-ring-builder <builder_file> search --region <region> --zone <zone> --ip <ip or hostname> --port <port> --replication-ip <r_ip or r_hostname> --replication-port <r_port> --device <device_name> --meta <meta> --weight <weight> Where <r_ip>, <r_hostname> and <r_port> are replication ip, hostname and port. Any of the options are optional in both cases. Shows information about matching devices. """ if len(argv) < 4: print Commands.search.__doc__.strip() print print parse_search_value.__doc__.strip() exit(EXIT_ERROR) devs = builder.search_devs(_parse_search_values(argv[3:])) if not devs: print 'No matching devices found' exit(EXIT_ERROR) print 'Devices: id region zone ip address port ' \ 'replication ip replication port name weight partitions ' \ 'balance meta' weighted_parts = builder.parts * builder.replicas / \ sum(d['weight'] for d in builder.devs if d is not None) for dev in devs: if not dev['weight']: if dev['parts']: balance = MAX_BALANCE else: balance = 0 else: balance = 100.0 * dev['parts'] / \ (dev['weight'] * weighted_parts) - 100.0 print(' %5d %7d %5d %15s %5d %15s %17d %9s %6.02f %10s ' '%7.02f %s' % (dev['id'], dev['region'], dev['zone'], dev['ip'], dev['port'], dev['replication_ip'], dev['replication_port'], dev['device'], dev['weight'], dev['parts'], balance, dev['meta'])) exit(EXIT_SUCCESS) def list_parts(): """ swift-ring-builder <builder_file> list_parts <search-value> [<search-value>] .. or swift-ring-builder <builder_file> list_parts --region <region> --zone <zone> --ip <ip or hostname> --port <port> --replication-ip <r_ip or r_hostname> --replication-port <r_port> --device <device_name> --meta <meta> --weight <weight> Where <r_ip>, <r_hostname> and <r_port> are replication ip, hostname and port. Any of the options are optional in both cases. Returns a 2 column list of all the partitions that are assigned to any of the devices matching the search values given. The first column is the assigned partition number and the second column is the number of device matches for that partition. The list is ordered from most number of matches to least. If there are a lot of devices to match against, this command could take a while to run. """ if len(argv) < 4: print Commands.list_parts.__doc__.strip() print print parse_search_value.__doc__.strip() exit(EXIT_ERROR) if not builder._replica2part2dev: print('Specified builder file \"%s\" is not rebalanced yet. ' 'Please rebalance first.' % argv[1]) exit(EXIT_ERROR) devs = _parse_list_parts_values(argv[3:]) if not devs: print 'No matching devices found' exit(EXIT_ERROR) sorted_partition_count = _find_parts(devs) if not sorted_partition_count: print 'No matching devices found' exit(EXIT_ERROR) print 'Partition Matches' for partition, count in sorted_partition_count: print '%9d %7d' % (partition, count) exit(EXIT_SUCCESS) def add(): """ swift-ring-builder <builder_file> add [r<region>]z<zone>-<ip>:<port>[R<r_ip>:<r_port>]/<device_name>_<meta> <weight> [[r<region>]z<zone>-<ip>:<port>[R<r_ip>:<r_port>]/<device_name>_<meta> <weight>] ... Where <r_ip> and <r_port> are replication ip and port. or swift-ring-builder <builder_file> add --region <region> --zone <zone> --ip <ip or hostname> --port <port> [--replication-ip <r_ip or r_hostname>] [--replication-port <r_port>] --device <device_name> --weight <weight> [--meta <meta>] Adds devices to the ring with the given information. No partitions will be assigned to the new device until after running 'rebalance'. This is so you can make multiple device changes and rebalance them all just once. """ if len(argv) < 5: print Commands.add.__doc__.strip() exit(EXIT_ERROR) try: for new_dev in _parse_add_values(argv[3:]): for dev in builder.devs: if dev is None: continue if dev['ip'] == new_dev['ip'] and \ dev['port'] == new_dev['port'] and \ dev['device'] == new_dev['device']: print 'Device %d already uses %s:%d/%s.' % \ (dev['id'], dev['ip'], dev['port'], dev['device']) print "The on-disk ring builder is unchanged.\n" exit(EXIT_ERROR) dev_id = builder.add_dev(new_dev) print('Device %s with %s weight got id %s' % (format_device(new_dev), new_dev['weight'], dev_id)) except ValueError as err: print err print 'The on-disk ring builder is unchanged.' exit(EXIT_ERROR) builder.save(argv[1]) exit(EXIT_SUCCESS) def set_weight(): """ swift-ring-builder <builder_file> set_weight <search-value> <weight> [<search-value> <weight] ... or swift-ring-builder <builder_file> set_weight --region <region> --zone <zone> --ip <ip or hostname> --port <port> --replication-ip <r_ip or r_hostname> --replication-port <r_port> --device <device_name> --meta <meta> --weight <weight> Where <r_ip>, <r_hostname> and <r_port> are replication ip, hostname and port. Any of the options are optional in both cases. Resets the devices' weights. No partitions will be reassigned to or from the device until after running 'rebalance'. This is so you can make multiple device changes and rebalance them all just once. """ # if len(argv) < 5 or len(argv) % 2 != 1: if len(argv) < 5: print Commands.set_weight.__doc__.strip() print print parse_search_value.__doc__.strip() exit(EXIT_ERROR) _parse_set_weight_values(argv[3:]) builder.save(argv[1]) exit(EXIT_SUCCESS) def set_info(): """ swift-ring-builder <builder_file> set_info <search-value> <ip>:<port>[R<r_ip>:<r_port>]/<device_name>_<meta> [<search-value> <ip>:<port>[R<r_ip>:<r_port>]/<device_name>_<meta>] ... or swift-ring-builder <builder_file> set_info --ip <ip or hostname> --port <port> --replication-ip <r_ip or r_hostname> --replication-port <r_port> --device <device_name> --meta <meta> --change-ip <ip or hostname> --change-port <port> --change-replication-ip <r_ip or r_hostname> --change-replication-port <r_port> --change-device <device_name> --change-meta <meta> Where <r_ip>, <r_hostname> and <r_port> are replication ip, hostname and port. Any of the options are optional in both cases. For each search-value, resets the matched device's information. This information isn't used to assign partitions, so you can use 'write_ring' afterward to rewrite the current ring with the newer device information. Any of the parts are optional in the final <ip>:<port>/<device_name>_<meta> parameter; just give what you want to change. For instance set_info d74 _"snet: 5.6.7.8" would just update the meta data for device id 74. """ if len(argv) < 5: print Commands.set_info.__doc__.strip() print print parse_search_value.__doc__.strip() exit(EXIT_ERROR) try: _parse_set_info_values(argv[3:]) except ValueError as err: print err exit(EXIT_ERROR) builder.save(argv[1]) exit(EXIT_SUCCESS) def remove(): """ swift-ring-builder <builder_file> remove <search-value> [search-value ...] or swift-ring-builder <builder_file> search --region <region> --zone <zone> --ip <ip or hostname> --port <port> --replication-ip <r_ip or r_hostname> --replication-port <r_port> --device <device_name> --meta <meta> --weight <weight> Where <r_ip>, <r_hostname> and <r_port> are replication ip, hostname and port. Any of the options are optional in both cases. Removes the device(s) from the ring. This should normally just be used for a device that has failed. For a device you wish to decommission, it's best to set its weight to 0, wait for it to drain all its data, then use this remove command. This will not take effect until after running 'rebalance'. This is so you can make multiple device changes and rebalance them all just once. """ if len(argv) < 4: print Commands.remove.__doc__.strip() print print parse_search_value.__doc__.strip() exit(EXIT_ERROR) devs = _parse_remove_values(argv[3:]) if not devs: print('Search value matched 0 devices.\n' 'The on-disk ring builder is unchanged.') exit(EXIT_ERROR) if len(devs) > 1: print 'Matched more than one device:' for dev in devs: print ' %s' % format_device(dev) if raw_input('Are you sure you want to remove these %s ' 'devices? (y/N) ' % len(devs)) != 'y': print 'Aborting device removals' exit(EXIT_ERROR) for dev in devs: try: builder.remove_dev(dev['id']) except exceptions.RingBuilderError as e: print '-' * 79 print( 'An error occurred while removing device with id %d\n' 'This usually means that you attempted to remove\n' 'the last device in a ring. If this is the case,\n' 'consider creating a new ring instead.\n' 'The on-disk ring builder is unchanged.\n' 'Original exception message: %s' % (dev['id'], e)) print '-' * 79 exit(EXIT_ERROR) print '%s marked for removal and will ' \ 'be removed next rebalance.' % format_device(dev) builder.save(argv[1]) exit(EXIT_SUCCESS) def rebalance(): """ swift-ring-builder <builder_file> rebalance [options] Attempts to rebalance the ring by reassigning partitions that haven't been recently reassigned. """ usage = Commands.rebalance.__doc__.strip() parser = optparse.OptionParser(usage) parser.add_option('-f', '--force', action='store_true', help='Force a rebalanced ring to save even ' 'if < 1% of parts changed') parser.add_option('-s', '--seed', help="seed to use for rebalance") parser.add_option('-d', '--debug', action='store_true', help="print debug information") options, args = parser.parse_args(argv) def get_seed(index): if options.seed: return options.seed try: return args[index] except IndexError: pass if options.debug: logger = logging.getLogger("swift.ring.builder") logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(stdout) formatter = logging.Formatter("%(levelname)s: %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) devs_changed = builder.devs_changed try: last_balance = builder.get_balance() parts, balance = builder.rebalance(seed=get_seed(3)) except exceptions.RingBuilderError as e: print '-' * 79 print("An error has occurred during ring validation. Common\n" "causes of failure are rings that are empty or do not\n" "have enough devices to accommodate the replica count.\n" "Original exception message:\n %s" % (e,)) print '-' * 79 exit(EXIT_ERROR) if not (parts or options.force): print 'No partitions could be reassigned.' print 'Either none need to be or none can be due to ' \ 'min_part_hours [%s].' % builder.min_part_hours exit(EXIT_WARNING) # If we set device's weight to zero, currently balance will be set # special value(MAX_BALANCE) until zero weighted device return all # its partitions. So we cannot check balance has changed. # Thus we need to check balance or last_balance is special value. if not options.force and \ not devs_changed and abs(last_balance - balance) < 1 and \ not (last_balance == MAX_BALANCE and balance == MAX_BALANCE): print 'Cowardly refusing to save rebalance as it did not change ' \ 'at least 1%.' exit(EXIT_WARNING) try: builder.validate() except exceptions.RingValidationError as e: print '-' * 79 print("An error has occurred during ring validation. Common\n" "causes of failure are rings that are empty or do not\n" "have enough devices to accommodate the replica count.\n" "Original exception message:\n %s" % (e,)) print '-' * 79 exit(EXIT_ERROR) print ('Reassigned %d (%.02f%%) partitions. ' 'Balance is now %.02f. ' 'Dispersion is now %.02f' % ( parts, 100.0 * parts / builder.parts, balance, builder.dispersion)) status = EXIT_SUCCESS if builder.dispersion > 0: print '-' * 79 print( 'NOTE: Dispersion of %.06f indicates some parts are not\n' ' optimally dispersed.\n\n' ' You may want to adjust some device weights, increase\n' ' the overload or review the dispersion report.' % builder.dispersion) status = EXIT_WARNING print '-' * 79 elif balance > 5 and balance / 100.0 > builder.overload: print '-' * 79 print 'NOTE: Balance of %.02f indicates you should push this ' % \ balance print ' ring, wait at least %d hours, and rebalance/repush.' \ % builder.min_part_hours print '-' * 79 status = EXIT_WARNING ts = time() builder.get_ring().save( pathjoin(backup_dir, '%d.' % ts + basename(ring_file))) builder.save(pathjoin(backup_dir, '%d.' % ts + basename(argv[1]))) builder.get_ring().save(ring_file) builder.save(argv[1]) exit(status) def dispersion(): """ swift-ring-builder <builder_file> dispersion <search_filter> [options] Output report on dispersion. --verbose option will display dispersion graph broken down by tier You can filter which tiers are evaluated to drill down using a regex in the optional search_filter arguemnt. The reports columns are: Tier : the name of the tier parts : the total number of partitions with assignment in the tier % : the percentage of parts in the tier with replicas over assigned max : maximum replicas a part should have assigned at the tier 0 - N : the number of parts with that many replicas assigned e.g. Tier: parts % max 0 1 2 3 r1z1 1022 79.45 1 2 210 784 28 r1z1 has 1022 total parts assigned, 79% of them have more than the recommend max replica count of 1 assigned. Only 2 parts in the ring are *not* assigned in this tier (0 replica count), 210 parts have the recommend replica count of 1, 784 have 2 replicas, and 28 sadly have all three replicas in this tier. """ status = EXIT_SUCCESS if not builder._replica2part2dev: print('Specified builder file \"%s\" is not rebalanced yet. ' 'Please rebalance first.' % argv[1]) exit(EXIT_ERROR) usage = Commands.dispersion.__doc__.strip() parser = optparse.OptionParser(usage) parser.add_option('-v', '--verbose', action='store_true', help='Display dispersion report for tiers') options, args = parser.parse_args(argv) if args[3:]: search_filter = args[3] else: search_filter = None report = dispersion_report(builder, search_filter=search_filter, verbose=options.verbose) print 'Dispersion is %.06f, Balance is %.06f, Overload is %0.2f%%' % ( builder.dispersion, builder.get_balance(), builder.overload * 100) if report['worst_tier']: status = EXIT_WARNING print 'Worst tier is %.06f (%s)' % (report['max_dispersion'], report['worst_tier']) if report['graph']: replica_range = range(int(math.ceil(builder.replicas + 1))) part_count_width = '%%%ds' % max(len(str(builder.parts)), 5) replica_counts_tmpl = ' '.join(part_count_width for i in replica_range) tiers = (tier for tier, _junk in report['graph']) tier_width = max(max(map(len, tiers)), 30) header_line = ('%-' + str(tier_width) + 's ' + part_count_width + ' %6s %6s ' + replica_counts_tmpl) % tuple( ['Tier', 'Parts', '%', 'Max'] + replica_range) underline = '-' * len(header_line) print(underline) print(header_line) print(underline) for tier_name, dispersion in report['graph']: replica_counts_repr = replica_counts_tmpl % tuple( dispersion['replicas']) print ('%-' + str(tier_width) + 's ' + part_count_width + ' %6.02f %6d %s') % (tier_name, dispersion['placed_parts'], dispersion['dispersion'], dispersion['max_replicas'], replica_counts_repr, ) exit(status) def validate(): """ swift-ring-builder <builder_file> validate Just runs the validation routines on the ring. """ builder.validate() exit(EXIT_SUCCESS) def write_ring(): """ swift-ring-builder <builder_file> write_ring Just rewrites the distributable ring file. This is done automatically after a successful rebalance, so really this is only useful after one or more 'set_info' calls when no rebalance is needed but you want to send out the new device information. """ ring_data = builder.get_ring() if not ring_data._replica2part2dev_id: if ring_data.devs: print 'Warning: Writing a ring with no partition ' \ 'assignments but with devices; did you forget to run ' \ '"rebalance"?' else: print 'Warning: Writing an empty ring' ring_data.save( pathjoin(backup_dir, '%d.' % time() + basename(ring_file))) ring_data.save(ring_file) exit(EXIT_SUCCESS) def write_builder(): """ swift-ring-builder <ring_file> write_builder [min_part_hours] Recreate a builder from a ring file (lossy) if you lost your builder backups. (Protip: don't lose your builder backups). [min_part_hours] is one of those numbers lost to the builder, you can change it with set_min_part_hours. """ if exists(builder_file): print 'Cowardly refusing to overwrite existing ' \ 'Ring Builder file: %s' % builder_file exit(EXIT_ERROR) if len(argv) > 3: min_part_hours = int(argv[3]) else: stderr.write("WARNING: default min_part_hours may not match " "the value in the lost builder.\n") min_part_hours = 24 ring = Ring(ring_file) for dev in ring.devs: dev.update({ 'parts': 0, 'parts_wanted': 0, }) builder_dict = { 'part_power': 32 - ring._part_shift, 'replicas': float(ring.replica_count), 'min_part_hours': min_part_hours, 'parts': ring.partition_count, 'devs': ring.devs, 'devs_changed': False, 'version': 0, '_replica2part2dev': ring._replica2part2dev_id, '_last_part_moves_epoch': None, '_last_part_moves': None, '_last_part_gather_start': 0, '_remove_devs': [], } builder = RingBuilder.from_dict(builder_dict) for parts in builder._replica2part2dev: for dev_id in parts: builder.devs[dev_id]['parts'] += 1 builder._set_parts_wanted() builder.save(builder_file) def pretend_min_part_hours_passed(): builder.pretend_min_part_hours_passed() builder.save(argv[1]) exit(EXIT_SUCCESS) def set_min_part_hours(): """ swift-ring-builder <builder_file> set_min_part_hours <hours> Changes the <min_part_hours> to the given <hours>. This should be set to however long a full replication/update cycle takes. We're working on a way to determine this more easily than scanning logs. """ if len(argv) < 4: print Commands.set_min_part_hours.__doc__.strip() exit(EXIT_ERROR) builder.change_min_part_hours(int(argv[3])) print 'The minimum number of hours before a partition can be ' \ 'reassigned is now set to %s' % argv[3] builder.save(argv[1]) exit(EXIT_SUCCESS) def set_replicas(): """ swift-ring-builder <builder_file> set_replicas <replicas> Changes the replica count to the given <replicas>. <replicas> may be a floating-point value, in which case some partitions will have floor(<replicas>) replicas and some will have ceiling(<replicas>) in the correct proportions. A rebalance is needed to make the change take effect. """ if len(argv) < 4: print Commands.set_replicas.__doc__.strip() exit(EXIT_ERROR) new_replicas = argv[3] try: new_replicas = float(new_replicas) except ValueError: print Commands.set_replicas.__doc__.strip() print "\"%s\" is not a valid number." % new_replicas exit(EXIT_ERROR) if new_replicas < 1: print "Replica count must be at least 1." exit(EXIT_ERROR) builder.set_replicas(new_replicas) print 'The replica count is now %.6f.' % builder.replicas print 'The change will take effect after the next rebalance.' builder.save(argv[1]) exit(EXIT_SUCCESS) def set_overload(): """ swift-ring-builder <builder_file> set_overload <overload>[%] Changes the overload factor to the given <overload>. A rebalance is needed to make the change take effect. """ if len(argv) < 4: print Commands.set_overload.__doc__.strip() exit(EXIT_ERROR) new_overload = argv[3] if new_overload.endswith('%'): percent = True new_overload = new_overload.rstrip('%') else: percent = False try: new_overload = float(new_overload) except ValueError: print Commands.set_overload.__doc__.strip() print "%r is not a valid number." % new_overload exit(EXIT_ERROR) if percent: new_overload *= 0.01 if new_overload < 0: print "Overload must be non-negative." exit(EXIT_ERROR) if new_overload > 1 and not percent: print "!?! Warning overload is greater than 100% !?!" status = EXIT_WARNING else: status = EXIT_SUCCESS builder.set_overload(new_overload) print 'The overload factor is now %0.2f%% (%.6f)' % ( builder.overload * 100, builder.overload) print 'The change will take effect after the next rebalance.' builder.save(argv[1]) exit(status) def main(arguments=None): global argv, backup_dir, builder, builder_file, ring_file if arguments: argv = arguments else: argv = sys_argv if len(argv) < 2: print "swift-ring-builder %(MAJOR_VERSION)s.%(MINOR_VERSION)s\n" % \ globals() print Commands.default.__doc__.strip() print cmds = [c for c, f in Commands.__dict__.iteritems() if f.__doc__ and c[0] != '_' and c != 'default'] cmds.sort() for cmd in cmds: print Commands.__dict__[cmd].__doc__.strip() print print parse_search_value.__doc__.strip() print for line in wrap(' '.join(cmds), 79, initial_indent='Quick list: ', subsequent_indent=' '): print line print('Exit codes: 0 = operation successful\n' ' 1 = operation completed with warnings\n' ' 2 = error') exit(EXIT_SUCCESS) builder_file, ring_file = parse_builder_ring_filename_args(argv) try: builder = RingBuilder.load(builder_file) except exceptions.UnPicklingError as e: print e exit(EXIT_ERROR) except (exceptions.FileNotFoundError, exceptions.PermissionError) as e: if len(argv) < 3 or argv[2] not in('create', 'write_builder'): print e exit(EXIT_ERROR) except Exception as e: print('Problem occurred while reading builder file: %s. %s' % (argv[1], e)) exit(EXIT_ERROR) backup_dir = pathjoin(dirname(argv[1]), 'backups') try: mkdir(backup_dir) except OSError as err: if err.errno != EEXIST: raise if len(argv) == 2: command = "default" else: command = argv[2] if argv[0].endswith('-safe'): try: with lock_parent_directory(abspath(argv[1]), 15): Commands.__dict__.get(command, Commands.unknown.im_func)() except exceptions.LockTimeout: print "Ring/builder dir currently locked." exit(2) else: Commands.__dict__.get(command, Commands.unknown.im_func)() if __name__ == '__main__': main()
apache-2.0
baslr/ArangoDB
3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-30.js
1124
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.4.4.21-8-b-iii-1-30 description: > Array.prototype.reduce - element changed by getter on current iterations is observed in subsequent iterations on an Array ---*/ var testResult = false; function callbackfn(prevVal, curVal, idx, obj) { if (idx === 1) { testResult = (curVal === 1); } } var arr = [, , 2]; var preIterVisible = false; Object.defineProperty(arr, "0", { get: function () { preIterVisible = true; return 0; }, configurable: true }); Object.defineProperty(arr, "1", { get: function () { if (preIterVisible) { return 1; } else { return 100; } }, configurable: true }); arr.reduce(callbackfn); assert(testResult, 'testResult !== true');
apache-2.0
sul-dlss/squash-web
spec/models/watch_spec.rb
1415
# Copyright 2013 Square 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. require 'spec_helper' describe Watch do context "[observers]" do before :all do @user = FactoryGirl.create(:user) @unwatched_event = FactoryGirl.create(:event) @watched_event = FactoryGirl.create(:event) @unwatched_bug = @unwatched_event.bug watched_bug = @watched_event.bug @watch = FactoryGirl.create(:watch, user: @user, bug: watched_bug) end it "should fill a user's feed with events when a bug is watched" do FactoryGirl.create :watch, user: @user, bug: @unwatched_bug @user.user_events.pluck(:event_id).should include(@unwatched_event.id) end it "should remove events from a user's feed when a bug is unwatched" do @watch.destroy @user.user_events.pluck(:event_id).should_not include(@watched_event.id) end end end
apache-2.0
Selventa/model-builder
tools/groovy/src/src/main/org/codehaus/groovy/runtime/dgmimpl/arrays/ShortArrayPutAtMetaMethod.java
4157
/* * Copyright 2003-2007 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.codehaus.groovy.runtime.dgmimpl.arrays; import groovy.lang.GString; import groovy.lang.MetaClassImpl; import groovy.lang.MetaMethod; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; public class ShortArrayPutAtMetaMethod extends ArrayPutAtMetaMethod { private static final CachedClass OBJECT_CLASS = ReflectionCache.OBJECT_CLASS; private static final CachedClass ARR_CLASS = ReflectionCache.getCachedClass(short[].class); private static final CachedClass[] PARAM_CLASS_ARR = new CachedClass[]{INTEGER_CLASS, OBJECT_CLASS}; public ShortArrayPutAtMetaMethod() { parameterTypes = PARAM_CLASS_ARR; } public final CachedClass getDeclaringClass() { return ARR_CLASS; } public Object invoke(Object object, Object[] args) { final short[] objects = (short[]) object; final int index = normaliseIndex((Integer) args[0], objects.length); Object newValue = args[1]; if (!(newValue instanceof Short)) { if (newValue instanceof Character || newValue instanceof String || newValue instanceof GString) { Character ch = DefaultTypeTransformation.getCharFromSizeOneString(newValue); objects[index] = (Short) DefaultTypeTransformation.castToType(ch, Short.class); } else { objects[index] = ((Number) newValue).shortValue(); } } else objects[index] = (Short) args[1]; return null; } public CallSite createPojoCallSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params, Object receiver, Object[] args) { if (!(args[0] instanceof Integer) || !(args[1] instanceof Short)) return PojoMetaMethodSite.createNonAwareCallSite(site, metaClass, metaMethod, params, args); else return new MyPojoMetaMethodSite(site, metaClass, metaMethod, params); } private static class MyPojoMetaMethodSite extends PojoMetaMethodSite { public MyPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, MetaMethod metaMethod, Class[] params) { super(site, metaClass, metaMethod, params); } public Object call(Object receiver, Object[] args) throws Throwable { if ((receiver instanceof short[] && args[0] instanceof Integer && args[1] instanceof Short) && checkPojoMetaClass()) { final short[] objects = (short[]) receiver; objects[normaliseIndex((Integer) args[0], objects.length)] = (Short) args[1]; return null; } else return super.call(receiver, args); } public Object call(Object receiver, Object arg1, Object arg2) throws Throwable { if (checkPojoMetaClass()) { try { final short[] objects = (short[]) receiver; objects[normaliseIndex((Integer) arg1, objects.length)] = (Short) arg2; return null; } catch (ClassCastException e) { if ((receiver instanceof short[]) && (arg1 instanceof Integer)) throw e; } } return super.call(receiver, arg1, arg2); } } }
apache-2.0
liuyuanyuan/dbeaver
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/core/CoreFeatures.java
1598
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org) * * 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.jkiss.dbeaver.core; import org.jkiss.dbeaver.model.runtime.features.DBRFeature; import org.jkiss.dbeaver.ui.controls.resultset.ResultSetHandlerMain; import org.jkiss.dbeaver.ui.editors.sql.SQLEditorCommands; /** * DBeaver project nature */ public interface CoreFeatures { DBRFeature ENTITY_EDITOR = DBRFeature.createCategory("Object Editor", "Object Editor features"); DBRFeature ENTITY_EDITOR_MODIFY = DBRFeature.createFeature(ENTITY_EDITOR, "Change object properties"); DBRFeature ENTITY_EDITOR_SAVE = DBRFeature.createFeature(ENTITY_EDITOR, "Save object properties"); DBRFeature ENTITY_EDITOR_REJECT = DBRFeature.createFeature(ENTITY_EDITOR, "Reject object properties changes"); DBRFeature RESULT_SET = DBRFeature.createCategory("Result Set", "ResultSet operation"); DBRFeature RESULT_SET_APPLY_CHANGES = DBRFeature.createCommandFeature(RESULT_SET, ResultSetHandlerMain.CMD_APPLY_CHANGES); }
apache-2.0
jimhotchkin-wf/wGulp
test/integration/modes/browserify/src/app.ts
266
declare var document: Document; declare var require; var Hat = require('./hat'); var Hello:any = require('./hello').Hello; var React:any = require('react'); var hat = new Hat('World'); var str = hat.go(); React.renderComponent(Hello({name: str}), document.body);
apache-2.0
hxf0801/guvnor
guvnor-structure/guvnor-structure-backend/src/main/java/org/guvnor/structure/backend/config/Added.java
941
/* * Copyright 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.guvnor.structure.backend.config; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.inject.Qualifier; @Qualifier @Target({PARAMETER, FIELD}) @Retention(RUNTIME) public @interface Added { }
apache-2.0
googleapis/google-cloud-php
AutoMl/src/V1/resources/prediction_service_descriptor_config.php
613
<?php return [ 'interfaces' => [ 'google.cloud.automl.v1.PredictionService' => [ 'BatchPredict' => [ 'longRunning' => [ 'operationReturnType' => '\Google\Cloud\AutoMl\V1\BatchPredictResult', 'metadataReturnType' => '\Google\Cloud\AutoMl\V1\OperationMetadata', 'initialPollDelayMillis' => '500', 'pollDelayMultiplier' => '1.5', 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], ], ], ], ];
apache-2.0
alexcreasy/pnc
build-coordinator/src/test/java/org/jboss/pnc/coordinator/test/BuildCoordinatorBeans.java
1236
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.coordinator.test; import org.jboss.pnc.coordinator.builder.BuildQueue; import org.jboss.pnc.spi.coordinator.BuildCoordinator; /** * Author: Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com Date: 4/26/16 Time: 9:29 AM */ public class BuildCoordinatorBeans { public final BuildQueue queue; public final BuildCoordinator coordinator; public BuildCoordinatorBeans(BuildQueue queue, BuildCoordinator coordinator) { this.queue = queue; this.coordinator = coordinator; } }
apache-2.0
vherilier/jmeter
test/src/org/apache/jmeter/control/TestSwitchController.java
11696
/* * 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.jmeter.control; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.HashMap; import java.util.Map; import org.apache.jmeter.engine.util.CompoundVariable; import org.apache.jmeter.engine.util.ReplaceStringWithFunctions; import org.apache.jmeter.junit.JMeterTestCase; import org.apache.jmeter.junit.stubs.TestSampler; import org.apache.jmeter.samplers.Sampler; import org.apache.jmeter.testelement.property.JMeterProperty; import org.apache.jmeter.testelement.property.StringProperty; import org.apache.jmeter.threads.JMeterContext; import org.apache.jmeter.threads.JMeterContextService; import org.apache.jmeter.threads.JMeterVariables; import org.junit.Test; public class TestSwitchController extends JMeterTestCase { // Get next sample and its name private String nextName(GenericController c) { Sampler s = c.next(); String n; if (s == null) { return null; } n = s.getName(); return n; } @Test public void test() throws Exception { runSimpleTests("", "zero"); } @Test public void test0() throws Exception { runSimpleTests("0", "zero"); } @Test public void test1() throws Exception { runSimpleTests("1", "one"); runSimpleTests(" 1 ", "one"); runSimpleTests("one", "one"); // Match by name runSimpleTests("one ", "one"); // Match by name with space } @Test public void test2() throws Exception { runSimpleTests("2", "two"); runSimpleTests("two", "two"); // Match by name } @Test public void test3() throws Exception { runSimpleTests("3", "three"); runSimpleTests("three", "three"); // Match by name } @Test public void test4() throws Exception { runSimpleTests("4", "zero"); } @Test public void testX() throws Exception { runSimpleTests("X", null); // should not run any children runSimpleTest2("X", "one", "Default"); // should match the default entry } private void runSimpleTests(String cond, String exp) throws Exception { runSimpleTest(cond, exp); runSimpleTest2(cond, exp, "one"); } /* * Simple test with single Selection controller * Generic Controller * + Sampler "before" * + Switch Controller * + + Sampler "zero" * + + Sampler "one" * + + Sampler "two" * + + Sampler "three" * + Sampler "after" */ private void runSimpleTest(String cond, String exp) throws Exception { GenericController controller = new GenericController(); SwitchController switch_cont = new SwitchController(); switch_cont.setSelection(cond); controller.addTestElement(new TestSampler("before")); controller.addTestElement(switch_cont); switch_cont.addTestElement(new TestSampler("zero")); switch_cont.addTestElement(new TestSampler("one")); switch_cont.addTestElement(new TestSampler("two")); switch_cont.addTestElement(new TestSampler("three")); controller.addTestElement(new TestSampler("after")); controller.initialize(); for (int i = 1; i <= 3; i++) { assertEquals("Loop " + i, "before", nextName(controller)); if (exp!=null){ assertEquals("Loop " + i, exp, nextName(controller)); } assertEquals("Loop " + i, "after", nextName(controller)); assertNull(nextName(controller)); } } // Selection controller with two sub-controllers, but each has only 1 // child /* * Controller * + Before * + Switch (cond) * + + zero * + + Controller sub_1 * + + + one * + + two * + + Controller sub_2 * + + + three * + After */ private void runSimpleTest2(String cond, String exp, String sub1Name) throws Exception { GenericController controller = new GenericController(); GenericController sub_1 = new GenericController(); GenericController sub_2 = new GenericController(); SwitchController switch_cont = new SwitchController(); switch_cont.setSelection(cond); switch_cont.addTestElement(new TestSampler("zero")); switch_cont.addTestElement(sub_1); sub_1.addTestElement(new TestSampler("one")); sub_1.setName(sub1Name); switch_cont.addTestElement(new TestSampler("two")); switch_cont.addTestElement(sub_2); sub_2.addTestElement(new TestSampler("three")); sub_2.setName("three"); controller.addTestElement(new TestSampler("before")); controller.addTestElement(switch_cont); controller.addTestElement(new TestSampler("after")); controller.initialize(); for (int i = 1; i <= 3; i++) { assertEquals("Loop="+i,"before", nextName(controller)); if (exp!=null){ assertEquals("Loop="+i,exp, nextName(controller)); } assertEquals("Loop="+i,"after", nextName(controller)); assertNull("Loop="+i,nextName(controller)); } } @Test public void testTest2() throws Exception { runTest2("", new String[] { "zero" }); runTest2("0", new String[] { "zero" }); runTest2("7", new String[] { "zero" }); runTest2("5", new String[] { "zero" }); runTest2("4", new String[] { "six" }); runTest2("4 ", new String[] { "six" }); runTest2("3", new String[] { "five" }); runTest2("1", new String[] { "one", "two" }); runTest2("2", new String[] { "three", "four" }); } /* * Test: * Before * Selection Controller * - zero (default) * - simple controller 1 * - - one * - - two * - simple controller 2 * - - three * - - four * - five * - six * After * * cond = Switch condition * exp[] = expected results */ private void runTest2(String cond, String[] exp) throws Exception { int loops = 3; LoopController controller = new LoopController(); controller.setLoops(loops); controller.setContinueForever(false); GenericController sub_1 = new GenericController(); GenericController sub_2 = new GenericController(); SwitchController switch_cont = new SwitchController(); switch_cont.setSelection(cond); switch_cont.addTestElement(new TestSampler("zero")); switch_cont.addTestElement(sub_1); sub_1.addTestElement(new TestSampler("one")); sub_1.addTestElement(new TestSampler("two")); switch_cont.addTestElement(sub_2); sub_2.addTestElement(new TestSampler("three")); sub_2.addTestElement(new TestSampler("four")); switch_cont.addTestElement(new TestSampler("five")); switch_cont.addTestElement(new TestSampler("six")); controller.addTestElement(new TestSampler("before")); controller.addTestElement(switch_cont); controller.addTestElement(new TestSampler("after")); controller.setRunningVersion(true); sub_1.setRunningVersion(true); sub_2.setRunningVersion(true); switch_cont.setRunningVersion(true); controller.initialize(); for (int i = 1; i <= 3; i++) { assertEquals("Loop:" + i, "before", nextName(controller)); for (String anExp : exp) { assertEquals("Loop:" + i, anExp, nextName(controller)); } assertEquals("Loop:" + i, "after", nextName(controller)); } assertNull("Loops:" + loops, nextName(controller)); } /* * N.B. Requires ApacheJMeter_functions.jar to be on the classpath, * otherwise the function cannot be resolved. */ @Test public void testFunction() throws Exception { JMeterContext jmctx = JMeterContextService.getContext(); Map<String, String> variables = new HashMap<>(); ReplaceStringWithFunctions transformer = new ReplaceStringWithFunctions(new CompoundVariable(), variables); jmctx.setVariables(new JMeterVariables()); JMeterVariables jmvars = jmctx.getVariables(); jmvars.put("VAR", "100"); StringProperty prop = new StringProperty(SwitchController.SWITCH_VALUE,"${__counter(TRUE,VAR)}"); JMeterProperty newProp = transformer.transformValue(prop); newProp.setRunningVersion(true); GenericController controller = new GenericController(); SwitchController switch_cont = new SwitchController(); switch_cont.setProperty(newProp); controller.addTestElement(new TestSampler("before")); controller.addTestElement(switch_cont); switch_cont.addTestElement(new TestSampler("0")); switch_cont.addTestElement(new TestSampler("1")); switch_cont.addTestElement(new TestSampler("2")); switch_cont.addTestElement(new TestSampler("3")); controller.addTestElement(new TestSampler("after")); controller.initialize(); assertEquals("100",jmvars.get("VAR")); for (int i = 1; i <= 3; i++) { assertEquals("Loop " + i, "before", nextName(controller)); assertEquals("Loop " + i, ""+i, nextName(controller)); assertEquals("Loop " + i, ""+i, jmvars.get("VAR")); assertEquals("Loop " + i, "after", nextName(controller)); assertNull(nextName(controller)); } int i = 4; assertEquals("Loop " + i, "before", nextName(controller)); assertEquals("Loop " + i, "0", nextName(controller)); assertEquals("Loop " + i, ""+i, jmvars.get("VAR")); assertEquals("Loop " + i, "after", nextName(controller)); assertNull(nextName(controller)); assertEquals("4",jmvars.get("VAR")); } }
apache-2.0
artem-aliev/tinkerpop
gremlin-python/src/test/java/org/apache/tinkerpop/gremlin/python/jsr223/PythonGremlinScriptEngineTest.java
1284
/* * 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.tinkerpop.gremlin.python.jsr223; import org.apache.tinkerpop.gremlin.jsr223.GremlinScriptEngineSuite; import org.apache.tinkerpop.gremlin.jsr223.ScriptEngineToTest; import org.junit.Ignore; import org.junit.runner.RunWith; /** * @author Stephen Mallette (http://stephen.genoprime.com) */ @Ignore @RunWith(GremlinScriptEngineSuite.class) @ScriptEngineToTest(scriptEngineName = "gremlin-jython") public class PythonGremlinScriptEngineTest { }
apache-2.0
OpenTrons/opentrons-api
app/src/protocol/index.js
2243
// @flow // protocol state and loading actions import { getFeatureFlags } from '../config/selectors' import { fileToProtocolFile, parseProtocolData, fileIsBinary, fileIsBundle, } from './protocol-data' import type { ThunkAction } from '../types' import type { OpenProtocolAction, UploadProtocolAction, InvalidProtocolFileAction, } from './types' export * from './constants' export * from './selectors' const BUNDLE_UPLOAD_DISABLED = 'ZIP uploads are not currently supported. Please unzip the ZIP archive and upload the uncompressed files.' const arrayBufferToBase64 = (buffer: ArrayBuffer): string => { let binary = '' const bytes = new Uint8Array(buffer) const len = bytes.byteLength for (let i = 0; i < len; i++) { binary += String.fromCharCode(bytes[i]) } return global.btoa(binary) } export function openProtocol(file: File): ThunkAction { return (dispatch, getState) => { const reader = new FileReader() const protocolFile = fileToProtocolFile(file) const openAction: OpenProtocolAction = { type: 'protocol:OPEN', payload: { file: protocolFile }, } const bundlesEnabled = getFeatureFlags(getState())?.enableBundleUpload === true reader.onload = () => { // when we use readAsText below, reader.result will be a string, // with readAsArrayBuffer, it will be an ArrayBuffer const _contents: any = reader.result const contents = fileIsBinary(protocolFile) ? arrayBufferToBase64(_contents) : _contents const uploadAction: UploadProtocolAction = { type: 'protocol:UPLOAD', payload: { contents, data: parseProtocolData(protocolFile, contents) }, meta: { robot: true }, } dispatch(uploadAction) } if (fileIsBundle(protocolFile) && !bundlesEnabled) { const invalidFileAction: InvalidProtocolFileAction = { type: 'protocol:INVALID_FILE', payload: { file: protocolFile, message: BUNDLE_UPLOAD_DISABLED, }, } return dispatch(invalidFileAction) } if (fileIsBinary(protocolFile)) { reader.readAsArrayBuffer(file) } else { reader.readAsText(file) } return dispatch(openAction) } }
apache-2.0
djechelon/spring-security
core/src/main/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManager.java
4175
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.authorization; import java.util.Arrays; import java.util.List; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.util.Assert; /** * A {@link ReactiveAuthorizationManager} that determines if the current user is * authorized by evaluating if the {@link Authentication} contains a specified authority. * * @param <T> the type of object being authorized * @author Rob Winch * @since 5.0 */ public class AuthorityReactiveAuthorizationManager<T> implements ReactiveAuthorizationManager<T> { private final List<String> authorities; AuthorityReactiveAuthorizationManager(String... authorities) { this.authorities = Arrays.asList(authorities); } @Override public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, T object) { // @formatter:off return authentication.filter((a) -> a.isAuthenticated()) .flatMapIterable(Authentication::getAuthorities) .map(GrantedAuthority::getAuthority) .any(this.authorities::contains) .map(AuthorizationDecision::new) .defaultIfEmpty(new AuthorizationDecision(false)); // @formatter:on } /** * Creates an instance of {@link AuthorityReactiveAuthorizationManager} with the * provided authority. * @param authority the authority to check for * @param <T> the type of object being authorized * @return the new instance */ public static <T> AuthorityReactiveAuthorizationManager<T> hasAuthority(String authority) { Assert.notNull(authority, "authority cannot be null"); return new AuthorityReactiveAuthorizationManager<>(authority); } /** * Creates an instance of {@link AuthorityReactiveAuthorizationManager} with the * provided authorities. * * @author Robbie Martinus * @param authorities the authorities to check for * @param <T> the type of object being authorized * @return the new instance */ public static <T> AuthorityReactiveAuthorizationManager<T> hasAnyAuthority(String... authorities) { Assert.notNull(authorities, "authorities cannot be null"); for (String authority : authorities) { Assert.notNull(authority, "authority cannot be null"); } return new AuthorityReactiveAuthorizationManager<>(authorities); } /** * Creates an instance of {@link AuthorityReactiveAuthorizationManager} with the * provided authority. * @param role the authority to check for prefixed with "ROLE_" * @param <T> the type of object being authorized * @return the new instance */ public static <T> AuthorityReactiveAuthorizationManager<T> hasRole(String role) { Assert.notNull(role, "role cannot be null"); return hasAuthority("ROLE_" + role); } /** * Creates an instance of {@link AuthorityReactiveAuthorizationManager} with the * provided authorities. * * @author Robbie Martinus * @param roles the authorities to check for prefixed with "ROLE_" * @param <T> the type of object being authorized * @return the new instance */ public static <T> AuthorityReactiveAuthorizationManager<T> hasAnyRole(String... roles) { Assert.notNull(roles, "roles cannot be null"); for (String role : roles) { Assert.notNull(role, "role cannot be null"); } return hasAnyAuthority(toNamedRolesArray(roles)); } private static String[] toNamedRolesArray(String... roles) { String[] result = new String[roles.length]; for (int i = 0; i < roles.length; i++) { result[i] = "ROLE_" + roles[i]; } return result; } }
apache-2.0
darciopacifico/omr
tags/module_1_0/JazzOMR/bsn/src/main/java/br/com/dlp/jazzomr/poc/ExamInstanceXMLHandler.java
8531
package br.com.dlp.jazzomr.poc; import java.io.IOException; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import br.com.dlp.framework.exception.JazzRuntimeException; import br.com.dlp.jazzomr.empresa.RelatorioVO; import br.com.dlp.jazzomr.exam.ExamOMRMetadataVO; import br.com.dlp.jazzomr.exam.coordinate.CriterionCoordinateVO; /** * Handler para SAX Parser. * Le as coordenadas das alternativas e criterios de questões * @author darcio * */ public class ExamInstanceXMLHandler extends DefaultHandler { private static final long serialVersionUID = 4996383560623589800L; private static final int GROUP_UM = 1; private static final int GROUP_DOIS = 2; private static final int GROUP_TRES = 3; private static final int GROUP_QCO = 1; private Map<Long, CriterionCoordinateVO> mapAlternativeCoords; private boolean waitForTextContentElement=false; private RelatorioVO relatorioVO; private StringBuffer strPage= new StringBuffer(); private Integer paginaAtual=0; private boolean colectPageIdentifier; private static final String ACO_REGEX_KEY = "aco_Key-(.+)-(\\d+)-(\\d+)"; private static final String OMR_MARK_REGEX_KEY = "OMRMark-(.+)-(.+)"; private static final String PAGEIDENTIFIER_REGEX_KEY = "(\\d+)-(\\d+)"; private static final Pattern pageIdentifier_pattern = Pattern.compile(PAGEIDENTIFIER_REGEX_KEY); private static final Pattern aco_pattern = Pattern.compile(ACO_REGEX_KEY); private static final Pattern omr_mark_pattern = Pattern.compile(OMR_MARK_REGEX_KEY); private static final Logger log = LoggerFactory.getLogger(ExamInstanceXMLHandler.class); /** * Apenas para evitar um erro comum quando nao ha conexao com a internet. * Simplesmente para evitar java.net.UnknownHostException para encontrar o dtd quando a internet está fora. */ @Override public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException { //simplesmente para evitar java.net.UnknownHostException para encontrar o dtd quando a internet está fora. return new org.xml.sax.InputSource(new java.io.StringReader("")); } /** * Construtor padrao * @param hibernateTemplate2 * @param mapAlternativeCoords * @param mapQuestionCoords * @param imageDocVO */ public ExamInstanceXMLHandler(RelatorioVO relatorioVO, Map<Long, CriterionCoordinateVO> mapAlternativeCoords) { this.relatorioVO=relatorioVO; this.mapAlternativeCoords = mapAlternativeCoords; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if(this.colectPageIdentifier){ strPage.append(ch,start,length); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if(qName.equals("textContent")){ if(this.colectPageIdentifier){ @SuppressWarnings("unused") String pageIdentifier = strPage.toString(); Matcher matcher = pageIdentifier_pattern.matcher(pageIdentifier); if(matcher.matches()){ String strPagina = matcher.group(GROUP_DOIS); this.paginaAtual = new Integer(strPagina); //ao termino do processamento, a ultima pagina setada sera o igual a quantidade de paginas getRelatorioVO().setTotalPages(this.paginaAtual); this.strPage=new StringBuffer(); this.waitForTextContentElement=false; this.colectPageIdentifier=false; } } } super.endElement(uri, localName, qName); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if(this.waitForTextContentElement && qName.equals("textContent")){ this.colectPageIdentifier=true; } if(qName!=null && qName.equals("reportElement")){ String key = attributes.getValue("key"); if(key!=null){ if(key.equals("pageIdentifier")){ waitForTextContentElement=true; super.startElement(uri, localName, qName, attributes); return; } Matcher aco_matcher = aco_pattern.matcher(key); Matcher omr_mark_matcher=null; if(!getRelatorioVO().isAllCornerOMRMarksfound()){ //apenas para evitar criar o matcher para sempre mesmo que todas as marcas tenham sido encontradas omr_mark_matcher = omr_mark_pattern.matcher(key); } if(aco_matcher.matches()){ //o valor do atributo key bate com o padrao esperado para uma coordenada de bullet fillAlternativeCoordinate(attributes, aco_matcher); }else if(isFindCornerOMRMarks(omr_mark_matcher)){ //o valor do atributo key bate com o padrao esperado para uma marca omr de quina *E* nem todas as necessárias foram encontradas fillOMRMarkCoordinate(attributes, omr_mark_matcher); } } if(log.isDebugEnabled()){ log.debug(key); } } super.startElement(uri, localName, qName, attributes); } /** * Testa se ainda será necessário processar as coordenadas das marcas OMR (discos pretos nas quinas dos relatórios), ou se todos as coordenadas necessárias já foram encontradas * @param omr_mark_matcher * @return */ protected boolean isFindCornerOMRMarks(Matcher omr_mark_matcher) { return !getRelatorioVO().isAllCornerOMRMarksfound() && omr_mark_matcher.matches(); } /** * @param attributes * @param matcher * @return */ protected void fillAlternativeCoordinate(Attributes attributes, Matcher matcher) { String strAco = matcher.group(ExamInstanceXMLHandler.GROUP_DOIS); Long pkAco = Long.parseLong(strAco); CriterionCoordinateVO acoVO = mapAlternativeCoords.get(pkAco); if(acoVO==null){ String msg = "A coordenada do criterio "+pkAco+", encontrado no xml de prova, nao foi encontrada no mapa de coordenadas ("+mapAlternativeCoords+"). Verifique se a query do relatorio está correta!"; log.error(msg); throw new JazzRuntimeException(msg); } if(!isCoordenadasPreenchidas(acoVO)){ //se o criterio possuir múltiplas páginas, eu devo registrar as coordenadas da primeira página onde aparece o critério, pois é onde está o enunciado do mesmo. String strX = attributes.getValue("x"); String strY = attributes.getValue("y"); String strW = attributes.getValue("width"); String strH = attributes.getValue("height"); Integer x=Integer.parseInt(strX); Integer y=Integer.parseInt(strY); Integer w=Integer.parseInt(strW); Integer h=Integer.parseInt(strH); acoVO.setPK(pkAco); acoVO.setH(h); acoVO.setW(w); acoVO.setX(x); acoVO.setY(y); acoVO.setPagina(this.paginaAtual); } acoVO.getPaginas().add(this.paginaAtual); } /** * Testa se as coordenadas deste critério já forma preenchidas * @param acoVO * @return */ protected boolean isCoordenadasPreenchidas(CriterionCoordinateVO acoVO) { return acoVO.getPagina()!=null; } /** * @param attributes * @param matcher * @return */ protected void fillOMRMarkCoordinate(Attributes attributes, Matcher matcher) { //simples leitura dos atributos String pos1 = matcher.group(1); String pos2 = matcher.group(2); String omrMarksKey = pos1+"-"+pos2; String strX = attributes.getValue("x"); String strY = attributes.getValue("y"); String strW = attributes.getValue("width"); String strH = attributes.getValue("height"); Integer x=Integer.parseInt(strX); Integer y=Integer.parseInt(strY); Integer w=Integer.parseInt(strW); Integer h=Integer.parseInt(strH); //Verificando (mais uma vez) se a coordenada esta registrada ExamOMRMetadataVO examOMRMetadataVO = this.getRelatorioVO().getExamOMRMetadataVO().get(omrMarksKey); if(examOMRMetadataVO==null){ //caso a coordenada ainda nao esteja registrada, cria-se uma nova com os valores encontrados no XML Double xCenter = x.doubleValue()+(w/2); Double yCenter = y.doubleValue()+(h/2); examOMRMetadataVO = new ExamOMRMetadataVO(); examOMRMetadataVO.setX(xCenter); examOMRMetadataVO.setY(yCenter); examOMRMetadataVO.setOmrKey(omrMarksKey); //atualiza mapa de coordenadas do exame this.getRelatorioVO().getExamOMRMetadataVO().put(omrMarksKey, examOMRMetadataVO); } } public RelatorioVO getRelatorioVO() { return relatorioVO; } public void setRelatorioVO(RelatorioVO relatorioVO) { this.relatorioVO = relatorioVO; } }
apache-2.0
lshain-android-source/tools-idea
java/java-psi-api/src/com/intellij/codeInsight/AnnotationUtil.java
20159
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.util.ArrayUtil; import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author max */ public class AnnotationUtil { /** * The full qualified name of the standard Nullable annotation. */ public static final String NULLABLE = "org.jetbrains.annotations.Nullable"; /** * The full qualified name of the standard NotNull annotation. */ public static final String NOT_NULL = "org.jetbrains.annotations.NotNull"; @NonNls public static final String NOT_NULL_SIMPLE_NAME = "NotNull"; @NonNls public static final String NULLABLE_SIMPLE_NAME = "Nullable"; /** * The full qualified name of the standard NonNls annotation. * * @since 5.0.1 */ public static final String NON_NLS = "org.jetbrains.annotations.NonNls"; public static final String NLS = "org.jetbrains.annotations.Nls"; public static final String PROPERTY_KEY = "org.jetbrains.annotations.PropertyKey"; @NonNls public static final String PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER = "resourceBundle"; @NonNls public static final String NON_NLS_SIMPLE_NAME = "NonNls"; @NonNls public static final String PROPERTY_KEY_SIMPLE_NAME = "PropertyKey"; public static final String TEST_ONLY = "org.jetbrains.annotations.TestOnly"; @NonNls public static final String TEST_ONLY_SIMPLE_NAME = "TestOnly"; public static final String LANGUAGE = "org.intellij.lang.annotations.Language"; public static final Set<String> ALL_ANNOTATIONS; @NonNls private static final String[] SIMPLE_NAMES = {NOT_NULL_SIMPLE_NAME, NULLABLE_SIMPLE_NAME, NON_NLS_SIMPLE_NAME, PROPERTY_KEY_SIMPLE_NAME, TEST_ONLY_SIMPLE_NAME, "Language", "Identifier", "Pattern", "PrintFormat", "RegExp", "Subst"}; static { ALL_ANNOTATIONS = new HashSet<String>(2); ALL_ANNOTATIONS.add(NULLABLE); ALL_ANNOTATIONS.add(NOT_NULL); } @Nullable public static PsiAnnotation findAnnotation(PsiModifierListOwner listOwner, @NotNull String... annotationNames) { return findAnnotation(listOwner, false, annotationNames); } @Nullable public static PsiAnnotation findAnnotation(PsiModifierListOwner listOwner, final boolean skipExternal, @NotNull String... annotationNames) { if (annotationNames.length == 0) return null; Set<String> set = annotationNames.length == 1 ? Collections.singleton(annotationNames[0]) : new HashSet<String>(Arrays.asList(annotationNames)); return findAnnotation(listOwner, set, skipExternal); } @Nullable public static PsiAnnotation findAnnotation(@Nullable PsiModifierListOwner listOwner, @NotNull Set<String> annotationNames) { return findAnnotation(listOwner, (Collection<String>)annotationNames); } @Nullable public static PsiAnnotation findAnnotation(@Nullable PsiModifierListOwner listOwner, Collection<String> annotationNames) { return findAnnotation(listOwner, annotationNames, false); } @Nullable public static PsiAnnotation findAnnotation(@Nullable PsiModifierListOwner listOwner, @NotNull Collection<String> annotationNames, final boolean skipExternal) { if (listOwner == null) return null; final PsiModifierList list = listOwner.getModifierList(); if (list == null) return null; final PsiAnnotation[] allAnnotations = list.getAnnotations(); for (PsiAnnotation annotation : allAnnotations) { String qualifiedName = annotation.getQualifiedName(); if (annotationNames.contains(qualifiedName)) { return annotation; } } if (!skipExternal) { final ExternalAnnotationsManager annotationsManager = ExternalAnnotationsManager.getInstance(listOwner.getProject()); for (String annotationName : annotationNames) { final PsiAnnotation annotation = annotationsManager.findExternalAnnotation(listOwner, annotationName); if (annotation != null) { return annotation; } } } return null; } @NotNull public static PsiAnnotation[] findAnnotations(final PsiModifierListOwner modifierListOwner, @NotNull Collection<String> annotationNames) { if (modifierListOwner == null) return PsiAnnotation.EMPTY_ARRAY; final PsiModifierList modifierList = modifierListOwner.getModifierList(); if (modifierList == null) return PsiAnnotation.EMPTY_ARRAY; final PsiAnnotation[] annotations = modifierList.getAnnotations(); ArrayList<PsiAnnotation> result = null; for (final PsiAnnotation psiAnnotation : annotations) { if (annotationNames.contains(psiAnnotation.getQualifiedName())) { if (result == null) result = new ArrayList<PsiAnnotation>(); result.add(psiAnnotation); } } return result == null ? PsiAnnotation.EMPTY_ARRAY : result.toArray(new PsiAnnotation[result.size()]); } @Nullable public static PsiAnnotation findAnnotationInHierarchy(PsiModifierListOwner listOwner, @NotNull Set<String> annotationNames) { PsiAnnotation directAnnotation = findAnnotation(listOwner, annotationNames); if (directAnnotation != null) return directAnnotation; if (listOwner instanceof PsiMethod) { PsiMethod method = (PsiMethod)listOwner; PsiClass aClass = method.getContainingClass(); if (aClass == null) return null; HierarchicalMethodSignature methodSignature = method.getHierarchicalMethodSignature(); return findAnnotationInHierarchy(methodSignature, annotationNames, method, null, JavaPsiFacade.getInstance(method.getProject()).getResolveHelper()); } if (listOwner instanceof PsiClass) { return findAnnotationInHierarchy((PsiClass)listOwner, annotationNames, null); } if (listOwner instanceof PsiParameter) { PsiParameter parameter = (PsiParameter)listOwner; return doFindAnnotationInHierarchy(parameter, annotationNames, null); } return null; } @Nullable private static PsiAnnotation doFindAnnotationInHierarchy(PsiParameter parameter, Set<String> annotationNames, @Nullable Set<PsiModifierListOwner> visited) { PsiAnnotation annotation = findAnnotation(parameter, annotationNames); if (annotation != null) return annotation; PsiElement scope = parameter.getDeclarationScope(); if (!(scope instanceof PsiMethod)) { return null; } PsiMethod method = (PsiMethod)scope; PsiClass aClass = method.getContainingClass(); PsiElement parent = parameter.getParent(); if (aClass == null || !(parent instanceof PsiParameterList)) { return null; } int index = ((PsiParameterList)parent).getParameterIndex(parameter); HierarchicalMethodSignature methodSignature = method.getHierarchicalMethodSignature(); final List<HierarchicalMethodSignature> superSignatures = methodSignature.getSuperSignatures(); PsiResolveHelper resolveHelper = PsiResolveHelper.SERVICE.getInstance(aClass.getProject()); for (final HierarchicalMethodSignature superSignature : superSignatures) { final PsiMethod superMethod = superSignature.getMethod(); if (visited == null) visited = new THashSet<PsiModifierListOwner>(); if (!visited.add(superMethod)) continue; if (!resolveHelper.isAccessible(superMethod, parameter, null)) continue; PsiParameter[] superParameters = superMethod.getParameterList().getParameters(); if (index < superParameters.length) { PsiAnnotation insuper = doFindAnnotationInHierarchy(superParameters[index], annotationNames, visited); if (insuper != null) return insuper; } } return null; } @Nullable private static PsiAnnotation findAnnotationInHierarchy(@NotNull final PsiClass psiClass, final Set<String> annotationNames, @Nullable Set<PsiClass> processed) { final PsiClass[] superClasses = psiClass.getSupers(); for (final PsiClass superClass : superClasses) { if (processed == null) processed = new THashSet<PsiClass>(); if (!processed.add(superClass)) return null; final PsiAnnotation annotation = findAnnotation(superClass, annotationNames); if (annotation != null) return annotation; final PsiAnnotation annotationInHierarchy = findAnnotationInHierarchy(superClass, annotationNames, processed); if (annotationInHierarchy != null) return annotationInHierarchy; } return null; } @Nullable private static PsiAnnotation findAnnotationInHierarchy(@NotNull HierarchicalMethodSignature signature, @NotNull Set<String> annotationNames, @NotNull PsiElement place, @Nullable Set<PsiMethod> processed, @NotNull PsiResolveHelper resolveHelper) { final List<HierarchicalMethodSignature> superSignatures = signature.getSuperSignatures(); for (final HierarchicalMethodSignature superSignature : superSignatures) { final PsiMethod superMethod = superSignature.getMethod(); if (processed == null) processed = new THashSet<PsiMethod>(); if (!processed.add(superMethod)) continue; if (!resolveHelper.isAccessible(superMethod, place, null)) continue; PsiAnnotation direct = findAnnotation(superMethod, annotationNames); if (direct != null) return direct; PsiAnnotation superResult = findAnnotationInHierarchy(superSignature, annotationNames, place, processed, resolveHelper); if (superResult != null) return superResult; } return null; } public static boolean isAnnotated(@NotNull PsiModifierListOwner listOwner, Collection<String> annotations) { return isAnnotated(listOwner, annotations, false); } public static boolean isAnnotated(@NotNull PsiModifierListOwner listOwner, Collection<String> annotations, final boolean checkHierarchy) { return isAnnotated(listOwner, annotations, checkHierarchy, true); } public static boolean isAnnotated(@NotNull PsiModifierListOwner listOwner, Collection<String> annotations, final boolean checkHierarchy, boolean skipExternal) { for (String annotation : annotations) { if (isAnnotated(listOwner, annotation, checkHierarchy, skipExternal)) return true; } return false; } public static boolean isAnnotated(@NotNull PsiModifierListOwner listOwner, @NonNls String annotationFQN, boolean checkHierarchy) { return isAnnotated(listOwner, annotationFQN, checkHierarchy, true, null); } public static boolean isAnnotated(@NotNull PsiModifierListOwner listOwner, @NonNls String annotationFQN, boolean checkHierarchy, boolean skipExternal) { return isAnnotated(listOwner, annotationFQN, checkHierarchy, skipExternal, null); } private static boolean isAnnotated(@NotNull PsiModifierListOwner listOwner, @NonNls String annotationFQN, boolean checkHierarchy, final boolean skipExternal, @Nullable Set<PsiMember> processed) { if (!listOwner.isValid()) return false; final PsiModifierList modifierList = listOwner.getModifierList(); if (modifierList == null) return false; PsiAnnotation annotation = modifierList.findAnnotation(annotationFQN); if (annotation != null) return true; if (!skipExternal && ExternalAnnotationsManager.getInstance(listOwner.getProject()).findExternalAnnotation(listOwner, annotationFQN) != null) { return true; } if (checkHierarchy) { if (listOwner instanceof PsiMethod) { PsiMethod method = (PsiMethod)listOwner; if (processed == null) processed = new THashSet<PsiMember>(); if (!processed.add(method)) return false; final PsiMethod[] superMethods = method.findSuperMethods(); for (PsiMethod superMethod : superMethods) { if (isAnnotated(superMethod, annotationFQN, checkHierarchy, skipExternal, processed)) return true; } } else if (listOwner instanceof PsiClass) { final PsiClass clazz = (PsiClass)listOwner; if (processed == null) processed = new THashSet<PsiMember>(); if (!processed.add(clazz)) return false; final PsiClass[] superClasses = clazz.getSupers(); for (PsiClass superClass : superClasses) { if (isAnnotated(superClass, annotationFQN, checkHierarchy, skipExternal, processed)) return true; } } } return false; } public static boolean isAnnotatingApplicable(@NotNull PsiElement elt) { return isAnnotatingApplicable(elt, NullableNotNullManager.getInstance(elt.getProject()).getDefaultNullable()); } public static boolean isAnnotatingApplicable(@NotNull PsiElement elt, final String annotationFQN) { final Project project = elt.getProject(); return PsiUtil.isLanguageLevel5OrHigher(elt) && JavaPsiFacade.getInstance(project).findClass(annotationFQN, elt.getResolveScope()) != null; } public static boolean isJetbrainsAnnotation(@NonNls final String simpleName) { return ArrayUtil.find(SIMPLE_NAMES, simpleName) != -1; } /** * Works similar to #isAnnotated(PsiModifierListOwner, Collection<String>) but supports FQN patters * like "javax.ws.rs.*". Supports ending "*" only. * * @param owner modifier list * @param annotations annotations qualified names or patterns. Patterns can have '*' at the end * @return <code>true</code> if annotated of at least one annotation from the annotations list */ public static boolean checkAnnotatedUsingPatterns(PsiModifierListOwner owner, Collection<String> annotations) { final PsiModifierList modList; if (owner == null || (modList = owner.getModifierList()) == null) return false; List<String> fqns = null; for (String fqn : annotations) { boolean isPattern = fqn.endsWith("*"); if (!isPattern && isAnnotated(owner, fqn, false)) { return true; } else if (isPattern) { if (fqns == null) { fqns = new ArrayList<String>(); final PsiAnnotation[] annos = modList.getAnnotations(); for (PsiAnnotation anno : annos) { final String qName = anno.getQualifiedName(); if (qName != null) { fqns.add(qName); } } if (fqns.isEmpty()) return false; } fqn = fqn.substring(0, fqn.length() - 2); for (String annoFQN : fqns) { if (annoFQN.startsWith(fqn)) { return true; } } } } return false; } @Nullable public static PsiMethod getAnnotationMethod(PsiNameValuePair pair) { final PsiAnnotation annotation = PsiTreeUtil.getParentOfType(pair.getParent(), PsiAnnotation.class); assert annotation != null; final String fqn = annotation.getQualifiedName(); if (fqn == null) return null; final PsiClass psiClass = JavaPsiFacade.getInstance(pair.getProject()).findClass(fqn, pair.getResolveScope()); if (psiClass != null && psiClass.isAnnotationType()) { final String name = pair.getName(); return ArrayUtil.getFirstElement(psiClass.findMethodsByName(name != null ? name : "value", false)); } return null; } @NotNull public static PsiAnnotation[] getAllAnnotations(@NotNull PsiModifierListOwner owner, boolean inHierarchy, Set<PsiModifierListOwner> visited) { final PsiModifierList list = owner.getModifierList(); PsiAnnotation[] annotations = PsiAnnotation.EMPTY_ARRAY; if (list != null) { annotations = list.getAnnotations(); } final PsiAnnotation[] externalAnnotations = ExternalAnnotationsManager.getInstance(owner.getProject()).findExternalAnnotations(owner); if (externalAnnotations != null) { annotations = ArrayUtil.mergeArrays(annotations, externalAnnotations, PsiAnnotation.ARRAY_FACTORY); } if (inHierarchy) { if (owner instanceof PsiClass) { for (PsiClass superClass : ((PsiClass)owner).getSupers()) { if (visited == null) visited = new THashSet<PsiModifierListOwner>(); if (visited.add(superClass)) annotations = ArrayUtil.mergeArrays(annotations, getAllAnnotations(superClass, inHierarchy, visited)); } } else if (owner instanceof PsiMethod) { PsiMethod method = (PsiMethod)owner; PsiClass aClass = method.getContainingClass(); if (aClass != null) { HierarchicalMethodSignature methodSignature = method.getHierarchicalMethodSignature(); final List<HierarchicalMethodSignature> superSignatures = methodSignature.getSuperSignatures(); PsiResolveHelper resolveHelper = PsiResolveHelper.SERVICE.getInstance(aClass.getProject()); for (final HierarchicalMethodSignature superSignature : superSignatures) { final PsiMethod superMethod = superSignature.getMethod(); if (visited == null) visited = new THashSet<PsiModifierListOwner>(); if (!visited.add(superMethod)) continue; if (!resolveHelper.isAccessible(superMethod, owner, null)) continue; annotations = ArrayUtil.mergeArrays(annotations, getAllAnnotations(superMethod, inHierarchy, visited)); } } } else if (owner instanceof PsiParameter) { PsiParameter parameter = (PsiParameter)owner; PsiElement scope = parameter.getDeclarationScope(); if (scope instanceof PsiMethod) { PsiMethod method = (PsiMethod)scope; PsiClass aClass = method.getContainingClass(); PsiElement parent = parameter.getParent(); if (aClass != null && parent instanceof PsiParameterList) { int index = ((PsiParameterList)parent).getParameterIndex(parameter); HierarchicalMethodSignature methodSignature = method.getHierarchicalMethodSignature(); final List<HierarchicalMethodSignature> superSignatures = methodSignature.getSuperSignatures(); PsiResolveHelper resolveHelper = PsiResolveHelper.SERVICE.getInstance(aClass.getProject()); for (final HierarchicalMethodSignature superSignature : superSignatures) { final PsiMethod superMethod = superSignature.getMethod(); if (visited == null) visited = new THashSet<PsiModifierListOwner>(); if (!visited.add(superMethod)) continue; if (!resolveHelper.isAccessible(superMethod, owner, null)) continue; PsiParameter[] superParameters = superMethod.getParameterList().getParameters(); if (index < superParameters.length) { annotations = ArrayUtil.mergeArrays(annotations, getAllAnnotations(superParameters[index], inHierarchy, visited)); } } } } } } return annotations; } public static boolean isInsideAnnotation(PsiElement element) { return PsiTreeUtil.getParentOfType(element, PsiNameValuePair.class, PsiArrayInitializerMemberValue.class) != null; } }
apache-2.0
ened/ExoPlayer
library/extractor/src/test/java/com/google/android/exoplayer2/extractor/ogg/DefaultOggSeekerTest.java
7812
/* * Copyright (C) 2016 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.google.android.exoplayer2.extractor.ogg; import static com.google.android.exoplayer2.testutil.TestUtil.getByteArray; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.testutil.FakeExtractorInput; import com.google.android.exoplayer2.testutil.TestUtil; import com.google.android.exoplayer2.util.ParsableByteArray; import java.io.EOFException; import java.io.IOException; import java.util.Random; import org.junit.Test; import org.junit.runner.RunWith; /** Unit test for {@link DefaultOggSeeker}. */ @RunWith(AndroidJUnit4.class) public final class DefaultOggSeekerTest { private final Random random = new Random(/* seed= */ 0); @Test public void setupWithUnsetEndPositionFails() { try { new DefaultOggSeeker( /* streamReader= */ new TestStreamReader(), /* payloadStartPosition= */ 0, /* payloadEndPosition= */ C.LENGTH_UNSET, /* firstPayloadPageSize= */ 1, /* firstPayloadPageGranulePosition= */ 1, /* firstPayloadPageIsLastPage= */ false); fail(); } catch (IllegalArgumentException e) { // ignored } } @Test public void seeking() throws Exception { byte[] data = getByteArray(ApplicationProvider.getApplicationContext(), "media/ogg/random_1000_pages"); int granuleCount = 49269395; int firstPayloadPageSize = 2023; int firstPayloadPageGranuleCount = 57058; int lastPayloadPageSize = 282; int lastPayloadPageGranuleCount = 20806; FakeExtractorInput input = new FakeExtractorInput.Builder().setData(data).build(); TestStreamReader streamReader = new TestStreamReader(); DefaultOggSeeker oggSeeker = new DefaultOggSeeker( streamReader, /* payloadStartPosition= */ 0, /* payloadEndPosition= */ data.length, firstPayloadPageSize, /* firstPayloadPageGranulePosition= */ firstPayloadPageGranuleCount, /* firstPayloadPageIsLastPage= */ false); OggPageHeader pageHeader = new OggPageHeader(); while (true) { long nextSeekPosition = oggSeeker.read(input); if (nextSeekPosition == -1) { break; } input.setPosition((int) nextSeekPosition); } // Test granule 0 from file start. long granule = seekTo(input, oggSeeker, 0, 0); assertThat(granule).isEqualTo(0); assertThat(input.getPosition()).isEqualTo(0); // Test granule 0 from file end. granule = seekTo(input, oggSeeker, 0, data.length - 1); assertThat(granule).isEqualTo(0); assertThat(input.getPosition()).isEqualTo(0); // Test last granule. granule = seekTo(input, oggSeeker, granuleCount - 1, 0); assertThat(granule).isEqualTo(granuleCount - lastPayloadPageGranuleCount); assertThat(input.getPosition()).isEqualTo(data.length - lastPayloadPageSize); for (int i = 0; i < 100; i += 1) { long targetGranule = random.nextInt(granuleCount); int initialPosition = random.nextInt(data.length); granule = seekTo(input, oggSeeker, targetGranule, initialPosition); int currentPosition = (int) input.getPosition(); if (granule == 0) { assertThat(currentPosition).isEqualTo(0); } else { int previousPageStart = findPreviousPageStart(data, currentPosition); input.setPosition(previousPageStart); pageHeader.populate(input, false); assertThat(granule).isEqualTo(pageHeader.granulePosition); } input.setPosition(currentPosition); pageHeader.populate(input, false); // The target granule should be within the current page. assertThat(granule).isAtMost(targetGranule); assertThat(targetGranule).isLessThan(pageHeader.granulePosition); } } @Test public void readGranuleOfLastPage() throws IOException { // This test stream has three headers with granule numbers 20000, 40000 and 60000. byte[] data = getByteArray(ApplicationProvider.getApplicationContext(), "media/ogg/three_headers"); FakeExtractorInput input = createInput(data, /* simulateUnknownLength= */ false); assertReadGranuleOfLastPage(input, 60000); } @Test public void readGranuleOfLastPage_afterLastHeader_throwsException() throws Exception { FakeExtractorInput input = createInput(TestUtil.buildTestData(100, random), /* simulateUnknownLength= */ false); try { assertReadGranuleOfLastPage(input, 60000); fail(); } catch (EOFException e) { // Ignored. } } @Test public void readGranuleOfLastPage_withUnboundedLength_throwsException() throws Exception { FakeExtractorInput input = createInput(new byte[0], /* simulateUnknownLength= */ true); try { assertReadGranuleOfLastPage(input, 60000); fail(); } catch (IllegalArgumentException e) { // Ignored. } } private static void assertReadGranuleOfLastPage(FakeExtractorInput input, int expected) throws IOException { DefaultOggSeeker oggSeeker = new DefaultOggSeeker( /* streamReader= */ new FlacReader(), /* payloadStartPosition= */ 0, /* payloadEndPosition= */ input.getLength(), /* firstPayloadPageSize= */ 1, /* firstPayloadPageGranulePosition= */ 2, /* firstPayloadPageIsLastPage= */ false); while (true) { try { assertThat(oggSeeker.readGranuleOfLastPage(input)).isEqualTo(expected); break; } catch (FakeExtractorInput.SimulatedIOException e) { // Ignored. } } } private static FakeExtractorInput createInput(byte[] data, boolean simulateUnknownLength) { return new FakeExtractorInput.Builder() .setData(data) .setSimulateIOErrors(true) .setSimulateUnknownLength(simulateUnknownLength) .setSimulatePartialReads(true) .build(); } private static long seekTo( FakeExtractorInput input, DefaultOggSeeker oggSeeker, long targetGranule, int initialPosition) throws IOException { long nextSeekPosition = initialPosition; oggSeeker.startSeek(targetGranule); int count = 0; while (nextSeekPosition >= 0) { if (count++ > 100) { fail("Seek failed to converge in 100 iterations"); } input.setPosition((int) nextSeekPosition); nextSeekPosition = oggSeeker.read(input); } return -(nextSeekPosition + 2); } private static int findPreviousPageStart(byte[] data, int position) { for (int i = position - 4; i >= 0; i--) { if (data[i] == 'O' && data[i + 1] == 'g' && data[i + 2] == 'g' && data[i + 3] == 'S') { return i; } } fail(); return -1; } private static class TestStreamReader extends StreamReader { @Override protected long preparePayload(ParsableByteArray packet) { return 0; } @Override protected boolean readHeaders(ParsableByteArray packet, long position, SetupData setupData) { return false; } } }
apache-2.0
missioncommand/mil-sym-android
renderer/src/main/java/sec/geo/shape/Circle.java
2430
package sec.geo.shape; import sec.geo.GeoPoint; import sec.geo.ShapeObject; import sec.geo.GeoEllipse; import sec.geo.kml.KmlOptions.AltitudeMode; public class Circle /*extends APivot*/ { //APivot extends AExtrusion protected GeoPoint pivot; protected double radiusMeters; private ShapeObject shape; protected double maxDistanceMeters; protected double flatnessDistanceMeters; protected AltitudeMode altitudeMode; private double minAltitudeMeters; private double maxAltitudeMeters; protected int limit; public Circle() { pivot = new GeoPoint(); maxDistanceMeters = 100000; flatnessDistanceMeters = 1; limit = 4; } public ShapeObject getShape() { if (shape == null) { shape = createShape(); } return shape; } //@Override public void setRadius(double radiusMeters) { this.radiusMeters = radiusMeters; shapeChanged(); } //@Override public void setPivot(GeoPoint pivot) { this.pivot = pivot; shapeChanged(); } //@Override protected ShapeObject createShape() { GeoEllipse e = new GeoEllipse(pivot, radiusMeters * 2, radiusMeters * 2, maxDistanceMeters, flatnessDistanceMeters, limit); return new ShapeObject(e); } protected void shapeChanged() { shape = null; } public double getMinAltitude() { return minAltitudeMeters; } public void setMinAltitude(double minAltitudeMeters) { this.minAltitudeMeters = minAltitudeMeters; shapeChanged(); } public double getMaxAltitude() { return maxAltitudeMeters; } public void setMaxAltitude(double maxAltitudeMeters) { this.maxAltitudeMeters = maxAltitudeMeters; shapeChanged(); } public void setMaxDistance(double maxDistanceMeters) { this.maxDistanceMeters = maxDistanceMeters; shapeChanged(); } public void setFlatness(double flatnessDistanceMeters) { this.flatnessDistanceMeters = flatnessDistanceMeters; shapeChanged(); } public void setLimit(int limit) { this.limit = limit; shapeChanged(); } public AltitudeMode getAltitudeMode() { return altitudeMode; } public void setAltitudeMode(AltitudeMode altitudeMode) { this.altitudeMode = altitudeMode; } }
apache-2.0
voke/google-adwords-api
test/examples/v201109_1/test_campaign_management.rb
3670
#!/usr/bin/env ruby # Encoding: utf-8 # # Author:: api.dklimkin@gmail.com (Danial Klimkin) # # Copyright:: Copyright 2012, Google Inc. All Rights Reserved. # # License:: 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. # # Tests the campaign management examples. require 'test/unit' require 'campaign_management/add_experiment' require 'campaign_management/add_keywords_in_bulk' require 'campaign_management/add_location_extension' require 'campaign_management/add_location_extension_override' require 'campaign_management/get_all_disapproved_ads' require 'campaign_management/promote_experiment' require 'campaign_management/set_ad_parameters' require 'campaign_management/validate_text_ad' RETRY_INTERVAL = 5 RETRIES_COUNT = 3 KEYWORD_NUMBER = 3 class TestCampaignManagementV201109_1 < Test::Unit::TestCase def setup @logger = Logger.new(STDOUT) @logger.level = Logger::ERROR @adwords = AdwordsApi::Api.new @adwords.logger = @logger @utils = UtilsV201109_1.new(@adwords) end def test_add_experiment campaign = @utils.get_campaign() ad_group = @utils.get_ad_group() criterion = @utils.get_keyword() assert_not_nil(campaign) assert_not_nil(campaign[:id]) assert_not_nil(ad_group) assert_not_nil(ad_group[:id]) assert_not_nil(criterion) assert_not_nil(criterion[:criterion]) assert_not_nil(criterion[:criterion][:id]) add_experiment(campaign[:id], ad_group[:id], criterion[:criterion][:id]) end def test_add_keywords_in_bulk add_keywords_in_bulk() end def test_add_location_extension campaign = @utils.get_campaign() assert_not_nil(campaign) assert_not_nil(campaign[:id]) add_location_extension(campaign[:id]) end def test_add_location_extension_override ad = @utils.get_ad() location_extension = @utils.get_location_extension() assert_not_nil(ad) assert_not_nil(ad[:ad]) assert_not_nil(ad[:ad][:id]) assert_not_nil(location_extension) assert_not_nil(location_extension[:ad_extension]) assert_not_nil(location_extension[:ad_extension][:id]) add_location_extension_override( ad[:ad][:id], location_extension[:ad_extension][:id]) end def test_get_all_disapproved_ads ad_group = @utils.get_ad_group() assert_not_nil(ad_group) assert_not_nil(ad_group[:id]) get_all_disapproved_ads(ad_group[:id]) end def test_promote_experiment experiment = @utils.get_experiment() assert_not_nil(experiment) assert_not_nil(experiment[:id]) promote_experiment(experiment[:id]) end def test_set_ad_parameters ad_group = @utils.get_ad_group() assert_not_nil(ad_group) assert_not_nil(ad_group[:id]) criterion = @utils.get_keyword() assert_not_nil(criterion) assert_not_nil(criterion[:criterion]) assert_not_nil(criterion[:criterion][:id]) set_ad_parameters(ad_group[:id], criterion[:criterion][:id]) end def test_validate_text_ad ad_group = @utils.get_ad_group() assert_not_nil(ad_group) assert_not_nil(ad_group[:id]) validate_text_ad(ad_group[:id]) end end
apache-2.0
arvindsv/gocd
common/src/main/java/com/thoughtworks/go/remote/work/AgentWorkContext.java
3533
/* * Copyright 2020 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.remote.work; import com.thoughtworks.go.plugin.access.artifact.ArtifactExtension; import com.thoughtworks.go.plugin.access.packagematerial.PackageRepositoryExtension; import com.thoughtworks.go.plugin.access.pluggabletask.TaskExtension; import com.thoughtworks.go.plugin.access.scm.SCMExtension; import com.thoughtworks.go.plugin.infra.PluginRequestProcessorRegistry; import com.thoughtworks.go.publishers.GoArtifactsManipulator; import com.thoughtworks.go.remote.AgentIdentifier; import com.thoughtworks.go.remote.BuildRepositoryRemote; import com.thoughtworks.go.server.service.AgentRuntimeInfo; public class AgentWorkContext { private AgentIdentifier agentIdentifier; private BuildRepositoryRemote repositoryRemote; private GoArtifactsManipulator artifactsManipulator; private AgentRuntimeInfo agentRuntimeInfo; private PackageRepositoryExtension packageRepositoryExtension; private SCMExtension scmExtension; private TaskExtension taskExtension; private ArtifactExtension artifactExtension; private final PluginRequestProcessorRegistry pluginRequestProcessorRegistry; public AgentWorkContext(AgentIdentifier agentIdentifier, BuildRepositoryRemote repositoryRemote, GoArtifactsManipulator artifactsManipulator, AgentRuntimeInfo agentRuntimeInfo, PackageRepositoryExtension packageRepositoryExtension, SCMExtension scmExtension, TaskExtension taskExtension, ArtifactExtension artifactExtension, PluginRequestProcessorRegistry pluginRequestProcessorRegistry) { this.agentIdentifier = agentIdentifier; this.repositoryRemote = repositoryRemote; this.artifactsManipulator = artifactsManipulator; this.agentRuntimeInfo = agentRuntimeInfo; this.packageRepositoryExtension = packageRepositoryExtension; this.scmExtension = scmExtension; this.taskExtension = taskExtension; this.artifactExtension = artifactExtension; this.pluginRequestProcessorRegistry = pluginRequestProcessorRegistry; } public AgentIdentifier getAgentIdentifier() { return agentIdentifier; } public BuildRepositoryRemote getRepositoryRemote() { return repositoryRemote; } public GoArtifactsManipulator getArtifactsManipulator() { return artifactsManipulator; } public AgentRuntimeInfo getAgentRuntimeInfo() { return agentRuntimeInfo; } public PackageRepositoryExtension getPackageRepositoryExtension() { return packageRepositoryExtension; } public SCMExtension getScmExtension() { return scmExtension; } public TaskExtension getTaskExtension() { return taskExtension; } public ArtifactExtension getArtifactExtension() { return artifactExtension; } public PluginRequestProcessorRegistry getPluginRequestProcessorRegistry() { return pluginRequestProcessorRegistry; } }
apache-2.0
documentcloud/document-viewer
public/javascripts/DV/models/document.js
4571
DV.model.Document = function(viewer){ this.viewer = viewer; this.currentPageIndex = 0; this.offsets = []; this.baseHeightsPortion = []; this.baseHeightsPortionOffsets = []; this.paddedOffsets = []; this.originalPageText = {}; this.totalDocumentHeight = 0; this.totalPages = 0; this.additionalPaddingOnPage = 0; this.ZOOM_RANGES = [500, 700, 800, 900, 1000]; var data = this.viewer.schema.data; this.state = data.state; this.baseImageURL = data.baseImageURL; this.canonicalURL = data.canonicalURL; this.additionalPaddingOnPage = data.additionalPaddingOnPage; this.pageWidthPadding = data.pageWidthPadding; this.totalPages = data.totalPages; this.onPageChangeCallbacks = []; var zoom = this.zoomLevel = this.viewer.options.zoom || data.zoomLevel; if (zoom == 'auto') this.zoomLevel = data.zoomLevel; // The zoom level cannot go over the maximum image width. var maxZoom = DV._.last(this.ZOOM_RANGES); if (this.zoomLevel > maxZoom) this.zoomLevel = maxZoom; }; DV.model.Document.prototype = { setPageIndex : function(index) { this.currentPageIndex = index; this.viewer.elements.currentPage.text(this.currentPage()); this.viewer.helpers.setActiveChapter(this.viewer.models.chapters.getChapterId(index)); DV._.each(this.onPageChangeCallbacks, function(c) { c(); }); return index; }, currentPage : function() { return this.currentPageIndex + 1; }, currentIndex : function() { return this.currentPageIndex; }, nextPage : function() { var nextIndex = this.currentIndex() + 1; if (nextIndex >= this.totalPages) return this.currentIndex(); return this.setPageIndex(nextIndex); }, previousPage : function() { var previousIndex = this.currentIndex() - 1; if (previousIndex < 0) return this.currentIndex(); return this.setPageIndex(previousIndex); }, zoom: function(zoomLevel,force){ if(this.zoomLevel != zoomLevel || force === true){ this.zoomLevel = zoomLevel; this.viewer.models.pages.resize(this.zoomLevel); this.viewer.models.annotations.renderAnnotations(); this.computeOffsets(); } }, computeOffsets: function() { var annotationModel = this.viewer.models.annotations; var totalDocHeight = 0; var adjustedOffset = 0; var len = this.totalPages; var diff = 0; var scrollPos = this.viewer.elements.window[0].scrollTop; for(var i = 0; i < len; i++) { if(annotationModel.offsetsAdjustments[i]){ adjustedOffset = annotationModel.offsetsAdjustments[i]; } var pageHeight = this.viewer.models.pages.getPageHeight(i); var previousOffset = this.offsets[i] || 0; var h = this.offsets[i] = adjustedOffset + totalDocHeight; if((previousOffset !== h) && (h < scrollPos)) { var delta = h - previousOffset - diff; scrollPos += delta; diff += delta; } this.baseHeightsPortion[i] = Math.round((pageHeight + this.additionalPaddingOnPage) / 3); this.baseHeightsPortionOffsets[i] = (i == 0) ? 0 : h - this.baseHeightsPortion[i]; totalDocHeight += (pageHeight + this.additionalPaddingOnPage); } // Add the sum of the page note heights to the total document height. totalDocHeight += adjustedOffset; // artificially set the scrollbar height if(totalDocHeight != this.totalDocumentHeight){ diff = (this.totalDocumentHeight != 0) ? diff : totalDocHeight - this.totalDocumentHeight; this.viewer.helpers.setDocHeight(totalDocHeight,diff); this.totalDocumentHeight = totalDocHeight; } }, getOffset: function(_index){ return this.offsets[_index]; }, resetRemovedPages: function() { this.viewer.models.removedPages = {}; }, addPageToRemovedPages: function(page) { this.viewer.models.removedPages[page] = true; }, removePageFromRemovedPages: function(page) { this.viewer.models.removedPages[page] = false; }, redrawPages: function() { DV._.each(this.viewer.pageSet.pages, function(page) { page.drawRemoveOverlay(); }); if (this.viewer.thumbnails) { this.viewer.thumbnails.render(); } }, redrawReorderedPages: function() { if (this.viewer.thumbnails) { this.viewer.thumbnails.render(); } } };
apache-2.0
IllusionRom-deprecated/android_platform_tools_idea
python/src/com/jetbrains/python/inspections/PyDocstringTypesInspection.java
5888
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.inspections; import com.intellij.codeInspection.*; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.jetbrains.python.PyBundle; import com.jetbrains.python.debugger.PySignature; import com.jetbrains.python.debugger.PySignatureCacheManager; import com.jetbrains.python.debugger.PySignatureUtil; import com.jetbrains.python.documentation.DocStringUtil; import com.jetbrains.python.psi.StructuredDocString; import com.jetbrains.python.toolbox.Substring; import com.jetbrains.python.psi.PyElementGenerator; import com.jetbrains.python.psi.PyFunction; import com.jetbrains.python.psi.PyStringLiteralExpression; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.PyTypeChecker; import com.jetbrains.python.psi.types.PyTypeParser; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author traff */ public class PyDocstringTypesInspection extends PyInspection { @Nls @NotNull @Override public String getDisplayName() { return PyBundle.message("INSP.NAME.docstring.types"); } @Override public boolean isEnabledByDefault() { return false; } @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { return new Visitor(holder, session); } public static class Visitor extends PyInspectionVisitor { public Visitor(@Nullable ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { super(holder, session); } @Override public void visitPyFunction(PyFunction function) { final String name = function.getName(); if (name != null && !name.startsWith("_")) checkDocString(function); } private void checkDocString(@NotNull PyFunction function) { final PyStringLiteralExpression docStringExpression = function.getDocStringExpression(); if (docStringExpression != null) { PySignatureCacheManager manager = PySignatureCacheManager.getInstance(function.getProject()); PySignature signature = manager.findSignature(function); if (signature != null) { checkParameters(function, docStringExpression, signature); } } } private void checkParameters(PyFunction function, PyStringLiteralExpression node, PySignature signature) { final String text = node.getText(); if (text == null) { return; } StructuredDocString docString = DocStringUtil.parse(text); if (docString == null) { return; } for (String param : docString.getParameters()) { Substring type = docString.getParamTypeSubstring(param); if (type != null) { String dynamicType = signature.getArgTypeQualifiedName(param); if (dynamicType != null) { String dynamicTypeShortName = PySignatureUtil.getShortestImportableName(function, dynamicType); if (!match(function, dynamicType, type.getValue())) { registerProblem(node, "Dynamically inferred type '" + dynamicTypeShortName + "' doesn't match specified type '" + type + "'", ProblemHighlightType.WEAK_WARNING, null, type.getTextRange(), new ChangeTypeQuickFix(param, type, dynamicTypeShortName, node) ); } } } } } private boolean match(PsiElement anchor, String dynamicTypeName, String specifiedTypeName) { final PyType dynamicType = PyTypeParser.getTypeByName(anchor, dynamicTypeName); final PyType specifiedType = PyTypeParser.getTypeByName(anchor, specifiedTypeName); return PyTypeChecker.match(specifiedType, dynamicType, myTypeEvalContext); } } private static class ChangeTypeQuickFix implements LocalQuickFix { private final String myParamName; private final Substring myTypeSubstring; private final String myNewType; private final PyStringLiteralExpression myStringLiteralExpression; private ChangeTypeQuickFix(String name, Substring substring, String type, PyStringLiteralExpression expression) { myParamName = name; myTypeSubstring = substring; myNewType = type; myStringLiteralExpression = expression; } @NotNull @Override public String getName() { return "Change " + myParamName + " type from " + myTypeSubstring.getValue() + " to " + myNewType; } @NotNull @Override public String getFamilyName() { return "Fix docstring"; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { String newValue = myTypeSubstring.getTextRange().replace(myTypeSubstring.getSuperString(), myNewType); PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); myStringLiteralExpression.replace(elementGenerator.createDocstring(newValue).getExpression()); } } }
apache-2.0
ropik/TypeScript
bin/lib.core.es6.d.ts
215295
/*! ***************************************************************************** Copyright (c) Microsoft Corporation. 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /// <reference no-default-lib="true"/> ///////////////////////////// /// ECMAScript APIs ///////////////////////////// declare var NaN: number; declare var Infinity: number; /** * Evaluates JavaScript code and executes it. * @param x A String value that contains valid JavaScript code. */ declare function eval(x: string): any; /** * Converts A string to an integer. * @param s A string to convert into a number. * @param radix A value between 2 and 36 that specifies the base of the number in numString. * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. * All other strings are considered decimal. */ declare function parseInt(s: string, radix?: number): number; /** * Converts a string to a floating-point number. * @param string A string that contains a floating-point number. */ declare function parseFloat(string: string): number; /** * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). * @param number A numeric value. */ declare function isNaN(number: number): boolean; /** * Determines whether a supplied number is finite. * @param number Any numeric value. */ declare function isFinite(number: number): boolean; /** * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). * @param encodedURI A value representing an encoded URI. */ declare function decodeURI(encodedURI: string): string; /** * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). * @param encodedURIComponent A value representing an encoded URI component. */ declare function decodeURIComponent(encodedURIComponent: string): string; /** * Encodes a text string as a valid Uniform Resource Identifier (URI) * @param uri A value representing an encoded URI. */ declare function encodeURI(uri: string): string; /** * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). * @param uriComponent A value representing an encoded URI component. */ declare function encodeURIComponent(uriComponent: string): string; interface PropertyDescriptor { configurable?: boolean; enumerable?: boolean; value?: any; writable?: boolean; get? (): any; set? (v: any): void; } interface PropertyDescriptorMap { [s: string]: PropertyDescriptor; } interface Object { /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ constructor: Function; /** Returns a string representation of an object. */ toString(): string; /** Returns a date converted to a string using the current locale. */ toLocaleString(): string; /** Returns the primitive value of the specified object. */ valueOf(): Object; /** * Determines whether an object has a property with the specified name. * @param v A property name. */ hasOwnProperty(v: string): boolean; /** * Determines whether an object exists in another object's prototype chain. * @param v Another object whose prototype chain is to be checked. */ isPrototypeOf(v: Object): boolean; /** * Determines whether a specified property is enumerable. * @param v A property name. */ propertyIsEnumerable(v: string): boolean; } interface ObjectConstructor { new (value?: any): Object; (): any; (value: any): any; /** A reference to the prototype for a class of objects. */ prototype: Object; /** * Returns the prototype of an object. * @param o The object that references the prototype. */ getPrototypeOf(o: any): any; /** * Gets the own property descriptor of the specified object. * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. * @param o Object that contains the property. * @param p Name of the property. */ getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; /** * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. * @param o Object that contains the own properties. */ getOwnPropertyNames(o: any): string[]; /** * Creates an object that has the specified prototype, and that optionally contains specified properties. * @param o Object to use as a prototype. May be null * @param properties JavaScript object that contains one or more property descriptors. */ create(o: any, properties?: PropertyDescriptorMap): any; /** * Adds a property to an object, or modifies attributes of an existing property. * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. * @param p The property name. * @param attributes Descriptor for the property. It can be for a data property or an accessor property. */ defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; /** * Adds one or more properties to an object, and/or modifies attributes of existing properties. * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. */ defineProperties(o: any, properties: PropertyDescriptorMap): any; /** * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. * @param o Object on which to lock the attributes. */ seal<T>(o: T): T; /** * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. * @param o Object on which to lock the attributes. */ freeze<T>(o: T): T; /** * Prevents the addition of new properties to an object. * @param o Object to make non-extensible. */ preventExtensions<T>(o: T): T; /** * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. * @param o Object to test. */ isSealed(o: any): boolean; /** * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. * @param o Object to test. */ isFrozen(o: any): boolean; /** * Returns a value that indicates whether new properties can be added to an object. * @param o Object to test. */ isExtensible(o: any): boolean; /** * Returns the names of the enumerable properties and methods of an object. * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ keys(o: any): string[]; } /** * Provides functionality common to all JavaScript objects. */ declare var Object: ObjectConstructor; /** * Creates a new function. */ interface Function { /** * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. * @param thisArg The object to be used as the this object. * @param argArray A set of arguments to be passed to the function. */ apply(thisArg: any, argArray?: any): any; /** * Calls a method of an object, substituting another object for the current object. * @param thisArg The object to be used as the current object. * @param argArray A list of arguments to be passed to the method. */ call(thisArg: any, ...argArray: any[]): any; /** * For a given function, creates a bound function that has the same body as the original function. * The this object of the bound function is associated with the specified object, and has the specified initial parameters. * @param thisArg An object to which the this keyword can refer inside the new function. * @param argArray A list of arguments to be passed to the new function. */ bind(thisArg: any, ...argArray: any[]): any; prototype: any; length: number; // Non-standard extensions arguments: any; caller: Function; } interface FunctionConstructor { /** * Creates a new function. * @param args A list of arguments the function accepts. */ new (...args: string[]): Function; (...args: string[]): Function; prototype: Function; } declare var Function: FunctionConstructor; interface IArguments { [index: number]: any; length: number; callee: Function; } interface String { /** Returns a string representation of a string. */ toString(): string; /** * Returns the character at the specified index. * @param pos The zero-based index of the desired character. */ charAt(pos: number): string; /** * Returns the Unicode value of the character at the specified location. * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. */ charCodeAt(index: number): number; /** * Returns a string that contains the concatenation of two or more strings. * @param strings The strings to append to the end of the string. */ concat(...strings: string[]): string; /** * Returns the position of the first occurrence of a substring. * @param searchString The substring to search for in the string * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. */ indexOf(searchString: string, position?: number): number; /** * Returns the last occurrence of a substring in the string. * @param searchString The substring to search for. * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. */ lastIndexOf(searchString: string, position?: number): number; /** * Determines whether two strings are equivalent in the current locale. * @param that String to compare to target string */ localeCompare(that: string): number; /** * Matches a string with a regular expression, and returns an array containing the results of that search. * @param regexp A variable name or string literal containing the regular expression pattern and flags. */ match(regexp: string): RegExpMatchArray; /** * Matches a string with a regular expression, and returns an array containing the results of that search. * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. */ match(regexp: RegExp): RegExpMatchArray; /** * Replaces text in a string, using a regular expression or search string. * @param searchValue A String object or string literal that represents the regular expression * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. */ replace(searchValue: string, replaceValue: string): string; /** * Replaces text in a string, using a regular expression or search string. * @param searchValue A String object or string literal that represents the regular expression * @param replaceValue A function that returns the replacement text. */ replace(searchValue: string, replaceValue: (substring: string, ...args: any[]) => string): string; /** * Replaces text in a string, using a regular expression or search string. * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. */ replace(searchValue: RegExp, replaceValue: string): string; /** * Replaces text in a string, using a regular expression or search string. * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags * @param replaceValue A function that returns the replacement text. */ replace(searchValue: RegExp, replaceValue: (substring: string, ...args: any[]) => string): string; /** * Finds the first substring match in a regular expression search. * @param regexp The regular expression pattern and applicable flags. */ search(regexp: string): number; /** * Finds the first substring match in a regular expression search. * @param regexp The regular expression pattern and applicable flags. */ search(regexp: RegExp): number; /** * Returns a section of a string. * @param start The index to the beginning of the specified portion of stringObj. * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. * If this value is not specified, the substring continues to the end of stringObj. */ slice(start?: number, end?: number): string; /** * Split a string into substrings using the specified separator and return them as an array. * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. * @param limit A value used to limit the number of elements returned in the array. */ split(separator: string, limit?: number): string[]; /** * Split a string into substrings using the specified separator and return them as an array. * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. * @param limit A value used to limit the number of elements returned in the array. */ split(separator: RegExp, limit?: number): string[]; /** * Returns the substring at the specified location within a String object. * @param start The zero-based index number indicating the beginning of the substring. * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. * If end is omitted, the characters from start through the end of the original string are returned. */ substring(start: number, end?: number): string; /** Converts all the alphabetic characters in a string to lowercase. */ toLowerCase(): string; /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ toLocaleLowerCase(): string; /** Converts all the alphabetic characters in a string to uppercase. */ toUpperCase(): string; /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ toLocaleUpperCase(): string; /** Removes the leading and trailing white space and line terminator characters from a string. */ trim(): string; /** Returns the length of a String object. */ length: number; // IE extensions /** * Gets a substring beginning at the specified location and having the specified length. * @param from The starting position of the desired substring. The index of the first character in the string is zero. * @param length The number of characters to include in the returned substring. */ substr(from: number, length?: number): string; /** Returns the primitive value of the specified object. */ valueOf(): string; [index: number]: string; } interface StringConstructor { new (value?: any): String; (value?: any): string; prototype: String; fromCharCode(...codes: number[]): string; } /** * Allows manipulation and formatting of text strings and determination and location of substrings within strings. */ declare var String: StringConstructor; interface Boolean { /** Returns the primitive value of the specified object. */ valueOf(): boolean; } interface BooleanConstructor { new (value?: any): Boolean; (value?: any): boolean; prototype: Boolean; } declare var Boolean: BooleanConstructor; interface Number { /** * Returns a string representation of an object. * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. */ toString(radix?: number): string; /** * Returns a string representing a number in fixed-point notation. * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. */ toFixed(fractionDigits?: number): string; /** * Returns a string containing a number represented in exponential notation. * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. */ toExponential(fractionDigits?: number): string; /** * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. */ toPrecision(precision?: number): string; /** Returns the primitive value of the specified object. */ valueOf(): number; } interface NumberConstructor { new (value?: any): Number; (value?: any): number; prototype: Number; /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ MAX_VALUE: number; /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ MIN_VALUE: number; /** * A value that is not a number. * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. */ NaN: number; /** * A value that is less than the largest negative number that can be represented in JavaScript. * JavaScript displays NEGATIVE_INFINITY values as -infinity. */ NEGATIVE_INFINITY: number; /** * A value greater than the largest number that can be represented in JavaScript. * JavaScript displays POSITIVE_INFINITY values as infinity. */ POSITIVE_INFINITY: number; } /** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ declare var Number: NumberConstructor; interface TemplateStringsArray extends Array<string> { raw: string[]; } interface Math { /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ E: number; /** The natural logarithm of 10. */ LN10: number; /** The natural logarithm of 2. */ LN2: number; /** The base-2 logarithm of e. */ LOG2E: number; /** The base-10 logarithm of e. */ LOG10E: number; /** Pi. This is the ratio of the circumference of a circle to its diameter. */ PI: number; /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ SQRT1_2: number; /** The square root of 2. */ SQRT2: number; /** * Returns the absolute value of a number (the value without regard to whether it is positive or negative). * For example, the absolute value of -5 is the same as the absolute value of 5. * @param x A numeric expression for which the absolute value is needed. */ abs(x: number): number; /** * Returns the arc cosine (or inverse cosine) of a number. * @param x A numeric expression. */ acos(x: number): number; /** * Returns the arcsine of a number. * @param x A numeric expression. */ asin(x: number): number; /** * Returns the arctangent of a number. * @param x A numeric expression for which the arctangent is needed. */ atan(x: number): number; /** * Returns the angle (in radians) from the X axis to a point. * @param y A numeric expression representing the cartesian y-coordinate. * @param x A numeric expression representing the cartesian x-coordinate. */ atan2(y: number, x: number): number; /** * Returns the smallest number greater than or equal to its numeric argument. * @param x A numeric expression. */ ceil(x: number): number; /** * Returns the cosine of a number. * @param x A numeric expression that contains an angle measured in radians. */ cos(x: number): number; /** * Returns e (the base of natural logarithms) raised to a power. * @param x A numeric expression representing the power of e. */ exp(x: number): number; /** * Returns the greatest number less than or equal to its numeric argument. * @param x A numeric expression. */ floor(x: number): number; /** * Returns the natural logarithm (base e) of a number. * @param x A numeric expression. */ log(x: number): number; /** * Returns the larger of a set of supplied numeric expressions. * @param values Numeric expressions to be evaluated. */ max(...values: number[]): number; /** * Returns the smaller of a set of supplied numeric expressions. * @param values Numeric expressions to be evaluated. */ min(...values: number[]): number; /** * Returns the value of a base expression taken to a specified power. * @param x The base value of the expression. * @param y The exponent value of the expression. */ pow(x: number, y: number): number; /** Returns a pseudorandom number between 0 and 1. */ random(): number; /** * Returns a supplied numeric expression rounded to the nearest number. * @param x The value to be rounded to the nearest number. */ round(x: number): number; /** * Returns the sine of a number. * @param x A numeric expression that contains an angle measured in radians. */ sin(x: number): number; /** * Returns the square root of a number. * @param x A numeric expression. */ sqrt(x: number): number; /** * Returns the tangent of a number. * @param x A numeric expression that contains an angle measured in radians. */ tan(x: number): number; } /** An intrinsic object that provides basic mathematics functionality and constants. */ declare var Math: Math; /** Enables basic storage and retrieval of dates and times. */ interface Date { /** Returns a string representation of a date. The format of the string depends on the locale. */ toString(): string; /** Returns a date as a string value. */ toDateString(): string; /** Returns a time as a string value. */ toTimeString(): string; /** Returns a value as a string value appropriate to the host environment's current locale. */ toLocaleString(): string; /** Returns a date as a string value appropriate to the host environment's current locale. */ toLocaleDateString(): string; /** Returns a time as a string value appropriate to the host environment's current locale. */ toLocaleTimeString(): string; /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ valueOf(): number; /** Gets the time value in milliseconds. */ getTime(): number; /** Gets the year, using local time. */ getFullYear(): number; /** Gets the year using Universal Coordinated Time (UTC). */ getUTCFullYear(): number; /** Gets the month, using local time. */ getMonth(): number; /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ getUTCMonth(): number; /** Gets the day-of-the-month, using local time. */ getDate(): number; /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ getUTCDate(): number; /** Gets the day of the week, using local time. */ getDay(): number; /** Gets the day of the week using Universal Coordinated Time (UTC). */ getUTCDay(): number; /** Gets the hours in a date, using local time. */ getHours(): number; /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ getUTCHours(): number; /** Gets the minutes of a Date object, using local time. */ getMinutes(): number; /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ getUTCMinutes(): number; /** Gets the seconds of a Date object, using local time. */ getSeconds(): number; /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ getUTCSeconds(): number; /** Gets the milliseconds of a Date, using local time. */ getMilliseconds(): number; /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ getUTCMilliseconds(): number; /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ getTimezoneOffset(): number; /** * Sets the date and time value in the Date object. * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. */ setTime(time: number): number; /** * Sets the milliseconds value in the Date object using local time. * @param ms A numeric value equal to the millisecond value. */ setMilliseconds(ms: number): number; /** * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). * @param ms A numeric value equal to the millisecond value. */ setUTCMilliseconds(ms: number): number; /** * Sets the seconds value in the Date object using local time. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setSeconds(sec: number, ms?: number): number; /** * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setUTCSeconds(sec: number, ms?: number): number; /** * Sets the minutes value in the Date object using local time. * @param min A numeric value equal to the minutes value. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setMinutes(min: number, sec?: number, ms?: number): number; /** * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). * @param min A numeric value equal to the minutes value. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setUTCMinutes(min: number, sec?: number, ms?: number): number; /** * Sets the hour value in the Date object using local time. * @param hours A numeric value equal to the hours value. * @param min A numeric value equal to the minutes value. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setHours(hours: number, min?: number, sec?: number, ms?: number): number; /** * Sets the hours value in the Date object using Universal Coordinated Time (UTC). * @param hours A numeric value equal to the hours value. * @param min A numeric value equal to the minutes value. * @param sec A numeric value equal to the seconds value. * @param ms A numeric value equal to the milliseconds value. */ setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; /** * Sets the numeric day-of-the-month value of the Date object using local time. * @param date A numeric value equal to the day of the month. */ setDate(date: number): number; /** * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). * @param date A numeric value equal to the day of the month. */ setUTCDate(date: number): number; /** * Sets the month value in the Date object using local time. * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. */ setMonth(month: number, date?: number): number; /** * Sets the month value in the Date object using Universal Coordinated Time (UTC). * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. */ setUTCMonth(month: number, date?: number): number; /** * Sets the year of the Date object using local time. * @param year A numeric value for the year. * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. * @param date A numeric value equal for the day of the month. */ setFullYear(year: number, month?: number, date?: number): number; /** * Sets the year value in the Date object using Universal Coordinated Time (UTC). * @param year A numeric value equal to the year. * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. * @param date A numeric value equal to the day of the month. */ setUTCFullYear(year: number, month?: number, date?: number): number; /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ toUTCString(): string; /** Returns a date as a string value in ISO format. */ toISOString(): string; /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ toJSON(key?: any): string; } interface DateConstructor { new (): Date; new (value: number): Date; new (value: string): Date; new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; prototype: Date; /** * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. * @param s A date string */ parse(s: string): number; /** * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. * @param month The month as an number between 0 and 11 (January to December). * @param date The date as an number between 1 and 31. * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. * @param ms An number from 0 to 999 that specifies the milliseconds. */ UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; now(): number; } declare var Date: DateConstructor; interface RegExpMatchArray extends Array<string> { index?: number; input?: string; } interface RegExpExecArray extends Array<string> { index: number; input: string; } interface RegExp { /** * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. * @param string The String object or string literal on which to perform the search. */ exec(string: string): RegExpExecArray; /** * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. * @param string String on which to perform the search. */ test(string: string): boolean; /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ source: string; /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ global: boolean; /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ ignoreCase: boolean; /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ multiline: boolean; lastIndex: number; // Non-standard extensions compile(): RegExp; } interface RegExpConstructor { new (pattern: string, flags?: string): RegExp; (pattern: string, flags?: string): RegExp; prototype: RegExp; // Non-standard extensions $1: string; $2: string; $3: string; $4: string; $5: string; $6: string; $7: string; $8: string; $9: string; lastMatch: string; } declare var RegExp: RegExpConstructor; interface Error { name: string; message: string; } interface ErrorConstructor { new (message?: string): Error; (message?: string): Error; prototype: Error; } declare var Error: ErrorConstructor; interface EvalError extends Error { } interface EvalErrorConstructor { new (message?: string): EvalError; (message?: string): EvalError; prototype: EvalError; } declare var EvalError: EvalErrorConstructor; interface RangeError extends Error { } interface RangeErrorConstructor { new (message?: string): RangeError; (message?: string): RangeError; prototype: RangeError; } declare var RangeError: RangeErrorConstructor; interface ReferenceError extends Error { } interface ReferenceErrorConstructor { new (message?: string): ReferenceError; (message?: string): ReferenceError; prototype: ReferenceError; } declare var ReferenceError: ReferenceErrorConstructor; interface SyntaxError extends Error { } interface SyntaxErrorConstructor { new (message?: string): SyntaxError; (message?: string): SyntaxError; prototype: SyntaxError; } declare var SyntaxError: SyntaxErrorConstructor; interface TypeError extends Error { } interface TypeErrorConstructor { new (message?: string): TypeError; (message?: string): TypeError; prototype: TypeError; } declare var TypeError: TypeErrorConstructor; interface URIError extends Error { } interface URIErrorConstructor { new (message?: string): URIError; (message?: string): URIError; prototype: URIError; } declare var URIError: URIErrorConstructor; interface JSON { /** * Converts a JavaScript Object Notation (JSON) string into an object. * @param text A valid JSON string. * @param reviver A function that transforms the results. This function is called for each member of the object. * If a member contains nested objects, the nested objects are transformed before the parent object is. */ parse(text: string, reviver?: (key: any, value: any) => any): any; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. */ stringify(value: any): string; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. * @param replacer A function that transforms the results. */ stringify(value: any, replacer: (key: string, value: any) => any): string; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. * @param replacer Array that transforms the results. */ stringify(value: any, replacer: any[]): string; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. * @param replacer A function that transforms the results. * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. */ stringify(value: any, replacer: (key: string, value: any) => any, space: any): string; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. * @param replacer Array that transforms the results. * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. */ stringify(value: any, replacer: any[], space: any): string; } /** * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. */ declare var JSON: JSON; ///////////////////////////// /// ECMAScript Array API (specially handled by compiler) ///////////////////////////// interface Array<T> { /** * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. */ length: number; /** * Returns a string representation of an array. */ toString(): string; toLocaleString(): string; /** * Appends new elements to an array, and returns the new length of the array. * @param items New elements of the Array. */ push(...items: T[]): number; /** * Removes the last element from an array and returns it. */ pop(): T; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ concat<U extends T[]>(...items: U[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ concat(...items: T[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Reverses the elements in an Array. */ reverse(): T[]; /** * Removes the first element from an array and returns it. */ shift(): T; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): T[]; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: T, b: T) => number): T[]; /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. */ splice(start: number): T[]; /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. * @param deleteCount The number of elements to remove. * @param items Elements to insert into the array in place of the deleted elements. */ splice(start: number, deleteCount: number, ...items: T[]): T[]; /** * Inserts new elements at the start of an array. * @param items Elements to insert at the start of the Array. */ unshift(...items: T[]): number; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number; /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. */ lastIndexOf(searchElement: T, fromIndex?: number): number; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; [n: number]: T; } interface ArrayConstructor { new (arrayLength?: number): any[]; new <T>(arrayLength: number): T[]; new <T>(...items: T[]): T[]; (arrayLength?: number): any[]; <T>(arrayLength: number): T[]; <T>(...items: T[]): T[]; isArray(arg: any): boolean; prototype: Array<any>; } declare var Array: ArrayConstructor; interface TypedPropertyDescriptor<T> { enumerable?: boolean; configurable?: boolean; writable?: boolean; value?: T; get?: () => T; set?: (value: T) => void; } declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void; declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void; declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; declare type PropertyKey = string | number | symbol; interface Symbol { /** Returns a string representation of an object. */ toString(): string; /** Returns the primitive value of the specified object. */ valueOf(): Object; [Symbol.toStringTag]: string; } interface SymbolConstructor { /** * A reference to the prototype. */ prototype: Symbol; /** * Returns a new unique Symbol value. * @param description Description of the new Symbol object. */ (description?: string|number): symbol; /** * Returns a Symbol object from the global symbol registry matching the given key if found. * Otherwise, returns a new symbol with this key. * @param key key to search for. */ for(key: string): symbol; /** * Returns a key from the global symbol registry matching the given Symbol if found. * Otherwise, returns a undefined. * @param sym Symbol to find the key for. */ keyFor(sym: symbol): string; // Well-known Symbols /** * A method that determines if a constructor object recognizes an object as one of the * constructor’s instances. Called by the semantics of the instanceof operator. */ hasInstance: symbol; /** * A Boolean value that if true indicates that an object should flatten to its array elements * by Array.prototype.concat. */ isConcatSpreadable: symbol; /** * A method that returns the default iterator for an object. Called by the semantics of the * for-of statement. */ iterator: symbol; /** * A regular expression method that matches the regular expression against a string. Called * by the String.prototype.match method. */ match: symbol; /** * A regular expression method that replaces matched substrings of a string. Called by the * String.prototype.replace method. */ replace: symbol; /** * A regular expression method that returns the index within a string that matches the * regular expression. Called by the String.prototype.search method. */ search: symbol; /** * A function valued property that is the constructor function that is used to create * derived objects. */ species: symbol; /** * A regular expression method that splits a string at the indices that match the regular * expression. Called by the String.prototype.split method. */ split: symbol; /** * A method that converts an object to a corresponding primitive value.Called by the ToPrimitive * abstract operation. */ toPrimitive: symbol; /** * A String value that is used in the creation of the default string description of an object. * Called by the built-in method Object.prototype.toString. */ toStringTag: symbol; /** * An Object whose own property names are property names that are excluded from the with * environment bindings of the associated objects. */ unscopables: symbol; } declare var Symbol: SymbolConstructor; interface Object { /** * Determines whether an object has a property with the specified name. * @param v A property name. */ hasOwnProperty(v: PropertyKey): boolean; /** * Determines whether a specified property is enumerable. * @param v A property name. */ propertyIsEnumerable(v: PropertyKey): boolean; } interface ObjectConstructor { /** * Copy the values of all of the enumerable own properties from one or more source objects to a * target object. Returns the target object. * @param target The target object to copy to. * @param sources One or more source objects to copy properties from. */ assign(target: any, ...sources: any[]): any; /** * Returns an array of all symbol properties found directly on object o. * @param o Object to retrieve the symbols from. */ getOwnPropertySymbols(o: any): symbol[]; /** * Returns true if the values are the same value, false otherwise. * @param value1 The first value. * @param value2 The second value. */ is(value1: any, value2: any): boolean; /** * Sets the prototype of a specified object o to object proto or null. Returns the object o. * @param o The object to change its prototype. * @param proto The value of the new prototype or null. */ setPrototypeOf(o: any, proto: any): any; /** * Gets the own property descriptor of the specified object. * An own property descriptor is one that is defined directly on the object and is not * inherited from the object's prototype. * @param o Object that contains the property. * @param p Name of the property. */ getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; /** * Adds a property to an object, or modifies attributes of an existing property. * @param o Object on which to add or modify the property. This can be a native JavaScript * object (that is, a user-defined object or a built in object) or a DOM object. * @param p The property name. * @param attributes Descriptor for the property. It can be for a data property or an accessor * property. */ defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; } interface Function { /** * Returns a new function object that is identical to the argument object in all ways except * for its identity and the value of its HomeObject internal slot. */ toMethod(newHome: Object): Function; /** * Returns the name of the function. Function names are read-only and can not be changed. */ name: string; } interface NumberConstructor { /** * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 * that is representable as a Number value, which is approximately: * 2.2204460492503130808472633361816 x 10‍−‍16. */ EPSILON: number; /** * Returns true if passed value is finite. * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a * number. Only finite values of the type number, result in true. * @param number A numeric value. */ isFinite(number: number): boolean; /** * Returns true if the value passed is an integer, false otherwise. * @param number A numeric value. */ isInteger(number: number): boolean; /** * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter * to a number. Only values of the type number, that are also NaN, result in true. * @param number A numeric value. */ isNaN(number: number): boolean; /** * Returns true if the value passed is a safe integer. * @param number A numeric value. */ isSafeInteger(number: number): boolean; /** * The value of the largest integer n such that n and n + 1 are both exactly representable as * a Number value. * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1. */ MAX_SAFE_INTEGER: number; /** * The value of the smallest integer n such that n and n − 1 are both exactly representable as * a Number value. * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). */ MIN_SAFE_INTEGER: number; /** * Converts a string to a floating-point number. * @param string A string that contains a floating-point number. */ parseFloat(string: string): number; /** * Converts A string to an integer. * @param s A string to convert into a number. * @param radix A value between 2 and 36 that specifies the base of the number in numString. * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. * All other strings are considered decimal. */ parseInt(string: string, radix?: number): number; } interface ArrayLike<T> { length: number; [n: number]: T; } interface Array<T> { /** Iterator */ [Symbol.iterator](): IterableIterator<T>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T]>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns an list of values in the array */ values(): IterableIterator<T>; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T; /** * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: T) => boolean, thisArg?: any): number; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: T, start?: number, end?: number): T[]; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): T[]; } interface ArrayConstructor { /** * Creates an array from an array-like object. * @param arrayLike An array-like object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>; /** * Creates an array from an iterable object. * @param iterable An iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from<T, U>(iterable: Iterable<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>; /** * Creates an array from an array-like object. * @param arrayLike An array-like object to convert to an array. */ from<T>(arrayLike: ArrayLike<T>): Array<T>; /** * Creates an array from an iterable object. * @param iterable An iterable object to convert to an array. */ from<T>(iterable: Iterable<T>): Array<T>; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of<T>(...items: T[]): Array<T>; } interface String { /** Iterator */ [Symbol.iterator](): IterableIterator<string>; /** * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point * value of the UTF-16 encoded code point starting at the string element at position pos in * the String resulting from converting this object to a String. * If there is no element at that position, the result is undefined. * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. */ codePointAt(pos: number): number; /** * Returns true if searchString appears as a substring of the result of converting this * object to a String, at one or more positions that are * greater than or equal to position; otherwise, returns false. * @param searchString search string * @param position If position is undefined, 0 is assumed, so as to search all of the String. */ contains(searchString: string, position?: number): boolean; /** * Returns true if the sequence of elements of searchString converted to a String is the * same as the corresponding elements of this object (converted to a String) starting at * endPosition – length(this). Otherwise returns false. */ endsWith(searchString: string, endPosition?: number): boolean; /** * Returns the String value result of normalizing the string into the normalization form * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default * is "NFC" */ normalize(form?: string): string; /** * Returns a String value that is made from count copies appended together. If count is 0, * T is the empty String is returned. * @param count number of copies to append */ repeat(count: number): string; /** * Returns true if the sequence of elements of searchString converted to a String is the * same as the corresponding elements of this object (converted to a String) starting at * position. Otherwise returns false. */ startsWith(searchString: string, position?: number): boolean; /** * Returns an <a> HTML anchor element and sets the name attribute to the text value * @param name */ anchor(name: string): string; /** Returns a <big> HTML element */ big(): string; /** Returns a <blink> HTML element */ blink(): string; /** Returns a <b> HTML element */ bold(): string; /** Returns a <tt> HTML element */ fixed(): string /** Returns a <font> HTML element and sets the color attribute value */ fontcolor(color: string): string /** Returns a <font> HTML element and sets the size attribute value */ fontsize(size: number): string; /** Returns a <font> HTML element and sets the size attribute value */ fontsize(size: string): string; /** Returns an <i> HTML element */ italics(): string; /** Returns an <a> HTML element and sets the href attribute value */ link(url: string): string; /** Returns a <small> HTML element */ small(): string; /** Returns a <strike> HTML element */ strike(): string; /** Returns a <sub> HTML element */ sub(): string; /** Returns a <sup> HTML element */ sup(): string; } interface StringConstructor { /** * Return the String value whose elements are, in order, the elements in the List elements. * If length is 0, the empty string is returned. */ fromCodePoint(...codePoints: number[]): string; /** * String.raw is intended for use as a tag function of a Tagged Template String. When called * as such the first argument will be a well formed template call site object and the rest * parameter will contain the substitution values. * @param template A well-formed template string call site representation. * @param substitutions A set of substitution values. */ raw(template: TemplateStringsArray, ...substitutions: any[]): string; } interface IteratorResult<T> { done: boolean; value?: T; } interface Iterator<T> { next(value?: any): IteratorResult<T>; return?(value?: any): IteratorResult<T>; throw?(e?: any): IteratorResult<T>; } interface Iterable<T> { [Symbol.iterator](): Iterator<T>; } interface IterableIterator<T> extends Iterator<T> { [Symbol.iterator](): IterableIterator<T>; } interface GeneratorFunction extends Function { } interface GeneratorFunctionConstructor { /** * Creates a new Generator function. * @param args A list of arguments the function accepts. */ new (...args: string[]): GeneratorFunction; (...args: string[]): GeneratorFunction; prototype: GeneratorFunction; } declare var GeneratorFunction: GeneratorFunctionConstructor; interface Generator<T> extends IterableIterator<T> { next(value?: any): IteratorResult<T>; throw(exception: any): IteratorResult<T>; return(value: T): IteratorResult<T>; [Symbol.iterator](): Generator<T>; [Symbol.toStringTag]: string; } interface Math { /** * Returns the number of leading zero bits in the 32-bit binary representation of a number. * @param x A numeric expression. */ clz32(x: number): number; /** * Returns the result of 32-bit multiplication of two numbers. * @param x First number * @param y Second number */ imul(x: number, y: number): number; /** * Returns the sign of the x, indicating whether x is positive, negative or zero. * @param x The numeric expression to test */ sign(x: number): number; /** * Returns the base 10 logarithm of a number. * @param x A numeric expression. */ log10(x: number): number; /** * Returns the base 2 logarithm of a number. * @param x A numeric expression. */ log2(x: number): number; /** * Returns the natural logarithm of 1 + x. * @param x A numeric expression. */ log1p(x: number): number; /** * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of * the natural logarithms). * @param x A numeric expression. */ expm1(x: number): number; /** * Returns the hyperbolic cosine of a number. * @param x A numeric expression that contains an angle measured in radians. */ cosh(x: number): number; /** * Returns the hyperbolic sine of a number. * @param x A numeric expression that contains an angle measured in radians. */ sinh(x: number): number; /** * Returns the hyperbolic tangent of a number. * @param x A numeric expression that contains an angle measured in radians. */ tanh(x: number): number; /** * Returns the inverse hyperbolic cosine of a number. * @param x A numeric expression that contains an angle measured in radians. */ acosh(x: number): number; /** * Returns the inverse hyperbolic sine of a number. * @param x A numeric expression that contains an angle measured in radians. */ asinh(x: number): number; /** * Returns the inverse hyperbolic tangent of a number. * @param x A numeric expression that contains an angle measured in radians. */ atanh(x: number): number; /** * Returns the square root of the sum of squares of its arguments. * @param values Values to compute the square root for. * If no arguments are passed, the result is +0. * If there is only one argument, the result is the absolute value. * If any argument is +Infinity or -Infinity, the result is +Infinity. * If any argument is NaN, the result is NaN. * If all arguments are either +0 or −0, the result is +0. */ hypot(...values: number[] ): number; /** * Returns the integral part of the a numeric expression, x, removing any fractional digits. * If x is already an integer, the result is x. * @param x A numeric expression. */ trunc(x: number): number; /** * Returns the nearest single precision float representation of a number. * @param x A numeric expression. */ fround(x: number): number; /** * Returns an implementation-dependent approximation to the cube root of number. * @param x A numeric expression. */ cbrt(x: number): number; [Symbol.toStringTag]: string; } interface RegExp { /** * Matches a string with a regular expression, and returns an array containing the results of * that search. * @param string A string to search within. */ match(string: string): string[]; /** * Replaces text in a string, using a regular expression. * @param searchValue A String object or string literal that represents the regular expression * @param replaceValue A String object or string literal containing the text to replace for every * successful match of rgExp in stringObj. */ replace(string: string, replaceValue: string): string; search(string: string): number; /** * Returns an Array object into which substrings of the result of converting string to a String * have been stored. The substrings are determined by searching from left to right for matches * of the this value regular expression; these occurrences are not part of any substring in the * returned array, but serve to divide up the String value. * * If the regular expression that contains capturing parentheses, then each time separator is * matched the results (including any undefined results) of the capturing parentheses are spliced. * @param string string value to split * @param limit if not undefined, the output array is truncated so that it contains no more * than limit elements. */ split(string: string, limit?: number): string[]; /** * Returns a string indicating the flags of the regular expression in question. This field is read-only. * The characters in this string are sequenced and concatenated in the following order: * * - "g" for global * - "i" for ignoreCase * - "m" for multiline * - "u" for unicode * - "y" for sticky * * If no flags are set, the value is the empty string. */ flags: string; /** * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular * expression. Default is false. Read-only. */ sticky: boolean; /** * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular * expression. Default is false. Read-only. */ unicode: boolean; } interface Map<K, V> { clear(): void; delete(key: K): boolean; entries(): IterableIterator<[K, V]>; forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void; get(key: K): V; has(key: K): boolean; keys(): IterableIterator<K>; set(key: K, value?: V): Map<K, V>; size: number; values(): IterableIterator<V>; [Symbol.iterator]():IterableIterator<[K,V]>; [Symbol.toStringTag]: string; } interface MapConstructor { new <K, V>(): Map<K, V>; new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>; prototype: Map<any, any>; } declare var Map: MapConstructor; interface WeakMap<K, V> { clear(): void; delete(key: K): boolean; get(key: K): V; has(key: K): boolean; set(key: K, value?: V): WeakMap<K, V>; [Symbol.toStringTag]: string; } interface WeakMapConstructor { new <K, V>(): WeakMap<K, V>; new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>; prototype: WeakMap<any, any>; } declare var WeakMap: WeakMapConstructor; interface Set<T> { add(value: T): Set<T>; clear(): void; delete(value: T): boolean; entries(): IterableIterator<[T, T]>; forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void; has(value: T): boolean; keys(): IterableIterator<T>; size: number; values(): IterableIterator<T>; [Symbol.iterator]():IterableIterator<T>; [Symbol.toStringTag]: string; } interface SetConstructor { new <T>(): Set<T>; new <T>(iterable: Iterable<T>): Set<T>; prototype: Set<any>; } declare var Set: SetConstructor; interface WeakSet<T> { add(value: T): WeakSet<T>; clear(): void; delete(value: T): boolean; has(value: T): boolean; [Symbol.toStringTag]: string; } interface WeakSetConstructor { new <T>(): WeakSet<T>; new <T>(iterable: Iterable<T>): WeakSet<T>; prototype: WeakSet<any>; } declare var WeakSet: WeakSetConstructor; interface JSON { [Symbol.toStringTag]: string; } /** * Represents a raw buffer of binary data, which is used to store data for the * different typed arrays. ArrayBuffers cannot be read from or written to directly, * but can be passed to a typed array or DataView Object to interpret the raw * buffer as needed. */ interface ArrayBuffer { /** * Read-only. The length of the ArrayBuffer (in bytes). */ byteLength: number; /** * Returns a section of an ArrayBuffer. */ slice(begin: number, end?: number): ArrayBuffer; [Symbol.toStringTag]: string; } interface ArrayBufferConstructor { prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; isView(arg: any): boolean; } declare var ArrayBuffer: ArrayBufferConstructor; interface DataView { buffer: ArrayBuffer; byteLength: number; byteOffset: number; /** * Gets the Float32 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getFloat32(byteOffset: number, littleEndian: boolean): number; /** * Gets the Float64 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getFloat64(byteOffset: number, littleEndian: boolean): number; /** * Gets the Int8 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getInt8(byteOffset: number): number; /** * Gets the Int16 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getInt16(byteOffset: number, littleEndian: boolean): number; /** * Gets the Int32 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getInt32(byteOffset: number, littleEndian: boolean): number; /** * Gets the Uint8 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getUint8(byteOffset: number): number; /** * Gets the Uint16 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getUint16(byteOffset: number, littleEndian: boolean): number; /** * Gets the Uint32 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getUint32(byteOffset: number, littleEndian: boolean): number; /** * Stores an Float32 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setFloat32(byteOffset: number, value: number, littleEndian: boolean): void; /** * Stores an Float64 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setFloat64(byteOffset: number, value: number, littleEndian: boolean): void; /** * Stores an Int8 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. */ setInt8(byteOffset: number, value: number): void; /** * Stores an Int16 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setInt16(byteOffset: number, value: number, littleEndian: boolean): void; /** * Stores an Int32 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setInt32(byteOffset: number, value: number, littleEndian: boolean): void; /** * Stores an Uint8 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. */ setUint8(byteOffset: number, value: number): void; /** * Stores an Uint16 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setUint16(byteOffset: number, value: number, littleEndian: boolean): void; /** * Stores an Uint32 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setUint32(byteOffset: number, value: number, littleEndian: boolean): void; [Symbol.toStringTag]: string; } interface DataViewConstructor { new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; } declare var DataView: DataViewConstructor; /** * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested * number of bytes could not be allocated an exception is raised. */ interface Int8Array { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ buffer: ArrayBuffer; /** * The length in bytes of the array. */ byteLength: number; /** * The offset in bytes of the array. */ byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): Int8Array; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): Int8Array; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): Int8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number; /** * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Int8Array; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Int8Array, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Int8Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): Int8Array; /** * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Int8Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; /** * Returns an list of values in the array */ values(): IterableIterator<number>; [index: number]: number; [Symbol.iterator](): IterableIterator<number>; } interface Int8ArrayConstructor { prototype: Int8Array; new (length: number): Int8Array; new (array: Int8Array): Int8Array; new (array: number[]): Int8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Int8Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number> | Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } declare var Int8Array: Int8ArrayConstructor; /** * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ interface Uint8Array { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ buffer: ArrayBuffer; /** * The length in bytes of the array. */ byteLength: number; /** * The offset in bytes of the array. */ byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): Uint8Array; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): Uint8Array; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): Uint8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number; /** * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Uint8Array; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Uint8Array, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Uint8Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): Uint8Array; /** * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Uint8Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; /** * Returns an list of values in the array */ values(): IterableIterator<number>; [index: number]: number; [Symbol.iterator](): IterableIterator<number>; } interface Uint8ArrayConstructor { prototype: Uint8Array; new (length: number): Uint8Array; new (array: Uint8Array): Uint8Array; new (array: number[]): Uint8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Uint8Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number> | Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } declare var Uint8Array: Uint8ArrayConstructor; /** * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. * If the requested number of bytes could not be allocated an exception is raised. */ interface Uint8ClampedArray { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ buffer: ArrayBuffer; /** * The length in bytes of the array. */ byteLength: number; /** * The offset in bytes of the array. */ byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): Uint8ClampedArray; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): Uint8ClampedArray; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): Uint8ClampedArray; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number; /** * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Uint8ClampedArray; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Uint8ClampedArray, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Uint8ClampedArray; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): Uint8ClampedArray; /** * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Uint8ClampedArray; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; /** * Returns an list of values in the array */ values(): IterableIterator<number>; [index: number]: number; [Symbol.iterator](): IterableIterator<number>; } interface Uint8ClampedArrayConstructor { prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: Uint8ClampedArray): Uint8ClampedArray; new (array: number[]): Uint8ClampedArray; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Uint8ClampedArray; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number> | Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } declare var Uint8ClampedArray: Uint8ClampedArrayConstructor; /** * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ interface Int16Array { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ buffer: ArrayBuffer; /** * The length in bytes of the array. */ byteLength: number; /** * The offset in bytes of the array. */ byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): Int16Array; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): Int16Array; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): Int16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number; /** * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Int16Array; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Int16Array, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Int16Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): Int16Array; /** * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Int16Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; /** * Returns an list of values in the array */ values(): IterableIterator<number>; [index: number]: number; [Symbol.iterator](): IterableIterator<number>; } interface Int16ArrayConstructor { prototype: Int16Array; new (length: number): Int16Array; new (array: Int16Array): Int16Array; new (array: number[]): Int16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Int16Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number> | Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } declare var Int16Array: Int16ArrayConstructor; /** * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ interface Uint16Array { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ buffer: ArrayBuffer; /** * The length in bytes of the array. */ byteLength: number; /** * The offset in bytes of the array. */ byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): Uint16Array; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): Uint16Array; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): Uint16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number; /** * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Uint16Array; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Uint16Array, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Uint16Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): Uint16Array; /** * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Uint16Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; /** * Returns an list of values in the array */ values(): IterableIterator<number>; [index: number]: number; [Symbol.iterator](): IterableIterator<number>; } interface Uint16ArrayConstructor { prototype: Uint16Array; new (length: number): Uint16Array; new (array: Uint16Array): Uint16Array; new (array: number[]): Uint16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Uint16Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number> | Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } declare var Uint16Array: Uint16ArrayConstructor; /** * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ interface Int32Array { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ buffer: ArrayBuffer; /** * The length in bytes of the array. */ byteLength: number; /** * The offset in bytes of the array. */ byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): Int32Array; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): Int32Array; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): Int32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number; /** * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Int32Array; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Int32Array, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Int32Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): Int32Array; /** * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Int32Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; /** * Returns an list of values in the array */ values(): IterableIterator<number>; [index: number]: number; [Symbol.iterator](): IterableIterator<number>; } interface Int32ArrayConstructor { prototype: Int32Array; new (length: number): Int32Array; new (array: Int32Array): Int32Array; new (array: number[]): Int32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Int32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number> | Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } declare var Int32Array: Int32ArrayConstructor; /** * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ interface Uint32Array { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ buffer: ArrayBuffer; /** * The length in bytes of the array. */ byteLength: number; /** * The offset in bytes of the array. */ byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): Uint32Array; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): Uint32Array; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): Uint32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number; /** * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Uint32Array; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Uint32Array, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Uint32Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): Uint32Array; /** * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Uint32Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; /** * Returns an list of values in the array */ values(): IterableIterator<number>; [index: number]: number; [Symbol.iterator](): IterableIterator<number>; } interface Uint32ArrayConstructor { prototype: Uint32Array; new (length: number): Uint32Array; new (array: Uint32Array): Uint32Array; new (array: number[]): Uint32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Uint32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number> | Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } declare var Uint32Array: Uint32ArrayConstructor; /** * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number * of bytes could not be allocated an exception is raised. */ interface Float32Array { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ buffer: ArrayBuffer; /** * The length in bytes of the array. */ byteLength: number; /** * The offset in bytes of the array. */ byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): Float32Array; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): Float32Array; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): Float32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number; /** * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Float32Array; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Float32Array, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Float32Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): Float32Array; /** * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Float32Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; /** * Returns an list of values in the array */ values(): IterableIterator<number>; [index: number]: number; [Symbol.iterator](): IterableIterator<number>; } interface Float32ArrayConstructor { prototype: Float32Array; new (length: number): Float32Array; new (array: Float32Array): Float32Array; new (array: number[]): Float32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Float32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number> | Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } declare var Float32Array: Float32ArrayConstructor; /** * A typed array of 64-bit float values. The contents are initialized to 0. If the requested * number of bytes could not be allocated an exception is raised. */ interface Float64Array { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ buffer: ArrayBuffer; /** * The length in bytes of the array. */ byteLength: number; /** * The offset in bytes of the array. */ byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): Float64Array; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in array1 until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): Float64Array; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): Float64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number; /** * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: number) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ reverse(): Float64Array; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Float64Array, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): Float64Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in array1 until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If * omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: number, b: number) => number): Float64Array; /** * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Float64Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; /** * Returns an list of values in the array */ values(): IterableIterator<number>; [index: number]: number; [Symbol.iterator](): IterableIterator<number>; } interface Float64ArrayConstructor { prototype: Float64Array; new (length: number): Float64Array; new (array: Float64Array): Float64Array; new (array: number[]): Float64Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Float64Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<number> | Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } declare var Float64Array: Float64ArrayConstructor; interface ProxyHandler<T> { getPrototypeOf? (target: T): any; setPrototypeOf? (target: T, v: any): boolean; isExtensible? (target: T): boolean; preventExtensions? (target: T): boolean; getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; has? (target: T, p: PropertyKey): boolean; get? (target: T, p: PropertyKey, receiver: any): any; set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; deleteProperty? (target: T, p: PropertyKey): boolean; defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; enumerate? (target: T): PropertyKey[]; ownKeys? (target: T): PropertyKey[]; apply? (target: T, thisArg: any, argArray?: any): any; construct? (target: T, thisArg: any, argArray?: any): any; } interface ProxyConstructor { revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; }; new <T>(target: T, handler: ProxyHandler<T>): T } declare var Proxy: ProxyConstructor; declare module Reflect { function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any; function construct(target: Function, argumentsList: ArrayLike<any>): any; function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; function deleteProperty(target: any, propertyKey: PropertyKey): boolean; function enumerate(target: any): IterableIterator<any>; function get(target: any, propertyKey: PropertyKey, receiver?: any): any; function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; function getPrototypeOf(target: any): any; function has(target: any, propertyKey: string): boolean; function has(target: any, propertyKey: symbol): boolean; function isExtensible(target: any): boolean; function ownKeys(target: any): Array<PropertyKey>; function preventExtensions(target: any): boolean; function set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean; function setPrototypeOf(target: any, proto: any): boolean; } interface PromiseLike<T> { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>; } /** * Represents the completion of an asynchronous operation */ interface Promise<T> { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>; [Symbol.toStringTag]: string; } interface PromiseConstructor { /** * A reference to the prototype. */ prototype: Promise<any>; /** * Creates a new Promise. * @param executor A callback used to initialize the promise. This callback is passed two arguments: * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T>(values: Iterable<T | PromiseLike<T>>): Promise<T[]>; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ reject(reason: any): Promise<void>; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ reject<T>(reason: any): Promise<T>; /** * Creates a new resolved promise for the provided value. * @param value A promise. * @returns A promise whose internal state matches the provided promise. */ resolve<T>(value: T | PromiseLike<T>): Promise<T>; /** * Creates a new resolved promise . * @returns A resolved promise. */ resolve(): Promise<void>; [Symbol.species]: Function; } declare var Promise: PromiseConstructor; interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ buffer: ArrayBuffer; /** * The length in bytes of the array. */ byteLength: number; /** * The offset in bytes of the array. */ byteOffset: number; }
apache-2.0
rpmoore/ds3_java_sdk
ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/spectrads3/ImportAllPoolsSpectraS3Response.java
1220
/* * ****************************************************************************** * Copyright 2014-2019 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ // This code is auto-generated, do not modify package com.spectralogic.ds3client.commands.spectrads3; import com.spectralogic.ds3client.models.ChecksumType; import com.spectralogic.ds3client.commands.interfaces.AbstractResponse; public class ImportAllPoolsSpectraS3Response extends AbstractResponse { public ImportAllPoolsSpectraS3Response(final String checksum, final ChecksumType.Type checksumType) { super(checksum, checksumType); } }
apache-2.0
philliprower/cas
api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/hazelcast/HazelcastWANReplicationTargetClusterProperties.java
4382
package org.apereo.cas.configuration.model.support.hazelcast; import org.apereo.cas.configuration.support.RequiresModule; import lombok.Getter; import lombok.Setter; import java.io.Serializable; /** * This is {@link HazelcastWANReplicationTargetClusterProperties}. * * @author Misagh Moayyed * @since 6.1.0 */ @RequiresModule(name = "cas-server-support-hazelcast-core") @Getter @Setter public class HazelcastWANReplicationTargetClusterProperties implements Serializable { private static final long serialVersionUID = 1635330607045885145L; /** * Name of this cluster. */ private String groupName; /** * Password for this cluster, if any. */ private String groupPassword; /** * Comma separated list of endpoints in this replication group. * IP addresses and ports of the cluster members for which the WAN replication is implemented. These endpoints are not necessarily * the entire target cluster and WAN does not perform the discovery of other members in the target cluster. It only expects * that these IP addresses (or at least some of them) are available. */ private String endpoints; /** * Publisher class name for WAN replication. */ private String publisherClassName = "com.hazelcast.enterprise.wan.replication.WanBatchReplication"; /** * Accepted values are: * <ul> * <li>{@code THROW_EXCEPTION}: Instruct WAN replication implementation to throw an exception and doesn't allow further processing.</li> * <li>{@code DISCARD_AFTER_MUTATION}: Instruct WAN replication implementation to drop new events when WAN event queues are full.</li> * <li>{@code THROW_EXCEPTION_ONLY_IF_REPLICATION_ACTIVE}: Similar to {@code THROW_EXCEPTION} but only throws exception when WAN replication is active. * * Discards the new events if WAN replication is stopped.</li> * </ul> */ private String queueFullBehavior = "THROW_EXCEPTION"; /** * Accepted values are: * <ul> * <li>{@code ACK_ON_RECEIPT}: ACK after WAN operation is received by the target cluster (without waiting the result of actual operation invocation).</li> * <li>{@code ACK_ON_OPERATION_COMPLETE}: Wait till the operation is complete on target cluster.</li> * </ul> */ private String acknowledgeType = "ACK_ON_OPERATION_COMPLETE"; /** * For huge clusters or high data mutation rates, you might need to increase the replication queue size. * The default queue size for replication queues is 10,000. This means, if you have heavy put/update/remove * rates, you might exceed the queue size so that the oldest, not yet replicated, updates might get * lost. */ private int queueCapacity = 10_000; /** * Maximum size of events that are sent to the target cluster in a single batch. */ private int batchSize = 500; /** * When set to true, only the latest events (based on key) are selected and sent in a batch. */ private boolean snapshotEnabled; /** * Maximum amount of time, in milliseconds, to be waited before * sending a batch of events in case batch.size is not reached. */ private int batchMaximumDelayMilliseconds = 1000; /** * Time, in milliseconds, to be waited for the acknowledgment of a sent WAN event to target cluster. */ private int responseTimeoutMilliseconds = 60_000; /** * The number of threads that the replication executor will have. The executor is used to send WAN * events to the endpoints and ideally you want to have one thread per endpoint. If this property is omitted * and you have specified the endpoints property, this will be the case. If necessary you can manually define * the number of threads that the executor will use. Once the executor has been initialized there is thread * affinity between the discovered endpoints and the executor threads - all events for a single endpoint will * go through a single executor thread, preserving event order. It is important to determine which number of * executor threads is a good value. Failure to do so can lead to performance issues - either contention on a * too small number of threads or wasted threads that will not be performing any work. */ private int executorThreadCount = 2; }
apache-2.0
lshain-android-source/tools-idea
java/compiler/impl/src/com/intellij/compiler/impl/CompilerErrorTreeView.java
7768
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.compiler.impl; import com.intellij.codeInsight.daemon.impl.actions.SuppressFix; import com.intellij.codeInsight.daemon.impl.actions.SuppressForClassFix; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.compiler.HelpID; import com.intellij.ide.errorTreeView.ErrorTreeElement; import com.intellij.ide.errorTreeView.NavigatableMessageElement; import com.intellij.ide.errorTreeView.NewErrorTreeViewPanel; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.module.LanguageLevelUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; public class CompilerErrorTreeView extends NewErrorTreeViewPanel { public CompilerErrorTreeView(Project project, Runnable rerunAction) { super(project, HelpID.COMPILER, true, true, rerunAction); } protected void fillRightToolbarGroup(DefaultActionGroup group) { super.fillRightToolbarGroup(group); group.add(new CompilerPropertiesAction()); } protected void addExtraPopupMenuActions(DefaultActionGroup group) { group.add(new ExcludeFromCompileAction(myProject, this)); group.addSeparator(); group.add(new SuppressJavacWarningsAction()); group.add(new SuppressJavacWarningForClassAction()); group.addSeparator(); ActionGroup popupGroup = (ActionGroup)ActionManager.getInstance().getAction(IdeActions.GROUP_COMPILER_ERROR_VIEW_POPUP); if (popupGroup != null) { for (AnAction action : popupGroup.getChildren(null)) { group.add(action); } } } protected boolean shouldShowFirstErrorInEditor() { return CompilerWorkspaceConfiguration.getInstance(myProject).AUTO_SHOW_ERRORS_IN_EDITOR; } private class SuppressJavacWarningsAction extends AnAction { public void actionPerformed(final AnActionEvent e) { final NavigatableMessageElement messageElement = (NavigatableMessageElement)getSelectedErrorTreeElement(); final String[] text = messageElement.getText(); final String id = text[0].substring(1, text[0].indexOf("]")); final SuppressFix suppressInspectionFix = getSuppressAction(id); final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); assert project != null; final OpenFileDescriptor navigatable = (OpenFileDescriptor)messageElement.getNavigatable(); final PsiFile file = PsiManager.getInstance(project).findFile(navigatable.getFile()); assert file != null; CommandProcessor.getInstance().executeCommand(project, new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { suppressInspectionFix.invoke(project, file.findElementAt(navigatable.getOffset())); } catch (IncorrectOperationException e1) { LOG.error(e1); } } }); } }, suppressInspectionFix.getText(), null); } @Override public void update(final AnActionEvent e) { final Presentation presentation = e.getPresentation(); presentation.setVisible(false); presentation.setEnabled(false); final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); if (project == null) { return; } final ErrorTreeElement errorTreeElement = getSelectedErrorTreeElement(); if (errorTreeElement instanceof NavigatableMessageElement) { final NavigatableMessageElement messageElement = (NavigatableMessageElement)errorTreeElement; final String[] text = messageElement.getText(); if (text.length > 0) { if (text[0].startsWith("[") && text[0].indexOf("]") != -1) { final Navigatable navigatable = messageElement.getNavigatable(); if (navigatable instanceof OpenFileDescriptor) { final OpenFileDescriptor fileDescriptor = (OpenFileDescriptor)navigatable; final VirtualFile virtualFile = fileDescriptor.getFile(); final Module module = ModuleUtilCore.findModuleForFile(virtualFile, project); if (module == null) { return; } final Sdk jdk = ModuleRootManager.getInstance(module).getSdk(); if (jdk == null) { return; } final boolean is_1_5 = JavaSdk.getInstance().isOfVersionOrHigher(jdk, JavaSdkVersion.JDK_1_5); if (!is_1_5) { return; } final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); if (psiFile == null) { return; } if (LanguageLevelUtil.getEffectiveLanguageLevel(module).compareTo(LanguageLevel.JDK_1_5) < 0) return; final PsiElement context = psiFile.findElementAt(fileDescriptor.getOffset()); if (context == null) { return; } final String id = text[0].substring(1, text[0].indexOf("]")); final SuppressFix suppressInspectionFix = getSuppressAction(id); final boolean available = suppressInspectionFix.isAvailable(project, context); presentation.setEnabled(available); presentation.setVisible(available); if (available) { presentation.setText(suppressInspectionFix.getText()); } } } } } } protected SuppressFix getSuppressAction(@NotNull final String id) { return new SuppressFix(id) { @Override @SuppressWarnings({"SimplifiableIfStatement"}) public boolean isAvailable(@NotNull final Project project, @NotNull final PsiElement context) { if (getContainer(context) instanceof PsiClass) return false; return super.isAvailable(project, context); } @Override protected boolean use15Suppressions(@NotNull final PsiDocCommentOwner container) { return true; } }; } } private class SuppressJavacWarningForClassAction extends SuppressJavacWarningsAction { @Override protected SuppressFix getSuppressAction(@NotNull final String id) { return new SuppressForClassFix(id){ @Override protected boolean use15Suppressions(@NotNull final PsiDocCommentOwner container) { return true; } }; } } }
apache-2.0
apache/commons-jcs
src/experimental/org/apache/commons/jcs/auxiliary/lateral/http/server/AbstractDeleteCacheServlet.java
10142
package org.apache.commons.jcs.auxiliary.lateral.http.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.jcs.engine.behavior.ICache; import org.apache.commons.jcs.engine.control.CompositeCacheManager; import org.apache.commons.jcs.utils.servlet.BasicHttpAuthenticator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.SingleThreadModel; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; public abstract class AbstractDeleteCacheServlet extends HttpServlet implements SingleThreadModel { private static final Log log = LogFactory.getLog( AbstractDeleteCacheServlet.class ); /** Description of the Field */ protected CompositeCacheManager cacheMgr; private BasicHttpAuthenticator authenticator; /** Description of the Method */ public void init( ServletConfig config ) throws ServletException { // subsclass must initialize the cacheMgr before here. authenticator = new BasicHttpAuthenticator( "jcs" ); super.init( config ); } /** Description of the Method */ public void service( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException { if ( !authenticator.authenticate( req, res ) ) { return; } Hashtable params = new Hashtable(); res.setContentType( "text/html" ); PrintWriter out = res.getWriter(); try { String paramName; String paramValue; // GET PARAMETERS INTO HASHTABLE for ( Enumeration e = req.getParameterNames(); e.hasMoreElements(); ) { paramName = ( String ) e.nextElement(); paramValue = req.getParameter( paramName ); params.put( paramName, paramValue ); if ( log.isDebugEnabled() ) { log.debug( paramName + "=" + paramValue ); } } String hashtableName = req.getParameter( "hashtableName" ); String key = req.getParameter( "key" ); if ( hashtableName == null ) { hashtableName = req.getParameter( "cacheName" ); } out.println( "<html><body bgcolor=#FFFFFF>" ); if ( hashtableName != null ) { if ( log.isDebugEnabled() ) { log.debug( "hashtableName = " + hashtableName ); } out.println( "(Last hashtableName = " + hashtableName + ")" ); if ( hashtableName.equals( "ALL" ) ) { // Clear all caches. String[] list = cacheMgr.getCacheNames(); Arrays.sort( list ); for ( int i = 0; i < list.length; i++ ) { String name = list[i]; ICache cache = cacheMgr.getCache( name ); cache.removeAll(); } out.println( "All caches have been cleared!" ); } else { ICache cache = cacheMgr.getCache( hashtableName ); String task = ( String ) params.get( "task" ); if ( task == null ) { task = "delete"; } if ( task.equalsIgnoreCase( "stats" ) ) { // out.println( "<br><br>" ); // out.println( "<b>Stats for " + hashtableName + ":</b><br>" ); // out.println( cache.getStats() ); // out.println( "<br>" ); } else { // Remove the specified cache. if ( key != null ) { if ( key.toUpperCase().equals( "ALL" ) ) { cache.removeAll(); if ( log.isDebugEnabled() ) { log.debug( "Removed all elements from " + hashtableName ); } out.println( "key = " + key ); } else { if ( log.isDebugEnabled() ) { log.debug( "key = " + key ); } out.println( "key = " + key ); StringTokenizer toke = new StringTokenizer( key, "_" ); while ( toke.hasMoreElements() ) { String temp = ( String ) toke.nextElement(); cache.remove( key ); if ( log.isDebugEnabled() ) { log.debug( "Removed " + temp + " from " + hashtableName ); } } } } else { out.println( "key is null" ); } } // end is task == delete } } else { out.println( "(No hashTableName specified.)" ); } // PRINT OUT MENU out.println( "<br>" ); int antiCacheRandom = ( int ) ( 10000.0 * Math.random() ); out.println( "<a href=?antiCacheRandom=" + antiCacheRandom + ">List all caches</a><br>" ); out.println( "<br>" ); out.println( "<a href=?hashtableName=ALL&key=ALL&antiCacheRandom=" + antiCacheRandom + "><font color=RED>Clear All Cache Regions</font></a><br>" ); out.println( "<br>" ); String[] list = cacheMgr.getCacheNames(); Arrays.sort( list ); out.println( "<div align=CENTER>" ); out.println( "<table border=1 width=80%>" ); out.println( "<tr bgcolor=#eeeeee><td>Cache Region Name</td><td>Size</td><td>Status</td><td>Stats</td>" ); for ( int i = 0; i < list.length; i++ ) { String name = list[i]; out.println( "<tr><td><a href=?hashtableName=" + name + "&key=ALL&antiCacheRandom=" + antiCacheRandom + ">" + name + "</a></td>" ); ICache cache = cacheMgr.getCache( name ); out.println( "<td>" ); out.print( cache.getSize() ); out.print( "</td><td>" ); int status = cache.getStatus(); out.print( status == CacheStatus.ALIVE ? "ALIVE" : status == CacheStatus.DISPOSED ? "DISPOSED" : status == CacheStatus.ERROR ? "ERROR" : "UNKNOWN" ); out.print( "</td>" ); out.println( "<td><a href=?task=stats&hashtableName=" + name + "&key=NONE&antiCacheRandom=" + antiCacheRandom + ">stats</a></td>" ); } out.println( "</table>" ); out.println( "</div>" ); } //CATCH EXCEPTIONS catch ( Exception e ) { log.error( e ); //log.logIt( "hashtableName = " + hashtableName ); //log.logIt( "key = " + key ); } // end try{ finally { String isRedirect = ( String ) params.get( "isRedirect" ); if ( isRedirect == null ) { isRedirect = "N"; } if ( log.isDebugEnabled() ) { log.debug( "isRedirect = " + isRedirect ); } String url; if ( isRedirect.equals( "Y" ) ) { url = ( String ) params.get( "url" ); if ( log.isDebugEnabled() ) { log.debug( "url = " + url ); } res.sendRedirect( url ); // will not work if there's a previously sent header out.println( "<br>\n" ); out.println( " <script>" ); out.println( " location.href='" + url + "'; " ); out.println( " </script> " ); out.flush(); } else { url = ""; } out.println( "</body></html>" ); } } //end service() } // end class
apache-2.0
fishstick/vcloud-rest
examples/example.rb
5189
### vcloud-rest example.rb ### fabio@rapposelli.org - github.com/frapposelli require 'vcloud-rest/connection' begin gem "awesome_print" rescue LoadError system("gem install awesome_print") Gem.clear_paths end require 'awesome_print' ### ### This Example shows how to utilize vcloud-rest to fetch information from your vCloud organization ### and how to compose a vApp from scratch, using VMs in a vApp Template and applying port forwarding NAT ### rules to the newly created vApp. ### host = 'https://vcloud.example.com' user = 'username' pass = 'password' org = 'organization' api = '5.1' puts "#################################################################" puts "# vcloud-rest example" puts "#" puts "### Connect to vCloud" ### Connect to vCloud connection = VCloudClient::Connection.new(host, user, pass, org, api) connection.login ### Fetch a list of the organizations you have access to puts "### Fetch and List Organizations" orgs = connection.get_organizations ap orgs ### Fetch and show an organization, COE is an example, you should replace it with your own organization puts "### Fetch and Show 'COE' Organization" org = connection.get_organization(orgs["COE"]) ap org ### Fetch and show a vDC, OvDC-PAYG-Bronze-01 is an example, you should replace it with your own vDC puts "### Fetch and Show 'OvDC-PAYG-Bronze-01' vDC" vdc = connection.get_vdc(org[:vdcs]["OvDC-PAYG-Bronze-01"]) ap vdc ### Fetch and show a Catalog, Vagrant is an example, you should replace it with your own Catalog puts "### Fetch and Show 'Vagrant' Catalog" cat = connection.get_catalog(org[:catalogs]["Vagrant"]) ap cat ### Fetch and show a Catalog Item, precise32 is an example, you should replace it with your own Catalog Item puts "### Fetch info on Catalog Item 'precise32'" catitem = connection.get_catalog_item(cat[:items]["precise32"]) ap catitem ### Fetch and show a vApp Template, precise32 is an example, you should replace it with your own vApp Template puts "### Show vApp Template 'precise32'" vapp = connection.get_vapp_template(catitem[:items]["precise32"]) ap vapp ### Compose a vApp, you should replace the Org vDC with your own, as well as changing the VM to be used as source puts "### Compose a vApp in 'OvDC-PAYG-Bronze-01' using VM coming from 'precise32'" compose = connection.compose_vapp_from_vm( org[:vdcs]["OvDC-PAYG-Bronze-01"], "Composed vApp", "Composed vApp created with vcloud-rest Ruby Bindings", { "VM1" => vapp[:vms_hash]["precise32"][:id], "VM2" => vapp[:vms_hash]["precise32"][:id], "VM3" => vapp[:vms_hash]["precise32"][:id], "VM4" => vapp[:vms_hash]["precise32"][:id] }, { :name => "test-network", :gateway => "192.168.0.253", :netmask => "255.255.255.0", :start_address => "192.168.0.1", :end_address => "192.168.0.100", :fence_mode => "natRouted", :ip_allocation_mode => "POOL", :parent_network => vdc[:networks]["Internet-NAT"], :enable_firewall => "false" }) puts "### Wait until the Task is completed" wait = connection.wait_task_completion(compose[:task_id]) ### Shows the vApp that has been composed with the previous action puts "### Details of the new vApp" newvapp = connection.get_vapp(compose[:vapp_id]) ap newvapp ### Here we build an array with the needed info, be aware that vm_id != vapp_scoped_local_id puts "### Building Port Forwarding NAT Rules" j = 2222 nat_rules = [] newvapp[:vms_hash].each do |key, value| nat_rules << { :nat_external_port => j.to_s, :nat_internal_port => "22", :nat_protocol => "TCP", :vm_scoped_local_id => value[:vapp_scoped_local_id]} j += 1 end newvapp[:vms_hash].each do |key, value| nat_rules << { :nat_external_port => j.to_s, :nat_internal_port => "873", :nat_protocol => "UDP", :vm_scoped_local_id => value[:vapp_scoped_local_id]} j += 1 end ap nat_rules ### Here we apply the nat_rules to the vApp we just built puts "### Applying Port Forwarding NAT Rules" setrule = connection.set_vapp_port_forwarding_rules( compose[:vapp_id], "test-network", { :fence_mode => "natRouted", :parent_network => vdc[:networks]["Internet-NAT"], :nat_policy_type => "allowTraffic", :nat_rules => nat_rules }) puts "### Wait until the Task is completed" wait = connection.wait_task_completion(setrule) ### After 4 minutes the vApp gets deleted, make sure to check the vCloud web UI to assess the creation. puts "### Waiting for 240 seconds before deleting the newly created vApp, check your vCloud web UI." sleep 240 puts "### Deleting the vApp" delete = connection.delete_vapp(compose[:vapp_id]) puts "### Wait until the Task is completed" wait = connection.wait_task_completion(delete) ### Upload an OVF to 'OvDC-PAYG-Bronze-01' 'Vagrant' catalog puts "### Upload vcloud_precise64.ovf to 'OvDC-PAYG-Bronze-01' 'Vagrant' catalog" upload = connection.upload_ovf( org[:vdcs]["OvDC-PAYG-Bronze-01"], "precise64", "Precise64 upload", "dumpster/vcloud_precise64.ovf", org[:catalogs]["Vagrant"], { :progressbar_enable => true, :retry_time => 20, :chunksize => 5242880, :progressbar_format => "%t |%w%i| %e", :progressbar_length => 80, :send_manifest => false }) ### Logout from vCloud Director connection.logout
apache-2.0
SwimGlass/rubi
progs/miller.rb
590
def modPow(b, p, m) res = 1 while p > 0 if p % 2 == 1 res = (res * b) % m end b = (b * b) % m p = p / 2 end res end def prime(n) if n < 2 return 0 elsif n == 2 return 1 elsif n % 2 == 0 return 0 end d = n - 1 while d % 2 == 0; d = d / 2; end for q = 0, q < 30, q++ a = (rand() % (n - 2)) + 1 t = d y = modPow(a, t, n) while t != n - 1 & y != 1 & y != n - 1 y = (y * y) % n t = t * 2 end if y != n - 1 & t % 2 == 0 return 0 end end 1 end isp = 0 while isp < 100 r = rand() % 65536 if prime(r) puts r, " is prime" isp++ end end
bsd-2-clause
useabode/redash
node_modules/plotly.js/src/fonts/mathjax_config.js
621
/** * Copyright 2012-2017, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; /* global MathJax:false */ /** * Check and configure MathJax */ if(typeof MathJax !== 'undefined') { exports.MathJax = true; MathJax.Hub.Config({ messageStyle: 'none', skipStartupTypeset: true, displayAlign: 'left', tex2jax: { inlineMath: [['$', '$'], ['\\(', '\\)']] } }); MathJax.Hub.Configured(); } else { exports.MathJax = false; }
bsd-2-clause
timsutton/homebrew-cask
Casks/lingon-x.rb
754
cask 'lingon-x' do if MacOS.version <= :high_sierra version '6.6.4' sha256 'fc788402fa16df39a3d48cdc501dae31368ec6fd69ffe0026ba99932b28cae19' else version '7.3' sha256 '7eff602f723735e51169c875ea84778fe79dcb5b01258ebdd44ec54ceeee2389' end url "https://www.peterborgapps.com/downloads/LingonX#{version.major}.zip" appcast "https://www.peterborgapps.com/updates/lingonx#{version.major}.plist" name 'Lingon X' homepage 'https://www.peterborgapps.com/lingon/' depends_on macos: '>= :high_sierra' app 'Lingon X.app' zap trash: [ "~/Library/Application Scripts/com.peterborgapps.LingonX#{version.major}", "~/Library/Containers/com.peterborgapps.LingonX#{version.major}", ] end
bsd-2-clause
jpcy/bgfx
3rdparty/spirv-tools/source/fuzz/instruction_message.cpp
2528
// Copyright (c) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "source/fuzz/instruction_message.h" #include "source/fuzz/fuzzer_util.h" namespace spvtools { namespace fuzz { protobufs::Instruction MakeInstructionMessage( SpvOp opcode, uint32_t result_type_id, uint32_t result_id, const opt::Instruction::OperandList& input_operands) { protobufs::Instruction result; result.set_opcode(opcode); result.set_result_type_id(result_type_id); result.set_result_id(result_id); for (auto& operand : input_operands) { auto operand_message = result.add_input_operand(); operand_message->set_operand_type(static_cast<uint32_t>(operand.type)); for (auto operand_word : operand.words) { operand_message->add_operand_data(operand_word); } } return result; } std::unique_ptr<opt::Instruction> InstructionFromMessage( opt::IRContext* ir_context, const protobufs::Instruction& instruction_message) { // First, update the module's id bound with respect to the new instruction, // if it has a result id. if (instruction_message.result_id()) { fuzzerutil::UpdateModuleIdBound(ir_context, instruction_message.result_id()); } // Now create a sequence of input operands from the input operand data in the // protobuf message. opt::Instruction::OperandList in_operands; for (auto& operand_message : instruction_message.input_operand()) { opt::Operand::OperandData operand_data; for (auto& word : operand_message.operand_data()) { operand_data.push_back(word); } in_operands.push_back( {static_cast<spv_operand_type_t>(operand_message.operand_type()), operand_data}); } // Create and return the instruction. return MakeUnique<opt::Instruction>( ir_context, static_cast<SpvOp>(instruction_message.opcode()), instruction_message.result_type_id(), instruction_message.result_id(), in_operands); } } // namespace fuzz } // namespace spvtools
bsd-2-clause
victorpopkov/homebrew-fonts
Casks/font-wire-one.rb
348
cask 'font-wire-one' do version '1.000' sha256 '1cf739c8fc17663059c2544be19cf590404e17fc9ec1778a080e13de5282e9fc' url 'https://googlefontdirectory.googlecode.com/hg-history/67342bc472599b4c32201ee4a002fe59a6447a42/ofl/wireone/WireOne.ttf' homepage 'http://www.google.com/fonts/specimen/Wire%20One' license :ofl font 'WireOne.ttf' end
bsd-2-clause
Sethtroll/runelite
cache/src/main/java/net/runelite/cache/definitions/WorldMapDefinition.java
1830
/* * Copyright (c) 2017, Adam <Adam@sigterm.info> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions 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. * * 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 COPYRIGHT OWNER 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. */ package net.runelite.cache.definitions; import java.util.List; import lombok.Data; import net.runelite.cache.region.Position; @Data public class WorldMapDefinition { public String name; public int field450; public int defaultZoom; public int fileId; public int field453; public int field454; public int field456; public boolean isSurface; public List regionList; public String safeName; public Position position; public int field463; }
bsd-2-clause
sscotth/homebrew-cask
Casks/marginnote.rb
625
cask 'marginnote' do version '3.6.11' sha256 '0c7560beecdd91396452890a919147c902191fc07ad6da841a81ac67832d5010' # marginstudy.com/ was verified as official when first introduced to the cask url "https://marginstudy.com/mac/MarginNote#{version.major}.dmg" appcast "https://dist.marginnote.cn/marginnote#{version.major}.xml" name 'MarginNote' homepage 'https://www.marginnote.com/' auto_updates true app "MarginNote #{version.major}.app" zap trash: [ '~/Library/Application Support/QReader.MarginStudyMac', '~/Library/Containers/QReader.MarginStudyMac', ] end
bsd-2-clause
MatterHackers/agg-sharp
agg/Platform/FileDialogs/SaveFileDialogParams.cs
679
using System; namespace MatterHackers.Agg.Platform { public class SaveFileDialogParams : FileDialogParams { /// The following are examples of valid Filter string values: /// Word Documents|*.doc /// All Files|*.* /// Word Documents|*.doc|Excel Worksheets|*.xls|PowerPoint Presentations|*.ppt|Office Files|*.doc;*.xls;*.ppt|All Files|*.* public SaveFileDialogParams(string fileTypeFilter, string initialDirectory = "", string title = "", string actionButtonLabel = "") : base(fileTypeFilter, initialDirectory, title, actionButtonLabel) { if (InitialDirectory == "") { InitialDirectory = AggContext.FileDialogs.LastDirectoryUsed; } } } }
bsd-2-clause
bmichotte/sugarcube
lib/ios/sugarcube-constants/symbol.rb
31138
=begin Adds constant lookups to the Symbol class. These methods are prefixed with `ui` or `ns` to make their intent clear, and to provide a little bit of "namespacing" # alignment :left.nsalignment => NSTextAlignmentLeft # uicolors :black.uicolor => UIColor.blackColor You can extend the defaults by adding entries: Symbol.css_colors[:my_color] = 0x123456 :my_color.uicolor => UIColor =end class Symbol def uidevice SugarCube.look_in(self, Symbol.uidevice) end def uideviceorientation SugarCube.look_in(self, Symbol.uideviceorientation) end def uiinterfaceorientation SugarCube.look_in(self, Symbol.uiinterfaceorientation) end alias uiorientation uiinterfaceorientation def uiinterfacemask SugarCube.look_in(self, Symbol.uiinterfacemask) end def uiautoresizemask SugarCube.look_in(self, Symbol.uiautoresizemask, Symbol.uiautoresizemask__deprecated) end alias uiviewautoresizing uiautoresizemask alias uiautoresizingmask uiautoresizemask alias uiautoresize uiautoresizemask def uireturnkey SugarCube.look_in(self, Symbol.uireturnkey, Symbol.uireturnkey__deprecated) end def uikeyboardtype SugarCube.look_in(self, Symbol.uikeyboardtype, Symbol.uikeyboardtype__deprecated) end def uitextalignment SugarCube.log('uitextalignment is deprecated. Use nstextalignment instead.') SugarCube.look_in(self, Symbol.nstextalignment) end alias uialignment uitextalignment def nstextalignment SugarCube.look_in(self, Symbol.nstextalignment) end alias nsalignment nstextalignment def uilinebreakmode SugarCube.log('uilinebreakmode is deprecated. Use nslinebreakmode instead.') SugarCube.look_in(self, Symbol.nslinebreakmode) end def nslinebreakmode SugarCube.look_in(self, Symbol.nslinebreakmode) end alias nslinebreak nslinebreakmode def uibaselineadjustment SugarCube.look_in(self, Symbol.uibaselineadjustment, Symbol.uibaselineadjustment__deprecated) end alias uibaseline uibaselineadjustment def uibordertype SugarCube.look_in(self, Symbol.uibordertype) end alias uiborderstyle uibordertype def nsdatestyle SugarCube.look_in(self, Symbol.nsdatestyle) end alias nsdateformatterstyle nsdatestyle def nsnumberstyle SugarCube.look_in(self, Symbol.nsnumberstyle, Symbol.nsnumberstyle__deprecated) end alias nsnumberformatterstyle nsnumberstyle def uistatusbarstyle SugarCube.look_in(self, Symbol.uistatusbarstyle) end def uibarmetrics SugarCube.look_in(self, Symbol.uibarmetrics) end def uibarbuttonitem SugarCube.look_in(self, Symbol.uibarbuttonitem, Symbol.uibarbuttonitem__deprecated) end def uibarbuttonstyle SugarCube.look_in(self, Symbol.uibarbuttonstyle) end def uitabbarsystemitem SugarCube.look_in(self, Symbol.uitabbarsystemitem) end alias uitabbaritem uitabbarsystemitem def uibuttontype SugarCube.look_in(self, Symbol.uibuttontype) end def uicontrolstate SugarCube.look_in(self, Symbol.uicontrolstate) end alias uistate uicontrolstate def uicontrolevent SugarCube.look_in(self, Symbol.uicontrolevent, Symbol.uicontrolevent__deprecated) end def uiactivityindicatorstyle SugarCube.look_in(self, Symbol.uiactivityindicatorstyle, Symbol.uiactivityindicatorstyle__deprecated) end alias uiactivityindicatorviewstyle uiactivityindicatorstyle def uisegmentedstyle SugarCube.look_in(self, Symbol.uisegmentedstyle) end alias uisegmentedcontrolstyle uisegmentedstyle def uidatepickermode SugarCube.look_in(self, Symbol.uidatepickermode, Symbol.uidatepickermode__deprecated) end def uicontentmode SugarCube.look_in(self, Symbol.uicontentmode, Symbol.uicontentmode__deprecated) end alias uiviewcontentmode uicontentmode def uianimationcurve SugarCube.look_in(self, Symbol.uianimationcurve) end alias uiviewanimationcurve uianimationcurve def uianimationoption SugarCube.look_in(self, Symbol.uianimationoption) end alias uiviewanimationoption uianimationoption def uitablestyle SugarCube.look_in(self, Symbol.uitablestyle) end alias uitableviewstyle uitablestyle def uitablerowanimation SugarCube.look_in(self, Symbol.uitablerowanimation) end alias uitableviewrowanimation uitablerowanimation def uitablecellstyle SugarCube.look_in(self, Symbol.uitablecellstyle) end alias uitableviewcellstyle uitablecellstyle def uitablecellaccessorytype SugarCube.look_in(self, Symbol.uitablecellaccessorytype, Symbol.uitablecellaccessorytype__deprecated) end alias uitablecellaccessory uitablecellaccessorytype alias uitableviewcellaccessorytype uitablecellaccessorytype def uitablecellselectionstyle SugarCube.look_in(self, Symbol.uitablecellselectionstyle) end alias uitableviewcellselectionstyle uitablecellselectionstyle def uitablecellseparatorstyle SugarCube.look_in(self, Symbol.uitablecellseparatorstyle, Symbol.uitablecellseparatorstyle__deprecated) end def presentationstyle SugarCube.look_in(self, Symbol.presentationstyle) end def transitionstyle SugarCube.look_in(self, Symbol.transitionstyle) end def uialertstyle SugarCube.look_in(self, Symbol.uialertstyle) end alias uialertviewstyle uialertstyle def uiactionstyle SugarCube.look_in(self, Symbol.uiactionstyle) end alias uiactionsheetstyle uiactionstyle def uialertcontrollerstyle SugarCube.look_in(self, Symbol.uialertcontrollerstyle) end def uialertactionstyle SugarCube.look_in(self, Symbol.uialertactionstyle) end def uiimagesource SugarCube.look_in(self, Symbol.uiimagesource) end alias uiimagesourcetype uiimagesource def uiimagecapture SugarCube.look_in(self, Symbol.uiimagecapture) end alias uiimagecapturemode uiimagecapture def uiimagecamera SugarCube.look_in(self, Symbol.uiimagecamera) end alias uiimagecameradevice uiimagecamera alias uiimagedevice uiimagecamera def uiimagequality SugarCube.look_in(self, Symbol.uiimagequality) end alias uiimagequalitytype uiimagequality def catimingfunction SugarCube.look_in(self, Symbol.catimingfunction, Symbol.catimingfunction__deprecated) end alias catiming catimingfunction def cglinecap SugarCube.look_in(self, Symbol.cglinecap) end alias cglinecapstyle cglinecap def cglinejoin SugarCube.look_in(self, Symbol.cglinejoin) end alias cglinejoinstyle cglinejoin def uigesturerecognizerstate SugarCube.look_in(self, Symbol.uigesturerecognizerstate) end alias uigesturestate uigesturerecognizerstate class << self attr :uidevice attr :uideviceorientation attr :uiinterfaceorientation attr :uiinterfacemask attr :uiautoresizemask attr :uiautoresizemask__deprecated attr :uireturnkey attr :uireturnkey__deprecated attr :uikeyboardtype attr :uikeyboardtype__deprecated attr :uitextalignment attr :nstextalignment attr :nslinebreakmode attr :uibaselineadjustment__deprecated attr :uibaselineadjustment attr :uibordertype attr :nsdatestyle attr :nsnumberstyle attr :nsnumberstyle__deprecated attr :uistatusbarstyle attr :uibarmetrics attr :uibarbuttonitem attr :uibarbuttonitem__deprecated attr :uibarbuttonstyle attr :uitabbarsystemitem attr :uibuttontype attr :uicontrolstate attr :uicontrolevent attr :uicontrolevent__deprecated attr :uiactivityindicatorstyle attr :uiactivityindicatorstyle__deprecated attr :uisegmentedstyle attr :uidatepickermode attr :uidatepickermode__deprecated attr :uicontentmode attr :uicontentmode__deprecated attr :uianimationcurve attr :uianimationoption attr :uitablestyle attr :uitablerowanimation attr :uitablecellstyle attr :uitablecellaccessorytype attr :uitablecellaccessorytype__deprecated attr :uitablecellselectionstyle attr :uitablecellseparatorstyle attr :uitablecellseparatorstyle__deprecated attr :presentationstyle attr :transitionstyle attr :uialertstyle attr :uiactionstyle attr :uialertcontrollerstyle attr :uialertactionstyle attr :uiimagesource attr :uiimagecapture attr :uiimagecamera attr :uiimagequality attr :catimingfunction attr :catimingfunction__deprecated attr :cglinecap attr :cglinejoin attr :uigesturerecognizerstate end @uidevice = { iphone: UIUserInterfaceIdiomPhone, ipad: UIUserInterfaceIdiomPad, } @uideviceorientation = { unknown: UIDeviceOrientationUnknown, portrait: UIDeviceOrientationPortrait, upside_down: UIDeviceOrientationPortraitUpsideDown, left: UIDeviceOrientationLandscapeLeft, right: UIDeviceOrientationLandscapeRight, face_up: UIDeviceOrientationFaceUp, face_down: UIDeviceOrientationFaceDown } @uiinterfaceorientation = { portrait: UIInterfaceOrientationPortrait, upside_down: UIInterfaceOrientationPortraitUpsideDown, left: UIInterfaceOrientationLandscapeLeft, right: UIInterfaceOrientationLandscapeRight, } @uiinterfacemask = { portrait: UIInterfaceOrientationMaskPortrait, landscrape: UIInterfaceOrientationMaskLandscape, left: UIInterfaceOrientationMaskLandscapeLeft, right: UIInterfaceOrientationMaskLandscapeRight, upside_down: UIInterfaceOrientationMaskPortraitUpsideDown, all_but_upside_down: UIInterfaceOrientationMaskAllButUpsideDown, iphone: UIInterfaceOrientationMaskAllButUpsideDown, all: UIInterfaceOrientationMaskAll, ipad: UIInterfaceOrientationMaskAll, } @uiautoresizemask__deprecated = { full: :fill, fixed_top: :fill_top, fixed_bottom: :fill_bottom, fixed_left: :fill_left, fixed_right: :fill_right, } @uiautoresizemask = { none: UIViewAutoresizingNone, flexible_left: UIViewAutoresizingFlexibleLeftMargin, flexible_width: UIViewAutoresizingFlexibleWidth, flexible_right: UIViewAutoresizingFlexibleRightMargin, flexible_top: UIViewAutoresizingFlexibleTopMargin, flexible_height: UIViewAutoresizingFlexibleHeight, flexible_bottom: UIViewAutoresizingFlexibleBottomMargin, fill: UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight, fill_top: UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin, fill_bottom: UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin, fill_left: UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin, fill_right: UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin, fixed_top_left: UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin, fixed_top_middle: UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin, fixed_top_right: UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin, fixed_middle_left: UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin, fixed_middle: UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin, fixed_middle_right: UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin, fixed_bottom_left: UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin, fixed_bottom_middle: UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin, fixed_bottom_right: UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin, float_horizontal: UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin, float_vertical: UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin, } @uireturnkey__deprecated = { emergencycall: :emergency_call } @uireturnkey = { default: UIReturnKeyDefault, return: UIReturnKeyDefault, go: UIReturnKeyGo, google: UIReturnKeyGoogle, join: UIReturnKeyJoin, next: UIReturnKeyNext, route: UIReturnKeyRoute, search: UIReturnKeySearch, send: UIReturnKeySend, yahoo: UIReturnKeyYahoo, done: UIReturnKeyDone, emergency_call: UIReturnKeyEmergencyCall, } @uikeyboardtype__deprecated = { asciicapable: :ascii_capable, numbersandpunctuation: :numbers_and_punctuation, numberpad: :number_pad, phonepad: :phone_pad, namephonepad: :name_phone_pad, nameandphone: :name_and_phone, emailaddress: :email_address, } @uikeyboardtype = { default: UIKeyboardTypeDefault, ascii_capable: UIKeyboardTypeASCIICapable, ascii: UIKeyboardTypeASCIICapable, numbers_and_punctuation: UIKeyboardTypeNumbersAndPunctuation, url: UIKeyboardTypeURL, number_pad: UIKeyboardTypeNumberPad, number: UIKeyboardTypeNumberPad, phone_pad: UIKeyboardTypePhonePad, phone: UIKeyboardTypePhonePad, name_phone_pad: UIKeyboardTypeNamePhonePad, name_and_phone: UIKeyboardTypeNamePhonePad, email_address: UIKeyboardTypeEmailAddress, email: UIKeyboardTypeEmailAddress, } @nstextalignment = { left: NSTextAlignmentLeft, right: NSTextAlignmentRight, center: NSTextAlignmentCenter, } @nslinebreakmode = { word_wrapping: NSLineBreakByWordWrapping, word_wrap: NSLineBreakByWordWrapping, word: NSLineBreakByWordWrapping, char_wrapping: NSLineBreakByCharWrapping, char_wrap: NSLineBreakByCharWrapping, character_wrap: NSLineBreakByCharWrapping, char: NSLineBreakByCharWrapping, clipping: NSLineBreakByClipping, clip: NSLineBreakByClipping, truncating_head: NSLineBreakByTruncatingHead, head_truncation: NSLineBreakByTruncatingHead, head: NSLineBreakByTruncatingHead, truncating_tail: NSLineBreakByTruncatingTail, tail_truncation: NSLineBreakByTruncatingTail, tail: NSLineBreakByTruncatingTail, truncating_middle: NSLineBreakByTruncatingMiddle, middle_truncation: NSLineBreakByTruncatingMiddle, middle: NSLineBreakByTruncatingMiddle } @uibaselineadjustment__deprecated = { alignbaselines: :align_baselines, aligncenters: :align_centers, } @uibaselineadjustment = { align_baselines: UIBaselineAdjustmentAlignBaselines, align_centers: UIBaselineAdjustmentAlignCenters, none: UIBaselineAdjustmentNone, } @uibordertype = { none: UITextBorderStyleNone, line: UITextBorderStyleLine, bezel: UITextBorderStyleBezel, rounded: UITextBorderStyleRoundedRect, rounded_rect: UITextBorderStyleRoundedRect, } @nsdatestyle = { no: NSDateFormatterNoStyle, none: NSDateFormatterNoStyle, short: NSDateFormatterShortStyle, medium: NSDateFormatterMediumStyle, long: NSDateFormatterLongStyle, full: NSDateFormatterFullStyle, } @nsnumberstyle__deprecated = { spellout: :spell_out, } @nsnumberstyle = { no: NSNumberFormatterNoStyle, none: NSNumberFormatterNoStyle, decimal: NSNumberFormatterDecimalStyle, currency: NSNumberFormatterCurrencyStyle, percent: NSNumberFormatterPercentStyle, scientific: NSNumberFormatterScientificStyle, spell_out: NSNumberFormatterSpellOutStyle, } @uistatusbarstyle = { default: UIStatusBarStyleDefault, black: UIStatusBarStyleBlackOpaque, translucent: UIStatusBarStyleBlackTranslucent, } @uibarmetrics = { default: UIBarMetricsDefault, landscape: UIBarMetricsLandscapePhone, } @uibarbuttonitem__deprecated = { flexiblespace: :flexible_space, fixedspace: :fixed_space, fastforward: :fast_forward, pagecurl: :page_curl, } @uibarbuttonitem = { done: UIBarButtonSystemItemDone, cancel: UIBarButtonSystemItemCancel, edit: UIBarButtonSystemItemEdit, save: UIBarButtonSystemItemSave, add: UIBarButtonSystemItemAdd, flexible_space: UIBarButtonSystemItemFlexibleSpace, fixed_space: UIBarButtonSystemItemFixedSpace, compose: UIBarButtonSystemItemCompose, reply: UIBarButtonSystemItemReply, action: UIBarButtonSystemItemAction, organize: UIBarButtonSystemItemOrganize, bookmarks: UIBarButtonSystemItemBookmarks, search: UIBarButtonSystemItemSearch, refresh: UIBarButtonSystemItemRefresh, stop: UIBarButtonSystemItemStop, camera: UIBarButtonSystemItemCamera, trash: UIBarButtonSystemItemTrash, play: UIBarButtonSystemItemPlay, pause: UIBarButtonSystemItemPause, rewind: UIBarButtonSystemItemRewind, fast_forward: UIBarButtonSystemItemFastForward, undo: UIBarButtonSystemItemUndo, redo: UIBarButtonSystemItemRedo, page_curl: UIBarButtonSystemItemPageCurl, } @uibarbuttonstyle = { plain: UIBarButtonItemStylePlain, bordered: UIBarButtonItemStyleBordered, done: UIBarButtonItemStyleDone } @uitabbarsystemitem = { more: UITabBarSystemItemMore, favorites: UITabBarSystemItemFavorites, featured: UITabBarSystemItemFeatured, top_rated: UITabBarSystemItemTopRated, recents: UITabBarSystemItemRecents, contacts: UITabBarSystemItemContacts, history: UITabBarSystemItemHistory, bookmarks: UITabBarSystemItemBookmarks, search: UITabBarSystemItemSearch, downloads: UITabBarSystemItemDownloads, most_recent: UITabBarSystemItemMostRecent, most_viewed: UITabBarSystemItemMostViewed, } @uibuttontype = { custom: UIButtonTypeCustom, rounded: UIButtonTypeRoundedRect, rounded_rect: UIButtonTypeRoundedRect, detail: UIButtonTypeDetailDisclosure, detail_disclosure: UIButtonTypeDetailDisclosure, info: UIButtonTypeInfoLight, info_light: UIButtonTypeInfoLight, info_dark: UIButtonTypeInfoDark, contact: UIButtonTypeContactAdd, contact_add: UIButtonTypeContactAdd, } if defined?(UIButtonTypeSystem) @uibuttontype[:system] = UIButtonTypeSystem end @uicontrolstate = { normal: UIControlStateNormal, highlighted: UIControlStateHighlighted, disabled: UIControlStateDisabled, selected: UIControlStateSelected, application: UIControlStateApplication, } @uicontrolevent__deprecated = { changed: :change, editing_did_endonexit: :editing_did_end_on_exit, } @uicontrolevent = { touch: UIControlEventTouchUpInside, touch_up: UIControlEventTouchUpInside, touch_down: UIControlEventTouchDown, touch_start: UIControlEventTouchDown | UIControlEventTouchDragEnter, touch_stop: UIControlEventTouchUpInside | UIControlEventTouchCancel | UIControlEventTouchDragExit, change: UIControlEventValueChanged | UIControlEventEditingChanged, begin: UIControlEventEditingDidBegin, end: UIControlEventEditingDidEnd, touch_down_repeat: UIControlEventTouchDownRepeat, touch_drag_inside: UIControlEventTouchDragInside, touch_drag_outside: UIControlEventTouchDragOutside, touch_drag_enter: UIControlEventTouchDragEnter, touch_drag_exit: UIControlEventTouchDragExit, touch_up_inside: UIControlEventTouchUpInside, touch_up_outside: UIControlEventTouchUpOutside, touch_cancel: UIControlEventTouchCancel, value_changed: UIControlEventValueChanged, editing_did_begin: UIControlEventEditingDidBegin, # nice. very consistent APPLE: editing_changed: UIControlEventEditingChanged, # now here's consistency: editing_did_change: UIControlEventEditingChanged, editing_did_end: UIControlEventEditingDidEnd, editing_did_end_on_exit: UIControlEventEditingDidEndOnExit, all_touch: UIControlEventAllTouchEvents, all_editing: UIControlEventAllEditingEvents, application: UIControlEventApplicationReserved, system: UIControlEventSystemReserved, all: UIControlEventAllEvents, } @uiactivityindicatorstyle__deprecated = { whitelarge: :white_large, } @uiactivityindicatorstyle = { large: UIActivityIndicatorViewStyleWhiteLarge, white_large: UIActivityIndicatorViewStyleWhiteLarge, white: UIActivityIndicatorViewStyleWhite, gray: UIActivityIndicatorViewStyleGray, } @uisegmentedstyle = { plain: UISegmentedControlStylePlain, bordered: UISegmentedControlStyleBordered, bar: UISegmentedControlStyleBar, bezeled: UISegmentedControlStyleBezeled, } @uidatepickermode__deprecated = { dateandtime: :date_and_time, countdowntimer: :count_down_timer, } @uidatepickermode = { time: UIDatePickerModeTime, date: UIDatePickerModeDate, date_and_time: UIDatePickerModeDateAndTime, count_down_timer: UIDatePickerModeCountDownTimer } @uicontentmode__deprecated = { scaletofill: :scale_to_fill, scaleaspectfit: :scale_aspect_fit, scaleaspectfill: :scale_aspect_fill, topleft: :top_left, topright: :top_right, bottomleft: :bottom_left, bottomright: :bottom_right, } @uicontentmode = { scale: UIViewContentModeScaleToFill, scale_to_fill: UIViewContentModeScaleToFill, fit: UIViewContentModeScaleAspectFit, scale_aspect_fit: UIViewContentModeScaleAspectFit, fill: UIViewContentModeScaleAspectFill, scale_aspect_fill: UIViewContentModeScaleAspectFill, redraw: UIViewContentModeRedraw, center: UIViewContentModeCenter, top: UIViewContentModeTop, bottom: UIViewContentModeBottom, left: UIViewContentModeLeft, right: UIViewContentModeRight, top_left: UIViewContentModeTopLeft, top_right: UIViewContentModeTopRight, bottom_left: UIViewContentModeBottomLeft, bottom_right: UIViewContentModeBottomRight, } @uianimationcurve = { ease_in_out: UIViewAnimationCurveEaseInOut, ease_in: UIViewAnimationCurveEaseIn, ease_out: UIViewAnimationCurveEaseOut, linear: UIViewAnimationCurveLinear } @uianimationoption = { layout_subviews: UIViewAnimationOptionLayoutSubviews, allow_user_interaction: UIViewAnimationOptionAllowUserInteraction, begin_from_current_state: UIViewAnimationOptionBeginFromCurrentState, repeat: UIViewAnimationOptionRepeat, autoreverse: UIViewAnimationOptionAutoreverse, override_inherited_duration: UIViewAnimationOptionOverrideInheritedDuration, override_inherited_curve: UIViewAnimationOptionOverrideInheritedCurve, allow_animated_content: UIViewAnimationOptionAllowAnimatedContent, show_hide_transition_views: UIViewAnimationOptionShowHideTransitionViews, override_inherited_options: UIViewAnimationOptionOverrideInheritedOptions, curve_ease_in_out: UIViewAnimationOptionCurveEaseInOut, ease_in_out: UIViewAnimationOptionCurveEaseInOut, curve_ease_in: UIViewAnimationOptionCurveEaseIn, ease_in: UIViewAnimationOptionCurveEaseIn, curve_ease_out: UIViewAnimationOptionCurveEaseOut, ease_out: UIViewAnimationOptionCurveEaseOut, curve_linear: UIViewAnimationOptionCurveLinear, linear: UIViewAnimationOptionCurveLinear, transition_none: UIViewAnimationOptionTransitionNone, transition_flip_from_left: UIViewAnimationOptionTransitionFlipFromLeft, transition_flip_from_right: UIViewAnimationOptionTransitionFlipFromRight, transition_curl_up: UIViewAnimationOptionTransitionCurlUp, transition_curl_down: UIViewAnimationOptionTransitionCurlDown, transition_cross_dissolve: UIViewAnimationOptionTransitionCrossDissolve, transition_flip_from_top: UIViewAnimationOptionTransitionFlipFromTop, transition_flip_from_bottom: UIViewAnimationOptionTransitionFlipFromBottom, } @uitablestyle = { plain: UITableViewStylePlain, grouped: UITableViewStyleGrouped, } @uitablerowanimation = { fade: UITableViewRowAnimationFade, right: UITableViewRowAnimationRight, left: UITableViewRowAnimationLeft, top: UITableViewRowAnimationTop, bottom: UITableViewRowAnimationBottom, none: UITableViewRowAnimationNone, middle: UITableViewRowAnimationMiddle, automatic: UITableViewRowAnimationAutomatic, } @uitablecellstyle = { default: UITableViewCellStyleDefault, value1: UITableViewCellStyleValue1, value2: UITableViewCellStyleValue2, subtitle: UITableViewCellStyleSubtitle, } @uitablecellaccessorytype__deprecated = { disclosureindicator: :disclosure_indicator, detaildisclosurebutton: :detail_disclosure_button, } @uitablecellaccessorytype = { none: UITableViewCellAccessoryNone, disclosure: UITableViewCellAccessoryDisclosureIndicator, disclosure_indicator: UITableViewCellAccessoryDisclosureIndicator, detail: UITableViewCellAccessoryDetailDisclosureButton, detail_disclosure_button: UITableViewCellAccessoryDetailDisclosureButton, checkmark: UITableViewCellAccessoryCheckmark, } @uitablecellselectionstyle = { none: UITableViewCellSelectionStyleNone, blue: UITableViewCellSelectionStyleBlue, gray: UITableViewCellSelectionStyleGray, } @uitablecellseparatorstyle__deprecated = { singleline: :single_line, singlelineetched: :single_line_etched, } @uitablecellseparatorstyle = { none: UITableViewCellSeparatorStyleNone, single_line: UITableViewCellSeparatorStyleSingleLine, single: UITableViewCellSeparatorStyleSingleLine, single_line_etched: UITableViewCellSeparatorStyleSingleLineEtched, etched: UITableViewCellSeparatorStyleSingleLineEtched, } @presentationstyle = { fullscreen: UIModalPresentationFullScreen, page_sheet: UIModalPresentationPageSheet, form_sheet: UIModalPresentationFormSheet, current_context: UIModalPresentationCurrentContext, custom: UIModalPresentationCustom, over_fullscreen: UIModalPresentationOverFullScreen, over_current_context: UIModalPresentationOverCurrentContext, popover: UIModalPresentationPopover, none: UIModalPresentationNone } @transitionstyle = { cover_vertical: UIModalTransitionStyleCoverVertical, flip_horizontal: UIModalTransitionStyleFlipHorizontal, cross_dissolve: UIModalTransitionStyleCrossDissolve, partial_curl: UIModalTransitionStylePartialCurl } @uialertstyle = { default: UIAlertViewStyleDefault, secure_text_input: UIAlertViewStyleSecureTextInput, plain_text_input: UIAlertViewStylePlainTextInput, login_and_password_input: UIAlertViewStyleLoginAndPasswordInput, } if defined?(UIAlertControllerStyleAlert) @uialertcontrollerstyle = { alert: UIAlertControllerStyleAlert, action_sheet: UIAlertControllerStyleActionSheet } @uialertactionstyle = { default: UIAlertActionStyleDefault, cancel: UIAlertActionStyleCancel, destructive: UIAlertActionStyleDestructive } else @uialertcontrollerstyle = {} @uialertactionstyle = {} end @uiactionstyle = { automatic: UIActionSheetStyleAutomatic, default: UIActionSheetStyleDefault, black_translucent: UIActionSheetStyleBlackTranslucent, black_opaque: UIActionSheetStyleBlackOpaque, } @uiimagesource = { camera: UIImagePickerControllerSourceTypeCamera, library: UIImagePickerControllerSourceTypePhotoLibrary, album: UIImagePickerControllerSourceTypeSavedPhotosAlbum, } @uiimagecapture = { photo: UIImagePickerControllerCameraCaptureModePhoto, video: UIImagePickerControllerCameraCaptureModeVideo, } @uiimagecamera = { front: UIImagePickerControllerCameraDeviceFront, rear: UIImagePickerControllerCameraDeviceRear, } @uiimagequality = { high: UIImagePickerControllerQualityTypeHigh, medium: UIImagePickerControllerQualityTypeMedium, low: UIImagePickerControllerQualityTypeLow, vga: UIImagePickerControllerQualityType640x480, i1280x720: UIImagePickerControllerQualityTypeIFrame1280x720, i1280: UIImagePickerControllerQualityTypeIFrame1280x720, i720: UIImagePickerControllerQualityTypeIFrame1280x720, i960x540: UIImagePickerControllerQualityTypeIFrame960x540, i960: UIImagePickerControllerQualityTypeIFrame960x540, i540: UIImagePickerControllerQualityTypeIFrame960x540, } @catimingfunction__deprecated = { easein: :ease_in, easeout: :ease_out, easeinout: :ease_in_out, } @catimingfunction = { linear: KCAMediaTimingFunctionLinear, ease_in: KCAMediaTimingFunctionEaseIn, ease_out: KCAMediaTimingFunctionEaseOut, ease_in_out: KCAMediaTimingFunctionEaseInEaseOut, ease_in_ease_out: KCAMediaTimingFunctionEaseInEaseOut, default: KCAMediaTimingFunctionDefault, } @cglinecap = { butt: KCGLineCapButt, round: KCGLineCapRound, square: KCGLineCapSquare, } @cglinejoin = { miter: KCGLineJoinMiter, round: KCGLineJoinRound, bevel: KCGLineJoinBevel, } @uigesturerecognizerstate = { possible: UIGestureRecognizerStatePossible, began: UIGestureRecognizerStateBegan, changed: UIGestureRecognizerStateChanged, ended: UIGestureRecognizerStateEnded, cancelled: UIGestureRecognizerStateCancelled, failed: UIGestureRecognizerStateFailed, recognized: UIGestureRecognizerStateRecognized, } end
bsd-2-clause
EIDSS/EIDSS-Legacy
EIDSS v6/eidss.webui/Utils/MenuCategory.cs
1141
using System; using System.Collections.Generic; using System.Xml.Linq; namespace eidss.webui.Utils { public class MenuCategory { public string Name { get; set; } public bool IsActive { get; set; } public List<MenuItem> Items { get; set; } public MenuCategory(string name, bool isActive = true, List<MenuItem> items = null) { Items = items ?? new List<MenuItem>(); Name = name; IsActive = isActive; } public static List<MenuCategory> GetMenuList(eidss.model.Core.EidssUserContext context, string menuPath) { //the menu is located in the MenuStructure.xml file, permissions are applied from current user context if (System.IO.File.Exists(menuPath)) { XDocument permissions = XDocument.Load(menuPath); return PermissionParser.GetPermittedMenu(permissions, context); } else throw new ArgumentException("Menu source file is not found at specified location."); } } }
bsd-2-clause
nask0/phalcon-skeletons
library/Phalcon/Mvc/Model/MetaData/Memcache.php
2437
<?php /** * Phalcon Framework * This source file is subject to the New BSD License that is bundled * with this package in the file docs/LICENSE.txt. * 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@phalconphp.com so we can send you a copy immediately. * * @author Nikita Vershinin <endeveit@gmail.com> */ namespace Phalcon\Mvc\Model\MetaData; use Phalcon\Cache\Backend\Memcache as CacheBackend; use Phalcon\Cache\Frontend\Data as CacheFrontend; use Phalcon\Mvc\Model\Exception; /** * \Phalcon\Mvc\Model\MetaData\Memcache * Memcache adapter for \Phalcon\Mvc\Model\MetaData */ class Memcache extends Base { /** * Default option for memcache port. * * @var array */ protected static $defaultPort = 11211; /** * Default option for persistent session. * * @var boolean */ protected static $defaultPersistent = false; /** * Memcache backend instance. * * @var \Phalcon\Cache\Backend\Memcache */ protected $memcache = null; /** * {@inheritdoc} * * @param null|array $options * @throws \Phalcon\Mvc\Model\Exception */ public function __construct($options = null) { if (is_array($options)) { if (!isset($options['host'])) { throw new Exception('No host given in options'); } if (!isset($options['port'])) { $options['port'] = self::$defaultPort; } if (!isset($options['persistent'])) { $options['persistent'] = self::$defaultPersistent; } } else { throw new Exception('No configuration given'); } parent::__construct($options); } /** * {@inheritdoc} * @return \Phalcon\Cache\Backend\Memcache */ protected function getCacheBackend() { if (null === $this->memcache) { $this->memcache = new CacheBackend( new CacheFrontend(array('lifetime' => $this->options['lifetime'])), array( 'host' => $this->options['host'], 'port' => $this->options['port'], 'persistent' => $this->options['persistent'], ) ); } return $this->memcache; } }
bsd-3-clause
INCF/lib9ML
nineml/abstraction/componentclass/visitors/queriers.py
9896
from past.builtins import basestring from copy import copy import sympy from sympy import sympify from sympy.logic.boolalg import BooleanTrue, BooleanFalse from sympy.functions.elementary.piecewise import ExprCondPair from ...expressions import reserved_identifiers from nineml.visitors import BaseVisitor, BaseVisitorWithContext from nineml.units import Dimension from nineml.abstraction.ports import SendPortBase from nineml.abstraction.expressions import Expression from nineml.exceptions import NineMLNameError import operator from functools import reduce class ComponentClassInterfaceInferer(BaseVisitor): """ Used to infer output |EventPorts|, |StateVariables| & |Parameters|.""" def __init__(self, component_class): super(ComponentClassInterfaceInferer, self).__init__() # Parameters: # Use visitation to collect all atoms that are not aliases and not # state variables self.component_class = component_class self.declared_symbols = copy(reserved_identifiers) self.atoms = set() self.input_event_port_names = set() self.event_out_port_names = set() self.visit(self.component_class) # Visit class and populate declared_symbols and atoms sets self.parameter_names = self.atoms - self.declared_symbols def action_alias(self, alias, **kwargs): # @UnusedVariable self.declared_symbols.add(alias.lhs) self.atoms.update(alias.rhs_atoms) def action_constant(self, constant, **kwargs): # @UnusedVariable self.declared_symbols.add(constant.name) def default_action(self, obj, nineml_cls, **kwargs): pass class ComponentRequiredDefinitions(BaseVisitor): """ Gets lists of required parameters, states, ports, random variables, constants and expressions (in resolved order of execution). """ def __init__(self, component_class, expressions): BaseVisitor.__init__(self) # Expression can either be a single expression or an iterable of # expressions self.parameters = [] self.ports = [] self.constants = [] self.random_variables = [] self.expressions = [] self._required_stack = [] self._push_required_symbols(expressions) self.component_class = component_class self.visit(component_class) def __repr__(self): return ("Parameters: {}\nPorts: {}\nConstants: {}\nAliases:\n{}" .format(', '.join(self.parameter_names), ', '.join(self.port_names), ', '.join(self.constant_names), ', '.join(self.expression_names))) def _push_required_symbols(self, expression): required_atoms = set() try: for expr in expression: try: required_atoms.update(expr.rhs_atoms) except AttributeError: # If a output port instead of expr required_atoms.add(expr.name) except TypeError: required_atoms.update(expression.rhs_atoms) # Strip builtin symbols from required atoms required_atoms.difference_update(reserved_identifiers) self._required_stack.append(required_atoms) def _is_required(self, element): return element.name in self._required_stack[-1] def action_parameter(self, parameter, **kwargs): # @UnusedVariable if self._is_required(parameter): self.parameters.append(parameter) def action_analogreceiveport(self, port, **kwargs): # @UnusedVariable if self._is_required(port): self.ports.append(port) def action_analogreduceport(self, port, **kwargs): # @UnusedVariable if self._is_required(port): self.ports.append(port) def action_constant(self, constant, **kwargs): # @UnusedVariable if self._is_required(constant): self.constants.append(constant) def action_alias(self, alias, **kwargs): # @UnusedVariable if (self._is_required(alias) and alias.name not in (e.name for e in self.expressions)): # Since aliases may be dependent on other aliases/piecewises the # order they are executed is important so we make sure their # dependencies are added first self._push_required_symbols(alias) self.visit(self.component_class) self._required_stack.pop() self.expressions.append(alias) def default_action(self, obj, nineml_cls, **kwargs): pass @property def parameter_names(self): return (p.name for p in self.parameters) @property def port_names(self): return (p.name for p in self.ports) @property def random_variable_names(self): return (rv.name for rv in self.random_variables) @property def constant_names(self): return (c.name for c in self.constants) @property def expression_names(self): return (e.name for e in self.expressions) class ComponentExpressionExtractor(BaseVisitor): def __init__(self): super(ComponentExpressionExtractor, self).__init__() self.expressions = [] def action_alias(self, alias, **kwargs): # @UnusedVariable self.expressions.append(alias.rhs) def default_action(self, obj, nineml_cls, **kwargs): pass class ComponentDimensionResolver(BaseVisitorWithContext): """ Used to calculate the unit dimension of elements within a component class """ reserved_symbol_dims = {sympy.Symbol('t'): sympy.Symbol('t')} def __init__(self, component_class): super(ComponentDimensionResolver, self).__init__() self.component_class = component_class self._dims = {} # Insert declared dimensions into dimensionality database for a in component_class.attributes_with_dimension: if not isinstance(a, SendPortBase): self._dims[sympify(a)] = sympify(a.dimension) for a in component_class.attributes_with_units: self._dims[sympify(a)] = sympify(a.units.dimension) self.visit(component_class) @property def base_nineml_children(self): return self.as_class.nineml_children def dimension_of(self, element): if isinstance(element, basestring): element = self.component_class.element( element, child_types=self.base_nineml_children) return Dimension.from_sympy(self._flatten(element)) def _flatten(self, expr, **kwargs): # @UnusedVariable expr = sympify(expr) if expr in self.reserved_symbol_dims: flattened = self._flatten_reserved(expr, **kwargs) elif isinstance(expr, sympy.Symbol): flattened = self._flatten_symbol(expr, **kwargs) elif isinstance(expr, (sympy.GreaterThan, sympy.LessThan, sympy.StrictGreaterThan, sympy.StrictLessThan, BooleanTrue, BooleanFalse, sympy.And, sympy.Or, sympy.Not)): flattened = self._flatten_boolean(expr, **kwargs) elif (isinstance(expr, (sympy.Integer, sympy.Float, int, float, sympy.Rational)) or type(expr).__name__ in ('Pi',)): flattened = self._flatten_constant(expr, **kwargs) elif isinstance(expr, sympy.Pow): flattened = self._flatten_power(expr, **kwargs) elif isinstance(expr, (sympy.Add, sympy.Piecewise, ExprCondPair)): flattened = self._flatten_matching(expr, **kwargs) elif isinstance(type(expr), sympy.FunctionClass): flattened = self._flatten_function(expr, **kwargs) elif isinstance(expr, sympy.Mul): flattened = self._flatten_multiplied(expr, **kwargs) else: assert False, "Unrecognised expression type '{}'".format(expr) return flattened def find_element(self, sym): name = Expression.symbol_to_str(sym) element = None for context in reversed(self.contexts): try: element = context.parent.element( name, child_types=context.parent_cls.nineml_children) except KeyError: pass if element is None: raise NineMLNameError( "'{}' element was not found in component class '{}'" .format(sym, self.component_class.name)) return element def _flatten_symbol(self, sym): try: flattened = self._dims[sym] except KeyError: element = self.find_element(sym) flattened = self._flatten(element.rhs) self._dims[sym] = flattened return flattened def _flatten_boolean(self, expr, **kwargs): # @UnusedVariable return 0 def _flatten_constant(self, expr, **kwargs): # @UnusedVariable return 1 def _flatten_function(self, expr, **kwargs): # @UnusedVariable return 1 def _flatten_matching(self, expr, **kwargs): # @UnusedVariable return self._flatten(expr.args[0]) def _flatten_multiplied(self, expr, **kwargs): # @UnusedVariable flattened = reduce(operator.mul, (self._flatten(a) for a in expr.args)) if isinstance(flattened, sympy.Basic): flattened = flattened.powsimp() # Simplify the expression return flattened def _flatten_power(self, expr, **kwargs): # @UnusedVariable return (self._flatten(expr.args[0]) ** expr.args[1]) def _flatten_reserved(self, expr, **kwargs): # @UnusedVariable return self.reserved_symbol_dims[expr] def action_alias(self, alias, **kwargs): # @UnusedVariable self._flatten(alias) def default_action(self, obj, nineml_cls, **kwargs): pass
bsd-3-clause
mowema/verano
vendor/zendframework/zendframework/library/Zend/ProgressBar/Adapter/Exception/RuntimeException.php
557
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\ProgressBar\Adapter\Exception; use Zend\ProgressBar\Exception; /** * Exception for Zend\Progressbar component. */ class RuntimeException extends Exception\RuntimeException implements ExceptionInterface {}
bsd-3-clause
pbrunet/pythran
third_party/boost/simd/include/functions/modf.hpp
173
#ifndef BOOST_SIMD_INCLUDE_FUNCTIONS_MODF_HPP_INCLUDED #define BOOST_SIMD_INCLUDE_FUNCTIONS_MODF_HPP_INCLUDED #include <boost/simd/ieee/include/functions/modf.hpp> #endif
bsd-3-clause
pongad/api-client-staging
generated/java/proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/MutationRecordProto.java
2811
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/mutation_record.proto package com.google.monitoring.v3; public final class MutationRecordProto { private MutationRecordProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_monitoring_v3_MutationRecord_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_monitoring_v3_MutationRecord_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n*google/monitoring/v3/mutation_record.p" + "roto\022\024google.monitoring.v3\032\037google/proto" + "buf/timestamp.proto\"U\n\016MutationRecord\022/\n" + "\013mutate_time\030\001 \001(\0132\032.google.protobuf.Tim" + "estamp\022\022\n\nmutated_by\030\002 \001(\tB\253\001\n\030com.googl" + "e.monitoring.v3B\023MutationRecordProtoP\001Z>" + "google.golang.org/genproto/googleapis/mo" + "nitoring/v3;monitoring\252\002\032Google.Cloud.Mo" + "nitoring.V3\312\002\032Google\\Cloud\\Monitoring\\V3" + "b\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.protobuf.TimestampProto.getDescriptor(), }, assigner); internal_static_google_monitoring_v3_MutationRecord_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_monitoring_v3_MutationRecord_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_monitoring_v3_MutationRecord_descriptor, new java.lang.String[] { "MutateTime", "MutatedBy", }); com.google.protobuf.TimestampProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
bsd-3-clause
steffeli/inf5750-tracker-capture
dhis-api/src/main/java/org/hisp/dhis/trackedentityattributevalue/TrackedEntityAttributeValueService.java
4960
package org.hisp.dhis.trackedentityattributevalue; /* * Copyright (c) 2004-2015, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions 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. * Neither the name of the HISP project nor the names of its contributors may * 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 COPYRIGHT OWNER 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. */ import java.util.Collection; import java.util.List; import org.hisp.dhis.trackedentity.TrackedEntityAttribute; import org.hisp.dhis.trackedentity.TrackedEntityInstance; /** * @author Abyot Asalefew * @version $Id$ */ public interface TrackedEntityAttributeValueService { String ID = TrackedEntityAttributeValueService.class.getName(); /** * Adds an {@link TrackedEntityAttribute} * * @param attributeValue The to TrackedEntityAttribute add. * */ void addTrackedEntityAttributeValue( TrackedEntityAttributeValue attributeValue ); /** * Updates an {@link TrackedEntityAttribute}. * * @param attributeValue the TrackedEntityAttribute to update. */ void updateTrackedEntityAttributeValue( TrackedEntityAttributeValue attributeValue ); /** * Deletes a {@link TrackedEntityAttribute}. * * @param attributeValue the TrackedEntityAttribute to delete. */ void deleteTrackedEntityAttributeValue( TrackedEntityAttributeValue attributeValue ); /** * Retrieve a {@link TrackedEntityAttributeValue} on a {@link TrackedEntityInstance} and * {@link TrackedEntityAttribute} * * @param attribute {@link TrackedEntityAttribute} * * @return TrackedEntityAttributeValue */ TrackedEntityAttributeValue getTrackedEntityAttributeValue( TrackedEntityInstance instance, TrackedEntityAttribute attribute ); /** * Retrieve {@link TrackedEntityAttributeValue} of a {@link TrackedEntityInstance} * * @param instance TrackedEntityAttributeValue * * @return TrackedEntityAttributeValue list */ List<TrackedEntityAttributeValue> getTrackedEntityAttributeValues( TrackedEntityInstance instance ); /** * Retrieve {@link TrackedEntityAttributeValue} of a {@link TrackedEntityAttribute} * * @param attribute {@link TrackedEntityAttribute} * * @return TrackedEntityAttributeValue list */ List<TrackedEntityAttributeValue> getTrackedEntityAttributeValues( TrackedEntityAttribute attribute ); /** * Retrieve {@link TrackedEntityAttributeValue} of a instance list * * @param instances TrackedEntityAttributeValue list * * @return TrackedEntityAttributeValue list */ List<TrackedEntityAttributeValue> getTrackedEntityAttributeValues( Collection<TrackedEntityInstance> instances ); /** * Search TrackedEntityAttributeValue objects by a TrackedEntityAttribute and a attribute * value (performs partial search ) * * @param attribute TrackedEntityAttribute * @param searchText A string for searching by attribute values * * @return TrackedEntityAttributeValue list */ List<TrackedEntityAttributeValue> searchTrackedEntityAttributeValue( TrackedEntityAttribute attribute, String searchText ); /** * Remove all attribute values of destination instance and copy attribute * values of source instance to destination instance * * @param source Source instance * @param destination Destination instance */ void copyTrackedEntityAttributeValues( TrackedEntityInstance source, TrackedEntityInstance destination ); }
bsd-3-clause
espadrine/opera
chromium/src/third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp
5262
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions 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. * * Neither the name of Google Inc. nor the names of its * contributors may 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 COPYRIGHT * OWNER 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. */ #include "config.h" #include "core/platform/SharedBufferChunkReader.h" #include "core/platform/SharedBuffer.h" namespace WebCore { SharedBufferChunkReader::SharedBufferChunkReader(SharedBuffer* buffer, const Vector<char>& separator) : m_buffer(buffer) , m_bufferPosition(0) , m_segment(0) , m_segmentLength(0) , m_segmentIndex(0) , m_reachedEndOfFile(false) , m_separator(separator) , m_separatorIndex(0) { } SharedBufferChunkReader::SharedBufferChunkReader(SharedBuffer* buffer, const char* separator) : m_buffer(buffer) , m_bufferPosition(0) , m_segment(0) , m_segmentLength(0) , m_segmentIndex(0) , m_reachedEndOfFile(false) , m_separatorIndex(0) { setSeparator(separator); } void SharedBufferChunkReader::setSeparator(const Vector<char>& separator) { m_separator = separator; } void SharedBufferChunkReader::setSeparator(const char* separator) { m_separator.clear(); m_separator.append(separator, strlen(separator)); } bool SharedBufferChunkReader::nextChunk(Vector<char>& chunk, bool includeSeparator) { if (m_reachedEndOfFile) return false; chunk.clear(); while (true) { while (m_segmentIndex < m_segmentLength) { char currentCharacter = m_segment[m_segmentIndex++]; if (currentCharacter != m_separator[m_separatorIndex]) { if (m_separatorIndex > 0) { ASSERT_WITH_SECURITY_IMPLICATION(m_separatorIndex <= m_separator.size()); chunk.append(m_separator.data(), m_separatorIndex); m_separatorIndex = 0; } chunk.append(currentCharacter); continue; } m_separatorIndex++; if (m_separatorIndex == m_separator.size()) { if (includeSeparator) chunk.append(m_separator); m_separatorIndex = 0; return true; } } // Read the next segment. m_segmentIndex = 0; m_bufferPosition += m_segmentLength; m_segmentLength = m_buffer->getSomeData(m_segment, m_bufferPosition); if (!m_segmentLength) { m_reachedEndOfFile = true; if (m_separatorIndex > 0) chunk.append(m_separator.data(), m_separatorIndex); return !chunk.isEmpty(); } } ASSERT_NOT_REACHED(); return false; } String SharedBufferChunkReader::nextChunkAsUTF8StringWithLatin1Fallback(bool includeSeparator) { Vector<char> data; if (!nextChunk(data, includeSeparator)) return String(); return data.size() ? String::fromUTF8WithLatin1Fallback(data.data(), data.size()) : emptyString(); } size_t SharedBufferChunkReader::peek(Vector<char>& data, size_t requestedSize) { data.clear(); if (requestedSize <= m_segmentLength - m_segmentIndex) { data.append(m_segment + m_segmentIndex, requestedSize); return requestedSize; } size_t readBytesCount = m_segmentLength - m_segmentIndex; data.append(m_segment + m_segmentIndex, readBytesCount); size_t bufferPosition = m_bufferPosition + m_segmentLength; const char* segment = 0; while (size_t segmentLength = m_buffer->getSomeData(segment, bufferPosition)) { if (requestedSize <= readBytesCount + segmentLength) { data.append(segment, requestedSize - readBytesCount); readBytesCount += (requestedSize - readBytesCount); break; } data.append(segment, segmentLength); readBytesCount += segmentLength; bufferPosition += segmentLength; } return readBytesCount; } }
bsd-3-clause
hzhao/galago-git
utility/src/main/java/org/lemurproject/galago/utility/btree/disk/DiskBTreeReader.java
7038
// BSD License (http://lemurproject.org/galago-license) package org.lemurproject.galago.utility.btree.disk; import org.lemurproject.galago.utility.CmpUtil; import org.lemurproject.galago.utility.Parameters; import org.lemurproject.galago.utility.buffer.CachedBufferDataStream; import org.lemurproject.galago.utility.buffer.FileReadableBuffer; import org.lemurproject.galago.utility.buffer.ReadableBuffer; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; /** * <p>This implements the core functionality for all inverted list readers. It * can also be used as a read-only TreeMap for disk-based data structures. In * Galago, it is used both to store index data and to store documents.</p> * * <p>An index is a mapping from String to byte[]. If compression is turned on, * the value must be small enough that it fits in memory. If compression is off, * values are streamed directly from disk so there is no size restriction. * Indexes support iteration over all keys, or direct lookup of a single key. * The structure is optimized to support fast random lookup on disks.</p> * * <p>Data is stored in blocks, typically 32K each. Each block has a * prefix-compressed set of keys at the beginning, followed by a block of value * data. For inverted list data it's best to use your own compression, but for * text data the GZip compression is a good choice.</p> * * <p>Typically this class is extended by composition instead of * inheritance.</p> * * <p>(11/29/2010, irmarc): After conferral with Sam, going to remove the * requirement that keys be Strings. It makes the mapping from other * classes/primitives to Strings really restrictive if they always have to be * mapped to Strings. Therefore, mapping byte[] keys to the client keyspace is * the responsibility of the client of the DiskBTreeReader.</p> * * @author trevor * @author irmarc */ public class DiskBTreeReader extends GalagoBTreeReader { // this input reader needs to be accesed in a synchronous manner. final ReadableBuffer input; // other variables do not VocabularyReader vocabulary; private Parameters manifest; int cacheGroupSize = 5; long fileLength; /** * Opens an index found in the buffer. * * @param buffer The buffer containing the BTree. * @throws IOException */ public DiskBTreeReader(ReadableBuffer buffer) throws IOException { input = buffer; CachedBufferDataStream inputStream = new CachedBufferDataStream(buffer); // Seek to the end of the file fileLength = input.length(); long footerOffset = fileLength - Integer.SIZE / 8 - 3 * Long.SIZE / 8; /** * In a constructor synchronized is not strictly necessary, no other threads * can use this object before it's creation... However, I'm wrapping *all* * usage. */ inputStream.seek(footerOffset); // Now, read metadata values: long vocabularyOffset = inputStream.readLong(); long manifestOffset = inputStream.readLong(); int blockSize = inputStream.readInt(); long magicNumber = inputStream.readLong(); if (magicNumber != DiskBTreeFormat.MAGIC_NUMBER) { throw new IOException("This does not appear to be an index file (wrong magic number)"); } long vocabularyLength = manifestOffset - vocabularyOffset; //input.seek(vocabularyOffset); vocabulary = new VocabularyReader(new CachedBufferDataStream(input, vocabularyOffset, vocabularyOffset + vocabularyLength), vocabularyOffset); ByteBuffer manifestData = ByteBuffer.allocate((int) (footerOffset - manifestOffset)); input.read(manifestData, manifestOffset); manifest = Parameters.parseBytes(manifestData.array()); this.cacheGroupSize = (int) manifest.get("cacheGroupSize", 1); } /** * Opens an index found in the at pathname. * * @param pathname Filename of the index to open. * @throws FileNotFoundException * @throws IOException */ public DiskBTreeReader(String pathname) throws IOException { this(new FileReadableBuffer(pathname)); } /** * Identical to the {@link #DiskBTreeReader(String) other constructor}, except * this one takes a File object instead of a string as the parameter. * * @throws java.io.IOException */ public DiskBTreeReader(File pathname) throws IOException { this(pathname.toString()); } /** * Returns a Parameters object that contains metadata about the contents of * the index. This is the place to store important data about the index * contents, like what stemmer was used or the total number of terms in the * collection. */ @Override public Parameters getManifest() { return manifest; } /** * Returns the vocabulary structure for this DiskBTreeReader. Note that the * vocabulary contains only the first key in each block. */ @Override public VocabularyReader getVocabulary() { return vocabulary; } /** * Returns an iterator pointing to the very first key in the index. This is * typically used for iterating through the entire index, which might be * useful for testing and debugging tools, but probably not for traditional * document retrieval. */ @Override public DiskBTreeIterator getIterator() throws IOException { // if we have an empty file - there is nothing to iterate over. if (manifest.get("emptyIndexFile", false)) { return null; } // otherwise there is some data. return new DiskBTreeIterator(this, vocabulary.getSlot(0)); } /** * Returns an iterator pointing at a specific key. Returns null if the key is * not found in the index. */ @Override public DiskBTreeIterator getIterator(byte[] key) throws IOException { // read from offset to offset in the vocab structure (right?) VocabularyReader.IndexBlockInfo slot = vocabulary.get(key); if (slot == null) { return null; } DiskBTreeIterator i = new DiskBTreeIterator(this, slot); i.find(key); if (CmpUtil.equals(key, i.getKey())) { return i; } return null; } /** * Closes all files associated with the DiskBTreeReader. */ @Override public void close() throws IOException { input.close(); } /** * Returns true if the file specified by this pathname was probably written by * DiskBTreeWriter. If this method returns false, the file is definitely not * readable by DiskBTreeReader. * * @throws java.io.IOException */ public static boolean isBTree(File file) throws IOException { RandomAccessFile f = null; boolean result = false; try { f = new RandomAccessFile(file, "r"); long length = f.length(); long magicNumber = 0; if (length > Long.SIZE / 8) { f.seek(length - Long.SIZE / 8); magicNumber = f.readLong(); } result = (magicNumber == DiskBTreeFormat.MAGIC_NUMBER); } finally { if(f != null) { f.close(); } } return result; } }
bsd-3-clause
dan-passaro/django-cachalot
cachalot/tests/models.py
1008
# coding: utf-8 from __future__ import unicode_literals from django.conf import settings from django.db.models import ( Model, CharField, ForeignKey, BooleanField, DateField, DateTimeField, ManyToManyField, BinaryField) class Test(Model): name = CharField(max_length=20) owner = ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) public = BooleanField(default=False) date = DateField(null=True, blank=True) datetime = DateTimeField(null=True, blank=True) permission = ForeignKey('auth.Permission', null=True, blank=True) bin = BinaryField(null=True, blank=True) class Meta(object): app_label = 'cachalot' ordering = ('name',) class TestParent(Model): name = CharField(max_length=20) class Meta(object): app_label = 'cachalot' class TestChild(TestParent): public = BooleanField(default=False) permissions = ManyToManyField('auth.Permission', blank=True) class Meta(object): app_label = 'cachalot'
bsd-3-clause
jfinkels/networkx
networkx/algorithms/tests/test_cycles.py
8279
#!/usr/bin/env python from nose.tools import * import networkx import networkx as nx from networkx.algorithms import find_cycle FORWARD = nx.algorithms.edgedfs.FORWARD REVERSE = nx.algorithms.edgedfs.REVERSE class TestCycles: def setUp(self): G=networkx.Graph() nx.add_cycle(G, [0,1,2,3]) nx.add_cycle(G, [0,3,4,5]) nx.add_cycle(G, [0,1,6,7,8]) G.add_edge(8,9) self.G=G def is_cyclic_permutation(self,a,b): n=len(a) if len(b)!=n: return False l=a+a return any(l[i:i+n]==b for i in range(2*n-n+1)) def test_cycle_basis(self): G=self.G cy=networkx.cycle_basis(G,0) sort_cy= sorted( sorted(c) for c in cy ) assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5]]) cy=networkx.cycle_basis(G,1) sort_cy= sorted( sorted(c) for c in cy ) assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5]]) cy=networkx.cycle_basis(G,9) sort_cy= sorted( sorted(c) for c in cy ) assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5]]) # test disconnected graphs nx.add_cycle(G, "ABC") cy=networkx.cycle_basis(G,9) sort_cy= sorted(sorted(c) for c in cy[:-1]) + [sorted(cy[-1])] assert_equal(sort_cy, [[0,1,2,3],[0,1,6,7,8],[0,3,4,5],['A','B','C']]) @raises(nx.NetworkXNotImplemented) def test_cycle_basis(self): G=nx.DiGraph() cy=networkx.cycle_basis(G,0) @raises(nx.NetworkXNotImplemented) def test_cycle_basis(self): G=nx.MultiGraph() cy=networkx.cycle_basis(G,0) def test_simple_cycles(self): G = nx.DiGraph([(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]) cc=sorted(nx.simple_cycles(G)) ca=[[0], [0, 1, 2], [0, 2], [1, 2], [2]] for c in cc: assert_true(any(self.is_cyclic_permutation(c,rc) for rc in ca)) @raises(nx.NetworkXNotImplemented) def test_simple_cycles_graph(self): G = nx.Graph() c = sorted(nx.simple_cycles(G)) def test_unsortable(self): # TODO What does this test do? das 6/2013 G=nx.DiGraph() nx.add_cycle(G, ['a',1]) c=list(nx.simple_cycles(G)) def test_simple_cycles_small(self): G = nx.DiGraph() nx.add_cycle(G, [1,2,3]) c=sorted(nx.simple_cycles(G)) assert_equal(len(c),1) assert_true(self.is_cyclic_permutation(c[0],[1,2,3])) nx.add_cycle(G, [10,20,30]) cc=sorted(nx.simple_cycles(G)) ca=[[1,2,3],[10,20,30]] for c in cc: assert_true(any(self.is_cyclic_permutation(c,rc) for rc in ca)) def test_simple_cycles_empty(self): G = nx.DiGraph() assert_equal(list(nx.simple_cycles(G)),[]) def test_complete_directed_graph(self): # see table 2 in Johnson's paper ncircuits=[1,5,20,84,409,2365,16064] for n,c in zip(range(2,9),ncircuits): G=nx.DiGraph(nx.complete_graph(n)) assert_equal(len(list(nx.simple_cycles(G))),c) def worst_case_graph(self,k): # see figure 1 in Johnson's paper # this graph has excactly 3k simple cycles G=nx.DiGraph() for n in range(2,k+2): G.add_edge(1,n) G.add_edge(n,k+2) G.add_edge(2*k+1,1) for n in range(k+2,2*k+2): G.add_edge(n,2*k+2) G.add_edge(n,n+1) G.add_edge(2*k+3,k+2) for n in range(2*k+3,3*k+3): G.add_edge(2*k+2,n) G.add_edge(n,3*k+3) G.add_edge(3*k+3,2*k+2) return G def test_worst_case_graph(self): # see figure 1 in Johnson's paper for k in range(3,10): G=self.worst_case_graph(k) l=len(list(nx.simple_cycles(G))) assert_equal(l,3*k) def test_recursive_simple_and_not(self): for k in range(2,10): G=self.worst_case_graph(k) cc=sorted(nx.simple_cycles(G)) rcc=sorted(nx.recursive_simple_cycles(G)) assert_equal(len(cc),len(rcc)) for c in cc: assert_true(any(self.is_cyclic_permutation(c,rc) for rc in rcc)) for rc in rcc: assert_true(any(self.is_cyclic_permutation(rc,c) for c in cc)) def test_simple_graph_with_reported_bug(self): G=nx.DiGraph() edges = [(0, 2), (0, 3), (1, 0), (1, 3), (2, 1), (2, 4), \ (3, 2), (3, 4), (4, 0), (4, 1), (4, 5), (5, 0), \ (5, 1), (5, 2), (5, 3)] G.add_edges_from(edges) cc=sorted(nx.simple_cycles(G)) assert_equal(len(cc),26) rcc=sorted(nx.recursive_simple_cycles(G)) assert_equal(len(cc),len(rcc)) for c in cc: assert_true(any(self.is_cyclic_permutation(c,rc) for rc in rcc)) for rc in rcc: assert_true(any(self.is_cyclic_permutation(rc,c) for c in cc)) # These tests might fail with hash randomization since they depend on # edge_dfs. For more information, see the comments in: # networkx/algorithms/traversal/tests/test_edgedfs.py class TestFindCycle(object): def setUp(self): self.nodes = [0, 1, 2, 3] self.edges = [(-1, 0), (0, 1), (1, 0), (1, 0), (2, 1), (3, 1)] def test_graph(self): G = nx.Graph(self.edges) assert_raises(nx.exception.NetworkXNoCycle, find_cycle, G, self.nodes) def test_digraph(self): G = nx.DiGraph(self.edges) x = list(find_cycle(G, self.nodes)) x_= [(0, 1), (1, 0)] assert_equal(x, x_) def test_multigraph(self): G = nx.MultiGraph(self.edges) x = list(find_cycle(G, self.nodes)) x_ = [(0, 1, 0), (1, 0, 1)] # or (1, 0, 2) # Hash randomization...could be any edge. assert_equal(x[0], x_[0]) assert_equal(x[1][:2], x_[1][:2]) def test_multidigraph(self): G = nx.MultiDiGraph(self.edges) x = list(find_cycle(G, self.nodes)) x_ = [(0, 1, 0), (1, 0, 0)] # (1, 0, 1) assert_equal(x[0], x_[0]) assert_equal(x[1][:2], x_[1][:2]) def test_digraph_ignore(self): G = nx.DiGraph(self.edges) x = list(find_cycle(G, self.nodes, orientation='ignore')) x_ = [(0, 1, FORWARD), (1, 0, FORWARD)] assert_equal(x, x_) def test_multidigraph_ignore(self): G = nx.MultiDiGraph(self.edges) x = list(find_cycle(G, self.nodes, orientation='ignore')) x_ = [(0, 1, 0, FORWARD), (1, 0, 0, FORWARD)] # or (1, 0, 1, 1) assert_equal(x[0], x_[0]) assert_equal(x[1][:2], x_[1][:2]) assert_equal(x[1][3], x_[1][3]) def test_multidigraph_ignore2(self): # Loop traversed an edge while ignoring its orientation. G = nx.MultiDiGraph([(0,1), (1,2), (1,2)]) x = list(find_cycle(G, [0,1,2], orientation='ignore')) x_ = [(1,2,0,FORWARD), (1,2,1,REVERSE)] assert_equal(x, x_) def test_multidigraph_ignore2(self): # Node 2 doesn't need to be searched again from visited from 4. # The goal here is to cover the case when 2 to be researched from 4, # when 4 is visited from the first time (so we must make sure that 4 # is not visited from 2, and hence, we respect the edge orientation). G = nx.MultiDiGraph([(0,1), (1,2), (2,3), (4,2)]) assert_raises(nx.exception.NetworkXNoCycle, find_cycle, G, [0,1,2,3,4], orientation='original') def test_dag(self): G = nx.DiGraph([(0,1), (0,2), (1,2)]) assert_raises(nx.exception.NetworkXNoCycle, find_cycle, G, orientation='original') x = list(find_cycle(G, orientation='ignore')) assert_equal(x, [(0,1,FORWARD), (1,2,FORWARD), (0,2,REVERSE)]) def test_prev_explored(self): # https://github.com/networkx/networkx/issues/2323 G = nx.DiGraph() G.add_edges_from([(1,0), (2,0), (1,2), (2,1)]) assert_raises(nx.exception.NetworkXNoCycle, find_cycle, G, source=0) x = list(nx.find_cycle(G, 1)) x_ = [(1, 2), (2, 1)] assert_equal(x, x_) x = list(nx.find_cycle(G, 2)) x_ = [(2, 1), (1, 2)] assert_equal(x, x_)
bsd-3-clause
ayumin/kozuchi
app/models/friend/rejection.rb
292
class Friend::Rejection < Friend::Permission validate :validates_not_rejected private def validates_not_rejected errors.add_to_base("すでにフレンド関係を拒否しています。") if Friend::Rejection.find_by_user_id_and_target_id(self.user_id, self.target_id) end end
bsd-3-clause
jack-pappas/PyTables
tables/description.py
36300
# -*- coding: utf-8 -*- ######################################################################## # # License: BSD # Created: September 21, 2002 # Author: Francesc Alted # # $Id$ # ######################################################################## """Classes for describing columns for ``Table`` objects.""" # Imports # ======= from __future__ import print_function import sys import copy import warnings import numpy from tables import atom from tables.path import check_name_validity from tables._past import previous_api, previous_api_property # Public variables # ================ __docformat__ = 'reStructuredText' """The format of documentation strings in this module.""" # Private functions # ================= def same_position(oldmethod): """Decorate `oldmethod` to also compare the `_v_pos` attribute.""" def newmethod(self, other): try: other._v_pos except AttributeError: return False # not a column definition return self._v_pos == other._v_pos and oldmethod(self, other) newmethod.__name__ = oldmethod.__name__ newmethod.__doc__ = oldmethod.__doc__ return newmethod # Column classes # ============== class Col(atom.Atom): """Defines a non-nested column. Col instances are used as a means to declare the different properties of a non-nested column in a table or nested column. Col classes are descendants of their equivalent Atom classes (see :ref:`AtomClassDescr`), but their instances have an additional _v_pos attribute that is used to decide the position of the column inside its parent table or nested column (see the IsDescription class in :ref:`IsDescriptionClassDescr` for more information on column positions). In the same fashion as Atom, you should use a particular Col descendant class whenever you know the exact type you will need when writing your code. Otherwise, you may use one of the Col.from_*() factory methods. Each factory method inherited from the Atom class is available with the same signature, plus an additional pos parameter (placed in last position) which defaults to None and that may take an integer value. This parameter might be used to specify the position of the column in the table. Besides, there are the next additional factory methods, available only for Col objects. The following parameters are available for most Col-derived constructors. Parameters ---------- itemsize : int For types with a non-fixed size, this sets the size in bytes of individual items in the column. shape : tuple Sets the shape of the column. An integer shape of N is equivalent to the tuple (N,). dflt Sets the default value for the column. pos : int Sets the position of column in table. If unspecified, the position will be randomly selected. """ # Avoid mangling atom class data. __metaclass__ = type _class_from_prefix = {} # filled as column classes are created """Maps column prefixes to column classes.""" # Class methods # ~~~~~~~~~~~~~ @classmethod def prefix(class_): """Return the column class prefix.""" cname = class_.__name__ return cname[:cname.rfind('Col')] @classmethod def from_atom(class_, atom, pos=None): """Create a Col definition from a PyTables atom. An optional position may be specified as the pos argument. """ prefix = atom.prefix() kwargs = atom._get_init_args() colclass = class_._class_from_prefix[prefix] return colclass(pos=pos, **kwargs) @classmethod def from_sctype(class_, sctype, shape=(), dflt=None, pos=None): """Create a `Col` definition from a NumPy scalar type `sctype`. Optional shape, default value and position may be specified as the `shape`, `dflt` and `pos` arguments, respectively. Information in the `sctype` not represented in a `Col` is ignored. """ newatom = atom.Atom.from_sctype(sctype, shape, dflt) return class_.from_atom(newatom, pos=pos) @classmethod def from_dtype(class_, dtype, dflt=None, pos=None): """Create a `Col` definition from a NumPy `dtype`. Optional default value and position may be specified as the `dflt` and `pos` arguments, respectively. The `dtype` must have a byte order which is irrelevant or compatible with that of the system. Information in the `dtype` not represented in a `Col` is ignored. """ newatom = atom.Atom.from_dtype(dtype, dflt) return class_.from_atom(newatom, pos=pos) @classmethod def from_type(class_, type, shape=(), dflt=None, pos=None): """Create a `Col` definition from a PyTables `type`. Optional shape, default value and position may be specified as the `shape`, `dflt` and `pos` arguments, respectively. """ newatom = atom.Atom.from_type(type, shape, dflt) return class_.from_atom(newatom, pos=pos) @classmethod def from_kind(class_, kind, itemsize=None, shape=(), dflt=None, pos=None): """Create a `Col` definition from a PyTables `kind`. Optional item size, shape, default value and position may be specified as the `itemsize`, `shape`, `dflt` and `pos` arguments, respectively. Bear in mind that not all columns support a default item size. """ newatom = atom.Atom.from_kind(kind, itemsize, shape, dflt) return class_.from_atom(newatom, pos=pos) @classmethod def _subclass_from_prefix(class_, prefix): """Get a column subclass for the given `prefix`.""" cname = '%sCol' % prefix class_from_prefix = class_._class_from_prefix if cname in class_from_prefix: return class_from_prefix[cname] atombase = getattr(atom, '%sAtom' % prefix) class NewCol(class_, atombase): """Defines a non-nested column of a particular type. The constructor accepts the same arguments as the equivalent `Atom` class, plus an additional ``pos`` argument for position information, which is assigned to the `_v_pos` attribute. """ def __init__(self, *args, **kwargs): pos = kwargs.pop('pos', None) class_from_prefix = self._class_from_prefix atombase.__init__(self, *args, **kwargs) # The constructor of an abstract atom may have changed # the class of `self` to something different of `NewCol` # and `atombase` (that's why the prefix map is saved). if self.__class__ is not NewCol: colclass = class_from_prefix[self.prefix()] self.__class__ = colclass self._v_pos = pos __eq__ = same_position(atombase.__eq__) _is_equal_to_atom = same_position(atombase._is_equal_to_atom) # XXX: API incompatible change for PyTables 3 line # Overriding __eq__ blocks inheritance of __hash__ in 3.x # def __hash__(self): # return hash((self._v_pos, self.atombase)) if prefix == 'Enum': _is_equal_to_enumatom = same_position( atombase._is_equal_to_enumatom) NewCol.__name__ = cname class_from_prefix[prefix] = NewCol return NewCol # Special methods # ~~~~~~~~~~~~~~~ def __repr__(self): # Reuse the atom representation. atomrepr = super(Col, self).__repr__() lpar = atomrepr.index('(') rpar = atomrepr.rindex(')') atomargs = atomrepr[lpar + 1:rpar] classname = self.__class__.__name__ return '%s(%s, pos=%s)' % (classname, atomargs, self._v_pos) # Private methods # ~~~~~~~~~~~~~~~ def _get_init_args(self): """Get a dictionary of instance constructor arguments.""" kwargs = dict((arg, getattr(self, arg)) for arg in ('shape', 'dflt')) kwargs['pos'] = getattr(self, '_v_pos', None) return kwargs def _generate_col_classes(): """Generate all column classes.""" # Abstract classes are not in the class map. cprefixes = ['Int', 'UInt', 'Float', 'Time'] for (kind, kdata) in atom.atom_map.iteritems(): if hasattr(kdata, 'kind'): # atom class: non-fixed item size atomclass = kdata cprefixes.append(atomclass.prefix()) else: # dictionary: fixed item size for atomclass in kdata.itervalues(): cprefixes.append(atomclass.prefix()) # Bottom-level complex classes are not in the type map, of course. # We still want the user to get the compatibility warning, though. cprefixes.extend(['Complex32', 'Complex64', 'Complex128']) if hasattr(atom, 'Complex192Atom'): cprefixes.append('Complex192') if hasattr(atom, 'Complex256Atom'): cprefixes.append('Complex256') for cprefix in cprefixes: newclass = Col._subclass_from_prefix(cprefix) yield newclass # Create all column classes. #for _newclass in _generate_col_classes(): # exec('%s = _newclass' % _newclass.__name__) #del _newclass StringCol = Col._subclass_from_prefix('String') BoolCol = Col._subclass_from_prefix('Bool') EnumCol = Col._subclass_from_prefix('Enum') IntCol = Col._subclass_from_prefix('Int') Int8Col = Col._subclass_from_prefix('Int8') Int16Col = Col._subclass_from_prefix('Int16') Int32Col = Col._subclass_from_prefix('Int32') Int64Col = Col._subclass_from_prefix('Int64') UIntCol = Col._subclass_from_prefix('UInt') UInt8Col = Col._subclass_from_prefix('UInt8') UInt16Col = Col._subclass_from_prefix('UInt16') UInt32Col = Col._subclass_from_prefix('UInt32') UInt64Col = Col._subclass_from_prefix('UInt64') FloatCol = Col._subclass_from_prefix('Float') if hasattr(atom, 'Float16Atom'): Float16Col = Col._subclass_from_prefix('Float16') Float32Col = Col._subclass_from_prefix('Float32') Float64Col = Col._subclass_from_prefix('Float64') if hasattr(atom, 'Float96Atom'): Float96Col = Col._subclass_from_prefix('Float96') if hasattr(atom, 'Float128Atom'): Float128Col = Col._subclass_from_prefix('Float128') ComplexCol = Col._subclass_from_prefix('Complex') Complex32Col = Col._subclass_from_prefix('Complex32') Complex64Col = Col._subclass_from_prefix('Complex64') Complex128Col = Col._subclass_from_prefix('Complex128') if hasattr(atom, 'Complex192Atom'): Complex192Col = Col._subclass_from_prefix('Complex192') if hasattr(atom, 'Complex256Atom'): Complex256Col = Col._subclass_from_prefix('Complex256') TimeCol = Col._subclass_from_prefix('Time') Time32Col = Col._subclass_from_prefix('Time32') Time64Col = Col._subclass_from_prefix('Time64') # Table description classes # ========================= class Description(object): """This class represents descriptions of the structure of tables. An instance of this class is automatically bound to Table (see :ref:`TableClassDescr`) objects when they are created. It provides a browseable representation of the structure of the table, made of non-nested (Col - see :ref:`ColClassDescr`) and nested (Description) columns. Column definitions under a description can be accessed as attributes of it (*natural naming*). For instance, if table.description is a Description instance with a column named col1 under it, the later can be accessed as table.description.col1. If col1 is nested and contains a col2 column, this can be accessed as table.description.col1.col2. Because of natural naming, the names of members start with special prefixes, like in the Group class (see :ref:`GroupClassDescr`). .. rubric:: Description attributes .. attribute:: _v_colobjects A dictionary mapping the names of the columns hanging directly from the associated table or nested column to their respective descriptions (Col - see :ref:`ColClassDescr` or Description - see :ref:`DescriptionClassDescr` instances). .. versionchanged:: 3.0 The *_v_colObjects* attobute has been renamed into *_v_colobjects*. .. attribute:: _v_dflts A dictionary mapping the names of non-nested columns hanging directly from the associated table or nested column to their respective default values. .. attribute:: _v_dtype The NumPy type which reflects the structure of this table or nested column. You can use this as the dtype argument of NumPy array factories. .. attribute:: _v_dtypes A dictionary mapping the names of non-nested columns hanging directly from the associated table or nested column to their respective NumPy types. .. attribute:: _v_is_nested Whether the associated table or nested column contains further nested columns or not. .. attribute:: _v_itemsize The size in bytes of an item in this table or nested column. .. attribute:: _v_name The name of this description group. The name of the root group is '/'. .. attribute:: _v_names A list of the names of the columns hanging directly from the associated table or nested column. The order of the names matches the order of their respective columns in the containing table. .. attribute:: _v_nested_descr A nested list of pairs of (name, format) tuples for all the columns under this table or nested column. You can use this as the dtype and descr arguments of NumPy array factories. .. versionchanged:: 3.0 The *_v_nestedDescr* attribute has been renamed into *_v_nested_descr*. .. attribute:: _v_nested_formats A nested list of the NumPy string formats (and shapes) of all the columns under this table or nested column. You can use this as the formats argument of NumPy array factories. .. versionchanged:: 3.0 The *_v_nestedFormats* attribute has been renamed into *_v_nested_formats*. .. attribute:: _v_nestedlvl The level of the associated table or nested column in the nested datatype. .. attribute:: _v_nested_names A nested list of the names of all the columns under this table or nested column. You can use this as the names argument of NumPy array factories. .. versionchanged:: 3.0 The *_v_nestedNames* attribute has been renamed into *_v_nested_names*. .. attribute:: _v_pathname Pathname of the table or nested column. .. attribute:: _v_pathnames A list of the pathnames of all the columns under this table or nested column (in preorder). If it does not contain nested columns, this is exactly the same as the :attr:`Description._v_names` attribute. .. attribute:: _v_types A dictionary mapping the names of non-nested columns hanging directly from the associated table or nested column to their respective PyTables types. """ _v_colObjects = previous_api_property('_v_colobjects') _v_nestedFormats = previous_api_property('_v_nested_formats') _v_nestedNames = previous_api_property('_v_nested_names') _v_nestedDesct = previous_api_property('_v_nested_descr') def __init__(self, classdict, nestedlvl=-1, validate=True): if not classdict: raise ValueError("cannot create an empty data type") # Do a shallow copy of classdict just in case this is going to # be shared by other instances newdict = self.__dict__ newdict["_v_name"] = "/" # The name for root descriptor newdict["_v_names"] = [] newdict["_v_dtypes"] = {} newdict["_v_types"] = {} newdict["_v_dflts"] = {} newdict["_v_colobjects"] = {} newdict["_v_is_nested"] = False nestedFormats = [] nestedDType = [] if not hasattr(newdict, "_v_nestedlvl"): newdict["_v_nestedlvl"] = nestedlvl + 1 cols_with_pos = [] # colum (position, name) pairs cols_no_pos = [] # just column names # Check for special variables and convert column descriptions for (name, descr) in classdict.iteritems(): if name.startswith('_v_'): if name in newdict: # print("Warning!") # special methods &c: copy to newdict, warn about conflicts warnings.warn("Can't set attr %r in description class %r" % (name, self)) else: # print("Special variable!-->", name, classdict[name]) newdict[name] = descr continue # This variable is not needed anymore columns = None if (type(descr) == type(IsDescription) and issubclass(descr, IsDescription)): # print("Nested object (type I)-->", name) columns = descr().columns elif (type(descr.__class__) == type(IsDescription) and issubclass(descr.__class__, IsDescription)): # print("Nested object (type II)-->", name) columns = descr.columns elif isinstance(descr, dict): # print("Nested object (type III)-->", name) columns = descr else: # print("Nested object (type IV)-->", name) descr = copy.copy(descr) # The copies above and below ensure that the structures # provided by the user will remain unchanged even if we # tamper with the values of ``_v_pos`` here. if columns is not None: descr = Description(copy.copy(columns), self._v_nestedlvl) classdict[name] = descr pos = getattr(descr, '_v_pos', None) if pos is None: cols_no_pos.append(name) else: cols_with_pos.append((pos, name)) # Sort field names: # # 1. Fields with explicit positions, according to their # positions (and their names if coincident). # 2. Fields with no position, in alfabetical order. cols_with_pos.sort() cols_no_pos.sort() keys = [name for (pos, name) in cols_with_pos] + cols_no_pos pos = 0 # Get properties for compound types for k in keys: if validate: # Check for key name validity check_name_validity(k) # Class variables object = classdict[k] newdict[k] = object # To allow natural naming if not (isinstance(object, Col) or isinstance(object, Description)): raise TypeError('Passing an incorrect value to a table column.' ' Expected a Col (or subclass) instance and ' 'got: "%s". Please make use of the Col(), or ' 'descendant, constructor to properly ' 'initialize columns.' % object) object._v_pos = pos # Set the position of this object object._v_parent = self # The parent description pos += 1 newdict['_v_colobjects'][k] = object newdict['_v_names'].append(k) object.__dict__['_v_name'] = k if not isinstance(k, str): # numpy only accepts "str" for field names if sys.version_info[0] < 3: # Python 2.x: unicode --> str kk = k.encode() # use the default encoding else: # Python 3.x: bytes --> str (unicode) kk = k.decode() else: kk = k if isinstance(object, Col): dtype = object.dtype newdict['_v_dtypes'][k] = dtype newdict['_v_types'][k] = object.type newdict['_v_dflts'][k] = object.dflt nestedFormats.append(object.recarrtype) baserecarrtype = dtype.base.str[1:] nestedDType.append((kk, baserecarrtype, dtype.shape)) else: # A description nestedFormats.append(object._v_nested_formats) nestedDType.append((kk, object._v_dtype)) # Assign the format list to _v_nested_formats newdict['_v_nested_formats'] = nestedFormats newdict['_v_dtype'] = numpy.dtype(nestedDType) # _v_itemsize is derived from the _v_dtype that already computes this newdict['_v_itemsize'] = newdict['_v_dtype'].itemsize if self._v_nestedlvl == 0: # Get recursively nested _v_nested_names and _v_nested_descr attrs self._g_set_nested_names_descr() # Get pathnames for nested groups self._g_set_path_names() # Check the _v_byteorder has been used an issue an Error if hasattr(self, "_v_byteorder"): raise ValueError( "Using a ``_v_byteorder`` in the description is obsolete. " "Use the byteorder parameter in the constructor instead.") def _g_set_nested_names_descr(self): """Computes the nested names and descriptions for nested datatypes.""" names = self._v_names fmts = self._v_nested_formats self._v_nested_names = names[:] # Important to do a copy! self._v_nested_descr = [(names[i], fmts[i]) for i in range(len(names))] for i in range(len(names)): name = names[i] new_object = self._v_colobjects[name] if isinstance(new_object, Description): new_object._g_set_nested_names_descr() # replace the column nested name by a correct tuple self._v_nested_names[i] = (name, new_object._v_nested_names) self._v_nested_descr[i] = (name, new_object._v_nested_descr) # set the _v_is_nested flag self._v_is_nested = True _g_setNestedNamesDescr = previous_api(_g_set_nested_names_descr) def _g_set_path_names(self): """Compute the pathnames for arbitrary nested descriptions. This method sets the ``_v_pathname`` and ``_v_pathnames`` attributes of all the elements (both descriptions and columns) in this nested description. """ def get_cols_in_order(description): return [description._v_colobjects[colname] for colname in description._v_names] def join_paths(path1, path2): if not path1: return path2 return '%s/%s' % (path1, path2) # The top of the stack always has a nested description # and a list of its child columns # (be they nested ``Description`` or non-nested ``Col`` objects). # In the end, the list contains only a list of column paths # under this one. # # For instance, given this top of the stack:: # # (<Description X>, [<Column A>, <Column B>]) # # After computing the rest of the stack, the top is:: # # (<Description X>, ['a', 'a/m', 'a/n', ... , 'b', ...]) stack = [] # We start by pushing the top-level description # and its child columns. self._v_pathname = '' stack.append((self, get_cols_in_order(self))) while stack: desc, cols = stack.pop() head = cols[0] # What's the first child in the list? if isinstance(head, Description): # A nested description. We remove it from the list and # push it with its child columns. This will be the next # handled description. head._v_pathname = join_paths(desc._v_pathname, head._v_name) stack.append((desc, cols[1:])) # alter the top stack.append((head, get_cols_in_order(head))) # new top elif isinstance(head, Col): # A non-nested column. We simply remove it from the # list and append its name to it. head._v_pathname = join_paths(desc._v_pathname, head._v_name) cols.append(head._v_name) # alter the top stack.append((desc, cols[1:])) # alter the top else: # Since paths and names are appended *to the end* of # children lists, a string signals that no more children # remain to be processed, so we are done with the # description at the top of the stack. assert isinstance(head, basestring) # Assign the computed set of descendent column paths. desc._v_pathnames = cols if len(stack) > 0: # Compute the paths with respect to the parent node # (including the path of the current description) # and append them to its list. descName = desc._v_name colPaths = [join_paths(descName, path) for path in cols] colPaths.insert(0, descName) parentCols = stack[-1][1] parentCols.extend(colPaths) # (Nothing is pushed, we are done with this description.) _g_setPathNames = previous_api(_g_set_path_names) def _f_walk(self, type='All'): """Iterate over nested columns. If type is 'All' (the default), all column description objects (Col and Description instances) are yielded in top-to-bottom order (preorder). If type is 'Col' or 'Description', only column descriptions of that type are yielded. """ if type not in ["All", "Col", "Description"]: raise ValueError("""\ type can only take the parameters 'All', 'Col' or 'Description'.""") stack = [self] while stack: object = stack.pop(0) # pop at the front so as to ensure the order if type in ["All", "Description"]: yield object # yield description names = object._v_names for i in range(len(names)): new_object = object._v_colobjects[names[i]] if isinstance(new_object, Description): stack.append(new_object) else: if type in ["All", "Col"]: yield new_object # yield column def __repr__(self): """Gives a detailed Description column representation.""" rep = ['%s\"%s\": %r' % (" " * self._v_nestedlvl, k, self._v_colobjects[k]) for k in self._v_names] return '{\n %s}' % (',\n '.join(rep)) def __str__(self): """Gives a brief Description representation.""" return 'Description(%s)' % self._v_nested_descr class MetaIsDescription(type): """Helper metaclass to return the class variables as a dictionary.""" def __new__(cls, classname, bases, classdict): """Return a new class with a "columns" attribute filled.""" newdict = {"columns": {}, } if '__doc__' in classdict: newdict['__doc__'] = classdict['__doc__'] for b in bases: if "columns" in b.__dict__: newdict["columns"].update(b.__dict__["columns"]) for k in classdict: # if not (k.startswith('__') or k.startswith('_v_')): # We let pass _v_ variables to configure class behaviour if not (k.startswith('__')): newdict["columns"][k] = classdict[k] # Return a new class with the "columns" attribute filled return type.__new__(cls, classname, bases, newdict) metaIsDescription = previous_api(MetaIsDescription) class IsDescription(object): """Description of the structure of a table or nested column. This class is designed to be used as an easy, yet meaningful way to describe the structure of new Table (see :ref:`TableClassDescr`) datasets or nested columns through the definition of *derived classes*. In order to define such a class, you must declare it as descendant of IsDescription, with as many attributes as columns you want in your table. The name of each attribute will become the name of a column, and its value will hold a description of it. Ordinary columns can be described using instances of the Col class (see :ref:`ColClassDescr`). Nested columns can be described by using classes derived from IsDescription, instances of it, or name-description dictionaries. Derived classes can be declared in place (in which case the column takes the name of the class) or referenced by name. Nested columns can have a _v_pos special attribute which sets the *relative* position of the column among sibling columns *also having explicit positions*. The pos constructor argument of Col instances is used for the same purpose. Columns with no explicit position will be placed afterwards in alphanumeric order. Once you have created a description object, you can pass it to the Table constructor, where all the information it contains will be used to define the table structure. .. rubric:: IsDescription attributes .. attribute:: _v_pos Sets the position of a possible nested column description among its sibling columns. This attribute can be specified *when declaring* an IsDescription subclass to complement its *metadata*. .. attribute:: columns Maps the name of each column in the description to its own descriptive object. This attribute is *automatically created* when an IsDescription subclass is declared. Please note that declared columns can no longer be accessed as normal class variables after its creation. """ __metaclass__ = MetaIsDescription def descr_from_dtype(dtype_): """Get a description instance and byteorder from a (nested) NumPy dtype.""" fields = {} fbyteorder = '|' for name in dtype_.names: dtype, pos = dtype_.fields[name][:2] kind = dtype.base.kind byteorder = dtype.base.byteorder if byteorder in '><=': if fbyteorder not in ['|', byteorder]: raise NotImplementedError( "structured arrays with mixed byteorders " "are not supported yet, sorry") fbyteorder = byteorder # Non-nested column if kind in 'biufSc': col = Col.from_dtype(dtype, pos=pos) # Nested column elif kind == 'V' and dtype.shape in [(), (1,)]: if dtype.shape != (): warnings.warn( "nested descriptions will be converted to scalar") col, _ = descr_from_dtype(dtype.base) col._v_pos = pos else: raise NotImplementedError( "structured arrays with columns with type description ``%s`` " "are not supported yet, sorry" % dtype) fields[name] = col return Description(fields), fbyteorder def dtype_from_descr(descr, byteorder=None): """Get a (nested) NumPy dtype from a description instance and byteorder. The descr parameter can be a Description or IsDescription instance, sub-class of IsDescription or a dictionary. """ if isinstance(descr, dict): descr = Description(descr) elif (type(descr) == type(IsDescription) and issubclass(descr, IsDescription)): descr = Description(descr().columns) elif isinstance(descr, IsDescription): descr = Description(descr.columns) elif not isinstance(descr, Description): raise ValueError('invalid description: %r' % descr) dtype_ = descr._v_dtype if byteorder and byteorder != '|': dtype_ = dtype_.newbyteorder(byteorder) return dtype_ if __name__ == "__main__": """Test code.""" class Info(IsDescription): _v_pos = 2 Name = UInt32Col() Value = Float64Col() class Test(IsDescription): """A description that has several columns.""" x = Col.from_type("int32", 2, 0, pos=0) y = Col.from_kind('float', dflt=1, shape=(2, 3)) z = UInt8Col(dflt=1) color = StringCol(2, dflt=" ") # color = UInt32Col(2) Info = Info() class info(IsDescription): _v_pos = 1 name = UInt32Col() value = Float64Col(pos=0) y2 = Col.from_kind('float', dflt=1, shape=(2, 3), pos=1) z2 = UInt8Col(dflt=1) class info2(IsDescription): y3 = Col.from_kind('float', dflt=1, shape=(2, 3)) z3 = UInt8Col(dflt=1) name = UInt32Col() value = Float64Col() class info3(IsDescription): name = UInt32Col() value = Float64Col() y4 = Col.from_kind('float', dflt=1, shape=(2, 3)) z4 = UInt8Col(dflt=1) # class Info(IsDescription): # _v_pos = 2 # Name = StringCol(itemsize=2) # Value = ComplexCol(itemsize=16) # class Test(IsDescription): # """A description that has several columns""" # x = Col.from_type("int32", 2, 0, pos=0) # y = Col.from_kind('float', dflt=1, shape=(2,3)) # z = UInt8Col(dflt=1) # color = StringCol(2, dflt=" ") # Info = Info() # class info(IsDescription): # _v_pos = 1 # name = StringCol(itemsize=2) # value = ComplexCol(itemsize=16, pos=0) # y2 = Col.from_kind('float', dflt=1, shape=(2,3), pos=1) # z2 = UInt8Col(dflt=1) # class info2(IsDescription): # y3 = Col.from_kind('float', dflt=1, shape=(2,3)) # z3 = UInt8Col(dflt=1) # name = StringCol(itemsize=2) # value = ComplexCol(itemsize=16) # class info3(IsDescription): # name = StringCol(itemsize=2) # value = ComplexCol(itemsize=16) # y4 = Col.from_kind('float', dflt=1, shape=(2,3)) # z4 = UInt8Col(dflt=1) # example cases of class Test klass = Test() # klass = Info() desc = Description(klass.columns) print("Description representation (short) ==>", desc) print("Description representation (long) ==>", repr(desc)) print("Column names ==>", desc._v_names) print("Column x ==>", desc.x) print("Column Info ==>", desc.Info) print("Column Info.value ==>", desc.Info.Value) print("Nested column names ==>", desc._v_nested_names) print("Defaults ==>", desc._v_dflts) print("Nested Formats ==>", desc._v_nested_formats) print("Nested Descriptions ==>", desc._v_nested_descr) print("Nested Descriptions (info) ==>", desc.info._v_nested_descr) print("Total size ==>", desc._v_dtype.itemsize) # check _f_walk for object in desc._f_walk(): if isinstance(object, Description): print("******begin object*************", end=' ') print("name -->", object._v_name) # print("name -->", object._v_dtype.name) # print("object childs-->", object._v_names) # print("object nested childs-->", object._v_nested_names) print("totalsize-->", object._v_dtype.itemsize) else: # pass print("leaf -->", object._v_name, object.dtype) class testDescParent(IsDescription): c = Int32Col() class testDesc(testDescParent): pass assert 'c' in testDesc.columns ## Local Variables: ## mode: python ## py-indent-offset: 4 ## tab-width: 4 ## fill-column: 72 ## End:
bsd-3-clause
pvanhorn/openthread
src/ncp/ncp_base_radio.cpp
12607
/* * Copyright (c) 2016-2017, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions 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. * 3. Neither the name of the copyright holder nor the * names of its contributors may 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 COPYRIGHT HOLDER 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. */ /** * @file * This file implements raw link required Spinel interface to the OpenThread stack. */ #include "ncp_base.hpp" #include <openthread/link.h> #include <openthread/link_raw.h> #include <openthread/ncp.h> #include <openthread/openthread.h> #include <openthread/platform/radio.h> #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" #include "mac/mac_frame.hpp" #if OPENTHREAD_RADIO || OPENTHREAD_ENABLE_RAW_LINK_API namespace ot { namespace Ncp { // ---------------------------------------------------------------------------- // MARK: Raw Link-Layer Datapath Glue // ---------------------------------------------------------------------------- void NcpBase::LinkRawReceiveDone(otInstance *, otRadioFrame *aFrame, otError aError) { sNcpInstance->LinkRawReceiveDone(aFrame, aError); } void NcpBase::LinkRawReceiveDone(otRadioFrame *aFrame, otError aError) { uint16_t flags = 0; uint8_t header = SPINEL_HEADER_FLAG | SPINEL_HEADER_IID_0; if (aFrame->mDidTX) { flags |= SPINEL_MD_FLAG_TX; } // Append frame header and frame length SuccessOrExit(mEncoder.BeginFrame(header, SPINEL_CMD_PROP_VALUE_IS, SPINEL_PROP_STREAM_RAW)); SuccessOrExit(mEncoder.WriteUint16((aError == OT_ERROR_NONE) ? aFrame->mLength : 0)); if (aError == OT_ERROR_NONE) { // Append the frame contents SuccessOrExit(mEncoder.WriteData(aFrame->mPsdu, aFrame->mLength)); } // Append metadata (rssi, etc) SuccessOrExit(mEncoder.WriteInt8(aFrame->mRssi)); // RSSI SuccessOrExit(mEncoder.WriteInt8(-128)); // Noise Floor (Currently unused) SuccessOrExit(mEncoder.WriteUint16(flags)); // Flags SuccessOrExit(mEncoder.OpenStruct()); // PHY-data SuccessOrExit(mEncoder.WriteUint8(aFrame->mChannel)); // 802.15.4 channel (Receive channel) SuccessOrExit(mEncoder.WriteUint8(aFrame->mLqi)); // 802.15.4 LQI SuccessOrExit(mEncoder.WriteUint32(aFrame->mMsec)); // The timestamp milliseconds SuccessOrExit(mEncoder.WriteUint16(aFrame->mUsec)); // The timestamp microseconds, offset to mMsec SuccessOrExit(mEncoder.CloseStruct()); SuccessOrExit(mEncoder.OpenStruct()); // Vendor-data SuccessOrExit(mEncoder.WriteUintPacked(aError)); // Receive error SuccessOrExit(mEncoder.CloseStruct()); SuccessOrExit(mEncoder.EndFrame()); exit: return; } void NcpBase::LinkRawTransmitDone(otInstance *, otRadioFrame *aFrame, otRadioFrame *aAckFrame, otError aError) { sNcpInstance->LinkRawTransmitDone(aFrame, aAckFrame, aError); } void NcpBase::LinkRawTransmitDone(otRadioFrame *aFrame, otRadioFrame *aAckFrame, otError aError) { if (mCurTransmitTID) { uint8_t header = SPINEL_HEADER_FLAG | SPINEL_HEADER_IID_0 | mCurTransmitTID; bool framePending = (aAckFrame != NULL && static_cast<Mac::Frame *>(aAckFrame)->GetFramePending()); // Clear cached transmit TID mCurTransmitTID = 0; SuccessOrExit(mEncoder.BeginFrame(header, SPINEL_CMD_PROP_VALUE_IS, SPINEL_PROP_LAST_STATUS)); SuccessOrExit(mEncoder.WriteUintPacked(ThreadErrorToSpinelStatus(aError))); SuccessOrExit(mEncoder.WriteBool(framePending)); if (aAckFrame && aError == OT_ERROR_NONE) { SuccessOrExit(mEncoder.WriteUint16(aAckFrame->mLength)); SuccessOrExit(mEncoder.WriteData(aAckFrame->mPsdu, aAckFrame->mLength)); SuccessOrExit(mEncoder.WriteInt8(aAckFrame->mRssi)); // RSSI SuccessOrExit(mEncoder.WriteInt8(-128)); // Noise Floor (Currently unused) SuccessOrExit(mEncoder.WriteUint16(0)); // Flags SuccessOrExit(mEncoder.OpenStruct()); // PHY-data SuccessOrExit(mEncoder.WriteUint8(aAckFrame->mChannel)); // Receive channel SuccessOrExit(mEncoder.WriteUint8(aAckFrame->mLqi)); // Link Quality Indicator SuccessOrExit(mEncoder.CloseStruct()); } SuccessOrExit(mEncoder.EndFrame()); } exit: OT_UNUSED_VARIABLE(aFrame); return; } void NcpBase::LinkRawEnergyScanDone(otInstance *, int8_t aEnergyScanMaxRssi) { sNcpInstance->LinkRawEnergyScanDone(aEnergyScanMaxRssi); } void NcpBase::LinkRawEnergyScanDone(int8_t aEnergyScanMaxRssi) { int8_t scanChannel = mCurScanChannel; // Clear current scan channel mCurScanChannel = kInvalidScanChannel; // Make sure we are back listening on the original receive channel, // since the energy scan could have been on a different channel. otLinkRawReceive(mInstance, &NcpBase::LinkRawReceiveDone); SuccessOrExit( mEncoder.BeginFrame( SPINEL_HEADER_FLAG | SPINEL_HEADER_IID_0, SPINEL_CMD_PROP_VALUE_IS, SPINEL_PROP_MAC_ENERGY_SCAN_RESULT )); SuccessOrExit(mEncoder.WriteUint8(static_cast<uint8_t>(scanChannel))); SuccessOrExit(mEncoder.WriteInt8(aEnergyScanMaxRssi)); SuccessOrExit(mEncoder.EndFrame()); // We are finished with the scan, so send out // a property update indicating such. SuccessOrExit( mEncoder.BeginFrame( SPINEL_HEADER_FLAG | SPINEL_HEADER_IID_0, SPINEL_CMD_PROP_VALUE_IS, SPINEL_PROP_MAC_SCAN_STATE )); SuccessOrExit(mEncoder.WriteUint8(SPINEL_SCAN_STATE_IDLE)); SuccessOrExit(mEncoder.EndFrame()); exit: return; } otError NcpBase::GetPropertyHandler_MAC_SRC_MATCH_ENABLED(void) { // TODO: Would be good to add an `otLinkRaw` API to give the the status of source match. return mEncoder.WriteBool(mSrcMatchEnabled); } otError NcpBase::SetPropertyHandler_MAC_SRC_MATCH_ENABLED(void) { otError error = OT_ERROR_NONE; SuccessOrExit(error = mDecoder.ReadBool(mSrcMatchEnabled)); error = otLinkRawSrcMatchEnable(mInstance, mSrcMatchEnabled); exit: return error; } otError NcpBase::SetPropertyHandler_MAC_SRC_MATCH_SHORT_ADDRESSES(void) { otError error = OT_ERROR_NONE; // Clear the list first SuccessOrExit(error = otLinkRawSrcMatchClearShortEntries(mInstance)); // Loop through the addresses and add them while (mDecoder.GetRemainingLengthInStruct() >= sizeof(uint16_t)) { uint16_t shortAddress; SuccessOrExit(error = mDecoder.ReadUint16(shortAddress)); SuccessOrExit(error = otLinkRawSrcMatchAddShortEntry(mInstance, shortAddress)); } exit: return error; } otError NcpBase::SetPropertyHandler_MAC_SRC_MATCH_EXTENDED_ADDRESSES(void) { otError error = OT_ERROR_NONE; // Clear the list first SuccessOrExit(error = otLinkRawSrcMatchClearExtEntries(mInstance)); // Loop through the addresses and add them while (mDecoder.GetRemainingLengthInStruct() >= sizeof(otExtAddress)) { const otExtAddress *extAddress; SuccessOrExit(error = mDecoder.ReadEui64(extAddress)); SuccessOrExit(error = otLinkRawSrcMatchAddExtEntry(mInstance, extAddress)); } exit: return error; } otError NcpBase::RemovePropertyHandler_MAC_SRC_MATCH_SHORT_ADDRESSES(void) { otError error = OT_ERROR_NONE; uint16_t shortAddress; SuccessOrExit(error = mDecoder.ReadUint16(shortAddress)); error = otLinkRawSrcMatchClearShortEntry(mInstance, shortAddress); exit: return error; } otError NcpBase::RemovePropertyHandler_MAC_SRC_MATCH_EXTENDED_ADDRESSES(void) { otError error = OT_ERROR_NONE; const otExtAddress *extAddress; SuccessOrExit(error = mDecoder.ReadEui64(extAddress));; error = otLinkRawSrcMatchClearExtEntry(mInstance, extAddress); exit: return error; } otError NcpBase::InsertPropertyHandler_MAC_SRC_MATCH_SHORT_ADDRESSES(void) { otError error = OT_ERROR_NONE; uint16_t shortAddress; SuccessOrExit(error = mDecoder.ReadUint16(shortAddress)); error = otLinkRawSrcMatchAddShortEntry(mInstance, shortAddress); exit: return error; } otError NcpBase::InsertPropertyHandler_MAC_SRC_MATCH_EXTENDED_ADDRESSES(void) { otError error = OT_ERROR_NONE; const otExtAddress *extAddress = NULL; SuccessOrExit(error = mDecoder.ReadEui64(extAddress)); error = otLinkRawSrcMatchAddExtEntry(mInstance, extAddress); exit: return error; } otError NcpBase::SetPropertyHandler_PHY_ENABLED(void) { bool value = false; otError error = OT_ERROR_NONE; SuccessOrExit(error = mDecoder.ReadBool(value)); if (value == false) { // If we have raw stream enabled stop receiving if (mIsRawStreamEnabled) { otLinkRawSleep(mInstance); } error = otLinkRawSetEnable(mInstance, false); } else { error = otLinkRawSetEnable(mInstance, true); // If we have raw stream enabled already, start receiving if (error == OT_ERROR_NONE && mIsRawStreamEnabled) { error = otLinkRawReceive(mInstance, &NcpBase::LinkRawReceiveDone); } } exit: return error; } otError NcpBase::SetPropertyHandler_MAC_15_4_SADDR(void) { uint16_t shortAddress; otError error = OT_ERROR_NONE; SuccessOrExit(error = mDecoder.ReadUint16(shortAddress)); error = otLinkSetShortAddress(mInstance, shortAddress); exit: return error; } otError NcpBase::SetPropertyHandler_STREAM_RAW(uint8_t aHeader) { const uint8_t *frameBuffer = NULL; otRadioFrame *frame; uint16_t frameLen = 0; otError error = OT_ERROR_NONE; VerifyOrExit(otLinkRawIsEnabled(mInstance), error = OT_ERROR_INVALID_STATE); frame = otLinkRawGetTransmitBuffer(mInstance); SuccessOrExit(error = mDecoder.ReadDataWithLen(frameBuffer, frameLen)); SuccessOrExit(error = mDecoder.ReadUint8(frame->mChannel)); VerifyOrExit(frameLen <= OT_RADIO_FRAME_MAX_SIZE, error = OT_ERROR_PARSE); // Cache the transaction ID for async response mCurTransmitTID = SPINEL_HEADER_GET_TID(aHeader); // Update frame buffer and length frame->mLength = static_cast<uint8_t>(frameLen); memcpy(frame->mPsdu, frameBuffer, frame->mLength); // TODO: This should be later added in the STREAM_RAW argument to allow user to directly specify it. frame->mMaxTxAttempts = OPENTHREAD_CONFIG_MAX_TX_ATTEMPTS_DIRECT; // Pass frame to the radio layer. Note, this fails if we // haven't enabled raw stream or are already transmitting. error = otLinkRawTransmit(mInstance, frame, &NcpBase::LinkRawTransmitDone); exit: if (error == OT_ERROR_NONE) { // Don't do anything here yet. We will complete the transaction when we get a transmit done callback } else { error = WriteLastStatusFrame(aHeader, ThreadErrorToSpinelStatus(error)); } return error; } } // namespace Ncp } // namespace ot #endif // OPENTHREAD_RADIO || OPENTHREAD_ENABLE_RAW_LINK_API
bsd-3-clause
meego-tablet-ux/meego-app-browser
views/test/test_views_delegate.cc
1004
// Copyright (c) 2011 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 "views/test/test_views_delegate.h" TestViewsDelegate::TestViewsDelegate() {} TestViewsDelegate::~TestViewsDelegate() {} ui::Clipboard* TestViewsDelegate::GetClipboard() const { if (!clipboard_.get()) { // Note that we need a MessageLoop for the next call to work. clipboard_.reset(new ui::Clipboard); } return clipboard_.get(); } bool TestViewsDelegate::GetSavedWindowBounds(views::Window* window, const std::wstring& window_name, gfx::Rect* bounds) const { return false; } bool TestViewsDelegate::GetSavedMaximizedState(views::Window* window, const std::wstring& window_name, bool* maximized) const { return false; }
bsd-3-clause
OrchardCMS/Brochard
src/OrchardCore/OrchardCore.Navigation.Core/NavigationManager.cs
10419
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Logging; using OrchardCore.Environment.Shell; namespace OrchardCore.Navigation { public class NavigationManager : INavigationManager { private readonly IEnumerable<INavigationProvider> _navigationProviders; private readonly ILogger _logger; protected readonly ShellSettings _shellSettings; private readonly IUrlHelperFactory _urlHelperFactory; private readonly IAuthorizationService _authorizationService; private IUrlHelper _urlHelper; public NavigationManager( IEnumerable<INavigationProvider> navigationProviders, ILogger<NavigationManager> logger, ShellSettings shellSettings, IUrlHelperFactory urlHelperFactory, IAuthorizationService authorizationService ) { _navigationProviders = navigationProviders; _logger = logger; _shellSettings = shellSettings; _urlHelperFactory = urlHelperFactory; _authorizationService = authorizationService; } public async Task<IEnumerable<MenuItem>> BuildMenuAsync(string name, ActionContext actionContext) { var builder = new NavigationBuilder(); // Processes all navigation builders to create a flat list of menu items. // If a navigation builder fails, it is ignored. foreach (var navigationProvider in _navigationProviders) { try { await navigationProvider.BuildNavigationAsync(name, builder); } catch (Exception e) { _logger.LogError(e, "An exception occurred while building the menu '{MenuName}'", name); } } var menuItems = builder.Build(); // Merge all menu hierarchies into a single one Merge(menuItems); // Remove unauthorized menu items menuItems = await AuthorizeAsync(menuItems, actionContext.HttpContext.User); // Compute Url and RouteValues properties to Href menuItems = ComputeHref(menuItems, actionContext); // Keep only menu items with an Href, or that have child items with an Href menuItems = Reduce(menuItems); return menuItems; } /// <summary> /// Mutates a list of <see cref="MenuItem"/> into a hierarchy /// </summary> private static void Merge(List<MenuItem> items) { // Use two cursors to find all similar captions. If the same caption is represented // by multiple menu item, try to merge it recursively. for (var i = 0; i < items.Count; i++) { var source = items[i]; var merged = false; for (var j = items.Count - 1; j > i; j--) { var cursor = items[j]; // A match is found, add all its items to the source if (String.Equals(cursor.Text.Name, source.Text.Name, StringComparison.OrdinalIgnoreCase)) { merged = true; foreach (var child in cursor.Items) { source.Items.Add(child); } items.RemoveAt(j); // If the item to merge is more authoritative then use its values if (cursor.Priority > source.Priority) { source.Culture = cursor.Culture; source.Href = cursor.Href; source.Id = cursor.Id; source.LinkToFirstChild = cursor.LinkToFirstChild; source.LocalNav = cursor.LocalNav; source.Position = cursor.Position; source.Resource = cursor.Resource; source.RouteValues = cursor.RouteValues; source.Text = cursor.Text; source.Url = cursor.Url; source.Permissions.Clear(); source.Permissions.AddRange(cursor.Permissions); source.Classes.Clear(); source.Classes.AddRange(cursor.Classes); } //Fallback to get the same behavior than before having the Priority var if (cursor.Priority == source.Priority) { if (cursor.Position != null && source.Position == null) { source.Culture = cursor.Culture; source.Href = cursor.Href; source.Id = cursor.Id; source.LinkToFirstChild = cursor.LinkToFirstChild; source.LocalNav = cursor.LocalNav; source.Position = cursor.Position; source.Resource = cursor.Resource; source.RouteValues = cursor.RouteValues; source.Text = cursor.Text; source.Url = cursor.Url; source.Permissions.Clear(); source.Permissions.AddRange(cursor.Permissions); source.Classes.Clear(); source.Classes.AddRange(cursor.Classes); } } } } // If some items have been merged, apply recursively if (merged) { Merge(source.Items); } } } /// <summary> /// Computes the <see cref="MenuItem.Href"/> properties based on <see cref="MenuItem.Url"/> /// and <see cref="MenuItem.RouteValues"/> values. /// </summary> private List<MenuItem> ComputeHref(List<MenuItem> menuItems, ActionContext actionContext) { foreach (var menuItem in menuItems) { menuItem.Href = GetUrl(menuItem.Url, menuItem.RouteValues, actionContext); menuItem.Items = ComputeHref(menuItem.Items, actionContext); } return menuItems; } /// <summary> /// Gets the url.from a menu item url a routeValueDictionary and an actionContext. /// </summary> /// <param name="menuItemUrl">The </param> /// <param name="routeValueDictionary"></param> /// <param name="actionContext"></param> /// <returns></returns> private string GetUrl(string menuItemUrl, RouteValueDictionary routeValueDictionary, ActionContext actionContext) { if (routeValueDictionary?.Count > 0) { if (_urlHelper == null) { _urlHelper = _urlHelperFactory.GetUrlHelper(actionContext); } return _urlHelper.RouteUrl(new UrlRouteContext { Values = routeValueDictionary }); } if (String.IsNullOrEmpty(menuItemUrl)) { return "#"; } if (menuItemUrl[0] == '/' || menuItemUrl.IndexOf("://", StringComparison.Ordinal) >= 0) { // Return the unescaped url and let the browser generate all uri components. return menuItemUrl; } if (menuItemUrl.StartsWith("~/", StringComparison.Ordinal)) { menuItemUrl = menuItemUrl.Substring(2); } // Use the unescaped 'Value' to not encode some possible reserved delimiters. return actionContext.HttpContext.Request.PathBase.Add('/' + menuItemUrl).Value; } /// <summary> /// Updates the items by checking for permissions /// </summary> private async Task<List<MenuItem>> AuthorizeAsync(IEnumerable<MenuItem> items, ClaimsPrincipal user) { var filtered = new List<MenuItem>(); foreach (var item in items) { // TODO: Attach actual user and remove this clause if (user == null) { filtered.Add(item); } else if (!item.Permissions.Any()) { filtered.Add(item); } else { foreach (var permission in item.Permissions) { if (await _authorizationService.AuthorizeAsync(user, permission, item.Resource)) { filtered.Add(item); } } } // Process child items var oldItems = item.Items; item.Items = (await AuthorizeAsync(item.Items, user)).ToList(); } return filtered; } /// <summary> /// Retains only menu items with an Href, or that have child items with an Href /// </summary> private List<MenuItem> Reduce(IEnumerable<MenuItem> items) { var filtered = items.ToList(); foreach (var item in items) { if (!HasHrefOrChildHref(item)) { filtered.Remove(item); } item.Items = Reduce(item.Items); } return filtered; } private static bool HasHrefOrChildHref(MenuItem item) { if (item.Href != "#") { return true; } return item.Items.Any(HasHrefOrChildHref); } } }
bsd-3-clause
littleflylongbow/guichan
include/guichan/widgets/dropdown.hpp
9825
/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 - 2008 Olof Naessén and Per Larsson * * * Per Larsson a.k.a finalman * Olof Naessén a.k.a jansem/yakslem * * Visit: http://guichan.sourceforge.net * * License: (BSD) * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions 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. * 3. Neither the name of Guichan nor the names of its contributors may * 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 COPYRIGHT * OWNER 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. */ #ifndef GCN_DROPDOWN_HPP #define GCN_DROPDOWN_HPP #include "guichan/actionlistener.hpp" #include "guichan/focushandler.hpp" #include "guichan/focuslistener.hpp" #include "guichan/keylistener.hpp" #include "guichan/mouselistener.hpp" #include "guichan/platform.hpp" #include "guichan/selectionlistener.hpp" #include "guichan/widget.hpp" namespace gcn { class ListBox; class ListModel; class ScrollArea; /** * An implementation of a drop downable list from which an item can be selected. * The drop down consists of an internal ScrollArea and an internal ListBox. * The drop down also uses an internal FocusHandler to handle the focus of the * internal ScollArea and the internal ListBox. The scroll area and the list box * can be passed to the drop down if a custom scroll area and or a custom list box * is preferable. * * To be able display a list the drop down uses a user provided list model. * A list model can be any class that implements the ListModel interface. * * If an item is selected in the drop down a select event will be sent to all selection * listeners of the drop down. If an item is selected by using a mouse click or by using * the enter or space key an action event will be sent to all action listeners of the * drop down. */ class GCN_CORE_DECLSPEC DropDown : public ActionListener, public KeyListener, public MouseListener, public FocusListener, public SelectionListener, public Widget { public: /** * Contructor. * * @param listModel the ListModel to use. * @param scrollArea the ScrollArea to use. * @param listBox the listBox to use. * @see ListModel, ScrollArea, ListBox. */ DropDown(ListModel *listModel = NULL, ScrollArea *scrollArea = NULL, ListBox *listBox = NULL); /** * Destructor. */ virtual ~DropDown(); /** * Gets the selected item as an index in the list model. * * @return the selected item as an index in the list model. * @see setSelected */ int getSelected() const; /** * Sets the selected item. The selected item is represented by * an index from the list model. * * @param selected the selected item as an index from the list model. * @see getSelected */ void setSelected(int selected); /** * Sets the list model to use when displaying the list. * * @param listModel the list model to use. * @see getListModel */ void setListModel(ListModel *listModel); /** * Gets the list model used. * * @return the ListModel used. * @see setListModel */ ListModel *getListModel() const; /** * Adjusts the height of the drop down to fit the height of the * drop down's parent's height. It's used to not make the drop down * draw itself outside of it's parent if folded down. */ void adjustHeight(); /** * Adds a selection listener to the drop down. When the selection * changes an event will be sent to all selection listeners of the * drop down. * * @param selectionListener the selection listener to add. * @since 0.8.0 */ void addSelectionListener(SelectionListener* selectionListener); /** * Removes a selection listener from the drop down. * * @param selectionListener the selection listener to remove. * @since 0.8.0 */ void removeSelectionListener(SelectionListener* selectionListener); // Inherited from Widget virtual void draw(Graphics* graphics); void setBaseColor(const Color& color); void setBackgroundColor(const Color& color); void setForegroundColor(const Color& color); void setFont(Font *font); void setSelectionColor(const Color& color); // Inherited from BasicContainer virtual Rectangle getChildrenArea(); // Inherited from FocusListener virtual void focusLost(const Event& event); // Inherited from ActionListener virtual void action(const ActionEvent& actionEvent); // Inherited from DeathListener virtual void death(const Event& event); // Inherited from KeyListener virtual void keyPressed(KeyEvent& keyEvent); // Inherited from MouseListener virtual void mousePressed(MouseEvent& mouseEvent); virtual void mouseReleased(MouseEvent& mouseEvent); virtual void mouseWheelMovedUp(MouseEvent& mouseEvent); virtual void mouseWheelMovedDown(MouseEvent& mouseEvent); virtual void mouseDragged(MouseEvent& mouseEvent); // Inherited from SelectionListener virtual void valueChanged(const SelectionEvent& event); protected: /** * Draws the button of the drop down. * * @param graphics a Graphics object to draw with. */ virtual void drawButton(Graphics *graphics); /** * Sets the drop down to be dropped down. */ virtual void dropDown(); /** * Sets the drop down to be folded up. */ virtual void foldUp(); /** * Distributes a value changed event to all selection listeners * of the drop down. * * @since 0.8.0 */ void distributeValueChangedEvent(); /** * True if the drop down is dropped down, false otherwise. */ bool mDroppedDown; /** * True if the drop down has been pushed with the mouse, false * otherwise. */ bool mPushed; /** * Holds what the height is if the drop down is folded up. Used when * checking if the list of the drop down was clicked or if the upper part * of the drop down was clicked on a mouse click */ int mFoldedUpHeight; /** * The scroll area used. */ ScrollArea* mScrollArea; /** * The list box used. */ ListBox* mListBox; /** * The internal focus handler used to keep track of focus for the * internal list box. */ FocusHandler mInternalFocusHandler; /** * True if an internal scroll area is used, false if a scroll area * has been passed to the drop down which the drop down should not * deleted in it's destructor. */ bool mInternalScrollArea; /** * True if an internal list box is used, false if a list box * has been passed to the drop down which the drop down should not * deleted in it's destructor. */ bool mInternalListBox; /** * True if the drop down is dragged. */ bool mIsDragged; /** * Typedef. */ typedef std::list<SelectionListener*> SelectionListenerList; /** * The selection listener's of the drop down. */ SelectionListenerList mSelectionListeners; /** * Typedef. */ typedef SelectionListenerList::iterator SelectionListenerIterator; }; } #endif // end GCN_DROPDOWN_HPP
bsd-3-clause
Cadair/ginga
ginga/tests/test_imap.py
2738
# # Unit Tests for the imap.py functions # # Rajul Srivastava (rajul09@gmail.com) # import unittest import logging import numpy as np import ginga.imap from ginga.imap import IntensityMap class TestError(Exception): pass class TestCmap(unittest.TestCase): def setUp(self): pass def test_IntensityMap_init(self): test_ilst = tuple(np.linspace(0, 1, ginga.imap.min_imap_len)) test_intensity_map = IntensityMap('test-name', test_ilst) expected = 'test-name' actual = test_intensity_map.name assert expected == actual expected = ginga.imap.min_imap_len actual = len(test_intensity_map.ilst) assert expected == actual expected = test_ilst actual = test_intensity_map.ilst assert np.allclose(expected, actual) def test_IntensityMap_init_exception(self): self.assertRaises(TypeError, IntensityMap, 'test-name') def test_imaps(self): count = 0 for attribute_name in dir(ginga.imap): if attribute_name.startswith('imap_'): count = count + 1 expected = count actual = len(ginga.imap.imaps) assert expected == actual def test_add_imap(self): test_ilst = tuple(np.linspace(0, 1, ginga.imap.min_imap_len)) ginga.imap.add_imap('test-name', test_ilst) expected = IntensityMap('test-name', test_ilst) actual = ginga.imap.imaps['test-name'] assert expected.name == actual.name assert np.allclose(expected.ilst, actual.ilst) # Teardown del ginga.imap.imaps['test-name'] def test_add_imap_exception(self): test_ilst = (0.0, 1.0) self.assertRaises( AssertionError, ginga.imap.add_imap, 'test-name', test_ilst) def test_get_imap(self): test_ilst = tuple(np.linspace(0, 1, ginga.imap.min_imap_len)) ginga.imap.add_imap('test-name', test_ilst) expected = IntensityMap('test-name', test_ilst) actual = ginga.imap.get_imap('test-name') assert expected.name == actual.name assert np.allclose(expected.ilst, actual.ilst) # Teardown del ginga.imap.imaps['test-name'] def test_get_imap_exception(self): self.assertRaises(KeyError, ginga.imap.get_imap, 'non-existent-name') def test_get_names(self): names = [] for attribute_name in dir(ginga.imap): if attribute_name.startswith('imap_'): names.append(attribute_name[5:]) expected = sorted(names) actual = ginga.imap.get_names() assert expected == actual def tearDown(self): pass if __name__ == '__main__': unittest.main() # END
bsd-3-clause
atul-bhouraskar/django
django/db/migrations/serializer.py
12965
import builtins import collections.abc import datetime import decimal import enum import functools import math import os import pathlib import re import types import uuid from django.conf import SettingsReference from django.db import models from django.db.migrations.operations.base import Operation from django.db.migrations.utils import COMPILED_REGEX_TYPE, RegexObject from django.utils.functional import LazyObject, Promise from django.utils.timezone import utc from django.utils.version import get_docs_version class BaseSerializer: def __init__(self, value): self.value = value def serialize(self): raise NotImplementedError('Subclasses of BaseSerializer must implement the serialize() method.') class BaseSequenceSerializer(BaseSerializer): def _format(self): raise NotImplementedError('Subclasses of BaseSequenceSerializer must implement the _format() method.') def serialize(self): imports = set() strings = [] for item in self.value: item_string, item_imports = serializer_factory(item).serialize() imports.update(item_imports) strings.append(item_string) value = self._format() return value % (", ".join(strings)), imports class BaseSimpleSerializer(BaseSerializer): def serialize(self): return repr(self.value), set() class ChoicesSerializer(BaseSerializer): def serialize(self): return serializer_factory(self.value.value).serialize() class DateTimeSerializer(BaseSerializer): """For datetime.*, except datetime.datetime.""" def serialize(self): return repr(self.value), {'import datetime'} class DatetimeDatetimeSerializer(BaseSerializer): """For datetime.datetime.""" def serialize(self): if self.value.tzinfo is not None and self.value.tzinfo != utc: self.value = self.value.astimezone(utc) imports = ["import datetime"] if self.value.tzinfo is not None: imports.append("from django.utils.timezone import utc") return repr(self.value).replace('<UTC>', 'utc'), set(imports) class DecimalSerializer(BaseSerializer): def serialize(self): return repr(self.value), {"from decimal import Decimal"} class DeconstructableSerializer(BaseSerializer): @staticmethod def serialize_deconstructed(path, args, kwargs): name, imports = DeconstructableSerializer._serialize_path(path) strings = [] for arg in args: arg_string, arg_imports = serializer_factory(arg).serialize() strings.append(arg_string) imports.update(arg_imports) for kw, arg in sorted(kwargs.items()): arg_string, arg_imports = serializer_factory(arg).serialize() imports.update(arg_imports) strings.append("%s=%s" % (kw, arg_string)) return "%s(%s)" % (name, ", ".join(strings)), imports @staticmethod def _serialize_path(path): module, name = path.rsplit(".", 1) if module == "django.db.models": imports = {"from django.db import models"} name = "models.%s" % name else: imports = {"import %s" % module} name = path return name, imports def serialize(self): return self.serialize_deconstructed(*self.value.deconstruct()) class DictionarySerializer(BaseSerializer): def serialize(self): imports = set() strings = [] for k, v in sorted(self.value.items()): k_string, k_imports = serializer_factory(k).serialize() v_string, v_imports = serializer_factory(v).serialize() imports.update(k_imports) imports.update(v_imports) strings.append((k_string, v_string)) return "{%s}" % (", ".join("%s: %s" % (k, v) for k, v in strings)), imports class EnumSerializer(BaseSerializer): def serialize(self): enum_class = self.value.__class__ module = enum_class.__module__ return ( '%s.%s[%r]' % (module, enum_class.__qualname__, self.value.name), {'import %s' % module}, ) class FloatSerializer(BaseSimpleSerializer): def serialize(self): if math.isnan(self.value) or math.isinf(self.value): return 'float("{}")'.format(self.value), set() return super().serialize() class FrozensetSerializer(BaseSequenceSerializer): def _format(self): return "frozenset([%s])" class FunctionTypeSerializer(BaseSerializer): def serialize(self): if getattr(self.value, "__self__", None) and isinstance(self.value.__self__, type): klass = self.value.__self__ module = klass.__module__ return "%s.%s.%s" % (module, klass.__name__, self.value.__name__), {"import %s" % module} # Further error checking if self.value.__name__ == '<lambda>': raise ValueError("Cannot serialize function: lambda") if self.value.__module__ is None: raise ValueError("Cannot serialize function %r: No module" % self.value) module_name = self.value.__module__ if '<' not in self.value.__qualname__: # Qualname can include <locals> return '%s.%s' % (module_name, self.value.__qualname__), {'import %s' % self.value.__module__} raise ValueError( 'Could not find function %s in %s.\n' % (self.value.__name__, module_name) ) class FunctoolsPartialSerializer(BaseSerializer): def serialize(self): # Serialize functools.partial() arguments func_string, func_imports = serializer_factory(self.value.func).serialize() args_string, args_imports = serializer_factory(self.value.args).serialize() keywords_string, keywords_imports = serializer_factory(self.value.keywords).serialize() # Add any imports needed by arguments imports = {'import functools', *func_imports, *args_imports, *keywords_imports} return ( 'functools.%s(%s, *%s, **%s)' % ( self.value.__class__.__name__, func_string, args_string, keywords_string, ), imports, ) class IterableSerializer(BaseSerializer): def serialize(self): imports = set() strings = [] for item in self.value: item_string, item_imports = serializer_factory(item).serialize() imports.update(item_imports) strings.append(item_string) # When len(strings)==0, the empty iterable should be serialized as # "()", not "(,)" because (,) is invalid Python syntax. value = "(%s)" if len(strings) != 1 else "(%s,)" return value % (", ".join(strings)), imports class ModelFieldSerializer(DeconstructableSerializer): def serialize(self): attr_name, path, args, kwargs = self.value.deconstruct() return self.serialize_deconstructed(path, args, kwargs) class ModelManagerSerializer(DeconstructableSerializer): def serialize(self): as_manager, manager_path, qs_path, args, kwargs = self.value.deconstruct() if as_manager: name, imports = self._serialize_path(qs_path) return "%s.as_manager()" % name, imports else: return self.serialize_deconstructed(manager_path, args, kwargs) class OperationSerializer(BaseSerializer): def serialize(self): from django.db.migrations.writer import OperationWriter string, imports = OperationWriter(self.value, indentation=0).serialize() # Nested operation, trailing comma is handled in upper OperationWriter._write() return string.rstrip(','), imports class PathLikeSerializer(BaseSerializer): def serialize(self): return repr(os.fspath(self.value)), {} class PathSerializer(BaseSerializer): def serialize(self): # Convert concrete paths to pure paths to avoid issues with migrations # generated on one platform being used on a different platform. prefix = 'Pure' if isinstance(self.value, pathlib.Path) else '' return 'pathlib.%s%r' % (prefix, self.value), {'import pathlib'} class RegexSerializer(BaseSerializer): def serialize(self): regex_pattern, pattern_imports = serializer_factory(self.value.pattern).serialize() # Turn off default implicit flags (e.g. re.U) because regexes with the # same implicit and explicit flags aren't equal. flags = self.value.flags ^ re.compile('').flags regex_flags, flag_imports = serializer_factory(flags).serialize() imports = {'import re', *pattern_imports, *flag_imports} args = [regex_pattern] if flags: args.append(regex_flags) return "re.compile(%s)" % ', '.join(args), imports class SequenceSerializer(BaseSequenceSerializer): def _format(self): return "[%s]" class SetSerializer(BaseSequenceSerializer): def _format(self): # Serialize as a set literal except when value is empty because {} # is an empty dict. return '{%s}' if self.value else 'set(%s)' class SettingsReferenceSerializer(BaseSerializer): def serialize(self): return "settings.%s" % self.value.setting_name, {"from django.conf import settings"} class TupleSerializer(BaseSequenceSerializer): def _format(self): # When len(value)==0, the empty tuple should be serialized as "()", # not "(,)" because (,) is invalid Python syntax. return "(%s)" if len(self.value) != 1 else "(%s,)" class TypeSerializer(BaseSerializer): def serialize(self): special_cases = [ (models.Model, "models.Model", ['from django.db import models']), (type(None), 'type(None)', []), ] for case, string, imports in special_cases: if case is self.value: return string, set(imports) if hasattr(self.value, "__module__"): module = self.value.__module__ if module == builtins.__name__: return self.value.__name__, set() else: return "%s.%s" % (module, self.value.__qualname__), {"import %s" % module} class UUIDSerializer(BaseSerializer): def serialize(self): return "uuid.%s" % repr(self.value), {"import uuid"} class Serializer: _registry = { # Some of these are order-dependent. frozenset: FrozensetSerializer, list: SequenceSerializer, set: SetSerializer, tuple: TupleSerializer, dict: DictionarySerializer, models.Choices: ChoicesSerializer, enum.Enum: EnumSerializer, datetime.datetime: DatetimeDatetimeSerializer, (datetime.date, datetime.timedelta, datetime.time): DateTimeSerializer, SettingsReference: SettingsReferenceSerializer, float: FloatSerializer, (bool, int, type(None), bytes, str, range): BaseSimpleSerializer, decimal.Decimal: DecimalSerializer, (functools.partial, functools.partialmethod): FunctoolsPartialSerializer, (types.FunctionType, types.BuiltinFunctionType, types.MethodType): FunctionTypeSerializer, collections.abc.Iterable: IterableSerializer, (COMPILED_REGEX_TYPE, RegexObject): RegexSerializer, uuid.UUID: UUIDSerializer, pathlib.PurePath: PathSerializer, os.PathLike: PathLikeSerializer, } @classmethod def register(cls, type_, serializer): if not issubclass(serializer, BaseSerializer): raise ValueError("'%s' must inherit from 'BaseSerializer'." % serializer.__name__) cls._registry[type_] = serializer @classmethod def unregister(cls, type_): cls._registry.pop(type_) def serializer_factory(value): if isinstance(value, Promise): value = str(value) elif isinstance(value, LazyObject): # The unwrapped value is returned as the first item of the arguments # tuple. value = value.__reduce__()[1][0] if isinstance(value, models.Field): return ModelFieldSerializer(value) if isinstance(value, models.manager.BaseManager): return ModelManagerSerializer(value) if isinstance(value, Operation): return OperationSerializer(value) if isinstance(value, type): return TypeSerializer(value) # Anything that knows how to deconstruct itself. if hasattr(value, 'deconstruct'): return DeconstructableSerializer(value) for type_, serializer_cls in Serializer._registry.items(): if isinstance(value, type_): return serializer_cls(value) raise ValueError( "Cannot serialize: %r\nThere are some values Django cannot serialize into " "migration files.\nFor more, see https://docs.djangoproject.com/en/%s/" "topics/migrations/#migration-serializing" % (value, get_docs_version()) )
bsd-3-clause
zzuegg/jmonkeyengine
jme3-vr/src/main/java/com/jme3/system/jopenvr/VR_IVRRenderModels_FnTable.java
8649
package com.jme3.system.jopenvr; import com.sun.jna.Callback; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import java.util.Arrays; import java.util.List; /** * <i>native declaration : headers\openvr_capi.h:2251</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class VR_IVRRenderModels_FnTable extends Structure { /** C type : LoadRenderModel_Async_callback* */ public VR_IVRRenderModels_FnTable.LoadRenderModel_Async_callback LoadRenderModel_Async; /** C type : FreeRenderModel_callback* */ public VR_IVRRenderModels_FnTable.FreeRenderModel_callback FreeRenderModel; /** C type : LoadTexture_Async_callback* */ public VR_IVRRenderModels_FnTable.LoadTexture_Async_callback LoadTexture_Async; /** C type : FreeTexture_callback* */ public VR_IVRRenderModels_FnTable.FreeTexture_callback FreeTexture; /** C type : LoadTextureD3D11_Async_callback* */ public VR_IVRRenderModels_FnTable.LoadTextureD3D11_Async_callback LoadTextureD3D11_Async; /** C type : LoadIntoTextureD3D11_Async_callback* */ public VR_IVRRenderModels_FnTable.LoadIntoTextureD3D11_Async_callback LoadIntoTextureD3D11_Async; /** C type : FreeTextureD3D11_callback* */ public VR_IVRRenderModels_FnTable.FreeTextureD3D11_callback FreeTextureD3D11; /** C type : GetRenderModelName_callback* */ public VR_IVRRenderModels_FnTable.GetRenderModelName_callback GetRenderModelName; /** C type : GetRenderModelCount_callback* */ public VR_IVRRenderModels_FnTable.GetRenderModelCount_callback GetRenderModelCount; /** C type : GetComponentCount_callback* */ public VR_IVRRenderModels_FnTable.GetComponentCount_callback GetComponentCount; /** C type : GetComponentName_callback* */ public VR_IVRRenderModels_FnTable.GetComponentName_callback GetComponentName; /** C type : GetComponentButtonMask_callback* */ public VR_IVRRenderModels_FnTable.GetComponentButtonMask_callback GetComponentButtonMask; /** C type : GetComponentRenderModelName_callback* */ public VR_IVRRenderModels_FnTable.GetComponentRenderModelName_callback GetComponentRenderModelName; /** C type : GetComponentStateForDevicePath_callback* */ public VR_IVRRenderModels_FnTable.GetComponentStateForDevicePath_callback GetComponentStateForDevicePath; /** C type : GetComponentState_callback* */ public VR_IVRRenderModels_FnTable.GetComponentState_callback GetComponentState; /** C type : RenderModelHasComponent_callback* */ public VR_IVRRenderModels_FnTable.RenderModelHasComponent_callback RenderModelHasComponent; /** C type : GetRenderModelThumbnailURL_callback* */ public VR_IVRRenderModels_FnTable.GetRenderModelThumbnailURL_callback GetRenderModelThumbnailURL; /** C type : GetRenderModelOriginalPath_callback* */ public VR_IVRRenderModels_FnTable.GetRenderModelOriginalPath_callback GetRenderModelOriginalPath; /** C type : GetRenderModelErrorNameFromEnum_callback* */ public VR_IVRRenderModels_FnTable.GetRenderModelErrorNameFromEnum_callback GetRenderModelErrorNameFromEnum; /** <i>native declaration : headers\openvr_capi.h:2232</i> */ public interface LoadRenderModel_Async_callback extends Callback { int apply(Pointer pchRenderModelName, PointerByReference ppRenderModel); }; /** <i>native declaration : headers\openvr_capi.h:2233</i> */ public interface FreeRenderModel_callback extends Callback { void apply(RenderModel_t pRenderModel); }; /** <i>native declaration : headers\openvr_capi.h:2234</i> */ public interface LoadTexture_Async_callback extends Callback { int apply(int textureId, PointerByReference ppTexture); }; /** <i>native declaration : headers\openvr_capi.h:2235</i> */ public interface FreeTexture_callback extends Callback { void apply(RenderModel_TextureMap_t pTexture); }; /** <i>native declaration : headers\openvr_capi.h:2236</i> */ public interface LoadTextureD3D11_Async_callback extends Callback { int apply(int textureId, Pointer pD3D11Device, PointerByReference ppD3D11Texture2D); }; /** <i>native declaration : headers\openvr_capi.h:2237</i> */ public interface LoadIntoTextureD3D11_Async_callback extends Callback { int apply(int textureId, Pointer pDstTexture); }; /** <i>native declaration : headers\openvr_capi.h:2238</i> */ public interface FreeTextureD3D11_callback extends Callback { void apply(Pointer pD3D11Texture2D); }; /** <i>native declaration : headers\openvr_capi.h:2239</i> */ public interface GetRenderModelName_callback extends Callback { int apply(int unRenderModelIndex, Pointer pchRenderModelName, int unRenderModelNameLen); }; /** <i>native declaration : headers\openvr_capi.h:2240</i> */ public interface GetRenderModelCount_callback extends Callback { int apply(); }; /** <i>native declaration : headers\openvr_capi.h:2241</i> */ public interface GetComponentCount_callback extends Callback { int apply(Pointer pchRenderModelName); }; /** <i>native declaration : headers\openvr_capi.h:2242</i> */ public interface GetComponentName_callback extends Callback { int apply(Pointer pchRenderModelName, int unComponentIndex, Pointer pchComponentName, int unComponentNameLen); }; /** <i>native declaration : headers\openvr_capi.h:2243</i> */ public interface GetComponentButtonMask_callback extends Callback { long apply(Pointer pchRenderModelName, Pointer pchComponentName); }; /** <i>native declaration : headers\openvr_capi.h:2244</i> */ public interface GetComponentRenderModelName_callback extends Callback { int apply(Pointer pchRenderModelName, Pointer pchComponentName, Pointer pchComponentRenderModelName, int unComponentRenderModelNameLen); }; /** <i>native declaration : headers\openvr_capi.h:2245</i> */ public interface GetComponentStateForDevicePath_callback extends Callback { byte apply(Pointer pchRenderModelName, Pointer pchComponentName, long devicePath, RenderModel_ControllerMode_State_t pState, RenderModel_ComponentState_t pComponentState); }; /** <i>native declaration : headers\openvr_capi.h:2246</i> */ public interface GetComponentState_callback extends Callback { byte apply(Pointer pchRenderModelName, Pointer pchComponentName, VRControllerState_t pControllerState, RenderModel_ControllerMode_State_t pState, RenderModel_ComponentState_t pComponentState); }; /** <i>native declaration : headers\openvr_capi.h:2247</i> */ public interface RenderModelHasComponent_callback extends Callback { byte apply(Pointer pchRenderModelName, Pointer pchComponentName); }; /** <i>native declaration : headers\openvr_capi.h:2248</i> */ public interface GetRenderModelThumbnailURL_callback extends Callback { int apply(Pointer pchRenderModelName, Pointer pchThumbnailURL, int unThumbnailURLLen, IntByReference peError); }; /** <i>native declaration : headers\openvr_capi.h:2249</i> */ public interface GetRenderModelOriginalPath_callback extends Callback { int apply(Pointer pchRenderModelName, Pointer pchOriginalPath, int unOriginalPathLen, IntByReference peError); }; /** <i>native declaration : headers\openvr_capi.h:2250</i> */ public interface GetRenderModelErrorNameFromEnum_callback extends Callback { Pointer apply(int error); }; public VR_IVRRenderModels_FnTable() { super(); } @Override protected List<String> getFieldOrder() { return Arrays.asList("LoadRenderModel_Async", "FreeRenderModel", "LoadTexture_Async", "FreeTexture", "LoadTextureD3D11_Async", "LoadIntoTextureD3D11_Async", "FreeTextureD3D11", "GetRenderModelName", "GetRenderModelCount", "GetComponentCount", "GetComponentName", "GetComponentButtonMask", "GetComponentRenderModelName", "GetComponentStateForDevicePath", "GetComponentState", "RenderModelHasComponent", "GetRenderModelThumbnailURL", "GetRenderModelOriginalPath", "GetRenderModelErrorNameFromEnum"); } public VR_IVRRenderModels_FnTable(Pointer peer) { super(peer); } public static class ByReference extends VR_IVRRenderModels_FnTable implements Structure.ByReference { }; public static class ByValue extends VR_IVRRenderModels_FnTable implements Structure.ByValue { }; }
bsd-3-clause
Segs/Segs
Utilities/SEGSAdmin/SyntaxHighlighter.cpp
2128
/* * SEGS - Super Entity Game Server * http://www.segs.dev/ * Copyright (c) 2006 - 2019 SEGS Team (see AUTHORS.md) * This software is licensed under the terms of the 3-clause BSD License. See LICENSE.md for details. */ /*! * @addtogroup SEGSAdmin Projects/CoX/Utilities/SEGSAdmin * @{ */ #include "SyntaxHighlighter.h" SyntaxHighlighter::SyntaxHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { HighlightingRule rule; keywordFormat.setForeground(Qt::darkCyan); keywordFormat.setFontWeight(QFont::Bold); QStringList keywordPatterns; keywordPatterns << "</[^>]+>" << "<[^>]+>"; foreach (const QString &pattern, keywordPatterns) { rule.pattern = QRegularExpression(pattern); rule.format = keywordFormat; highlightingRules.append(rule); } commentStartExpression = QRegularExpression("/\\*"); commentEndExpression = QRegularExpression("\\*/"); } void SyntaxHighlighter::highlightBlock(const QString &text) { foreach (const HighlightingRule &rule, highlightingRules) { QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text); while (matchIterator.hasNext()) { QRegularExpressionMatch match = matchIterator.next(); setFormat(match.capturedStart(), match.capturedLength(), rule.format); } } setCurrentBlockState(0); int startIndex = 0; if(previousBlockState() != 1) startIndex = text.indexOf(commentStartExpression); while (startIndex >= 0) { QRegularExpressionMatch match = commentEndExpression.match(text, startIndex); int endIndex = match.capturedStart(); int commentLength = 0; if(endIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startIndex; } else { commentLength = endIndex - startIndex + match.capturedLength(); } setFormat(startIndex, commentLength, multiLineCommentFormat); startIndex = text.indexOf(commentStartExpression, startIndex + commentLength); } } //!@}
bsd-3-clause