max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
377
/* * Licensed to the Technische Universität Darmstadt under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The Technische Universität Darmstadt * 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. * * 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 de.tudarmstadt.ukp.clarin.webanno.api.annotation.adapter; import static de.tudarmstadt.ukp.clarin.webanno.api.annotation.util.WebAnnoCasUtil.selectFsByAddr; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.TreeMap; import java.util.function.Supplier; import org.apache.uima.cas.CAS; import org.apache.uima.cas.Feature; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.fit.util.FSUtil; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationSchemaService; import de.tudarmstadt.ukp.clarin.webanno.api.annotation.event.FeatureValueUpdatedEvent; import de.tudarmstadt.ukp.clarin.webanno.api.annotation.feature.FeatureSupportRegistry; import de.tudarmstadt.ukp.clarin.webanno.api.annotation.layer.LayerSupportRegistry; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationFeature; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument; public abstract class TypeAdapter_ImplBase implements TypeAdapter { private final LayerSupportRegistry layerSupportRegistry; private final FeatureSupportRegistry featureSupportRegistry; private final AnnotationLayer layer; private final Supplier<Collection<AnnotationFeature>> featureSupplier; private Map<String, AnnotationFeature> features; private ApplicationEventPublisher applicationEventPublisher; private Map<AnnotationLayer, Object> layerTraitsCache; /** * Constructor. * * @param aLayerSupportRegistry * the layer support registry to allow e.g. convenient decoding of layer traits. * @param aFeatureSupportRegistry * the feature support registry to allow e.g. convenient generation of features or * getting/setting feature values. * @param aEventPublisher * an optional publisher for Spring events. * @param aLayer * the layer for which the adapter is created. * @param aFeatures * supplier for the features, typically * {@link AnnotationSchemaService#listAnnotationFeature(AnnotationLayer)}. Since the * features are not always needed, we use a supplied here so they can be loaded * lazily. To facilitate testing, we do not pass the entire * {@link AnnotationSchemaService}. */ public TypeAdapter_ImplBase(LayerSupportRegistry aLayerSupportRegistry, FeatureSupportRegistry aFeatureSupportRegistry, ApplicationEventPublisher aEventPublisher, AnnotationLayer aLayer, Supplier<Collection<AnnotationFeature>> aFeatures) { layerSupportRegistry = aLayerSupportRegistry; featureSupportRegistry = aFeatureSupportRegistry; applicationEventPublisher = aEventPublisher; layer = aLayer; featureSupplier = aFeatures; } @Override public AnnotationLayer getLayer() { return layer; } @Override public Collection<AnnotationFeature> listFeatures() { if (features == null) { // Using a sorted map here so we have reliable positions in the map when iterating. We // use these positions to remember the armed slots! features = new TreeMap<>(); for (AnnotationFeature f : featureSupplier.get()) { features.put(f.getName(), f); } } return features.values(); } @Override public void setFeatureValue(SourceDocument aDocument, String aUsername, CAS aCas, int aAddress, AnnotationFeature aFeature, Object aValue) { FeatureStructure fs = selectFsByAddr(aCas, aAddress); Object oldValue = getValue(fs, aFeature); featureSupportRegistry.findExtension(aFeature).orElseThrow().setFeatureValue(aCas, aFeature, aAddress, aValue); Object newValue = getValue(fs, aFeature); if (!Objects.equals(oldValue, newValue)) { publishEvent(new FeatureValueUpdatedEvent(this, aDocument, aUsername, getLayer(), fs, aFeature, newValue, oldValue)); } } private Object getValue(FeatureStructure fs, AnnotationFeature aFeature) { Feature f = fs.getType().getFeatureByBaseName(aFeature.getName()); if (f == null) { return null; } if (f.getRange().isPrimitive()) { return FSUtil.getFeature(fs, aFeature.getName(), Object.class); } if (FSUtil.isMultiValuedFeature(fs, f)) { return FSUtil.getFeature(fs, aFeature.getName(), List.class); } return FSUtil.getFeature(fs, aFeature.getName(), FeatureStructure.class); } @Override public <T> T getFeatureValue(AnnotationFeature aFeature, FeatureStructure aFs) { return (T) featureSupportRegistry.findExtension(aFeature).orElseThrow() .getFeatureValue(aFeature, aFs); } public void publishEvent(ApplicationEvent aEvent) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent(aEvent); } } @Override public void initializeLayerConfiguration(AnnotationSchemaService aSchemaService) { // Nothing to do } @Override public String getAttachFeatureName() { return getLayer().getAttachFeature() == null ? null : getLayer().getAttachFeature().getName(); } /** * A field that takes the name of the annotation to attach to, e.g. * "de.tudarmstadt...type.Token" (Token.class.getName()) */ @Override public String getAttachTypeName() { return getLayer().getAttachType() == null ? null : getLayer().getAttachType().getName(); } @Override public void silenceEvents() { applicationEventPublisher = null; } /** * Decodes the traits for the current layer and returns them if they implement the requested * interface. This method internally caches the decoded traits, so it can be called often. */ @Override @SuppressWarnings("unchecked") public <T> Optional<T> getTraits(Class<T> aInterface) { if (layerTraitsCache == null) { layerTraitsCache = new HashMap<>(); } Object trait = layerTraitsCache.computeIfAbsent(getLayer(), feature -> layerSupportRegistry.getLayerSupport(feature).readTraits(feature)); if (trait != null && aInterface.isAssignableFrom(trait.getClass())) { return Optional.of((T) trait); } return Optional.empty(); } }
2,819
1,056
<reponame>timfel/netbeans /* * 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.openide.explorer.view; import org.openide.explorer.*; import org.openide.explorer.ExplorerManager.Provider; import org.openide.nodes.Node; import org.openide.nodes.Node.Property; import java.awt.*; import java.beans.*; import java.util.logging.Logger; import javax.swing.*; import javax.swing.tree.*; /** A view displaying tree of {@link Node}s but not showing its leaf nodes. * Works well together (e.g. sharing one {@link ExplorerManager}) with {@link ListView}. * * <p> * This class is a <q>view</q> * to use it properly you need to add it into a component which implements * {@link Provider}. Good examples of that can be found * in {@link ExplorerUtils}. Then just use * {@link Provider#getExplorerManager} call to get the {@link ExplorerManager} * and control its state. * </p> * <p> * There can be multiple <q>views</q> under one container implementing {@link Provider}. Select from * range of predefined ones or write your own: * </p> * <ul> * <li>{@link org.openide.explorer.view.BeanTreeView} - shows a tree of nodes</li> * <li>{@link org.openide.explorer.view.ContextTreeView} - shows a tree of nodes without leaf nodes</li> * <li>{@link org.openide.explorer.view.ListView} - shows a list of nodes</li> * <li>{@link org.openide.explorer.view.IconView} - shows a rows of nodes with bigger icons</li> * <li>{@link org.openide.explorer.view.ChoiceView} - creates a combo box based on the explored nodes</li> * <li>{@link org.openide.explorer.view.TreeTableView} - shows tree of nodes together with a set of their {@link Property}</li> * <li>{@link org.openide.explorer.view.MenuView} - can create a {@link JMenu} structure based on structure of {@link Node}s</li> * </ul> * <p> * All of these views use {@link ExplorerManager#find} to walk up the AWT hierarchy and locate the * {@link ExplorerManager} to use as a controler. They attach as listeners to * it and also call its setter methods to update the shared state based on the * user action. Not all views make sence together, but for example * {@link org.openide.explorer.view.ContextTreeView} and {@link org.openide.explorer.view.ListView} were designed to complement * themselves and behaves like windows explorer. The {@link org.openide.explorer.propertysheet.PropertySheetView} * for example should be able to work with any other view. * </p> * * @author <NAME> */ public class ContextTreeView extends TreeView { /** generated Serialized Version UID */ static final long serialVersionUID = -8282594827988436813L; /** logger to find out why the ContextTreeView tests fail so randomly */ static final Logger LOG = Logger.getLogger(ContextTreeView.class.getName()); /** Constructor. */ public ContextTreeView() { tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); } /* @return true if this TreeView accept the selected beans. */ protected boolean selectionAccept(Node[] nodes) { if (nodes.length == 0) { return true; } Node parent = nodes[0].getParentNode(); for (int i = 1; i < nodes.length; i++) { if (nodes[i].getParentNode() != parent) { return false; } } return true; } /* Called whenever the value of the selection changes. * @param listSelectionEvent the event that characterizes the change. */ protected void selectionChanged(Node[] nodes, ExplorerManager man) throws PropertyVetoException { if (nodes.length > 0) { man.setExploredContext(nodes[0]); } man.setSelectedNodes(nodes); } /** Expand the given path and makes it visible. * @param path the path */ protected void showPath(TreePath path) { tree.makeVisible(path); Rectangle rect = tree.getPathBounds(path); if (rect != null) { rect.width += rect.x; rect.x = 0; tree.scrollRectToVisible(rect); } tree.setSelectionPath(path); } /** Shows selection to reflect the current state of the selection in the explorer. * * @param paths array of paths that should be selected */ protected void showSelection(TreePath[] paths) { if (paths.length == 0) { tree.setSelectionPaths(new TreePath[0]); } else { tree.setSelectionPath(paths[0].getParentPath()); } } /** Permit use of explored contexts. * * @return <code>true</code> always */ protected boolean useExploredContextMenu() { return true; } /** Create model. */ protected NodeTreeModel createModel() { return new NodeContextModel(); } /** Excludes leafs from the model. */ static final class NodeContextModel extends NodeTreeModel { // // Event filtering // private int[] newIndices; private Object[] newChildren; public java.lang.Object getChild(java.lang.Object parent, int index) { int superCnt = super.getChildCount(parent); int myCnt = 0; for (int i = 0; i < superCnt; i++) { Object origChild = super.getChild(parent, i); Node n = Visualizer.findNode(origChild); if (!n.isLeaf()) { if (myCnt++ == index) { return origChild; } } } return null; } public int getChildCount(java.lang.Object parent) { int superCnt = super.getChildCount(parent); int myCnt = 0; for (int i = 0; i < superCnt; i++) { Node n = Visualizer.findNode(super.getChild(parent, i)); if (!n.isLeaf()) { myCnt++; } } return myCnt; } public int getIndexOfChild(java.lang.Object parent, java.lang.Object child) { int superCnt = super.getChildCount(parent); int myCnt = 0; for (int i = 0; i < superCnt; i++) { Object origChild = super.getChild(parent, i); if (child.equals(origChild)) { return myCnt; } Node n = Visualizer.findNode(origChild); if (!n.isLeaf()) { myCnt++; } } return -1; } public boolean isLeaf(java.lang.Object node) { return false; } /** Filters given childIndices and children to contain only non-leafs * return true if there is still something changed. */ private boolean filterEvent(Object[] path, int[] childIndices, Object[] children) { if (path.length == 1 && path[0] == root && childIndices == null) { return true; } assert (childIndices != null) && (children != null) : " ch: " + children + " indices: " + childIndices; // NOI18N assert children.length == childIndices.length : "They should be the same: " + children.length + " == " + childIndices.length; // NOI18N assert newChildren == null : "Children should be cleared: " + newChildren; // NOI18N assert newIndices == null : "indices should be cleared: " + newIndices; // NOI18N assert path.length > 0 : "Path has to be greater than zero " + path.length; // NOI18N VisualizerNode parent = (VisualizerNode) path[path.length - 1]; int[] filter = new int[childIndices.length]; int accepted = 0; for (int i = 0; i < childIndices.length; i++) { VisualizerNode n = (VisualizerNode) children[i]; if (!n.isLeaf()) { filter[accepted++] = i; } } if (accepted == 0) { return false; } newIndices = new int[accepted]; newChildren = new Object[accepted]; for (int i = 0; i < accepted; i++) { newChildren[i] = children[filter[i]]; newIndices[i] = getIndexOfChild(parent, newChildren[i]); } return true; } /** Filters given childIndices and children to contain only non-leafs * return true if there is still something changed. */ private boolean removalEvent(Object[] path, int[] childIndices, Object[] children) { assert (childIndices != null) && (children != null) : " ch: " + children + " indices: " + childIndices; // NOI18N assert children.length == childIndices.length : "They should be the same: " + children.length + " == " + childIndices.length; // NOI18N assert newChildren == null : "Children should be cleared: " + newChildren; // NOI18N assert newIndices == null : "indices should be cleared: " + newIndices; // NOI18N assert path.length > 0 : "Path has to be greater than zero " + path.length; // NOI18N VisualizerNode parent = (VisualizerNode) path[path.length - 1]; int[] filter = new int[childIndices.length]; int accepted = 0; for (int i = 0; i < childIndices.length; i++) { VisualizerNode n = (VisualizerNode) children[i]; if (!n.isLeaf()) { filter[accepted++] = i; } } if (accepted == 0) { return false; } newIndices = new int[accepted]; newChildren = new Object[accepted]; int size = getChildCount(parent); int index = 0; int myPos = 0; int actualI = 0; int i = 0; for (int pos = 0; pos < accepted;) { if (childIndices[index] <= i) { VisualizerNode n = (VisualizerNode) children[index]; if (!n.isLeaf()) { newIndices[pos] = myPos++; newChildren[pos] = n; pos++; } index++; } else { VisualizerNode n = (VisualizerNode) getChild(parent, actualI++); if ((n != null) && !n.isLeaf()) { myPos++; } } i++; } return true; } /* sends childIndices and children == null, no tranformation protected void fireTreeStructureChanged (Object source, Object[] path, int[] childIndices, Object[] children) { if (!filterEvent (childIndices, children)) return; super.fireTreeStructureChanged(source, path, newIndices, newChildren); newIndices = null; newChildren = null; } */ @Override protected void fireTreeNodesRemoved(Object source, Object[] path, int[] childIndices, Object[] children) { LOG.fine("fireTreeNodesRemoved"); // NOI18N if (!removalEvent(path, childIndices, children)) { LOG.fine("fireTreeNodesRemoved - exit"); // NOI18N return; } super.fireTreeNodesRemoved(source, path, newIndices, newChildren); newIndices = null; newChildren = null; LOG.fine("fireTreeNodesRemoved - end"); // NOI18N } @Override void nodesWereInsertedInternal(final VisualizerEvent ev) { TreeNode node = ev.getVisualizer(); int[] childIndices = ev.getArray(); Object[] path = getPathToRoot(node); fireTreeNodesInserted(this, path, childIndices, NodeTreeModel.computeChildren(ev)); } @Override protected void fireTreeNodesInserted(Object source, Object[] path, int[] childIndices, Object[] children) { LOG.fine("fireTreeNodesInserted"); // NOI18N if (!filterEvent(path, childIndices, children)) { LOG.fine("fireTreeNodesInserted - exit"); // NOI18N return; } super.fireTreeNodesInserted(source, path, newIndices, newChildren); newIndices = null; newChildren = null; LOG.fine("fireTreeNodesInserted - end"); // NOI18N } @Override protected void fireTreeNodesChanged(Object source, Object[] path, int[] childIndices, Object[] children) { LOG.fine("fireTreeNodesChanged"); // NOI18N if (!filterEvent(path, childIndices, children)) { LOG.fine("fireTreeNodesChanged - exit"); // NOI18N return; } super.fireTreeNodesChanged(source, path, newIndices, newChildren); newIndices = null; newChildren = null; LOG.fine("fireTreeNodesChanged - end"); // NOI18N } } // end of NodeContextModel }
6,064
3,377
<filename>src/main/java/com/github/javafaker/Music.java<gh_stars>1000+ package com.github.javafaker; public class Music { private static final String[] KEYS = new String[] { "C", "D", "E", "F", "G", "A", "B" }; private static final String[] KEY_VARIANTS = new String[] { "b", "#", "" }; private static final String[] CHORD_TYPES = new String[] { "", "maj", "6", "maj7", "m", "m7", "-7", "7", "dom7", "dim", "dim7", "m7b5"}; private final Faker faker; protected Music(Faker faker) { this.faker = faker; } public String instrument() { return faker.resolve("music.instruments"); } public String key() { return faker.options().option(KEYS) + faker.options().option(KEY_VARIANTS); } public String chord() { return key() + faker.options().option(CHORD_TYPES); } public String genre() { return faker.resolve("music.genres"); } }
380
3,200
<filename>mindspore/lite/src/ops/populate/v0/embedding_lookup_populate_v0.cc /** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "schema/model_v0_generated.h" #include "src/ops/populate/populate_register.h" #include "nnacl/fp32/embedding_lookup_fp32.h" namespace mindspore { namespace lite { namespace { OpParameter *PopulateEmbeddingLookupParameter(const void *prim) { auto *primitive = static_cast<const schema::v0::Primitive *>(prim); MS_ASSERT(primitive != nullptr); auto embedding_lookup_prim = primitive->value_as_EmbeddingLookup(); if (embedding_lookup_prim == nullptr) { MS_LOG(ERROR) << "embedding_lookup_prim is nullptr"; return nullptr; } auto *embedding_lookup_parameter = reinterpret_cast<EmbeddingLookupParameter *>(malloc(sizeof(EmbeddingLookupParameter))); if (embedding_lookup_parameter == nullptr) { MS_LOG(ERROR) << "malloc EmbeddingLookupParameter failed."; return nullptr; } memset(embedding_lookup_parameter, 0, sizeof(EmbeddingLookupParameter)); embedding_lookup_parameter->op_parameter_.type_ = schema::PrimitiveType_EmbeddingLookupFusion; embedding_lookup_parameter->max_norm_ = embedding_lookup_prim->maxNorm(); if (embedding_lookup_parameter->max_norm_ < 0) { MS_LOG(ERROR) << "Embedding lookup max norm should be positive number, got " << embedding_lookup_parameter->max_norm_; free(embedding_lookup_parameter); return nullptr; } return reinterpret_cast<OpParameter *>(embedding_lookup_parameter); } } // namespace Registry g_embeddingLookupV0ParameterRegistry(schema::v0::PrimitiveType_EmbeddingLookup, PopulateEmbeddingLookupParameter, SCHEMA_V0); } // namespace lite } // namespace mindspore
807
2,189
#include <fc/io/sstream.hpp> #include <fc/fwd_impl.hpp> #include <fc/exception/exception.hpp> #include <fc/log/logger.hpp> #include <sstream> namespace fc { class stringstream::impl { public: impl( fc::string&s ) :ss( s ) { ss.exceptions( std::stringstream::badbit ); } impl( const fc::string&s ) :ss( s ) { ss.exceptions( std::stringstream::badbit ); } impl(){ss.exceptions( std::stringstream::badbit ); } std::stringstream ss; }; stringstream::stringstream( fc::string& s ) :my(s) { } stringstream::stringstream( const fc::string& s ) :my(s) { } stringstream::stringstream(){} stringstream::~stringstream(){} fc::string stringstream::str(){ return my->ss.str();//.c_str();//*reinterpret_cast<fc::string*>(&st); } void stringstream::str(const fc::string& s) { my->ss.str(s); } void stringstream::clear() { my->ss.clear(); } bool stringstream::eof()const { return my->ss.eof(); } size_t stringstream::writesome( const char* buf, size_t len ) { my->ss.write(buf,len); if( my->ss.eof() ) { FC_THROW_EXCEPTION( eof_exception, "stringstream" ); } return len; } size_t stringstream::writesome( const std::shared_ptr<const char>& buf, size_t len, size_t offset ) { return writesome(buf.get() + offset, len); } size_t stringstream::readsome( char* buf, size_t len ) { size_t r = static_cast<size_t>(my->ss.readsome(buf,len)); if( my->ss.eof() || r == 0 ) { FC_THROW_EXCEPTION( eof_exception, "stringstream" ); } return r; } size_t stringstream::readsome( const std::shared_ptr<char>& buf, size_t len, size_t offset ) { return readsome(buf.get() + offset, len); } void stringstream::close(){ my->ss.flush(); }; void stringstream::flush(){ my->ss.flush(); }; /* istream& stringstream::read( char* buf, size_t len ) { my->ss.read(buf,len); return *this; } istream& stringstream::read( int64_t& v ) { my->ss >> v; return *this; } istream& stringstream::read( uint64_t& v ) { my->ss >> v; return *this; } istream& stringstream::read( int32_t& v ) { my->ss >> v; return *this; } istream& stringstream::read( uint32_t& v ) { my->ss >> v; return *this; } istream& stringstream::read( int16_t& v ) { my->ss >> v; return *this; } istream& stringstream::read( uint16_t& v ) { my->ss >> v; return *this; } istream& stringstream::read( int8_t& v ) { my->ss >> v; return *this; } istream& stringstream::read( uint8_t& v ) { my->ss >> v; return *this; } istream& stringstream::read( float& v ) { my->ss >> v; return *this; } istream& stringstream::read( double& v ) { my->ss >> v; return *this; } istream& stringstream::read( bool& v ) { my->ss >> v; return *this; } istream& stringstream::read( char& v ) { my->ss >> v; return *this; } istream& stringstream::read( fc::string& v ) { my->ss >> *reinterpret_cast<std::string*>(&v); return *this; } ostream& stringstream::write( const fc::string& s) { my->ss.write( s.c_str(), s.size() ); return *this; } */ char stringstream::peek() { char c = my->ss.peek(); if( my->ss.eof() ) { FC_THROW_EXCEPTION( eof_exception, "stringstream" ); } return c; } }
1,429
852
#ifndef DATAFORMATS_HGCRECHIT_H #define DATAFORMATS_HGCRECHIT_H 1 #include "DataFormats/CaloRecHit/interface/CaloRecHit.h" #include <vector> /** \class HGCRecHit * * based on EcalRecHit * * \author <NAME> */ class HGCRecHit : public CaloRecHit { public: typedef DetId key_type; // HGCEE recHit flags enum Flags { kGood = 0, // channel ok, the energy and time measurement are reliable kPoorReco, // the energy is available from the UncalibRecHit, but approximate (bad shape, large chi2) kOutOfTime, // the energy is available from the UncalibRecHit (sync reco), but the event is out of time kFaultyHardware, // The energy is available from the UncalibRecHit, channel is faulty at some hardware level (e.g. noisy) kNoisy, // the channel is very noisy kPoorCalib, // the energy is available from the UncalibRecHit, but the calibration of the channel is poor kSaturated, // saturated channel (recovery not tried) kDead, // channel is dead and any recovery fails kKilled, // MC only flag: the channel is killed in the real detector kWeird, // the signal is believed to originate from an anomalous deposit (spike) kDiWeird, // the signal is anomalous, and neighbors another anomalous signal // kUnknown // to ease the interface with functions returning flags. }; // HGCfhe recHit flags enum HGCfheFlags { kHGCfheGood, kHGCfheDead, kHGCfheHot, kHGCfhePassBX, kHGCfheSaturated }; // HGCbhe recHit flags enum HGCbheFlags { kHGCbheGood, kHGCbheDead, kHGCbheHot, kHGCbhePassBX, kHGCbheSaturated }; // HFnose rechit flags enum HFNoseFlags { kHFNoseGood, kHFNosePoorReco, kHFNoseOutOfTime, kHFNoseFaultyHardware, kHFNoseNoisy, kHFNosePoorCalib, kHFNoseSaturated, kHFNoseDead, kHFNoseKilled, kHFNoseWeird, kHFNoseDiWeird, kHFNoseUnknown }; /** bit structure of CaloRecHit::flags_ used in EcalRecHit: * * | 32 | 31...25 | 24...12 | 11...5 | 4...1 | * | | | | | * | | | | +--> reco flags ( 4 bits) * | | | +--> chi2 for in time events ( 7 bits) * | | +--> energy for out-of-time events (13 bits) * | +--> chi2 for out-of-time events ( 7 bits) * +--> spare ( 1 bit ) */ HGCRecHit(); // by default a recHit is greated with no flag HGCRecHit(const DetId& id, float energy, float time, uint32_t flags = 0, uint32_t flagBits = 0, uint8_t son = 0, float timeError = 0.f); /// get the id // For the moment not returning a specific id for subdetector DetId id() const { return DetId(detid()); } ///// bool isRecovered() const; bool isTimeValid() const; bool isTimeErrorValid() const; float chi2() const; float outOfTimeChi2() const; float signalOverSigmaNoise() const; // set the energy for out of time events // (only energy >= 0 will be stored) float outOfTimeEnergy() const; float timeError() const; void setChi2(float chi2); void setOutOfTimeChi2(float chi2); void setOutOfTimeEnergy(float energy); void setSignalOverSigmaNoise(float sOverNoise); void setTimeError(float timeErr); /// set the flags (from Flags or ESFlags) void setFlag(int flag) { flagBits_ |= (0x1 << flag); } void unsetFlag(int flag) { flagBits_ &= ~(0x1 << flag); } /// check if the flag is true bool checkFlag(int flag) const { return flagBits_ & (0x1 << flag); } /// check if one of the flags in a set is true bool checkFlags(const std::vector<int>& flagsvec) const; //added for validation uint32_t flagBits() const { return flagBits_; } private: /// store rechit condition (see Flags enum) in a bit-wise way uint32_t flagBits_; uint8_t signalOverSigmaNoise_; float timeError_; }; std::ostream& operator<<(std::ostream& s, const HGCRecHit& hit); #endif
1,692
444
{ "name": "blockly-realtime-demo", "version": "0.0.0", "private": true, "scripts": { "audit": "npm audit fix", "update": "npm update", "build": "npm run build:frontend", "build:frontend": "rimraf ./build && webpack", "serve-http": "concurrently \"npm run serve:frontend\" \"npm run serve:backend-http\"", "serve-websocket": "concurrently \"npm run serve:frontend\" \"npm run serve:backend-websocket\"", "serve:backend-http": "node server/http_server.js", "serve:backend-websocket": "node server/websocket_server.js", "serve:frontend": "webpack-dev-server", "start": "npm run start-websocket", "start-http": "npm run build && npm run serve-http", "start-websocket": "npm run build && npm run serve-websocket", "test": "mocha test/*test.js" }, "dependencies": { "blockly": "^4.20201217.0", "socket.io": "^2.4.0", "socket.io-client": "^2.3.0", "sqlite3": "^4.1.1" }, "devDependencies": { "concurrently": "^5.1.0", "copy-webpack-plugin": "^5.1.1", "mocha": "^6.2.3", "rimraf": "^3.0.2", "sinon": "^7.5.0", "webpack": "^4.42.1", "webpack-cli": "^3.3.11", "webpack-dev-server": "^3.11.0" } }
561
575
// Copyright 2020 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 "chrome/browser/web_applications/components/web_app_uninstallation_via_os_settings_registration.h" #include "base/check.h" #include "build/build_config.h" namespace web_app { #if !defined(OS_WIN) // This block defines stub implementations of OS specific methods for // uninstallation command. Currently, only Windows has their own implementation. bool ShouldRegisterUninstallationViaOsSettingsWithOs() { return false; } void RegisterUninstallationViaOsSettingsWithOs(const AppId& app_id, const std::string& app_name, Profile* profile) { DCHECK(ShouldRegisterUninstallationViaOsSettingsWithOs()); // Stub function for OS's which don't register uninstallation command with the // OS. } void UnegisterUninstallationViaOsSettingsWithOs(const AppId& app_id, Profile* profile) { DCHECK(ShouldRegisterUninstallationViaOsSettingsWithOs()); // Stub function for OS's which don't register uninstallation command with the // OS. } #endif // !defined (OS_WIN) } // namespace web_app
477
879
<filename>utils/src/main/java/org/zstack/utils/form/FormReader.java package org.zstack.utils.form; public interface FormReader { String getType(); String[] getHeader(); /** * get next record, exclude header. * @return * NULL when form has no more records; * new String[0] if next record has no data. */ String[] nextRecord(); }
145
515
<gh_stars>100-1000 #!/usr/bin/env python3 # Copyright (c) 2020-2021, <NAME> # License: MIT License import argparse import signal import sys from ezdxf.addons.xqt import QtWidgets as qw import ezdxf from ezdxf import recover from ezdxf.addons.drawing.qtviewer import CadViewer from ezdxf.addons.drawing.config import Configuration, LinePolicy # IMPORTANT: This example is just a remaining skeleton, the implementation # details moved into module: ezdxf.addon.drawing.qtviewer # # The CAD viewer can be executed by the new ezdxf command line launcher: # C:\> ezdxf view FILE # Load and draw proxy graphic: ezdxf.options.preserve_proxy_graphics() def _main(): parser = argparse.ArgumentParser() parser.add_argument("--cad_file") parser.add_argument("--layout", default="Model") parser.add_argument( "--ltype", default="internal", choices=["internal", "ezdxf"] ) # disable lineweight at all by default: parser.add_argument("--lineweight_scaling", type=float, default=0) args = parser.parse_args() # setup drawing add-on configuration config = Configuration.defaults() config = config.with_changes( line_policy=LinePolicy.ACCURATE if args.ltype == "ezdxf" else config.line_policy, lineweight_scaling=args.lineweight_scaling, ) signal.signal(signal.SIGINT, signal.SIG_DFL) # handle Ctrl+C properly app = qw.QApplication(sys.argv) v = CadViewer(config=config) if args.cad_file is not None: try: doc, auditor = recover.readfile(args.cad_file) except IOError: print(f"Not a DXF file or a generic I/O error: {args.cad_file}") sys.exit(1) except ezdxf.DXFStructureError: print(f"Invalid or corrupted DXF file: {args.cad_file}") sys.exit(2) v.set_document(doc, auditor) try: v.draw_layout(args.layout) except KeyError: print( f'could not find layout "{args.layout}". Valid layouts: {[l.name for l in v.doc.layouts]}' ) sys.exit(3) sys.exit(app.exec()) if __name__ == "__main__": print(f"C-Extension: {ezdxf.options.use_c_ext}") _main()
940
1,867
package net.glowstone.constants; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.material.MaterialData; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; /** * Tests for {@link GlowParticle}. */ // TODO: test Particle class instead @Disabled public class ParticleTest { private static final MaterialData STONE = new MaterialData(Material.STONE, (byte) 1); public static Stream<Particle> getCases() { return Stream.of(Particle.values()); } @MethodSource("getCases") @ParameterizedTest public void testGetData(Particle particle) { /* TODO: test Particle class instead switch (particle) { case ITEM_CRACK: assertThat("Wrong data for " + particle, particle.getData() != null, is(true)); assertThat("Wrong extra data for " + particle, GlowParticle.getExtData(particle, STONE), is(new int[]{Material.STONE.getId(), 1})); break; case TILE_BREAK: assertThat("Wrong data for " + particle, particle.getData() != null, is(true)); assertThat("Wrong extra data for " + particle, GlowParticle.getExtData(particle, STONE), is(new int[]{4097})); break; case REDSTONE: assertThat("Wrong data for " + particle, particle.getData() != null, is(true)); assertThat("Wrong extra data for " + particle, GlowParticle.getExtData(particle, STONE), is(new int[]{Material.STONE.getId()})); break; default: assertThat("Wrong data for " + particle, particle.getData() != null, is(false)); assertThat("Wrong extra data for " + particle, GlowParticle.getExtData(particle, null), is(new Object[]{})); }*/ } }
909
3,336
{ "Get-AzAksUpgradeProfile+[NoContext]+Get+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/aks-test/providers/Microsoft.ContainerService/managedClusters/aks/upgradeProfiles/default?api-version=2020-09-01+1": { "Request": { "Method": "GET", "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/aks-test/providers/Microsoft.ContainerService/managedClusters/aks/upgradeProfiles/default?api-version=2020-09-01", "Content": null, "isContentBase64": false, "Headers": { "x-ms-unique-id": [ "2" ], "x-ms-client-request-id": [ "424b8ce4-d338-4b56-a425-43577bfaedda" ], "CommandName": [ "Get-AzAksUpgradeProfile" ], "FullCommandName": [ "Get-AzAksUpgradeProfile_Get" ], "ParameterSetName": [ "__AllParameterSets" ], "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], "Authorization": [ "[Filtered]" ] }, "ContentHeaders": { } }, "Response": { "StatusCode": 200, "Headers": { "Cache-Control": [ "no-cache" ], "Pragma": [ "no-cache" ], "x-ms-ratelimit-remaining-subscription-reads": [ "11998" ], "x-ms-correlation-request-id": [ "abdb517b-0d1f-4f9c-9d30-801bf5ccf653" ], "x-ms-request-id": [ "dc1c2f4d-8fb5-4493-a385-44e158d49421" ], "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], "X-Content-Type-Options": [ "nosniff" ], "Server": [ "nginx" ], "x-ms-routing-request-id": [ "SOUTHEASTASIA:20210707T064943Z:abdb517b-0d1f-4f9c-9d30-801bf5ccf653" ], "Date": [ "Wed, 07 Jul 2021 06:49:43 GMT" ] }, "ContentHeaders": { "Content-Length": [ "534" ], "Content-Type": [ "application/json" ], "Expires": [ "-1" ] }, "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/aks-test/providers/Microsoft.ContainerService/managedClusters/aks/upgradeprofiles/default\",\n \"name\": \"default\",\n \"type\": \"Microsoft.ContainerService/managedClusters/upgradeprofiles\",\n \"properties\": {\n \"controlPlaneProfile\": {\n \"kubernetesVersion\": \"1.19.11\",\n \"osType\": \"Linux\",\n \"upgrades\": [\n {\n \"kubernetesVersion\": \"1.20.5\"\n },\n {\n \"kubernetesVersion\": \"1.20.7\"\n }\n ]\n },\n \"agentPoolProfiles\": null\n }\n }", "isContentBase64": false } } }
1,189
1,428
print("Hello, pyLadies!")
10
1,001
__version__ = '3.0.30'
11
809
/** * @file * * @date 15.05.2016 * @author <NAME> */ #ifndef ES1370_H_ #define ES1370_H_ #define ES1370_REG_CONTROL 0x00 /* Interups/Chip select */ #define ES1370_REG_STATUS 0x04 #define ES1370_REG_UART_DATA 0x08 /* UART */ #define ES1370_REG_UART_STATUS 0x09 #define ES1370_REG_UART_CONTROL 0x09 #define ES1370_REG_UART_TEST 0x0a #define ES1370_REG_MEMPAGE 0x0c /* Host interface - Memory page */ #define ES1370_REG_CODEC 0x10 /* CODEC Interface*/ #define ES1370_REG_LEGACY 0x18 #define ES1370_REG_SERIAL_CONTROL 0x20 /*serial interface */ #define ES1370_REG_DAC1_SCOUNT 0x24 #define ES1370_REG_DAC2_SCOUNT 0x28 #define ES1370_REG_ADC_SCOUNT 0x2c #define ES1370_REG_MEMORY 0x30 #define ES1370_REG_ADC_BUFFER_SIZE 0x34 #define ES1370_REG_DAC1_BUFFER_SIZE 0x34 #define ES1370_REG_DAC2_BUFFER_SIZE 0X3c #define ES1370_REG_ADC_PCI_ADDRESS 0x30 #define ES1370_REG_DAC1_PCI_ADDRESS 0x30 #define ES1370_REG_DAC2_PCI_ADDRESS 0x38 #if 0 #define ES1370_REG_DAC1_FRAMEADR 0xc30 #define ES1370_REG_DAC1_FRAMECNT 0xc34 #define ES1370_REG_DAC2_FRAMEADR 0xc38 #define ES1370_REG_DAC2_FRAMECNT 0xc3c #define ES1370_REG_ADC_FRAMEADR 0xd30 #define ES1370_REG_ADC_FRAMECNT 0xd34 #define ES1370_REG_PHANTOM_FRAMEADR 0xd38 #define ES1370_REG_PHANTOM_FRAMECNT 0xd3c #endif #define ES1370_FMT_U8_MONO 0 #define ES1370_FMT_U8_STEREO 1 #define ES1370_FMT_S16_MONO 2 #define ES1370_FMT_S16_STEREO 3 #define ES1370_FMT_STEREO 1 #define ES1370_FMT_S16 2 #define ES1370_FMT_MASK 3 #define CTRL_ADC_STOP 0x80000000 /* 1 = ADC stopped */ #define CTRL_XCTL1 0x40000000 /* electret mic bias */ #define CTRL_OPEN 0x20000000 /* no function, can be read and written */ #define CTRL_PCLKDIV 0x1fff0000 /* ADC/DAC2 clock divider */ #define CTRL_SH_PCLKDIV 16 #define CTRL_MSFMTSEL 0x00008000 /* MPEG serial data fmt: 0 = Sony, 1 = I2S */ #define CTRL_M_SBB 0x00004000 /* DAC2 clock: 0 = PCLKDIV, 1 = MPEG */ #define CTRL_WTSRSEL 0x00003000 /* DAC1 clock freq: 0=5512, 1=11025, 2=22050, 3=44100 */ #define CTRL_SH_WTSRSEL 12 #define CTRL_DAC_SYNC 0x00000800 /* 1 = DAC2 runs off DAC1 clock */ #define CTRL_CCB_INTRM 0x00000400 /* 1 = CCB "voice" ints enabled */ #define CTRL_M_CB 0x00000200 /* recording source: 0 = ADC, 1 = MPEG */ #define CTRL_XCTL0 0x00000100 /* 0 = Line in, 1 = Line out */ #define CTRL_BREQ 0x00000080 /* 1 = test mode (internal mem test) */ #define CTRL_DAC1_EN 0x00000040 /* enable DAC1 */ #define CTRL_DAC2_EN 0x00000020 /* enable DAC2 */ #define CTRL_ADC_EN 0x00000010 /* enable ADC */ #define CTRL_UART_EN 0x00000008 /* enable MIDI uart */ #define CTRL_JYSTK_EN 0x00000004 /* enable Joystick port (presumably at address 0x200) */ #define CTRL_CDC_EN 0x00000002 /* enable serial (CODEC) interface */ #define CTRL_SERR_DIS 0x00000001 /* 1 = disable PCI SERR signal */ #define STAT_INTR 0x80000000 /* wired or of all interrupt bits */ #define STAT_CSTAT 0x00000400 /* 1 = codec busy or codec write in progress */ #define STAT_CBUSY 0x00000200 /* 1 = codec busy */ #define STAT_CWRIP 0x00000100 /* 1 = codec write in progress */ #define STAT_VC 0x00000060 /* CCB int source, 0=DAC1, 1=DAC2, 2=ADC, 3=undef */ #define STAT_SH_VC 5 #define STAT_MCCB 0x00000010 /* CCB int pending */ #define STAT_UART 0x00000008 /* UART int pending */ #define STAT_DAC1 0x00000004 /* DAC1 int pending */ #define STAT_DAC2 0x00000002 /* DAC2 int pending */ #define STAT_ADC 0x00000001 /* ADC int pending */ #define USTAT_RXINT 0x80 /* UART rx int pending */ #define USTAT_TXINT 0x04 /* UART tx int pending */ #define USTAT_TXRDY 0x02 /* UART tx ready */ #define USTAT_RXRDY 0x01 /* UART rx ready */ #define UCTRL_RXINTEN 0x80 /* 1 = enable RX ints */ #define UCTRL_TXINTEN 0x60 /* TX int enable field mask */ #define UCTRL_ENA_TXINT 0x20 /* enable TX int */ #define UCTRL_CNTRL 0x03 /* control field */ #define UCTRL_CNTRL_SWR 0x03 /* software reset command */ #define SCTRL_P2ENDINC 0x00380000 /* */ #define SCTRL_SH_P2ENDINC 19 #define SCTRL_P2STINC 0x00070000 /* */ #define SCTRL_SH_P2STINC 16 #define SCTRL_R1LOOPSEL 0x00008000 /* 0 = loop mode */ #define SCTRL_P2LOOPSEL 0x00004000 /* 0 = loop mode */ #define SCTRL_P1LOOPSEL 0x00002000 /* 0 = loop mode */ #define SCTRL_P2PAUSE 0x00001000 /* 1 = pause mode */ #define SCTRL_P1PAUSE 0x00000800 /* 1 = pause mode */ #define SCTRL_R1INTEN 0x00000400 /* enable interrupt */ #define SCTRL_P2INTEN 0x00000200 /* enable interrupt */ #define SCTRL_P1INTEN 0x00000100 /* enable interrupt */ #define SCTRL_P1SCTRLD 0x00000080 /* reload sample count register for DAC1 */ #define SCTRL_P2DACSEN 0x00000040 /* 1 = DAC2 play back last sample when disabled */ #define SCTRL_R1SEB 0x00000020 /* 1 = 16bit */ #define SCTRL_R1SMB 0x00000010 /* 1 = stereo */ #define SCTRL_R1FMT 0x00000030 /* format mask */ #define SCTRL_SH_R1FMT 4 #define SCTRL_P2SEB 0x00000008 /* 1 = 16bit */ #define SCTRL_P2SMB 0x00000004 /* 1 = stereo */ #define SCTRL_P2FMT 0x0000000c /* format mask */ #define SCTRL_SH_P2FMT 2 #define SCTRL_P1SEB 0x00000002 /* 1 = 16bit */ #define SCTRL_P1SMB 0x00000001 /* 1 = stereo */ #define SCTRL_P1FMT 0x00000003 /* format mask */ #define SCTRL_SH_P1FMT 0 /* for ES1370_REG_MEMPAGE */ #define ADC_MEM_PAGE 0x0d #define DAC_MEM_PAGE 0x0c /* for DAC1 and DAC2 */ /* channels or subdevices */ #define DAC1_CHAN 0 #define ADC1_CHAN 1 #define MIXER 2 #define DAC2_CHAN 3 /*max is 64k long words for es1370 = 256k bytes */ #define ES1370_MAX_BUF_LEN 0x40000 extern int es1370_update_dma(uint32_t length, int chan); extern int es1370_drv_start(int sub_dev); extern int es1370_drv_pause(int sub_dev); extern int es1370_drv_resume(int sub_dev); extern int es1370_drv_reenable_int(int sub_dev); #endif /* ES1370_H_ */
2,895
583
<filename>platforms/android/app/src/main/java/dk/area9/flowrunner/FlowMediaStreamSupport.java package dk.area9.flowrunner; import android.Manifest; import org.webrtc.AudioSource; import org.webrtc.AudioTrack; import org.webrtc.Camera1Enumerator; import org.webrtc.Camera2Enumerator; import org.webrtc.CameraEnumerator; import org.webrtc.DefaultVideoDecoderFactory; import org.webrtc.DefaultVideoEncoderFactory; import org.webrtc.EglBase; import org.webrtc.MediaConstraints; import org.webrtc.MediaStream; import org.webrtc.PeerConnectionFactory; import org.webrtc.SurfaceTextureHelper; import org.webrtc.VideoCapturer; import org.webrtc.VideoSource; import org.webrtc.VideoTrack; import java.util.HashMap; import java.util.Map; class FlowMediaStreamSupport { private static EglBase rootEglBase = EglBase.create(); private CameraEnumerator cameraEnumerator; private Map<String, String> videoDevices = new HashMap<>(); private Map<String, String> audioDevices = new HashMap<>(); private FlowRunnerActivity flowRunnerActivity; private FlowRunnerWrapper wrapper; FlowMediaStreamSupport(FlowRunnerActivity ctx, FlowRunnerWrapper wrp) { flowRunnerActivity = ctx; wrapper = wrp; PeerConnectionFactory.initialize( PeerConnectionFactory.InitializationOptions.builder(ctx) .createInitializationOptions() ); if (Utils.isCamera2Supported) { cameraEnumerator = new Camera2Enumerator(ctx); } else { cameraEnumerator = new Camera1Enumerator(false); } } void initializeDeviceInfo() { videoDevices.clear(); audioDevices.clear(); String[] cameras = cameraEnumerator.getDeviceNames(); for (String camera : cameras) { if (cameraEnumerator.isFrontFacing(camera)) { videoDevices.put(camera, "Front camera"); } else { videoDevices.put(camera, "Back camera"); } } audioDevices.put("", "Default"); } Map<String, String> getVideoDevices() { return videoDevices; } Map<String, String> getAudioDevices() { return audioDevices; } void makeMediaStream(boolean recordAudio, boolean recordVideo, String videoDeviceId, String audioDeviceId, int cbOnReadyRoot, int cbOnErrorRoot) { if (Utils.isRequestPermissionsSupported) { Utils.checkAndRequestPermissions(flowRunnerActivity, new String[]{ Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO }, -1); } final FlowMediaStreamObject mediaStreamObject = new FlowMediaStreamObject(); mediaStreamObject.isLocalStream = true; PeerConnectionFactory.Options options = new PeerConnectionFactory.Options(); DefaultVideoEncoderFactory defaultVideoEncoderFactory = new DefaultVideoEncoderFactory( rootEglBase.getEglBaseContext(), true, true); DefaultVideoDecoderFactory defaultVideoDecoderFactory = new DefaultVideoDecoderFactory(rootEglBase.getEglBaseContext()); PeerConnectionFactory peerConnectionFactory = PeerConnectionFactory.builder() .setVideoEncoderFactory(defaultVideoEncoderFactory) .setVideoDecoderFactory(defaultVideoDecoderFactory) .setOptions(options) .createPeerConnectionFactory(); MediaStream mediaStream = peerConnectionFactory.createLocalMediaStream("LocalStream"); if (recordAudio) { AudioSource audioSource = peerConnectionFactory.createAudioSource(new MediaConstraints()); AudioTrack audioTrack = peerConnectionFactory.createAudioTrack("Audio1", audioSource); mediaStream.addTrack(audioTrack); audioTrack.setEnabled(true); } if (recordVideo) { if (videoDeviceId.isEmpty()) { videoDeviceId = cameraEnumerator.getDeviceNames()[0]; } VideoCapturer videoCapturer = cameraEnumerator.createCapturer(videoDeviceId, null); VideoSource videoSource = peerConnectionFactory.createVideoSource(false); VideoTrack videoTrack = peerConnectionFactory.createVideoTrack("Video1", videoSource); mediaStream.addTrack(videoTrack); videoTrack.setEnabled(true); SurfaceTextureHelper videoSourceTextureHelper = SurfaceTextureHelper.create("VideoSourceTextureHelper", rootEglBase.getEglBaseContext()); videoCapturer.initialize(videoSourceTextureHelper, flowRunnerActivity, videoSource.getCapturerObserver()); videoCapturer.startCapture(mediaStreamObject.width, mediaStreamObject.height, mediaStreamObject.fps); mediaStreamObject.videoCapturer = videoCapturer; } mediaStreamObject.peerConnectionFactory = peerConnectionFactory; mediaStreamObject.mediaStream = mediaStream; wrapper.cbOnMediaStreamReady(cbOnReadyRoot, mediaStreamObject); } void stopMediaStream(FlowMediaStreamObject flowMediaStream) { if (flowMediaStream.mediaStream != null) { for (AudioTrack track : flowMediaStream.mediaStream.audioTracks) { flowMediaStream.mediaStream.removeTrack(track); track.dispose(); } for (VideoTrack track : flowMediaStream.mediaStream.videoTracks) { flowMediaStream.mediaStream.removeTrack(track); track.dispose(); } } if (flowMediaStream.videoCapturer != null) { flowMediaStream.videoCapturer.dispose(); } } static EglBase getRootEglBase(){ return rootEglBase; } static class FlowMediaStreamObject { PeerConnectionFactory peerConnectionFactory; MediaStream mediaStream; boolean isCameraFrontFacing; VideoCapturer videoCapturer; boolean isLocalStream; int width = 800; int height = 600; int fps = 20; FlowMediaStreamObject() { } } }
2,416
1,615
/** * Created by MomoLuaNative. * Copyright (c) 2019, Momo Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.immomo.mls.weight.load; import androidx.annotation.NonNull; import android.view.View; /** * Created by XiongFangyu on 2018/6/21. */ public interface ILoadWithTextView extends ILoadView { /** * 设置加载时的文字 * @param text */ void setLoadText(CharSequence text); /** * 获取view * @return */ @NonNull View getView(); }
243
634
<reponame>halotroop2288/consulo<gh_stars>100-1000 /* * 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.completion; import com.intellij.openapi.project.Project; import consulo.util.dataholder.Key; import consulo.util.dataholder.UserDataHolder; import com.intellij.util.ProcessingContext; import javax.annotation.Nonnull; /** * @author peter */ public class CompletionLocation implements UserDataHolder { private final CompletionParameters myCompletionParameters; private final ProcessingContext myProcessingContext = new ProcessingContext(); public CompletionLocation(final CompletionParameters completionParameters) { myCompletionParameters = completionParameters; } public CompletionParameters getCompletionParameters() { return myCompletionParameters; } public CompletionType getCompletionType() { return myCompletionParameters.getCompletionType(); } public Project getProject() { return myCompletionParameters.getPosition().getProject(); } public ProcessingContext getProcessingContext() { return myProcessingContext; } @Override public <T> T getUserData(@Nonnull Key<T> key) { return myProcessingContext.get(key); } @Override public <T> void putUserData(@Nonnull Key<T> key, @javax.annotation.Nullable T value) { myProcessingContext.put(key, value); } }
552
34,359
<filename>thirdparty/boost/include/boost/move/algorithm.hpp ////////////////////////////////////////////////////////////////////////////// // // (C) Copyright <NAME> 2012-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/move for documentation. // ////////////////////////////////////////////////////////////////////////////// //! \file #ifndef BOOST_MOVE_ALGORITHM_HPP #define BOOST_MOVE_ALGORITHM_HPP #ifndef BOOST_CONFIG_HPP # include <boost/config.hpp> #endif # #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif #include <boost/move/detail/config_begin.hpp> #include <boost/move/utility_core.hpp> #include <boost/move/iterator.hpp> #include <boost/move/algo/move.hpp> #include <boost/core/no_exceptions_support.hpp> #include <algorithm> //copy, copy_backward #include <memory> //uninitialized_copy namespace boost { ////////////////////////////////////////////////////////////////////////////// // // uninitialized_copy_or_move // ////////////////////////////////////////////////////////////////////////////// namespace move_detail { template <typename I, // I models InputIterator typename F> // F models ForwardIterator inline F uninitialized_move_move_iterator(I f, I l, F r // ,typename ::boost::move_detail::enable_if< has_move_emulation_enabled<typename I::value_type> >::type* = 0 ) { return ::boost::uninitialized_move(f, l, r); } /* template <typename I, // I models InputIterator typename F> // F models ForwardIterator F uninitialized_move_move_iterator(I f, I l, F r, typename ::boost::move_detail::disable_if< has_move_emulation_enabled<typename I::value_type> >::type* = 0) { return std::uninitialized_copy(f.base(), l.base(), r); } */ } //namespace move_detail { template <typename I, // I models InputIterator typename F> // F models ForwardIterator inline F uninitialized_copy_or_move(I f, I l, F r, typename ::boost::move_detail::enable_if< move_detail::is_move_iterator<I> >::type* = 0) { return ::boost::move_detail::uninitialized_move_move_iterator(f, l, r); } ////////////////////////////////////////////////////////////////////////////// // // copy_or_move // ////////////////////////////////////////////////////////////////////////////// namespace move_detail { template <typename I, // I models InputIterator typename F> // F models ForwardIterator inline F move_move_iterator(I f, I l, F r // ,typename ::boost::move_detail::enable_if< has_move_emulation_enabled<typename I::value_type> >::type* = 0 ) { return ::boost::move(f, l, r); } /* template <typename I, // I models InputIterator typename F> // F models ForwardIterator F move_move_iterator(I f, I l, F r, typename ::boost::move_detail::disable_if< has_move_emulation_enabled<typename I::value_type> >::type* = 0) { return std::copy(f.base(), l.base(), r); } */ } //namespace move_detail { template <typename I, // I models InputIterator typename F> // F models ForwardIterator inline F copy_or_move(I f, I l, F r, typename ::boost::move_detail::enable_if< move_detail::is_move_iterator<I> >::type* = 0) { return ::boost::move_detail::move_move_iterator(f, l, r); } /// @endcond //! <b>Effects</b>: //! \code //! for (; first != last; ++result, ++first) //! new (static_cast<void*>(&*result)) //! typename iterator_traits<ForwardIterator>::value_type(*first); //! \endcode //! //! <b>Returns</b>: result //! //! <b>Note</b>: This function is provided because //! <i>std::uninitialized_copy</i> from some STL implementations //! is not compatible with <i>move_iterator</i> template <typename I, // I models InputIterator typename F> // F models ForwardIterator inline F uninitialized_copy_or_move(I f, I l, F r /// @cond ,typename ::boost::move_detail::disable_if< move_detail::is_move_iterator<I> >::type* = 0 /// @endcond ) { return std::uninitialized_copy(f, l, r); } //! <b>Effects</b>: //! \code //! for (; first != last; ++result, ++first) //! *result = *first; //! \endcode //! //! <b>Returns</b>: result //! //! <b>Note</b>: This function is provided because //! <i>std::uninitialized_copy</i> from some STL implementations //! is not compatible with <i>move_iterator</i> template <typename I, // I models InputIterator typename F> // F models ForwardIterator inline F copy_or_move(I f, I l, F r /// @cond ,typename ::boost::move_detail::disable_if< move_detail::is_move_iterator<I> >::type* = 0 /// @endcond ) { return std::copy(f, l, r); } } //namespace boost { #include <boost/move/detail/config_end.hpp> #endif //#ifndef BOOST_MOVE_ALGORITHM_HPP
1,931
775
<gh_stars>100-1000 #pragma once #include <windows.h> #include <stdio.h> #include "ntdll_undoc.h" #include "createproc.h" #include "relocate.h" #include "pe_raw_to_virtual.h" /* runPE32: targetPath - application where we want to inject payload - buffer with raw image of PE that we want to inject payload_size - size of the above desiredBase - address where we want to map the payload in the target memory; NULL if we don't care. This address will be ignored if the payload has no relocations table, because then it must be mapped to it's original ImageBase. unmap_target - do we want to unmap the target? (we are not forced to do it if it doesn't disturb our chosen base) */ bool runPE32(LPWSTR targetPath, BYTE* payload, SIZE_T payload_size, ULONGLONG desiredBase = NULL, bool unmap_target = false) { if (!load_ntdll_functions()) return false; //check payload: IMAGE_NT_HEADERS32* payload_nt_hdr32 = get_nt_hrds32(payload); if (payload_nt_hdr32 == NULL) { printf("Invalid payload: %p\n", payload); return false; } const ULONGLONG oldImageBase = payload_nt_hdr32->OptionalHeader.ImageBase; SIZE_T payloadImageSize = payload_nt_hdr32->OptionalHeader.SizeOfImage; //set subsystem always to GUI to avoid crashes: payload_nt_hdr32->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI; //create target process: PROCESS_INFORMATION pi; if (!create_new_process1(targetPath, pi)) return false; printf("PID: %d\n", pi.dwProcessId); //get initial context of the target: #if defined(_WIN64) WOW64_CONTEXT context; memset(&context, 0, sizeof(WOW64_CONTEXT)); context.ContextFlags = CONTEXT_INTEGER; Wow64GetThreadContext(pi.hThread, &context); #else CONTEXT context; memset(&context, 0, sizeof(CONTEXT)); context.ContextFlags = CONTEXT_INTEGER; GetThreadContext(pi.hThread, &context); #endif //get image base of the target: DWORD PEB_addr = context.Ebx; printf("PEB = %x\n", PEB_addr); DWORD targetImageBase = 0; //for 32 bit if (!ReadProcessMemory(pi.hProcess, LPVOID(PEB_addr + 8), &targetImageBase, sizeof(DWORD), NULL)) { printf("[ERROR] Cannot read from PEB - incompatibile target!\n"); return false; } if (targetImageBase == NULL) { return false; } printf("targetImageBase = %x\n", targetImageBase); if (has_relocations(payload) == false) { //payload have no relocations, so we are bound to use it's original image base desiredBase = payload_nt_hdr32->OptionalHeader.ImageBase; } if (unmap_target || (ULONGLONG)targetImageBase == desiredBase) { //unmap the target: if (_NtUnmapViewOfSection(pi.hProcess, (PVOID)targetImageBase) != ERROR_SUCCESS) { printf("Unmapping the target failed!\n"); return false; } } //try to allocate space that will be the most suitable for the payload: LPVOID remoteAddress = VirtualAllocEx(pi.hProcess, (LPVOID)desiredBase, payloadImageSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (remoteAddress == NULL) { printf("Could not allocate memory in the remote process\n"); return false; } printf("Allocated remote ImageBase: %p size: %lx\n", remoteAddress, static_cast<ULONG>(payloadImageSize)); //change the image base saved in headers - this is very important for loading imports: payload_nt_hdr32->OptionalHeader.ImageBase = static_cast<DWORD>((ULONGLONG)remoteAddress); //first we will prepare the payload image in the local memory, so that it will be easier to edit it, apply relocations etc. //when it will be ready, we will copy it into the space reserved in the target process LPVOID localCopyAddress = VirtualAlloc(NULL, payloadImageSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);; if (localCopyAddress == NULL) { printf("Could not allocate memory in the current process\n"); return false; } printf("Allocated local memory: %p size: %lx\n", localCopyAddress, static_cast<ULONG>(payloadImageSize)); if (!copy_pe_to_virtual_l(payload, payload_size, localCopyAddress)) { printf("Could not copy PE file\n"); return false; } //if the base address of the payload changed, we need to apply relocations: if ((ULONGLONG)remoteAddress != oldImageBase) { if (apply_relocations((ULONGLONG)remoteAddress, oldImageBase, localCopyAddress) == false) { printf("[ERROR] Could not relocate image!\n"); return false; } } SIZE_T written = 0; // paste the local copy of the prepared image into the reserved space inside the remote process: if (!WriteProcessMemory(pi.hProcess, remoteAddress, localCopyAddress, payloadImageSize, &written) || written != payloadImageSize) { printf("[ERROR] Could not paste the image into remote process!\n"); return false; } //free the localy allocated copy VirtualFree(localCopyAddress, payloadImageSize, MEM_FREE); //overwrite ImageBase stored in PEB DWORD remoteAddr32b = static_cast<DWORD>((ULONGLONG)remoteAddress); if (!WriteProcessMemory(pi.hProcess, LPVOID(PEB_addr + 8), &remoteAddr32b, sizeof(DWORD), &written) || written != sizeof(DWORD)) { printf("Failed overwriting PEB: %d\n", static_cast<int>(written)); return false; } //overwrite context: set new Entry Point DWORD newEP = static_cast<DWORD>((ULONGLONG)remoteAddress + payload_nt_hdr32->OptionalHeader.AddressOfEntryPoint); printf("newEP: %x\n", newEP); context.Eax = newEP; #if defined(_WIN64) Wow64SetThreadContext(pi.hThread, &context); #else SetThreadContext(pi.hThread, &context); #endif //start the injected: printf("--\n"); ResumeThread(pi.hThread); //free the handles CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return true; }
2,185
2,990
/* * GDevelop JS Platform * Copyright 2008-2016 <NAME> (<EMAIL>). All rights * reserved. This project is released under the MIT License. */ #ifndef FILEEXTENSION_H #define FILEEXTENSION_H #include "GDCore/Extensions/PlatformExtension.h" namespace gdjs { /** * \brief Built-in extension providing functions for storing data. * * \ingroup BuiltinExtensions */ class FileExtension : public gd::PlatformExtension { public: FileExtension(); virtual ~FileExtension(){}; }; } // namespace gdjs #endif // FILEEXTENSION_H
169
787
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ <NAME> * * 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. * * Author: * <NAME> (<EMAIL>) */ package io.jenetics.prog.op; import static java.lang.Math.asin; import static java.lang.Math.ceil; import static java.lang.Math.cos; import static java.lang.Math.cosh; import static java.lang.Math.floor; import static java.lang.Math.hypot; import static java.lang.Math.log; import static java.lang.Math.rint; import static java.lang.Math.signum; import static java.lang.Math.sinh; import static java.lang.Math.sqrt; import static java.lang.Math.tan; import java.util.Random; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; /** * @author <a href="mailto:<EMAIL>"><NAME></a> */ @Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) @Fork(value = 3) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @State(Scope.Benchmark) public class MathExprPerf { private static final MathExpr MATH_EXPR = MathExpr.parse( "cos(signum(tan(sqrt(asin(rint(sinh(log(floor(log(hypot(cosh(sinh(log(y)%" + "hypot(y, 1.0))), signum(tan(ceil(ceil(y)))))))))))))))" ); private static double expr(final double x, final double y) { return cos(signum(tan(sqrt(asin(rint(sinh(log(floor(log(hypot(cosh(sinh(log(y)% hypot(y, 1.0))), signum(tan(ceil(ceil(y))))))))))))))); } double x; double y; @Setup public void setup() { final Random random = new Random(); x = random.nextDouble()*10; y = random.nextDouble(); } @Benchmark public double mathExpr() { return MATH_EXPR.eval(x, y); } @Benchmark public double exprSin() { return MathOp.SIN.eval(x); } @Benchmark public double sin() { return Math.sin(x); } @Benchmark public double javaExpr() { return expr(x, y); } } /* Benchmark Mode Cnt Score Error Units MathExprPerf.javaExpr avgt 15 230.869 ± 6.066 ns/op MathExprPerf.mathExpr avgt 15 2434.524 ± 57.198 ns/op */ /* Benchmark Mode Cnt Score Error Units MathExprPerf.exprSin avgt 15 73.456 ± 3.725 ns/op MathExprPerf.javaExpr avgt 15 246.253 ± 3.908 ns/op MathExprPerf.mathExpr avgt 15 1237.706 ± 55.264 ns/op MathExprPerf.sin avgt 15 14.984 ± 0.146 ns/op */
1,296
777
// Copyright 2016 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. #ifndef IOS_WEB_PUBLIC_TEST_EARL_GREY_JS_TEST_UTIL_H_ #define IOS_WEB_PUBLIC_TEST_EARL_GREY_JS_TEST_UTIL_H_ #import <Foundation/Foundation.h> #import "ios/web/public/web_state/web_state.h" namespace web { // Waits until the Window ID has been injected and the page is thus ready to // respond to JavaScript injection. Fails with a GREYAssert on timeout or if // unrecoverable error (such as no web view) occurs. void WaitUntilWindowIdInjected(WebState* web_state); // Executes |javascript| on the given |web_state|, and waits until execution is // completed. If |out_error| is not nil, it is set to the error resulting from // the execution, if one occurs. The return value is the result of the // JavaScript execution. If the script execution is timed out, then this method // fails with a GREYAssert. id ExecuteJavaScript(WebState* web_state, NSString* javascript, NSError** out_error); // Synchronously returns the result of executed JavaScript on interstitial page // displayed for |web_state|. id ExecuteScriptOnInterstitial(WebState* web_state, NSString* script); } // namespace web #endif // IOS_WEB_PUBLIC_TEST_EARL_GREY_JS_TEST_UTIL_H_
459
852
// L1Offset jet corrector class. Inherits from JetCorrector.h #ifndef L1OffsetCorrector_h #define L1OffsetCorrector_h #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "JetMETCorrections/Objects/interface/JetCorrector.h" #include "CondFormats/JetMETObjects/interface/FactorizedJetCorrectorCalculator.h" #include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h" //----- classes declaration ----------------------------------- namespace edm { class ParameterSet; } class FactorizedJetCorrectorCalculator; //----- LXXXCorrector interface ------------------------------- class L1OffsetCorrector : public JetCorrector { public: //----- constructors--------------------------------------- L1OffsetCorrector(const JetCorrectorParameters& fConfig, const edm::ParameterSet& fParameters); //----- destructor ---------------------------------------- ~L1OffsetCorrector() override; //----- apply correction using Jet information only ------- double correction(const LorentzVector& fJet) const override; //----- apply correction using Jet information only ------- double correction(const reco::Jet& fJet) const override; //----- apply correction using all event information double correction(const reco::Jet& fJet, const edm::Event& fEvent, const edm::EventSetup& fSetup) const override; //----- if correction needs event information ------------- bool eventRequired() const override { return true; } //----- if correction needs a jet reference ------------- bool refRequired() const override { return false; } private: //----- member data --------------------------------------- std::string mVertexCollName; int mMinVtxNdof; FactorizedJetCorrectorCalculator* mCorrector; }; #endif
446
852
<reponame>ckamtsikis/cmssw class filereader: def __init__(self): self.aList=['Module', 'ESSource'] def startswith(self,line): "Checks if the first word of the line starts with any of the aList elements" for item in self.aList: if line.startswith(item): return True return False def readfile(self,nomefile): "Reads the file line by line and searches for the begin and the end of each Module block" aFile = open(nomefile) module = [] source = [] file_modules = {} insideModuleBlock = False insideParameterBlock = False for line in aFile.readlines(): if self.startswith(line): if insideParameterBlock: file_modules[key]=module insideParameterBlock = False #print line[:-1] module=[] module.append(line[:-1]) key=line[line.index(':')+2:-1] #print key insideModuleBlock = True insideParameterBlock = False elif (line.startswith(' parameters')) and insideModuleBlock: insideParameterBlock = True module.append(line[:-1]) #print line[:-1] elif line.startswith('ESModule') and insideParameterBlock: file_modules[key]=module insideParameterBlock = False insideModuleBlock = False elif (insideParameterBlock): module.append(line[:-1]) #print line[:-1] return file_modules
843
503
package utils; import java.io.*; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; /** * ZipUtil * * Intended to compress string contents */ public class ZipUtil { public static byte[] compress(String text) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { OutputStream out = new DeflaterOutputStream(baos); out.write(text.getBytes("UTF-8")); out.close(); } catch (IOException e) { throw new AssertionError(e); } return baos.toByteArray(); } public static String decompress(byte[] bytes) { InputStream in = new InflaterInputStream(new ByteArrayInputStream(bytes)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { byte[] buffer = new byte[8192]; int len; while((len = in.read(buffer))>0) baos.write(buffer, 0, len); return new String(baos.toByteArray(), "UTF-8"); } catch (IOException e) { throw new AssertionError(e); } } }
489
617
<reponame>jbdelcuv/openenclave // Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #define MEM_MIN_CAP 1 #include <openenclave/internal/mem.h> #include <openenclave/internal/tests.h> #include <stdio.h> void TestMem(mem_t* m) { OE_TEST(mem_cpy(m, "hijk", 4) == 0); OE_TEST(mem_size(m) == 4); OE_TEST(mem_cap(m) >= 4); OE_TEST(memcmp(mem_ptr(m), "hijk", 4) == 0); OE_TEST(mem_append(m, "lmnop", 5) == 0); OE_TEST(mem_size(m) == 9); OE_TEST(mem_cap(m) >= 9); OE_TEST(memcmp(mem_ptr(m), "hijklmnop", 9) == 0); OE_TEST(mem_insert(m, 0, "abcdefg", 7) == 0); OE_TEST(mem_size(m) == 16); OE_TEST(mem_cap(m) >= 16); OE_TEST(memcmp(mem_ptr(m), "abcdefghijklmnop", 16) == 0); OE_TEST(mem_append(m, "qrstuv", 6) == 0); OE_TEST(mem_size(m) == 22); OE_TEST(mem_cap(m) >= 22); OE_TEST(memcmp(mem_ptr(m), "abcdefghijklmnopqrstuv", 22) == 0); OE_TEST(mem_append(m, "wxyz", 4) == 0); OE_TEST(mem_size(m) == 26); OE_TEST(mem_cap(m) >= 26); OE_TEST(memcmp(mem_ptr(m), "abcdefghijklmnopqrstuvwxyz", 26) == 0); OE_TEST(mem_remove(m, 22, 4) == 0); OE_TEST(mem_size(m) == 22); OE_TEST(mem_cap(m) >= 22); OE_TEST(memcmp(mem_ptr(m), "abcdefghijklmnopqrstuv", 22) == 0); OE_TEST(mem_append(m, "wxyz", 4) == 0); OE_TEST(mem_size(m) == 26); OE_TEST(mem_cap(m) >= 26); OE_TEST(memcmp(mem_ptr(m), "abcdefghijklmnopqrstuvwxyz", 26) == 0); OE_TEST(mem_remove(m, 0, 7) == 0); OE_TEST(mem_size(m) == 19); OE_TEST(mem_cap(m) >= 19); OE_TEST(memcmp(mem_ptr(m), "hijklmnopqrstuvwxyz", 19) == 0); OE_TEST(mem_prepend(m, "abcdefg", 7) == 0); OE_TEST(mem_size(m) == 26); OE_TEST(mem_cap(m) >= 26); OE_TEST(memcmp(mem_ptr(m), "abcdefghijklmnopqrstuvwxyz", 26) == 0); OE_TEST(mem_prepend(m, NULL, 1) == 0); OE_TEST(mem_size(m) == 27); OE_TEST(mem_cap(m) >= 27); OE_TEST(memcmp(mem_ptr(m), "\0abcdefghijklmnopqrstuvwxyz", 27) == 0); OE_TEST(mem_append(m, NULL, 1) == 0); OE_TEST(mem_size(m) == 28); OE_TEST(mem_cap(m) >= 28); OE_TEST(memcmp(mem_ptr(m), "\0abcdefghijklmnopqrstuvwxyz\0", 28) == 0); OE_TEST(mem_remove(m, 0, 1) == 0); OE_TEST(mem_remove(m, mem_size(m) - 1, 1) == 0); OE_TEST(memcmp(mem_ptr(m), "abcdefghijklmnopqrstuvwxyz", 26) == 0); OE_TEST(mem_resize(m, 7) == 0); OE_TEST(mem_size(m) == 7); OE_TEST(mem_cap(m) >= 7); OE_TEST(memcmp(mem_ptr(m), "abcdefg", 7) == 0); OE_TEST(mem_append(m, NULL, 1) == 0); OE_TEST(mem_size(m) == 8); OE_TEST(memcmp(mem_ptr(m), "abcdefg\0", 8) == 0); printf("=== passed TestMem()\n"); } int main() { /* TestMem dynamic */ { mem_t m; OE_TEST(mem_dynamic(&m, NULL, 0, 0) == 0); OE_TEST(mem_type(&m) == MEM_TYPE_DYNAMIC); TestMem(&m); mem_free(&m); } /* TestMem static */ { unsigned char buf[32]; mem_t m; OE_TEST(mem_static(&m, buf, sizeof(buf)) == 0); OE_TEST(mem_type(&m) == MEM_TYPE_STATIC); TestMem(&m); } /* TestMem dynamic initializer expression */ { mem_t m = MEM_DYNAMIC_INIT; OE_TEST(mem_type(&m) == MEM_TYPE_DYNAMIC); TestMem(&m); mem_free(&m); } printf("=== passed all tests (mem)\n"); return 0; }
1,840
575
// Copyright 2020 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 "components/viz/service/display/overlay_processor_ozone.h" #include "components/viz/test/test_context_provider.h" #include "gpu/command_buffer/client/shared_image_interface.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/linux/native_pixmap_dmabuf.h" #include "ui/gfx/native_pixmap.h" #include "ui/gfx/native_pixmap_handle.h" using ::testing::_; using ::testing::Return; namespace viz { namespace { class FakeOverlayCandidatesOzone : public ui::OverlayCandidatesOzone { public: ~FakeOverlayCandidatesOzone() override = default; // We don't really care about OverlayCandidatesOzone internals, but we do need // to detect if the OverlayProcessor skipped a candidate. In that case, // ui::OverlaySurfaceCandidate would be default constructed (except for the Z // order). Therefore, we use the buffer size of the candidate to decide // whether to mark the candidate as handled. void CheckOverlaySupport( std::vector<ui::OverlaySurfaceCandidate>* candidates) override { for (auto& candidate : *candidates) { candidate.overlay_handled = !candidate.buffer_size.IsEmpty(); } } }; class FakeNativePixmap : public gfx::NativePixmap { public: FakeNativePixmap(gfx::Size size, gfx::BufferFormat format) : size_(size), format_(format) {} bool AreDmaBufFdsValid() const override { return false; } int GetDmaBufFd(size_t plane) const override { return -1; } uint32_t GetDmaBufPitch(size_t plane) const override { return 0; } size_t GetDmaBufOffset(size_t plane) const override { return 0; } size_t GetDmaBufPlaneSize(size_t plane) const override { return 0; } uint64_t GetBufferFormatModifier() const override { return 0; } gfx::BufferFormat GetBufferFormat() const override { return format_; } size_t GetNumberOfPlanes() const override { return 0; } gfx::Size GetBufferSize() const override { return size_; } uint32_t GetUniqueId() const override { return 0; } bool ScheduleOverlayPlane( gfx::AcceleratedWidget widget, int plane_z_order, gfx::OverlayTransform plane_transform, const gfx::Rect& display_bounds, const gfx::RectF& crop_rect, bool enable_blend, std::vector<gfx::GpuFence> acquire_fences, std::vector<gfx::GpuFence> release_fences) override { return false; } gfx::NativePixmapHandle ExportHandle() override { return gfx::NativePixmapHandle(); } private: ~FakeNativePixmap() override = default; gfx::Size size_; gfx::BufferFormat format_; }; class MockSharedImageInterface : public TestSharedImageInterface { public: MOCK_METHOD1(GetNativePixmap, scoped_refptr<gfx::NativePixmap>(const gpu::Mailbox& mailbox)); }; } // namespace // TODO(crbug.com/1138568): Fuchsia claims support for presenting primary // plane as overlay, but does not provide a mailbox. Handle this case. #if !defined(OS_FUCHSIA) TEST(OverlayProcessorOzoneTest, PrimaryPlaneSizeAndFormatMatches) { // Set up the primary plane. gfx::Size size(128, 128); OverlayProcessorInterface::OutputSurfaceOverlayPlane primary_plane; primary_plane.resource_size = size; primary_plane.format = gfx::BufferFormat::BGRA_8888; primary_plane.mailbox = gpu::Mailbox::GenerateForSharedImage(); // Set up a dummy OverlayCandidate. OverlayCandidate candidate; candidate.resource_size_in_pixels = size; candidate.format = gfx::BufferFormat::BGRA_8888; candidate.mailbox = gpu::Mailbox::GenerateForSharedImage(); candidate.overlay_handled = false; OverlayCandidateList candidates; candidates.push_back(candidate); // Initialize a MockSharedImageInterface that returns a NativePixmap with // matching params to the primary plane. std::unique_ptr<MockSharedImageInterface> sii = std::make_unique<MockSharedImageInterface>(); scoped_refptr<gfx::NativePixmap> primary_plane_pixmap = base::MakeRefCounted<FakeNativePixmap>(size, gfx::BufferFormat::BGRA_8888); scoped_refptr<gfx::NativePixmap> candidate_pixmap = base::MakeRefCounted<FakeNativePixmap>(size, gfx::BufferFormat::BGRA_8888); EXPECT_CALL(*sii, GetNativePixmap(_)) .WillOnce(Return(primary_plane_pixmap)) .WillOnce(Return(candidate_pixmap)); OverlayProcessorOzone processor( std::make_unique<FakeOverlayCandidatesOzone>(), {}, sii.get()); processor.CheckOverlaySupport(&primary_plane, &candidates); // Since the |OutputSurfaceOverlayPlane|'s size and format match those of // primary plane's NativePixmap, the overlay candidate is promoted. EXPECT_TRUE(candidates.at(0).overlay_handled); } TEST(OverlayProcessorOzoneTest, PrimaryPlaneFormatMismatch) { // Set up the primary plane. gfx::Size size(128, 128); OverlayProcessorInterface::OutputSurfaceOverlayPlane primary_plane; primary_plane.resource_size = size; primary_plane.format = gfx::BufferFormat::BGRA_8888; primary_plane.mailbox = gpu::Mailbox::GenerateForSharedImage(); // Set up a dummy OverlayCandidate. OverlayCandidate candidate; candidate.resource_size_in_pixels = size; candidate.format = gfx::BufferFormat::BGRA_8888; candidate.mailbox = gpu::Mailbox::GenerateForSharedImage(); candidate.overlay_handled = false; OverlayCandidateList candidates; candidates.push_back(candidate); // Initialize a MockSharedImageInterface that returns a NativePixmap with // a different buffer format than that of the primary plane. std::unique_ptr<MockSharedImageInterface> sii = std::make_unique<MockSharedImageInterface>(); scoped_refptr<gfx::NativePixmap> primary_plane_pixmap = base::MakeRefCounted<FakeNativePixmap>(size, gfx::BufferFormat::R_8); EXPECT_CALL(*sii, GetNativePixmap(_)).WillOnce(Return(primary_plane_pixmap)); OverlayProcessorOzone processor( std::make_unique<FakeOverlayCandidatesOzone>(), {}, sii.get()); processor.CheckOverlaySupport(&primary_plane, &candidates); // Since the |OutputSurfaceOverlayPlane|'s format doesn't match that of the // primary plane's NativePixmap, the overlay candidate is NOT promoted. EXPECT_FALSE(candidates.at(0).overlay_handled); } TEST(OverlayProcessorOzoneTest, ColorSpaceMismatch) { // Set up the primary plane. gfx::Size size(128, 128); OverlayProcessorInterface::OutputSurfaceOverlayPlane primary_plane; primary_plane.resource_size = size; primary_plane.format = gfx::BufferFormat::BGRA_8888; primary_plane.mailbox = gpu::Mailbox::GenerateForSharedImage(); // Set up a dummy OverlayCandidate. OverlayCandidate candidate; candidate.resource_size_in_pixels = size; candidate.format = gfx::BufferFormat::BGRA_8888; candidate.mailbox = gpu::Mailbox::GenerateForSharedImage(); candidate.overlay_handled = false; OverlayCandidateList candidates; candidates.push_back(candidate); // Initialize a MockSharedImageInterface that returns a NativePixmap with // matching params to the primary plane. std::unique_ptr<MockSharedImageInterface> sii = std::make_unique<::testing::NiceMock<MockSharedImageInterface>>(); scoped_refptr<gfx::NativePixmap> primary_plane_pixmap = base::MakeRefCounted<FakeNativePixmap>(size, gfx::BufferFormat::BGRA_8888); scoped_refptr<gfx::NativePixmap> candidate_pixmap = base::MakeRefCounted<FakeNativePixmap>(size, gfx::BufferFormat::BGRA_8888); ON_CALL(*sii, GetNativePixmap(primary_plane.mailbox)) .WillByDefault(Return(primary_plane_pixmap)); ON_CALL(*sii, GetNativePixmap(candidate.mailbox)) .WillByDefault(Return(candidate_pixmap)); OverlayProcessorOzone processor( std::make_unique<FakeOverlayCandidatesOzone>(), {}, sii.get()); // In Chrome OS, we don't allow the promotion of the candidate if the // ContentColorUsage is different from the primary plane (e.g., SDR vs. HDR). // In other platforms, this is not a restriction. primary_plane.color_space = gfx::ColorSpace::CreateSRGB(); candidates[0].color_space = gfx::ColorSpace::CreateHDR10(); processor.CheckOverlaySupport(&primary_plane, &candidates); #if BUILDFLAG(IS_CHROMEOS_ASH) EXPECT_FALSE(candidates.at(0).overlay_handled); #else EXPECT_TRUE(candidates.at(0).overlay_handled); #endif // BUILDFLAG(IS_CHROMEOS_ASH) candidates[0] = candidate; // We do allow color space mismatches as long as the ContentColorUsage is the // same as the primary plane's (and this applies to all platforms). primary_plane.color_space = gfx::ColorSpace::CreateHDR10(); candidates[0].color_space = gfx::ColorSpace::CreateHLG(); processor.CheckOverlaySupport(&primary_plane, &candidates); EXPECT_TRUE(candidates.at(0).overlay_handled); candidates[0] = candidate; // Also, if the candidate requires an overlay, then it should be promoted // regardless of the color space mismatch. primary_plane.color_space = gfx::ColorSpace::CreateSRGB(); candidates[0].color_space = gfx::ColorSpace::CreateHDR10(); candidates[0].requires_overlay = true; processor.CheckOverlaySupport(&primary_plane, &candidates); EXPECT_TRUE(candidates.at(0).overlay_handled); candidates[0] = candidate; // And finally, if the candidate's color space is invalid, then it also should // be promoted. primary_plane.color_space = gfx::ColorSpace::CreateHDR10(); candidates[0].color_space = gfx::ColorSpace(); EXPECT_FALSE(candidates[0].color_space.IsValid()); processor.CheckOverlaySupport(&primary_plane, &candidates); EXPECT_TRUE(candidates.at(0).overlay_handled); } #endif } // namespace viz
3,420
82,518
<gh_stars>1000+ # Copyright 2021 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. """Tests for panoptic_segmentation_generator.py.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow.python.distribute import combinations from tensorflow.python.distribute import strategy_combinations from official.vision.beta.projects.panoptic_maskrcnn.modeling.layers import panoptic_segmentation_generator PANOPTIC_SEGMENTATION_GENERATOR = panoptic_segmentation_generator.PanopticSegmentationGenerator class PanopticSegmentationGeneratorTest( parameterized.TestCase, tf.test.TestCase): def test_serialize_deserialize(self): config = { 'output_size': [640, 640], 'max_num_detections': 100, 'stuff_classes_offset': 90, 'mask_binarize_threshold': 0.5, 'score_threshold': 0.005, 'things_class_label': 1, 'void_class_label': 0, 'void_instance_id': -1 } generator = PANOPTIC_SEGMENTATION_GENERATOR(**config) expected_config = dict(config) self.assertEqual(generator.get_config(), expected_config) new_generator = PANOPTIC_SEGMENTATION_GENERATOR.from_config( generator.get_config()) self.assertAllEqual(generator.get_config(), new_generator.get_config()) @combinations.generate( combinations.combine( strategy=[ strategy_combinations.default_strategy, strategy_combinations.one_device_strategy_gpu, ])) def test_outputs(self, strategy): # 0 represents the void class label thing_class_ids = [0, 1, 2, 3, 4] stuff_class_ids = [0, 5, 6, 7, 8, 9, 10] all_class_ids = set(thing_class_ids + stuff_class_ids) num_thing_classes = len(thing_class_ids) num_stuff_classes = len(stuff_class_ids) num_classes_for_segmentation = num_stuff_classes + 1 # all thing classes are mapped to class_id=1, stuff class ids are offset # such that the stuff class_ids start from 2, this means the semantic # segmentation head will have ground truths with class_ids belonging to # [0, 1, 2, 3, 4, 5, 6, 7] config = { 'output_size': [640, 640], 'max_num_detections': 100, 'stuff_classes_offset': 3, 'mask_binarize_threshold': 0.5, 'score_threshold': 0.005, 'things_class_label': 1, 'void_class_label': 0, 'void_instance_id': -1 } generator = PANOPTIC_SEGMENTATION_GENERATOR(**config) crop_height = 112 crop_width = 112 boxes = tf.constant([[ [167, 398, 342, 619], [192, 171, 363, 449], [211, 1, 382, 74] ]]) num_detections = boxes.get_shape().as_list()[1] scores = tf.random.uniform([1, num_detections], 0, 1) classes = tf.random.uniform( [1, num_detections], 1, num_thing_classes, dtype=tf.int32) masks = tf.random.normal( [1, num_detections, crop_height, crop_width]) segmentation_mask = tf.random.uniform( [1, *config['output_size']], 0, num_classes_for_segmentation, dtype=tf.int32) segmentation_mask_one_hot = tf.one_hot( segmentation_mask, depth=num_stuff_classes + 1) inputs = { 'detection_boxes': boxes, 'detection_scores': scores, 'detection_classes': classes, 'detection_masks': masks, 'num_detections': tf.constant([num_detections]), 'segmentation_outputs': segmentation_mask_one_hot } def _run(inputs): return generator(inputs=inputs) @tf.function def _distributed_run(inputs): outputs = strategy.run(_run, args=((inputs,))) return strategy.gather(outputs, axis=0) outputs = _distributed_run(inputs) self.assertIn('category_mask', outputs) self.assertIn('instance_mask', outputs) self.assertAllEqual( outputs['category_mask'][0].get_shape().as_list(), config['output_size']) self.assertAllEqual( outputs['instance_mask'][0].get_shape().as_list(), config['output_size']) for category_id in np.unique(outputs['category_mask']): self.assertIn(category_id, all_class_ids) if __name__ == '__main__': tf.test.main()
1,900
1,210
<filename>deps/cinder/include/boost/intrusive/linear_slist_algorithms.hpp ///////////////////////////////////////////////////////////////////////////// // // (C) Copyright <NAME> 2004-2006. // (C) Copyright <NAME> 2006-2014 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTRUSIVE_LINEAR_SLIST_ALGORITHMS_HPP #define BOOST_INTRUSIVE_LINEAR_SLIST_ALGORITHMS_HPP #include <boost/intrusive/detail/config_begin.hpp> #include <boost/intrusive/intrusive_fwd.hpp> #include <boost/intrusive/detail/common_slist_algorithms.hpp> #include <boost/intrusive/detail/algo_type.hpp> #include <cstddef> #include <boost/intrusive/detail/minimal_pair_header.hpp> //std::pair #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif namespace boost { namespace intrusive { //! linear_slist_algorithms provides basic algorithms to manipulate nodes //! forming a linear singly linked list. //! //! linear_slist_algorithms is configured with a NodeTraits class, which encapsulates the //! information about the node to be manipulated. NodeTraits must support the //! following interface: //! //! <b>Typedefs</b>: //! //! <tt>node</tt>: The type of the node that forms the linear list //! //! <tt>node_ptr</tt>: A pointer to a node //! //! <tt>const_node_ptr</tt>: A pointer to a const node //! //! <b>Static functions</b>: //! //! <tt>static node_ptr get_next(const_node_ptr n);</tt> //! //! <tt>static void set_next(node_ptr n, node_ptr next);</tt> template<class NodeTraits> class linear_slist_algorithms /// @cond : public detail::common_slist_algorithms<NodeTraits> /// @endcond { /// @cond typedef detail::common_slist_algorithms<NodeTraits> base_t; /// @endcond public: typedef typename NodeTraits::node node; typedef typename NodeTraits::node_ptr node_ptr; typedef typename NodeTraits::const_node_ptr const_node_ptr; typedef NodeTraits node_traits; #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //! <b>Effects</b>: Constructs an non-used list element, putting the next //! pointer to null: //! <tt>NodeTraits::get_next(this_node) == node_ptr()</tt> //! //! <b>Complexity</b>: Constant //! //! <b>Throws</b>: Nothing. static void init(const node_ptr & this_node); //! <b>Requires</b>: this_node must be in a circular list or be an empty circular list. //! //! <b>Effects</b>: Returns true is "this_node" is the only node of a circular list: //! or it's a not inserted node: //! <tt>return node_ptr() == NodeTraits::get_next(this_node) || NodeTraits::get_next(this_node) == this_node</tt> //! //! <b>Complexity</b>: Constant //! //! <b>Throws</b>: Nothing. static bool unique(const_node_ptr this_node); //! <b>Effects</b>: Returns true is "this_node" has the same state as if //! it was inited using "init(node_ptr)" //! //! <b>Complexity</b>: Constant //! //! <b>Throws</b>: Nothing. static bool inited(const_node_ptr this_node); //! <b>Requires</b>: prev_node must be in a circular list or be an empty circular list. //! //! <b>Effects</b>: Unlinks the next node of prev_node from the circular list. //! //! <b>Complexity</b>: Constant //! //! <b>Throws</b>: Nothing. static void unlink_after(const node_ptr & prev_node); //! <b>Requires</b>: prev_node and last_node must be in a circular list //! or be an empty circular list. //! //! <b>Effects</b>: Unlinks the range (prev_node, last_node) from the linear list. //! //! <b>Complexity</b>: Constant //! //! <b>Throws</b>: Nothing. static void unlink_after(const node_ptr & prev_node, const node_ptr & last_node); //! <b>Requires</b>: prev_node must be a node of a linear list. //! //! <b>Effects</b>: Links this_node after prev_node in the linear list. //! //! <b>Complexity</b>: Constant //! //! <b>Throws</b>: Nothing. static void link_after(const node_ptr & prev_node, const node_ptr & this_node); //! <b>Requires</b>: b and e must be nodes of the same linear list or an empty range. //! and p must be a node of a different linear list. //! //! <b>Effects</b>: Removes the nodes from (b, e] range from their linear list and inserts //! them after p in p's linear list. //! //! <b>Complexity</b>: Constant //! //! <b>Throws</b>: Nothing. static void transfer_after(const node_ptr & p, const node_ptr & b, const node_ptr & e); #endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //! <b>Effects</b>: Constructs an empty list, making this_node the only //! node of the circular list: //! <tt>NodeTraits::get_next(this_node) == this_node</tt>. //! //! <b>Complexity</b>: Constant //! //! <b>Throws</b>: Nothing. static void init_header(const node_ptr & this_node) { NodeTraits::set_next(this_node, node_ptr ()); } //! <b>Requires</b>: this_node and prev_init_node must be in the same linear list. //! //! <b>Effects</b>: Returns the previous node of this_node in the linear list starting. //! the search from prev_init_node. The first node checked for equality //! is NodeTraits::get_next(prev_init_node). //! //! <b>Complexity</b>: Linear to the number of elements between prev_init_node and this_node. //! //! <b>Throws</b>: Nothing. static node_ptr get_previous_node(const node_ptr & prev_init_node, const node_ptr & this_node) { return base_t::get_previous_node(prev_init_node, this_node); } //! <b>Requires</b>: this_node must be in a linear list or be an empty linear list. //! //! <b>Effects</b>: Returns the number of nodes in a linear list. If the linear list //! is empty, returns 1. //! //! <b>Complexity</b>: Linear //! //! <b>Throws</b>: Nothing. static std::size_t count(const const_node_ptr & this_node) { std::size_t result = 0; const_node_ptr p = this_node; do{ p = NodeTraits::get_next(p); ++result; } while (p); return result; } //! <b>Requires</b>: this_node and other_node must be nodes inserted //! in linear lists or be empty linear lists. //! //! <b>Effects</b>: Moves all the nodes previously chained after this_node after other_node //! and vice-versa. //! //! <b>Complexity</b>: Constant //! //! <b>Throws</b>: Nothing. static void swap_trailing_nodes(const node_ptr & this_node, const node_ptr & other_node) { node_ptr this_nxt = NodeTraits::get_next(this_node); node_ptr other_nxt = NodeTraits::get_next(other_node); NodeTraits::set_next(this_node, other_nxt); NodeTraits::set_next(other_node, this_nxt); } //! <b>Effects</b>: Reverses the order of elements in the list. //! //! <b>Returns</b>: The new first node of the list. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: This function is linear to the contained elements. static node_ptr reverse(const node_ptr & p) { if(!p) return node_ptr(); node_ptr i = NodeTraits::get_next(p); node_ptr first(p); while(i){ node_ptr nxti(NodeTraits::get_next(i)); base_t::unlink_after(p); NodeTraits::set_next(i, first); first = i; i = nxti; } return first; } //! <b>Effects</b>: Moves the first n nodes starting at p to the end of the list. //! //! <b>Returns</b>: A pair containing the new first and last node of the list or //! if there has been any movement, a null pair if n leads to no movement. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Linear to the number of elements plus the number moved positions. static std::pair<node_ptr, node_ptr> move_first_n_backwards(const node_ptr & p, std::size_t n) { std::pair<node_ptr, node_ptr> ret; //Null shift, or count() == 0 or 1, nothing to do if(!n || !p || !NodeTraits::get_next(p)){ return ret; } node_ptr first = p; bool end_found = false; node_ptr new_last = node_ptr(); node_ptr old_last = node_ptr(); //Now find the new last node according to the shift count. //If we find 0 before finding the new last node //unlink p, shortcut the search now that we know the size of the list //and continue. for(std::size_t i = 1; i <= n; ++i){ new_last = first; first = NodeTraits::get_next(first); if(first == node_ptr()){ //Shortcut the shift with the modulo of the size of the list n %= i; if(!n) return ret; old_last = new_last; i = 0; //Unlink p and continue the new first node search first = p; //unlink_after(new_last); end_found = true; } } //If the p has not been found in the previous loop, find it //starting in the new first node and unlink it if(!end_found){ old_last = base_t::get_previous_node(first, node_ptr()); } //Now link p after the new last node NodeTraits::set_next(old_last, p); NodeTraits::set_next(new_last, node_ptr()); ret.first = first; ret.second = new_last; return ret; } //! <b>Effects</b>: Moves the first n nodes starting at p to the beginning of the list. //! //! <b>Returns</b>: A pair containing the new first and last node of the list or //! if there has been any movement, a null pair if n leads to no movement. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Linear to the number of elements plus the number moved positions. static std::pair<node_ptr, node_ptr> move_first_n_forward(const node_ptr & p, std::size_t n) { std::pair<node_ptr, node_ptr> ret; //Null shift, or count() == 0 or 1, nothing to do if(!n || !p || !NodeTraits::get_next(p)) return ret; node_ptr first = p; //Iterate until p is found to know where the current last node is. //If the shift count is less than the size of the list, we can also obtain //the position of the new last node after the shift. node_ptr old_last(first), next_to_it, new_last(p); std::size_t distance = 1; while(!!(next_to_it = node_traits::get_next(old_last))){ if(distance++ > n) new_last = node_traits::get_next(new_last); old_last = next_to_it; } //If the shift was bigger or equal than the size, obtain the equivalent //forward shifts and find the new last node. if(distance <= n){ //Now find the equivalent forward shifts. //Shortcut the shift with the modulo of the size of the list std::size_t new_before_last_pos = (distance - (n % distance))% distance; //If the shift is a multiple of the size there is nothing to do if(!new_before_last_pos) return ret; for( new_last = p ; --new_before_last_pos ; new_last = node_traits::get_next(new_last)){ //empty } } //Get the first new node node_ptr new_first(node_traits::get_next(new_last)); //Now put the old beginning after the old end NodeTraits::set_next(old_last, p); NodeTraits::set_next(new_last, node_ptr()); ret.first = new_first; ret.second = new_last; return ret; } }; /// @cond template<class NodeTraits> struct get_algo<LinearSListAlgorithms, NodeTraits> { typedef linear_slist_algorithms<NodeTraits> type; }; /// @endcond } //namespace intrusive } //namespace boost #include <boost/intrusive/detail/config_end.hpp> #endif //BOOST_INTRUSIVE_LINEAR_SLIST_ALGORITHMS_HPP
4,846
1,405
package com.lenovo.performancecenter.framework; public class WhitelistAuth { public static final String AUTHORITY = "com.lenovo.performancecenter.provider.querywhitelist"; public static final int QUERYWHITELISTAPPS = 1; public static final int UPDATEWHITELISTAPPS = 2; }
87
445
#include "Python.h" #include "astropy_wcs_api.h" static PyObject* test( PyObject* self, PyObject* args, PyObject* kwds) { pipeline_t p; pipeline_clear(&p); return Py_None; } static PyMethodDef module_methods[] = { {"test", (PyCFunction)test, METH_NOARGS, ""}, {NULL} /* Sentinel */ }; struct module_state { /* The Sun compiler can't handle empty structs */ #if defined(__SUNPRO_C) || defined(_MSC_VER) int _dummy; #endif }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "wcsapi_test", NULL, sizeof(struct module_state), module_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_wcsapi_test(void) { PyObject* m; m = PyModule_Create(&moduledef); if (m == NULL) { return NULL; } import_astropy_wcs(); if (PyErr_Occurred()) return NULL; else return m; }
381
546
<filename>include/Msnhnet/math/MsnhVector3S.h #ifndef VECTOR3S_H #define VECTOR3S_H #include "Msnhnet/config/MsnhnetCfg.h" #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> namespace Msnhnet { class MsnhNet_API Vector3DS { public : double val[3]; inline Vector3DS(){val[0]=val[1]=val[2]=0;} inline Vector3DS(const double &x,const double &y,const double &z) { val[0] = x; val[1] = y; val[2] = z; } inline Vector3DS(const std::vector<double>& vec) { assert(vec.size()==3); val[0] = vec[0]; val[1] = vec[1]; val[2] = vec[2]; } inline Vector3DS(const Vector3DS& vec) { val[0] = vec.val[0]; val[1] = vec.val[1]; val[2] = vec.val[2]; } inline Vector3DS& operator =(const Vector3DS& vec) { if(this!=&vec) { val[0] = vec.val[0]; val[1] = vec.val[1]; val[2] = vec.val[2]; } return *this; } inline void setval(const double &x,const double &y,const double &z) { val[0] = x; val[1] = y; val[2] = z; } inline double operator [](const uint8_t &index) const { assert(index < 3); return val[index]; } inline double &operator [](const uint8_t &index) { assert(index < 3); return val[index]; } void print(); std::string toString() const; std::string toHtmlString() const; inline friend bool operator ==(const Vector3DS& A, const Vector3DS& B) { if(std::abs(A.val[0]-B.val[0]) < MSNH_F64_EPS && std::abs(A.val[1]-B.val[1]) < MSNH_F64_EPS && std::abs(A.val[2]-B.val[2]) < MSNH_F64_EPS) { return true; } else { return false; } } inline friend bool operator !=(const Vector3DS& A, const Vector3DS& B) { if(std::abs(A.val[0]-B.val[0]) < MSNH_F64_EPS && std::abs(A.val[1]-B.val[1]) < MSNH_F64_EPS && std::abs(A.val[2]-B.val[2]) < MSNH_F64_EPS) { return false; } else { return true; } } inline bool isFuzzyNull() const { for (int i = 0; i < 3; ++i) { if(std::abs(val[i])>MSNH_F64_EPS) { return false; } } return true; } inline bool isNan() const { for (int i = 0; i < 3; ++i) { if(std::isnan(static_cast<double>(val[i]))) { return true; } } return false; } inline bool closeToEps(const double &eps) { for (int i = 0; i < 3; ++i) { if(std::abs(val[i]-eps)>MSNH_F64_EPS) { return false; } } return true; } inline friend Vector3DS operator +(const Vector3DS& A, const Vector3DS& B) { Vector3DS tmp; tmp.val[0] = A.val[0]+B.val[0]; tmp.val[1] = A.val[1]+B.val[1]; tmp.val[2] = A.val[2]+B.val[2]; return tmp; } inline friend Vector3DS operator +(const Vector3DS& A, const double& b) { Vector3DS tmp; tmp.val[0] = A.val[0] + b; tmp.val[1] = A.val[1] + b; tmp.val[2] = A.val[2] + b; return tmp; } inline friend Vector3DS operator +(const double& a, const Vector3DS& B) { Vector3DS tmp; tmp.val[0] = B.val[0] + a; tmp.val[1] = B.val[1] + a; tmp.val[2] = B.val[2] + a; return tmp; } inline Vector3DS &operator +=(const Vector3DS& A) { val[0] = val[0] + A.val[0] ; val[1] = val[1] + A.val[1] ; val[2] = val[2] + A.val[2] ; return *this; } inline Vector3DS &operator +=(const double& a) { val[0] = val[0] + a ; val[1] = val[1] + a ; val[2] = val[2] + a ; return *this; } inline friend Vector3DS operator -(const Vector3DS& A, const Vector3DS& B) { Vector3DS tmp; tmp.val[0] = A.val[0]-B.val[0]; tmp.val[1] = A.val[1]-B.val[1]; tmp.val[2] = A.val[2]-B.val[2]; return tmp; } inline friend Vector3DS operator -(const Vector3DS& A, const double& b) { Vector3DS tmp; tmp.val[0] = A.val[0] - b; tmp.val[1] = A.val[1] - b; tmp.val[2] = A.val[2] - b; return tmp; } inline friend Vector3DS operator -(const double& a, const Vector3DS& B) { Vector3DS tmp; tmp.val[0] = a - B.val[0]; tmp.val[1] = a - B.val[1]; tmp.val[2] = a - B.val[2]; return tmp; } inline Vector3DS &operator -=(const Vector3DS& A) { val[0] = val[0] - A.val[0] ; val[1] = val[1] - A.val[1] ; val[2] = val[2] - A.val[2] ; return *this; } inline Vector3DS &operator -=(const double& a) { val[0] = val[0] - a ; val[1] = val[1] - a ; val[2] = val[2] - a ; return *this; } inline friend Vector3DS operator *(const Vector3DS& A, const Vector3DS& B) { Vector3DS tmp; tmp.val[0] = A.val[0]*B.val[0]; tmp.val[1] = A.val[1]*B.val[1]; tmp.val[2] = A.val[2]*B.val[2]; return tmp; } inline friend Vector3DS operator *(const Vector3DS& A, const double& b) { Vector3DS tmp; tmp.val[0] = A.val[0] * b; tmp.val[1] = A.val[1] * b; tmp.val[2] = A.val[2] * b; return tmp; } inline friend Vector3DS operator *(const double& a, const Vector3DS& B) { Vector3DS tmp; tmp.val[0] = a * B.val[0]; tmp.val[1] = a * B.val[1]; tmp.val[2] = a * B.val[2]; return tmp; } inline Vector3DS &operator *=(const Vector3DS& A) { val[0] = val[0] * A.val[0] ; val[1] = val[1] * A.val[1] ; val[2] = val[2] * A.val[2] ; return *this; } inline Vector3DS &operator *=(const double& a) { val[0] = val[0] * a ; val[1] = val[1] * a ; val[2] = val[2] * a ; return *this; } inline static Vector3DS crossProduct(const Vector3DS& A, const Vector3DS& B) { Vector3DS tmp; tmp.val[0] = A.val[1]*B.val[2]-A.val[2]*B.val[1]; tmp.val[1] = A.val[2]*B.val[0]-A.val[0]*B.val[2]; tmp.val[2] = A.val[0]*B.val[1]-A.val[1]*B.val[0]; return tmp; } inline static double dotProduct(const Vector3DS& A, const Vector3DS& B) { return A.val[0]*B.val[0] + A.val[1]*B.val[1] + A.val[2]*B.val[2]; } inline friend Vector3DS operator /(const Vector3DS& A, const double& b) { Vector3DS tmp; tmp.val[0] = A.val[0] / b; tmp.val[1] = A.val[1] / b; tmp.val[2] = A.val[2] / b; return tmp; } inline friend Vector3DS operator /(const Vector3DS& A, const Vector3DS& B) { Vector3DS tmp; tmp.val[0] = A.val[0] / B.val[0]; tmp.val[1] = A.val[1] / B.val[1]; tmp.val[2] = A.val[2] / B.val[2]; return tmp; } inline Vector3DS &operator /=(const Vector3DS& A) { val[0] = val[0] / A.val[0] ; val[1] = val[1] / A.val[1] ; val[2] = val[2] / A.val[2] ; return *this; } inline Vector3DS &operator /=(const double& a) { val[0] = val[0] / a ; val[1] = val[1] / a ; val[2] = val[2] / a ; return *this; } inline Vector3DS normalized() { Vector3DS vec; double len = val[0]*val[0] + val[1]*val[1] + val[2]*val[2]; if(std::abs(len - 1.0) < MSNH_F64_EPS) { return *this; } if(std::abs(len) < MSNH_F64_EPS) { return vec; } len = sqrt(len); vec.val[0] = val[0] / len; vec.val[1] = val[1] / len; vec.val[2] = val[2] / len; return vec; } inline void normalize() { double len = val[0]*val[0] + val[1]*val[1] + val[2]*val[2]; if(std::abs(len - 1.0) < MSNH_F64_EPS || std::abs(len) < MSNH_F64_EPS) { return; } len = sqrt(len); val[0] = val[0] / len; val[1] = val[1] / len; val[2] = val[2] / len; } inline double length() const { return sqrt(val[0]*val[0] + val[1]*val[1] + val[2]*val[2]); } inline double lengthSquared() const { return val[0]*val[0] + val[1]*val[1] + val[2]*val[2]; } /* 点到点之间的距离 * .eg ^ * | * A x --> --> ---> * | \ OA - OB = |BA| * | \ * O |-----x--> * B */ inline double distanceToPoint(const Vector3DS &point) const { return (*this - point).length(); } /* 点到线之间的距离 * .eg ^ * \ | * x x(A) * | \ * | x (point) * | \ * O |-------x--> B * \(direction) * \LINE(point + direction) */ inline double distanceToLine(const Vector3DS &point, const Vector3DS &direction) const { if(direction.isFuzzyNull()) { return (*this - point).length(); } Vector3DS p = point + Vector3DS::dotProduct((*this-point)*direction,direction); return (*this - p).length(); } /* 点到线之间的距离 * .eg ^ * / \ | *(normal) * / x * * / | \ * / | \ x(A) * \ *| \ * \ O |-------x--> B * * \ / / * * /\ / * / \ / (plane) * / \/ * */ inline double distanceToPlane(const Vector3DS& plane, const Vector3DS& normal) const { return dotProduct((*this-plane),normal); } inline static Vector3DS normal(const Vector3DS &v1, const Vector3DS &v2) { return crossProduct(v1,v2).normalized(); } inline static Vector3DS normal(const Vector3DS &v1, const Vector3DS &v2, const Vector3DS &v3) { return crossProduct((v2-v1),(v3-v1)).normalized(); } }; class Vector3FS { public : float val[3]; inline Vector3FS(){val[0]=val[1]=val[2]=0;} inline Vector3FS(const float &x,const float &y,const float &z) { val[0] = x; val[1] = y; val[2] = z; } inline Vector3FS(const std::vector<float>& vec) { assert(vec.size()==3); val[0] = vec[0]; val[1] = vec[1]; val[2] = vec[2]; } inline Vector3FS(const Vector3FS& vec) { val[0] = vec.val[0]; val[1] = vec.val[1]; val[2] = vec.val[2]; } inline Vector3FS& operator =(const Vector3FS& vec) { if(this!=&vec) { val[0] = vec.val[0]; val[1] = vec.val[1]; val[2] = vec.val[2]; } return *this; } inline void setval(const float &x,const float &y,const float &z) { val[0] = x; val[1] = y; val[2] = z; } inline float operator [](const uint8_t &index) const { assert(index < 3); return val[index]; } inline float &operator [](const uint8_t &index) { assert(index < 3); return val[index]; } void print(); std::string toString() const; std::string toHtmlString() const; inline friend bool operator ==(const Vector3FS& A, const Vector3FS& B) { if(fabsf(A.val[0]-B.val[0]) < MSNH_F32_EPS && fabsf(A.val[1]-B.val[1]) < MSNH_F32_EPS && fabsf(A.val[2]-B.val[2]) < MSNH_F32_EPS) { return true; } else { return false; } } inline friend bool operator !=(const Vector3FS& A, const Vector3FS& B) { if(fabsf(A.val[0]-B.val[0]) < MSNH_F32_EPS && fabsf(A.val[1]-B.val[1]) < MSNH_F32_EPS && fabsf(A.val[2]-B.val[2]) < MSNH_F32_EPS) { return false; } else { return true; } } inline bool isFuzzyNull() const { for (int i = 0; i < 3; ++i) { if(fabsf(val[i])>MSNH_F32_EPS) { return false; } } return true; } inline bool isNan() const { for (int i = 0; i < 3; ++i) { if(std::isnan(static_cast<float>(val[i]))) { return true; } } return false; } inline bool closeToEps(const float &eps) { for (int i = 0; i < 3; ++i) { if(std::abs(val[i]-eps)>MSNH_F32_EPS) { return false; } } return true; } inline friend Vector3FS operator +(const Vector3FS& A, const Vector3FS& B) { Vector3FS tmp; tmp.val[0] = A.val[0]+B.val[0]; tmp.val[1] = A.val[1]+B.val[1]; tmp.val[2] = A.val[2]+B.val[2]; return tmp; } inline friend Vector3FS operator +(const Vector3FS& A, const float& b) { Vector3FS tmp; tmp.val[0] = A.val[0] + b; tmp.val[1] = A.val[1] + b; tmp.val[2] = A.val[2] + b; return tmp; } inline friend Vector3FS operator +(const float& a, const Vector3FS& B) { Vector3FS tmp; tmp.val[0] = B.val[0] + a; tmp.val[1] = B.val[1] + a; tmp.val[2] = B.val[2] + a; return tmp; } inline Vector3FS &operator +=(const Vector3FS& A) { val[0] = val[0] + A.val[0] ; val[1] = val[1] + A.val[1] ; val[2] = val[2] + A.val[2] ; return *this; } inline Vector3FS &operator +=(const float& a) { val[0] = val[0] + a ; val[1] = val[1] + a ; val[2] = val[2] + a ; return *this; } inline friend Vector3FS operator -(const Vector3FS& A, const Vector3FS& B) { Vector3FS tmp; tmp.val[0] = A.val[0]-B.val[0]; tmp.val[1] = A.val[1]-B.val[1]; tmp.val[2] = A.val[2]-B.val[2]; return tmp; } inline friend Vector3FS operator -(const Vector3FS& A, const float& b) { Vector3FS tmp; tmp.val[0] = A.val[0] - b; tmp.val[1] = A.val[1] - b; tmp.val[2] = A.val[2] - b; return tmp; } inline friend Vector3FS operator -(const float& a, const Vector3FS& B) { Vector3FS tmp; tmp.val[0] = a - B.val[0]; tmp.val[1] = a - B.val[1]; tmp.val[2] = a - B.val[2]; return tmp; } inline Vector3FS &operator -=(const Vector3FS& A) { val[0] = val[0] - A.val[0] ; val[1] = val[1] - A.val[1] ; val[2] = val[2] - A.val[2] ; return *this; } inline Vector3FS &operator -=(const float& a) { val[0] = val[0] - a ; val[1] = val[1] - a ; val[2] = val[2] - a ; return *this; } inline friend Vector3FS operator *(const Vector3FS& A, const Vector3FS& B) { Vector3FS tmp; tmp.val[0] = A.val[0]*B.val[0]; tmp.val[1] = A.val[1]*B.val[1]; tmp.val[2] = A.val[2]*B.val[2]; return tmp; } inline friend Vector3FS operator *(const Vector3FS& A, const float& b) { Vector3FS tmp; tmp.val[0] = A.val[0] * b; tmp.val[1] = A.val[1] * b; tmp.val[2] = A.val[2] * b; return tmp; } inline friend Vector3FS operator *(const float& a, const Vector3FS& B) { Vector3FS tmp; tmp.val[0] = a * B.val[0]; tmp.val[1] = a * B.val[1]; tmp.val[2] = a * B.val[2]; return tmp; } inline Vector3FS &operator *=(const Vector3FS& A) { val[0] = val[0] * A.val[0] ; val[1] = val[1] * A.val[1] ; val[2] = val[2] * A.val[2] ; return *this; } inline Vector3FS &operator *=(const float& a) { val[0] = val[0] * a ; val[1] = val[1] * a ; val[2] = val[2] * a ; return *this; } inline static Vector3FS crossProduct(const Vector3FS& A, const Vector3FS& B) { Vector3FS tmp; tmp.val[0] = A.val[1]*B.val[2]-A.val[2]*B.val[1]; tmp.val[1] = A.val[2]*B.val[0]-A.val[0]*B.val[2]; tmp.val[2] = A.val[0]*B.val[1]-A.val[1]*B.val[0]; return tmp; } inline static float dotProduct(const Vector3FS& A, const Vector3FS& B) { return A.val[0]*B.val[0] + A.val[1]*B.val[1] + A.val[2]*B.val[2]; } inline friend Vector3FS operator /(const Vector3FS& A, const float& b) { Vector3FS tmp; tmp.val[0] = A.val[0] / b; tmp.val[1] = A.val[1] / b; tmp.val[2] = A.val[2] / b; return tmp; } inline friend Vector3FS operator /(const Vector3FS& A, const Vector3FS& B) { Vector3FS tmp; tmp.val[0] = A.val[0] / B.val[0]; tmp.val[1] = A.val[1] / B.val[1]; tmp.val[2] = A.val[2] / B.val[2]; return tmp; } inline Vector3FS &operator /=(const Vector3FS& A) { val[0] = val[0] / A.val[0] ; val[1] = val[1] / A.val[1] ; val[2] = val[2] / A.val[2] ; return *this; } inline Vector3FS &operator /=(const float& a) { val[0] = val[0] / a ; val[1] = val[1] / a ; val[2] = val[2] / a ; return *this; } inline Vector3FS normalized() { Vector3FS vec; float len = val[0]*val[0] + val[1]*val[1] + val[2]*val[2]; if(fabsf(len - 1.0f) < MSNH_F32_EPS) { return *this; } if(fabsf(len) < MSNH_F32_EPS) { return vec; } len = sqrtf(len); vec.val[0] = val[0] / len; vec.val[1] = val[1] / len; vec.val[2] = val[2] / len; return vec; } inline void normalize() { float len = val[0]*val[0] + val[1]*val[1] + val[2]*val[2]; if(fabsf(len - 1.0f) < MSNH_F32_EPS || fabsf(len) < MSNH_F32_EPS) { return; } len = sqrtf(len); val[0] = val[0] / len; val[1] = val[1] / len; val[2] = val[2] / len; } inline float length() const { return sqrtf(val[0]*val[0] + val[1]*val[1] + val[2]*val[2]); } inline float lengthSquared() const { return val[0]*val[0] + val[1]*val[1] + val[2]*val[2]; } /* 点到点之间的距离 * .eg ^ * | * A x --> --> ---> * | \ OA - OB = |BA| * | \ * O |-----x--> * B */ inline float distanceToPoint(const Vector3FS &point) const { return (*this - point).length(); } /* 点到线之间的距离 * .eg ^ * \ | * x x(A) * | \ * | x (point) * | \ * O |-------x--> B * \(direction) * \LINE(point + direction) */ inline float distanceToLine(const Vector3FS &point, const Vector3FS &direction) const { if(direction.isFuzzyNull()) { return (*this - point).length(); } Vector3FS p = point + Vector3FS::dotProduct((*this-point)*direction,direction); return (*this - p).length(); } /* 点到线之间的距离 * .eg ^ * / \ | *(normal) * / x * * / | \ * / | \ x(A) * \ *| \ * \ O |-------x--> B * * \ / / * * /\ / * / \ / (plane) * / \/ * */ inline float distanceToPlane(const Vector3FS& plane, const Vector3FS& normal) const { return dotProduct((*this-plane),normal); } inline static Vector3FS normal(const Vector3FS &v1, const Vector3FS &v2) { return crossProduct(v1,v2).normalized(); } inline static Vector3FS normal(const Vector3FS &v1, const Vector3FS &v2, const Vector3FS &v3) { return crossProduct((v2-v1),(v3-v1)).normalized(); } }; typedef Vector3DS EulerDS; typedef Vector3DS TranslationDS; typedef Vector3DS RotationVecDS; typedef Vector3DS LinearVelDS; typedef Vector3DS AngularVelDS; typedef Vector3FS EulerFS; typedef Vector3FS TranslationFS; typedef Vector3FS RotationVecFS; typedef Vector3FS LinearVelFS; typedef Vector3FS AngularVelFS; } #endif
11,871
3,262
<gh_stars>1000+ package com.tencent.angel.psagent.matrix.transport.router.operator; public interface IIntKeyFloatValuePartOp { int[] getKeys(); float[] getValues(); void add(int key, float value); void add(int[] keys, float[] values); }
83
367
//***********************************************************************// // // // - "Talk to me like I'm a 3 year old!" Programming Lessons - // // // // $Author: DigiBen <EMAIL> // // // // $Program: Octree3 // // // // $Description: A working octree with a .3ds file format scene // // // //***********************************************************************// #pragma comment(lib, "winmm.lib") #include "main.h" #include "Camera.h" // This is how fast our camera moves #define kSpeed 5.0f ///////////////////////////////// CALCULATE FRAME RATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This function calculates the frame rate and time intervals between frames ///// ///////////////////////////////// CALCULATE FRAME RATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* void CalculateFrameRate() { static int framesPerSecond = 0; // This will store our fps static float fpsTime = 0.0f; // Amount of elapsed time until we update the FPS count char strFrameRate[50] = {0}; // We will store the string here for the window title // Increase the fps elapsed time fpsTime += g_DT; // Now we want to subtract the current time by the last time that was stored // to see if the time elapsed has been over a second, which means we found our FPS. if( fpsTime > 1.0f ) { // Reset the fpsTime fpsTime = 0.0f; // Copy the frames per second into a string to display in the window title bar sprintf(strFrameRate, "Current Frames Per Second: %d", framesPerSecond); // Set the window title bar to our string SetWindowText(g_hWnd, strFrameRate); // Reset the frames per second framesPerSecond = 0; } else { // Increase the frame counter ++framesPerSecond; } } ///////////////////////////////// CCAMERA \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This is the class constructor ///// ///////////////////////////////// CCAMERA \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* CCamera::CCamera() { CVector3 vZero = CVector3(0.0, 0.0, 0.0); // Init a vVector to 0 0 0 for our position CVector3 vView = CVector3(0.0, 1.0, 0.5); // Init a starting view vVector (looking up and out the screen) CVector3 vUp = CVector3(0.0, 0.0, 1.0); // Init a standard up vVector (Rarely ever changes) m_vPosition = vZero; // Init the position to zero m_vView = vView; // Init the view to a std starting view m_vUpVector = vUp; // Init the UpVector } ///////////////////////////////// POSITION CAMERA \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This function sets the camera's position and view and up vVector. ///// ///////////////////////////////// POSITION CAMERA \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* void CCamera::PositionCamera(float positionX, float positionY, float positionZ, float viewX, float viewY, float viewZ, float upVectorX, float upVectorY, float upVectorZ) { CVector3 vPosition = CVector3(positionX, positionY, positionZ); CVector3 vView = CVector3(viewX, viewY, viewZ); CVector3 vUpVector = CVector3(upVectorX, upVectorY, upVectorZ); // The code above just makes it cleaner to set the variables. // Otherwise we would have to set each variable x y and z. m_vPosition = vPosition; // Assign the position m_vView = vView; // Assign the view m_vUpVector = vUpVector; // Assign the up vector } ///////////////////////////////// SET VIEW BY MOUSE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This allows us to look around using the mouse, like in most first person games. ///// ///////////////////////////////// SET VIEW BY MOUSE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* void CCamera::SetViewByMouse() { POINT mousePos; // This is a window structure that holds an X and Y int middleX = SCREEN_WIDTH >> 1; // This is a binary shift to get half the width int middleY = SCREEN_HEIGHT >> 1; // This is a binary shift to get half the height float angleY = 0.0f; // This is the direction for looking up or down float angleZ = 0.0f; // This will be the value we need to rotate around the Y axis (Left and Right) static float currentRotX = 0.0f; // Get the mouse's current X,Y position GetCursorPos(&mousePos); // If our cursor is still in the middle, we never moved... so don't update the screen if( (mousePos.x == middleX) && (mousePos.y == middleY) ) return; // Set the mouse position to the middle of our window SetCursorPos(middleX, middleY); // Get the direction the mouse moved in, but bring the number down to a reasonable amount angleY = (float)( (middleX - mousePos.x) ) / 500.0f; angleZ = (float)( (middleY - mousePos.y) ) / 500.0f; static float lastRotX = 0.0f; lastRotX = currentRotX; // We store off the currentRotX and will use it in when the angle is capped // Here we keep track of the current rotation (for up and down) so that // we can restrict the camera from doing a full 360 loop. currentRotX += angleZ; // If the current rotation (in radians) is greater than 1.0, we want to cap it. if(currentRotX > 1.0f) { currentRotX = 1.0f; // Rotate by remaining angle if there is any if(lastRotX != 1.0f) { // To find the axis we need to rotate around for up and down // movements, we need to get a perpendicular vector from the // camera's view vector and up vector. This will be the axis. // Before using the axis, it's a good idea to normalize it first. CVector3 vAxis = Cross(m_vView - m_vPosition, m_vUpVector); vAxis = Normalize(vAxis); // rotate the camera by the remaining angle (1.0f - lastRotX) RotateView( 1.0f - lastRotX, vAxis.x, vAxis.y, vAxis.z); } } // Check if the rotation is below -1.0, if so we want to make sure it doesn't continue else if(currentRotX < -1.0f) { currentRotX = -1.0f; // Rotate by the remaining angle if there is any if(lastRotX != -1.0f) { // To find the axis we need to rotate around for up and down // movements, we need to get a perpendicular vector from the // camera's view vector and up vector. This will be the axis. // Before using the axis, it's a good idea to normalize it first. CVector3 vAxis = Cross(m_vView - m_vPosition, m_vUpVector); vAxis = Normalize(vAxis); // rotate the camera by ( -1.0f - lastRotX) RotateView( -1.0f - lastRotX, vAxis.x, vAxis.y, vAxis.z); } } // Otherwise, we can rotate the view around our position else { // To find the axis we need to rotate around for up and down // movements, we need to get a perpendicular vector from the // camera's view vector and up vector. This will be the axis. // Before using the axis, it's a good idea to normalize it first. CVector3 vAxis = Cross(m_vView - m_vPosition, m_vUpVector); vAxis = Normalize(vAxis); // Rotate around our perpendicular axis RotateView(angleZ, vAxis.x, vAxis.y, vAxis.z); } // Always rotate the camera around the y-axis RotateView(angleY, 0, 1, 0); } ///////////////////////////////// ROTATE VIEW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This rotates the view around the position using an axis-angle rotation ///// ///////////////////////////////// ROTATE VIEW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* void CCamera::RotateView(float angle, float x, float y, float z) { CVector3 vNewView; // Get the view vector (The direction we are facing) CVector3 vView = m_vView - m_vPosition; // Calculate the sine and cosine of the angle once float cosTheta = (float)cos(angle); float sinTheta = (float)sin(angle); // Find the new x position for the new rotated point vNewView.x = (cosTheta + (1 - cosTheta) * x * x) * vView.x; vNewView.x += ((1 - cosTheta) * x * y - z * sinTheta) * vView.y; vNewView.x += ((1 - cosTheta) * x * z + y * sinTheta) * vView.z; // Find the new y position for the new rotated point vNewView.y = ((1 - cosTheta) * x * y + z * sinTheta) * vView.x; vNewView.y += (cosTheta + (1 - cosTheta) * y * y) * vView.y; vNewView.y += ((1 - cosTheta) * y * z - x * sinTheta) * vView.z; // Find the new z position for the new rotated point vNewView.z = ((1 - cosTheta) * x * z - y * sinTheta) * vView.x; vNewView.z += ((1 - cosTheta) * y * z + x * sinTheta) * vView.y; vNewView.z += (cosTheta + (1 - cosTheta) * z * z) * vView.z; // Now we just add the newly rotated vector to our position to set // our new rotated view of our camera. m_vView = m_vPosition + vNewView; } ///////////////////////////////// STRAFE CAMERA \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This strafes the camera left and right depending on the speed (-/+) ///// ///////////////////////////////// STRAFE CAMERA \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* void CCamera::StrafeCamera(float speed) { // Add the strafe vector to our position m_vPosition.x += m_vStrafe.x * speed; m_vPosition.z += m_vStrafe.z * speed; // Add the strafe vector to our view m_vView.x += m_vStrafe.x * speed; m_vView.z += m_vStrafe.z * speed; } ///////////////////////////////// MOVE CAMERA \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This will move the camera forward or backward depending on the speed ///// ///////////////////////////////// MOVE CAMERA \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* void CCamera::MoveCamera(float speed) { // Get the current view vector (the direction we are looking) CVector3 vVector = m_vView - m_vPosition; vVector = Normalize(vVector); m_vPosition.x += vVector.x * speed; // Add our acceleration to our position's X m_vPosition.y += vVector.y * speed; // Add our acceleration to our position's Y m_vPosition.z += vVector.z * speed; // Add our acceleration to our position's Z m_vView.x += vVector.x * speed; // Add our acceleration to our view's X m_vView.y += vVector.y * speed; // Add our acceleration to our view's Y m_vView.z += vVector.z * speed; // Add our acceleration to our view's Z } //////////////////////////// CHECK FOR MOVEMENT \\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This function handles the input faster than in the WinProc() ///// //////////////////////////// CHECK FOR MOVEMENT \\\\\\\\\\\\\\\\\\\\\\\\\\\\* void CCamera::CheckForMovement() { // Once we have the frame interval, we find the current speed float speed = kSpeed * g_DT; // Check if we hit the Up arrow or the 'w' key if(GetKeyState(VK_UP) & 0x80 || GetKeyState('W') & 0x80) { // Move our camera forward by a positive SPEED MoveCamera(speed); } // Check if we hit the Down arrow or the 's' key if(GetKeyState(VK_DOWN) & 0x80 || GetKeyState('S') & 0x80) { // Move our camera backward by a negative SPEED MoveCamera(-speed); } // Check if we hit the Left arrow or the 'a' key if(GetKeyState(VK_LEFT) & 0x80 || GetKeyState('A') & 0x80) { // Strafe the camera left StrafeCamera(-speed); } // Check if we hit the Right arrow or the 'd' key if(GetKeyState(VK_RIGHT) & 0x80 || GetKeyState('D') & 0x80) { // Strafe the camera right StrafeCamera(speed); } } ///////////////////////////////// UPDATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This updates the camera's view and strafe vector ///// ///////////////////////////////// UPDATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* void CCamera::Update() { // Initialize a variable for the cross product result CVector3 vCross = Cross(m_vView - m_vPosition, m_vUpVector); // Normalize the strafe vector m_vStrafe = Normalize(vCross); // Move the camera's view by the mouse SetViewByMouse(); // This checks to see if the keyboard was pressed CheckForMovement(); // Calculate our frame rate and set our frame interval for time based movement CalculateFrameRate(); } ///////////////////////////////// LOOK \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This updates the camera according to the ///// ///////////////////////////////// LOOK \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* void CCamera::Look() { // Give openGL our camera position, then camera view, then camera up vector gluLookAt(m_vPosition.x, m_vPosition.y, m_vPosition.z, m_vView.x, m_vView.y, m_vView.z, m_vUpVector.x, m_vUpVector.y, m_vUpVector.z); } ///////////////////////////////////////////////////////////////////////////////// // // * QUICK NOTES * // // Nothing was changed since the Time Based Movement tutorial, except in // MoveCamera() we allowed the user to enter fly mode with using the Y value. // The 1000 was changed to 500 in SetViewByMouse() to make the camera faster. // // // <NAME> (DigiBen) // Game Programmer // <EMAIL> // Co-Web Host of www.GameTutorials.com // //
4,355
313
package com.daivd.chart.provider.component.cross; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.Rect; /** * Created by huang on 2017/10/19. * 十字轴 */ public interface ICross { void drawCross(Canvas canvas, PointF pointF, Rect rect, Paint paint); }
118
348
<gh_stars>100-1000 {"nom":"Saint-Martin-la-Garenne","circ":"8ème circonscription","dpt":"Yvelines","inscrits":682,"abs":337,"votants":345,"blancs":46,"nuls":5,"exp":294,"res":[{"nuance":"LR","nom":"<NAME>","voix":171},{"nuance":"REM","nom":"<NAME>","voix":123}]}
104
582
/******************************************************************************* * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.gef.dnd; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DragSourceListener; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.dnd.TransferData; /** * A DragSourceListener that maintains and delegates to a set of * {@link TransferDragSourceListener}s. Each TransferDragSourceListener can then * be implemented as if it were the DragSource's only DragSourceListener. * <P> * When a native Drag is started, a subset of all * <code>TransferDragSourceListeners</code> is generated and stored in a list of * <i>active</i> listeners. This subset is calculated by forwarding * {@link DragSourceListener#dragStart(DragSourceEvent)} to every listener, and * inspecting changes to the {@link DragSourceEvent#doit doit} field. The * <code>DragSource</code>'s set of supported Transfer types ( * {@link DragSource#setTransfer(Transfer[])}) is updated to reflect the * Transfer types corresponding to the active listener subset. * <P> * If and when {@link #dragSetData(DragSourceEvent)} is called, a single * <code>TransferDragSourceListener</code> is chosen, and only it is allowed to * set the drag data. The chosen listener is the first listener in the subset of * active listeners whose Transfer supports ( * {@link Transfer#isSupportedType(TransferData)}) the dataType on the * <code>DragSourceEvent</code>. */ public class DelegatingDragAdapter extends org.eclipse.jface.util.DelegatingDragAdapter { /** * Adds the given TransferDragSourceListener. The set of Transfer types is * updated to reflect the change. * * @param listener * the new listener * @deprecated */ public void addDragSourceListener(TransferDragSourceListener listener) { super.addDragSourceListener(listener); } /** * Combines the <code>Transfer</code>s from every * TransferDragSourceListener. * * @return the combined <code>Transfer</code>s * @deprecated call getTransfers() instead. */ public Transfer[] getTransferTypes() { return super.getTransfers(); } /** * Adds the given TransferDragSourceListener. The set of Transfer types is * updated to reflect the change. * * @param listener * the listener being removed * @deprecated */ public void removeDragSourceListener(TransferDragSourceListener listener) { super.removeDragSourceListener(listener); } }
921
594
/* Test for builtin abs, labs, llabs, imaxabs. */ /* Origin: <NAME> <<EMAIL>> */ #include <limits.h> typedef __INTMAX_TYPE__ intmax_t; #define INTMAX_MAX __INTMAX_MAX__ extern int abs (int); extern long labs (long); extern long long llabs (long long); extern intmax_t imaxabs (intmax_t); extern void abort (void); extern void link_error (void); void main_test (void) { /* For each type, test both runtime and compile time (constant folding) optimization. */ volatile int i0 = 0, i1 = 1, im1 = -1, imin = -INT_MAX, imax = INT_MAX; volatile long l0 = 0L, l1 = 1L, lm1 = -1L, lmin = -LONG_MAX, lmax = LONG_MAX; volatile long long ll0 = 0LL, ll1 = 1LL, llm1 = -1LL; volatile long long llmin = -__LONG_LONG_MAX__, llmax = __LONG_LONG_MAX__; volatile intmax_t imax0 = 0, imax1 = 1, imaxm1 = -1; volatile intmax_t imaxmin = -INTMAX_MAX, imaxmax = INTMAX_MAX; if (abs (i0) != 0) abort (); if (abs (0) != 0) link_error (); if (abs (i1) != 1) abort (); if (abs (1) != 1) link_error (); if (abs (im1) != 1) abort (); if (abs (-1) != 1) link_error (); if (abs (imin) != INT_MAX) abort (); if (abs (-INT_MAX) != INT_MAX) link_error (); if (abs (imax) != INT_MAX) abort (); if (abs (INT_MAX) != INT_MAX) link_error (); if (labs (l0) != 0L) abort (); if (labs (0L) != 0L) link_error (); if (labs (l1) != 1L) abort (); if (labs (1L) != 1L) link_error (); if (labs (lm1) != 1L) abort (); if (labs (-1L) != 1L) link_error (); if (labs (lmin) != LONG_MAX) abort (); if (labs (-LONG_MAX) != LONG_MAX) link_error (); if (labs (lmax) != LONG_MAX) abort (); if (labs (LONG_MAX) != LONG_MAX) link_error (); if (llabs (ll0) != 0LL) abort (); if (llabs (0LL) != 0LL) link_error (); if (llabs (ll1) != 1LL) abort (); if (llabs (1LL) != 1LL) link_error (); if (llabs (llm1) != 1LL) abort (); if (llabs (-1LL) != 1LL) link_error (); if (llabs (llmin) != __LONG_LONG_MAX__) abort (); if (llabs (-__LONG_LONG_MAX__) != __LONG_LONG_MAX__) link_error (); if (llabs (llmax) != __LONG_LONG_MAX__) abort (); if (llabs (__LONG_LONG_MAX__) != __LONG_LONG_MAX__) link_error (); if (imaxabs (imax0) != 0) abort (); if (imaxabs (0) != 0) link_error (); if (imaxabs (imax1) != 1) abort (); if (imaxabs (1) != 1) link_error (); if (imaxabs (imaxm1) != 1) abort (); if (imaxabs (-1) != 1) link_error (); if (imaxabs (imaxmin) != INTMAX_MAX) abort (); if (imaxabs (-INTMAX_MAX) != INTMAX_MAX) link_error (); if (imaxabs (imaxmax) != INTMAX_MAX) abort (); if (imaxabs (INTMAX_MAX) != INTMAX_MAX) link_error (); }
1,254
4,756
<filename>mace/runtimes/opencl/mtk_ion/opencl_mtk_ion_runtime.cc // Copyright 2021 The MACE Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mace/runtimes/opencl/mtk_ion/opencl_mtk_ion_runtime.h" #include <memory> #include "mace/core/runtime/runtime_registry.h" #include "mace/runtimes/opencl/core/opencl_context.h" #include "mace/runtimes/opencl/mtk_ion/opencl_base_mtk_ion_allocator.h" #include "mace/runtimes/opencl/mtk_ion/opencl_mtk_ion_executor.h" namespace mace { OpenclMtkIonRuntime::OpenclMtkIonRuntime(RuntimeContext *runtime_context) : OpenclRuntime(runtime_context) { MACE_CHECK(runtime_context->context_type == RuntimeContextType::RCT_ION); auto *ion_runtime_context = static_cast<IonRuntimeContext *>(runtime_context); rpcmem_ = ion_runtime_context->rpcmem; } MaceStatus OpenclMtkIonRuntime::Init(const MaceEngineCfgImpl *engine_config, const MemoryType mem_type) { MACE_RETURN_IF_ERROR(OpenclRuntime::Init(engine_config, mem_type)); buffer_ion_allocator_ = make_unique<OpenclBufferMtkIonAllocator>(opencl_executor_.get(), rpcmem_); image_ion_allocator_ = make_unique<OpenclImageMtkIonAllocator>(opencl_executor_.get(), rpcmem_); buffer_ion_manager_ = make_unique<GeneralMemoryManager>(buffer_ion_allocator_.get()); image_ion_manager_ = make_unique<OpenclImageManager>(image_ion_allocator_.get()); return MaceStatus::MACE_SUCCESS; } MaceStatus OpenclMtkIonRuntime::CreateOpenclExecutorAndInit( const MaceEngineCfgImpl *engine_config) { if (opencl_executor_ == nullptr) { opencl_executor_ = make_unique<OpenclMtkIonExecutor>(); MACE_RETURN_IF_ERROR(opencl_executor_->Init( engine_config->opencl_context(), engine_config->gpu_priority_hint(), engine_config->gpu_perf_hint())); } return MaceStatus::MACE_SUCCESS; } RuntimeSubType OpenclMtkIonRuntime::GetRuntimeSubType() { return RuntimeSubType::RT_SUB_MTK_ION; } MaceStatus OpenclMtkIonRuntime::MapBuffer(Buffer *buffer, bool wait_for_finish) { auto *opencl_executor = OpenclMtkIonExecutor::Get(opencl_executor_.get()); MACE_CHECK((buffer->mem_type == MemoryType::GPU_BUFFER || buffer->mem_type == MemoryType::GPU_IMAGE) && opencl_executor->ion_type() == IONType::MTK_ION); MACE_LATENCY_LOGGER(1, "OpenclMtkIonRuntime Map OpenCL buffer"); OpenclBaseMtkIonAllocator *ion_allocator = nullptr; if (buffer->mem_type == MemoryType::GPU_IMAGE) { ion_allocator = image_ion_allocator_.get(); } else { ion_allocator = buffer_ion_allocator_.get(); } void *mapped_ptr = ion_allocator->GetMappedPtrByIonBuffer(buffer->mutable_memory<void>()); MACE_CHECK(mapped_ptr != nullptr, "Try to map unallocated Buffer!"); if (wait_for_finish) { opencl_executor->command_queue().finish(); } const auto ret = rpcmem_->SyncCacheStart(mapped_ptr); MACE_CHECK(ret == 0, "Ion map failed, ret = ", ret); buffer->SetHost(static_cast<uint8_t *>(mapped_ptr) + buffer->offset()); return MaceStatus::MACE_SUCCESS; } MaceStatus OpenclMtkIonRuntime::UnMapBuffer(Buffer *buffer) { auto *opencl_executor = OpenclMtkIonExecutor::Get(opencl_executor_.get()); MACE_CHECK(opencl_executor->ion_type() == IONType::MTK_ION); MACE_LATENCY_LOGGER(1, "OpenclMtkIonRuntime Unmap OpenCL buffer/Image"); if (buffer->data<void>() != nullptr) { auto *mapped_ptr = buffer->mutable_data<uint8_t>() - buffer->offset(); MACE_CHECK(rpcmem_->SyncCacheEnd(mapped_ptr) == 0); } buffer->SetHost(nullptr); return MaceStatus::MACE_SUCCESS; } MemoryManager *OpenclMtkIonRuntime::GetMemoryManager(MemoryType mem_type) { MemoryManager *buffer_manager = nullptr; if (mem_type == MemoryType::GPU_BUFFER) { buffer_manager = buffer_ion_manager_.get(); } else if (mem_type == MemoryType::GPU_IMAGE) { buffer_manager = image_ion_manager_.get(); } else { MACE_CHECK(false, "OpenclRuntime::GetMemoryManagerByMemType", "find an invalid mem type:", mem_type); } return buffer_manager; } std::shared_ptr<Rpcmem> OpenclMtkIonRuntime::GetRpcmem() { return rpcmem_; } void RegisterOpenclMtkIonRuntime(RuntimeRegistry *runtime_registry) { MACE_REGISTER_RUNTIME(runtime_registry, RuntimeType::RT_OPENCL, RuntimeSubType::RT_SUB_MTK_ION, OpenclMtkIonRuntime); } } // namespace mace
1,859
839
<gh_stars>100-1000 /** * 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.cxf.systest.jaxrs.metrics; import java.util.Arrays; import javax.ws.rs.NotFoundException; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.core.MediaType; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import org.apache.cxf.Bus; import org.apache.cxf.endpoint.Endpoint; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider; import org.apache.cxf.jaxrs.model.AbstractResourceInfo; import org.apache.cxf.message.Exchange; import org.apache.cxf.metrics.MetricsContext; import org.apache.cxf.metrics.MetricsFeature; import org.apache.cxf.metrics.MetricsProvider; import org.apache.cxf.service.model.BindingOperationInfo; import org.apache.cxf.testutil.common.AbstractClientServerTestBase; import org.apache.cxf.testutil.common.AbstractServerTestServerBase; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.times; @RunWith(MockitoJUnitRunner.class) public class JAXRSServerMetricsTest extends AbstractClientServerTestBase { public static final String PORT = allocatePort(JAXRSServerMetricsTest.class); private static MetricsProvider provider; private static MetricsContext operationContext; private static MetricsContext resourceContext; private static MetricsContext endpointContext; @Rule public ExpectedException expectedException = ExpectedException.none(); public static class BookLibrary implements Library { @Override public Book getBook(int id) { if (id == 10) { throw new NotFoundException(); } else { return new Book(id); } } } public static class Server extends AbstractServerTestServerBase { @Override protected org.apache.cxf.endpoint.Server createServer(Bus bus) throws Exception { final JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); sf.setResourceClasses(BookLibrary.class); sf.setResourceProvider(BookLibrary.class, new SingletonResourceProvider(new BookLibrary())); sf.setFeatures(Arrays.asList(new MetricsFeature(provider))); sf.setAddress("http://localhost:" + PORT + "/"); sf.setProvider(new JacksonJsonProvider()); return sf.create(); } public static void main(String[] args) throws Exception { new Server().start(); } } @BeforeClass public static void startServers() throws Exception { endpointContext = Mockito.mock(MetricsContext.class); operationContext = Mockito.mock(MetricsContext.class); resourceContext = Mockito.mock(MetricsContext.class); provider = new MetricsProvider() { public MetricsContext createEndpointContext(Endpoint endpoint, boolean asClient, String cid) { return endpointContext; } public MetricsContext createOperationContext(Endpoint endpoint, BindingOperationInfo boi, boolean asClient, String cid) { return operationContext; } public MetricsContext createResourceContext(Endpoint endpoint, String resourceName, boolean asClient, String cid) { return resourceContext; } }; AbstractResourceInfo.clearAllMaps(); //keep out of process due to stack traces testing failures assertTrue("server did not launch correctly", launchServer(Server.class, true)); } @Before public void setUp() { Mockito.reset(resourceContext); Mockito.reset(operationContext); Mockito.reset(endpointContext); } @Test public void usingClientProxyStopIsCalledWhenServerReturnsNotFound() throws Exception { final JAXRSClientFactoryBean factory = new JAXRSClientFactoryBean(); factory.setResourceClass(Library.class); factory.setAddress("http://localhost:" + PORT + "/"); factory.setProvider(JacksonJsonProvider.class); try { final Library client = factory.create(Library.class); expectedException.expect(NotFoundException.class); client.getBook(10); } finally { Mockito.verify(resourceContext, times(1)).start(any(Exchange.class)); Mockito.verify(resourceContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class)); Mockito.verify(endpointContext, times(1)).start(any(Exchange.class)); Mockito.verify(endpointContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class)); Mockito.verifyNoInteractions(operationContext); } } @Test public void usingClientStopIsCalledWhenServerReturnsNotFound() throws Exception { final Client client = ClientBuilder .newClient() .register(JacksonJsonProvider.class); try { expectedException.expect(ProcessingException.class); client .target("http://localhost:" + PORT + "/books/10") .request(MediaType.APPLICATION_JSON).get() .readEntity(Book.class); } finally { Mockito.verify(resourceContext, times(1)).start(any(Exchange.class)); Mockito.verify(resourceContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class)); Mockito.verify(endpointContext, times(1)).start(any(Exchange.class)); Mockito.verify(endpointContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class)); Mockito.verifyNoInteractions(operationContext); } } @Test public void usingClientStopIsCalledWhenServerReturnSuccessfulResponse() throws Exception { final Client client = ClientBuilder .newClient() .register(JacksonJsonProvider.class); try { client .target("http://localhost:" + PORT + "/books/11") .request(MediaType.APPLICATION_JSON) .get() .readEntity(Book.class); } finally { Mockito.verify(resourceContext, times(1)).start(any(Exchange.class)); Mockito.verify(resourceContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class)); Mockito.verify(endpointContext, times(1)).start(any(Exchange.class)); Mockito.verify(endpointContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class)); Mockito.verifyNoInteractions(operationContext); } } @Test public void usingWebClientStopIsCalledWhenServerReturnsNotFound() throws Exception { final WebClient client = WebClient.create("http://localhost:" + PORT + "/books/10", Arrays.asList(JacksonJsonProvider.class)); try { expectedException.expect(ProcessingException.class); client.get().readEntity(Book.class); } finally { Mockito.verify(resourceContext, times(1)).start(any(Exchange.class)); Mockito.verify(resourceContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class)); Mockito.verify(endpointContext, times(1)).start(any(Exchange.class)); Mockito.verify(endpointContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class)); Mockito.verifyNoInteractions(operationContext); } } @Test public void usingWebClientStopIsCalledWhenUrlIsNotServed() throws Exception { final WebClient client = WebClient.create("http://localhost:" + PORT + "/books", Arrays.asList(JacksonJsonProvider.class)); try { expectedException.expect(ProcessingException.class); client.get().readEntity(Book.class); } finally { Mockito.verify(endpointContext, times(1)).start(any(Exchange.class)); Mockito.verify(endpointContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class)); Mockito.verifyNoInteractions(resourceContext); Mockito.verifyNoInteractions(operationContext); } } }
3,730
647
<filename>client/src/main/java/io/atomix/copycat/client/ServerSelectionStrategies.java /* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package io.atomix.copycat.client; import io.atomix.catalyst.transport.Address; import io.atomix.copycat.Query; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Strategies for managing how clients connect to and communicate with the cluster. * <p> * Selection strategies manage which servers a client attempts to contact and submit operations * to. Clients can communicate with followers, leaders, or both. Selection strategies offer the * option for clients to spread connections across the cluster for scalability or connect to the * cluster's leader for performance. * * @author <a href="http://github.com/kuujo><NAME></a> */ public enum ServerSelectionStrategies implements ServerSelectionStrategy { /** * The {@code ANY} selection strategy allows the client to connect to any server in the cluster. Clients * will attempt to connect to a random server, and the client will persist its connection with the first server * through which it is able to communicate. If the client becomes disconnected from a server, it will attempt * to connect to the next random server again. */ ANY { @Override public List<Address> selectConnections(Address leader, List<Address> servers) { Collections.shuffle(servers); return servers; } }, /** * The {@code LEADER} selection strategy forces the client to attempt to connect to the cluster's leader. * Connecting to the leader means the client's operations are always handled by the first server to receive * them. However, clients connected to the leader will not significantly benefit from {@link Query queries} * with lower consistency levels, and more clients connected to the leader could mean more load on a single * point in the cluster. * <p> * If the client is unable to find a leader in the cluster, the client will connect to a random server. */ LEADER { @Override public List<Address> selectConnections(Address leader, List<Address> servers) { if (leader != null) { return Collections.singletonList(leader); } Collections.shuffle(servers); return servers; } }, /** * The {@code FOLLOWERS} selection strategy forces the client to connect only to followers. Connecting to * followers ensures that the leader is not overloaded with direct client requests. This strategy should be * used when clients frequently submit {@link Query queries} with lower consistency levels that don't need to * be forwarded to the cluster leader. For clients that frequently submit commands or queries with linearizable * consistency, the {@link #LEADER} ConnectionStrategy may be more performant. */ FOLLOWERS { @Override public List<Address> selectConnections(Address leader, List<Address> servers) { Collections.shuffle(servers); if (leader != null && servers.size() > 1) { List<Address> results = new ArrayList<>(servers.size()); for (Address address : servers) { if (!address.equals(leader)) { results.add(address); } } return results; } return servers; } } }
1,110
1,510
/* * 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.drill.exec.physical.impl.scan.v3.schema; import java.util.Collection; import org.apache.drill.common.expression.PathSegment; import org.apache.drill.common.expression.PathSegment.ArraySegment; import org.apache.drill.common.expression.PathSegment.NameSegment; import org.apache.drill.common.expression.SchemaPath; import org.apache.drill.exec.record.metadata.ColumnMetadata; import org.apache.drill.exec.record.metadata.Propertied; import org.apache.drill.exec.record.metadata.TupleMetadata; import org.apache.drill.exec.record.metadata.TupleSchema; import org.apache.drill.shaded.guava.com.google.common.base.Preconditions; /** * Parse the projection list into a dynamic tuple schema. Using * an enhanced form of dynamic column which records projection list * information (such as map members and array indexes.) * <p> * A wildcard project list can contain implicit columns in * addition to the wildcard. The wildcard defines the * <i>insert point</i>: the point at which reader-defined * columns are inserted as found. */ public class ScanProjectionParser { public static final String PROJECTION_TYPE_PROP = Propertied.DRILL_PROP_PREFIX + "proj-type"; public static final String PROJECT_ALL = "all"; public static final String PROJECT_NONE = "none"; public static class ProjectionParseResult { public final int wildcardPosn; public final TupleMetadata dynamicSchema; public ProjectionParseResult(int wildcardPosn, TupleMetadata dynamicSchema) { this.wildcardPosn = wildcardPosn; this.dynamicSchema = dynamicSchema; } public boolean isProjectAll() { return wildcardPosn != -1; } } private int wildcardPosn = -1; public static ProjectionParseResult parse(Collection<SchemaPath> projList) { if (projList == null) { return SchemaUtils.projectAll(); } if (projList.isEmpty()) { return SchemaUtils.projectNone(); } return new ScanProjectionParser().parseProjection(projList); } private ProjectionParseResult parseProjection(Collection<SchemaPath> projList) { TupleMetadata tupleProj = new TupleSchema(); for (SchemaPath col : projList) { parseMember(tupleProj, 0, col.getRootSegment()); } return new ProjectionParseResult(wildcardPosn, tupleProj); } private void parseMember(TupleMetadata tuple, int depth, NameSegment nameSeg) { String colName = nameSeg.getPath(); if (colName.equals(SchemaPath.DYNAMIC_STAR)) { tuple.setProperty(PROJECTION_TYPE_PROP, PROJECT_ALL); if (depth == 0) { Preconditions.checkState(wildcardPosn == -1); wildcardPosn = tuple.size(); } } else { ProjectedColumn col = project(tuple, nameSeg.getPath()); parseChildSeg(col, depth + 1, nameSeg); } } protected ProjectedColumn project(TupleMetadata tuple, String colName) { ColumnMetadata col = tuple.metadata(colName); ProjectedColumn projCol; if (col == null) { projCol = new ProjectedColumn(colName); tuple.addColumn(projCol); } else { projCol = (ProjectedColumn) col; projCol.bumpRefCount(); } return projCol; } private void parseChildSeg(ProjectedColumn column, int depth, PathSegment parentPath) { if (parentPath.isLastPath()) { parseLeaf(column, depth); } else { PathSegment seg = parentPath.getChild(); if (seg.isArray()) { parseArraySeg(column, depth, (ArraySegment) seg); } else { parseMemberSeg(column, depth, (NameSegment) seg); } } } /** * Parse a projection of the form {@code a}: that is, just a bare column. */ private void parseLeaf(ProjectedColumn parent, int depth) { if (parent.isSimple()) { // Nothing to do } else if (parent.isArray() && depth == 1) { parent.projectAllElements(); } else if (parent.isMap()) { parent.projectAllMembers(); } } private void parseArraySeg(ProjectedColumn column, int depth, ArraySegment arraySeg) { boolean wasArray = column.isArray(); column.becomeArray(Math.max(depth, column.arrayDims())); // Record only outermost dimension indexes if (depth == 1) { if (column.refCount() > 1 && !wasArray) { column.projectAllElements(); } else { column.addIndex(arraySeg.getIndex()); } } parseChildSeg(column, depth + 1, arraySeg); } private void parseMemberSeg(ProjectedColumn column, int depth, NameSegment memberSeg) { if (column.refCount() > 1 && !column.isMap()) { column.projectAllMembers(); } TupleMetadata tuple = column.explicitMembers(); if (tuple != null) { parseMember(tuple, depth, memberSeg); } } }
1,883
2,180
<filename>kafka-manager-common/src/main/java/com/xiaojukeji/kafka/manager/common/entity/ao/consumer/ConsumerGroup.java<gh_stars>1000+ package com.xiaojukeji.kafka.manager.common.entity.ao.consumer; import com.xiaojukeji.kafka.manager.common.bizenum.OffsetLocationEnum; import java.util.Objects; public class ConsumerGroup { private Long clusterId; private String consumerGroup; private OffsetLocationEnum offsetStoreLocation; public ConsumerGroup(Long clusterId, String consumerGroup, OffsetLocationEnum offsetStoreLocation) { this.clusterId = clusterId; this.consumerGroup = consumerGroup; this.offsetStoreLocation = offsetStoreLocation; } public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getConsumerGroup() { return consumerGroup; } public void setConsumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; } public OffsetLocationEnum getOffsetStoreLocation() { return offsetStoreLocation; } public void setOffsetStoreLocation(OffsetLocationEnum offsetStoreLocation) { this.offsetStoreLocation = offsetStoreLocation; } @Override public String toString() { return "ConsumerGroup{" + "clusterId=" + clusterId + ", consumerGroup='" + consumerGroup + '\'' + ", offsetStoreLocation=" + offsetStoreLocation + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConsumerGroup that = (ConsumerGroup) o; return clusterId.equals(that.clusterId) && consumerGroup.equals(that.consumerGroup) && offsetStoreLocation == that.offsetStoreLocation; } @Override public int hashCode() { return Objects.hash(clusterId, consumerGroup, offsetStoreLocation); } }
824
381
package com.tngtech.jgiven.impl; /** * A default scenario implementation that takes three type arguments, * one for each stage. * * @param <GIVEN> the Given stage * @param <WHEN> then When stage * @param <THEN> then Then stage */ public class Scenario<GIVEN, WHEN, THEN> extends ScenarioBase { private GIVEN givenStage; private WHEN whenStage; private THEN thenStage; private final Class<GIVEN> givenClass; private final Class<WHEN> whenClass; private final Class<THEN> thenClass; private Scenario( Class<GIVEN> stageClass ) { this.givenClass = stageClass; this.whenClass = null; this.thenClass = null; } public Scenario( Class<GIVEN> givenClass, Class<WHEN> whenClass, Class<THEN> thenClass ) { this.givenClass = givenClass; this.whenClass = whenClass; this.thenClass = thenClass; } public GIVEN getGivenStage() { return givenStage; } public WHEN getWhenStage() { return whenStage; } public THEN getThenStage() { return thenStage; } public void addIntroWord( String word ) { executor.addIntroWord( word ); } /** * Creates a scenario with 3 different steps classes. * * To share state between the different steps instances use the * {@link com.tngtech.jgiven.annotation.ScenarioState} annotation * * @param givenClass the Given steps class * @param whenClass the When steps class * @param thenClass the Then steps class * @return the new scenario */ public static <GIVEN, WHEN, THEN> Scenario<GIVEN, WHEN, THEN> create( Class<GIVEN> givenClass, Class<WHEN> whenClass, Class<THEN> thenClass ) { return new Scenario<GIVEN, WHEN, THEN>( givenClass, whenClass, thenClass ); } /** * Creates a scenario with a single steps class. * Only creates a single steps instance for all three step types, * so no {@link com.tngtech.jgiven.annotation.ScenarioState} annotations are needed * to share state between the different steps instances. * * @param stepsClass the class to use for given, when and then steps * @return the new scenario */ public static <STEPS> Scenario<STEPS, STEPS, STEPS> create( Class<STEPS> stepsClass ) { return new Scenario<STEPS, STEPS, STEPS>( stepsClass ); } /** * Describes the scenario. Must be called before any step invocation. * @param description the description * @return this for a fluent interface */ @Override public Scenario<GIVEN, WHEN, THEN> startScenario( String description ) { super.startScenario( description ); return this; } @Override @SuppressWarnings("unchecked") protected void initialize() { super.initialize(); if (whenClass == null) { givenStage = (GIVEN) executor.addStage( givenClass ); whenStage = (WHEN) givenStage; thenStage = (THEN) givenStage; } else { givenStage = executor.addStage( givenClass ); whenStage = executor.addStage( whenClass ); thenStage = executor.addStage( thenClass ); } } /** * Alias for {@link #startScenario(String)}. */ public Scenario<GIVEN, WHEN, THEN> as( String description ) { return startScenario( description ); } public GIVEN given() { return given( "Given" ); } public WHEN when() { return when( "When" ); } public THEN then() { return then( "Then" ); } public GIVEN given( String translatedGiven ) { addIntroWord( translatedGiven ); return getGivenStage(); } public WHEN when( String translatedWhen ) { addIntroWord( translatedWhen ); return getWhenStage(); } public THEN then( String translatedThen ) { addIntroWord( translatedThen ); return getThenStage(); } }
1,522
432
<reponame>lambdaxymox/DragonFlyBSD /* * Copyright (c) 2004 <NAME>. All rights reserved. * Copyright (c) 2004 The DragonFly Project. All rights reserved. * * This code is derived from software contributed to The DragonFly Project * by <NAME>. * * 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 DragonFly 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 HOLDERS 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. */ /* * Copyright (c) 1980, 1986, 1989, 1993 * The Regents of the University of California. 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 University 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 REGENTS 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 REGENTS 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. * * @(#)netisr.h 8.1 (Berkeley) 6/10/93 * $FreeBSD: src/sys/net/netisr.h,v 1.21.2.5 2002/02/09 23:02:39 luigi Exp $ */ #ifndef _NET_NETISR2_H_ #define _NET_NETISR2_H_ #ifndef _KERNEL #error "kernel only header file" #endif #include <sys/systm.h> #include <sys/msgport2.h> #include <sys/thread.h> #include <net/netisr.h> extern struct thread *netisr_threads[MAXCPU]; /* * Return the message port for the general protocol message servicing * thread for a particular cpu. */ static __inline lwkt_port_t netisr_cpuport(int cpu) { KKASSERT(cpu >= 0 && cpu < ncpus); return &netisr_threads[cpu]->td_msgport; } /* * Return the current cpu's network protocol thread. */ static __inline lwkt_port_t netisr_curport(void) { return netisr_cpuport(mycpuid); } /* * Return the LSB of the hash. */ static __inline uint32_t netisr_hashlsb(uint32_t hash) { return (hash & NETISR_CPUMASK); } /* * Return the cpu for the hash. */ static __inline int netisr_hashcpu(uint16_t hash) { return (netisr_hashlsb(hash) % netisr_ncpus); } /* * Return the message port for the general protocol message servicing * thread for the hash. */ static __inline lwkt_port_t netisr_hashport(uint16_t hash) { return netisr_cpuport(netisr_hashcpu(hash)); } #define IN_NETISR(n) \ (&curthread->td_msgport == netisr_cpuport((n))) #define IN_NETISR_NCPUS(n) \ ((n) < netisr_ncpus && IN_NETISR((n))) #define ASSERT_NETISR0 \ KASSERT(IN_NETISR(0), ("thread %p is not netisr0", curthread)) #define ASSERT_NETISR_NCPUS(n) \ KASSERT(IN_NETISR_NCPUS(n), \ ("thread %p cpu%d is not within netisr_ncpus %d", \ curthread, (n), netisr_ncpus)) static __inline int netisr_domsg_port(struct netmsg_base *nm, lwkt_port_t port) { #ifdef INVARIANTS /* * Only netisr0, netisrN itself, or non-netisr threads * can perform synchronous message sending to netisrN. */ KASSERT(curthread->td_type != TD_TYPE_NETISR || IN_NETISR(0) || port == &curthread->td_msgport, ("can't domsg to netisr port %p from thread %p", port, curthread)); #endif return (lwkt_domsg(port, &nm->lmsg, 0)); } static __inline int netisr_domsg(struct netmsg_base *nm, int cpu) { return (netisr_domsg_port(nm, netisr_cpuport(cpu))); } static __inline int netisr_domsg_global(struct netmsg_base *nm) { /* Start from netisr0. */ return (netisr_domsg(nm, 0)); } static __inline void netisr_sendmsg(struct netmsg_base *nm, int cpu) { lwkt_sendmsg(netisr_cpuport(cpu), &nm->lmsg); } static __inline void netisr_sendmsg_oncpu(struct netmsg_base *nm) { lwkt_sendmsg_oncpu(netisr_cpuport(mycpuid), &nm->lmsg); } static __inline void netisr_replymsg(struct netmsg_base *nm, int error) { lwkt_replymsg(&nm->lmsg, error); } static __inline void netisr_dropmsg(struct netmsg_base *nm) { lwkt_dropmsg(&nm->lmsg); } /* * To all netisrs, instead of netisr_ncpus. */ static __inline void netisr_forwardmsg_all(struct netmsg_base *nm, int next_cpu) { KKASSERT(next_cpu > mycpuid && next_cpu <= ncpus); if (next_cpu < ncpus) lwkt_forwardmsg(netisr_cpuport(next_cpu), &nm->lmsg); else netisr_replymsg(nm, 0); } /* * To netisr_ncpus. */ static __inline void netisr_forwardmsg_error(struct netmsg_base *nm, int next_cpu, int error) { KKASSERT(next_cpu > mycpuid && next_cpu <= netisr_ncpus); if (next_cpu < netisr_ncpus) lwkt_forwardmsg(netisr_cpuport(next_cpu), &nm->lmsg); else netisr_replymsg(nm, error); } /* * To netisr_ncpus. */ static __inline void netisr_forwardmsg(struct netmsg_base *nm, int next_cpu) { netisr_forwardmsg_error(nm, next_cpu, 0); } #endif /* _NET_NETISR2_H_ */
2,496
892
{ "schema_version": "1.2.0", "id": "GHSA-7h63-9wr7-vcw2", "modified": "2022-05-13T01:33:46Z", "published": "2022-05-13T01:33:46Z", "aliases": [ "CVE-2018-17915" ], "details": "All versions of Hangzhou Xiongmai Technology Co., Ltd XMeye P2P Cloud Server do not encrypt all device communication. This includes the XMeye service and firmware update communication. This could allow an attacker to eavesdrop on video feeds, steal XMeye login credentials, or impersonate the update server with malicious update code.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-17915" }, { "type": "WEB", "url": "https://ics-cert.us-cert.gov/advisories/ICSA-18-282-06" } ], "database_specific": { "cwe_ids": [ "CWE-311" ], "severity": "CRITICAL", "github_reviewed": false } }
458
587
<gh_stars>100-1000 /* * Copyright 2012-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lightadmin.core.persistence.repository.event; import org.lightadmin.core.config.domain.GlobalAdministrationConfiguration; import org.lightadmin.core.persistence.repository.DynamicJpaRepository; import org.lightadmin.core.persistence.support.FileReferencePropertyHandler; import org.lightadmin.core.storage.FileResourceStorage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanWrapper; import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.util.DirectFieldAccessFallbackBeanWrapper; import java.io.IOException; import java.util.Map; import static com.google.common.collect.Maps.newLinkedHashMap; import static org.apache.commons.lang3.StringUtils.isNotBlank; public class FileManipulationRepositoryEventListener extends ManagedRepositoryEventListener { private static final Logger logger = LoggerFactory.getLogger(FileManipulationRepositoryEventListener.class); private final ThreadLocal<FileReferenceProperties> fileReferencePropertiesContext = newFileItemsContext(); private final FileResourceStorage fileResourceStorage; public FileManipulationRepositoryEventListener(GlobalAdministrationConfiguration configuration, FileResourceStorage fileResourceStorage) { super(configuration); this.fileResourceStorage = fileResourceStorage; } @Override protected void onBeforeCreate(Object entity) { onBeforeSave(entity); } @Override protected void onAfterCreate(final Object entity) { onAfterSave(entity); } @Override protected void onBeforeSave(Object entity) { PersistentEntity persistentEntity = persistentEntityFor(entity.getClass()); NotEmptyFileReferencePropertiesCollector propertyValueCollector = new NotEmptyFileReferencePropertiesCollector(entity); persistentEntity.doWithProperties(propertyValueCollector); FileReferenceProperties fileReferenceProperties = propertyValueCollector.getFilePropertyValues(); persistentEntity.doWithProperties(new FileReferencePropertiesValueEraser(entity, fileReferenceProperties)); fileReferencePropertiesContext.set(fileReferenceProperties); } @Override protected void onAfterSave(Object entity) { PersistentEntity persistentEntity = persistentEntityFor(entity.getClass()); DynamicJpaRepository repository = repositoryFor(entity.getClass()); FileReferenceProperties fileReferenceProperties = fileReferencePropertiesContext.get(); try { persistentEntity.doWithProperties(new FileReferencePropertiesSaveHandler(entity, fileReferenceProperties)); repository.save(entity); } finally { fileReferencePropertiesContext.remove(); } } @Override protected void onAfterDelete(final Object entity) { PersistentEntity persistentEntity = persistentEntityFor(entity.getClass()); persistentEntity.doWithProperties(new PersistentPropertyFileDeletionHandler(entity)); } private class PersistentPropertyFileDeletionHandler extends FileReferencePropertyHandler { private final Object entity; public PersistentPropertyFileDeletionHandler(Object entity) { this.entity = entity; } @Override protected void doWithPersistentPropertyInternal(PersistentProperty<?> property) { fileResourceStorage.delete(entity, property); } } private static class NotEmptyFileReferencePropertiesCollector extends FileReferencePropertyHandler { private final BeanWrapper beanWrapper; private final FileReferenceProperties fileReferenceProperties; private NotEmptyFileReferencePropertiesCollector(Object instance) { this.beanWrapper = new DirectFieldAccessFallbackBeanWrapper(instance); this.fileReferenceProperties = new FileReferenceProperties(); } @Override protected void doWithPersistentPropertyInternal(PersistentProperty<?> property) { String propertyName = property.getName(); String propertyValue = (String) beanWrapper.getPropertyValue(propertyName); if (isNotBlank(propertyValue)) { fileReferenceProperties.addPropertyValue(propertyName, propertyValue.getBytes()); } } public FileReferenceProperties getFilePropertyValues() { return fileReferenceProperties; } } private class FileReferencePropertiesSaveHandler extends FileReferencePropertyHandler { private final Object entity; private final FileReferenceProperties fileReferenceProperties; public FileReferencePropertiesSaveHandler(Object entity, FileReferenceProperties fileReferenceProperties) { this.entity = entity; this.fileReferenceProperties = fileReferenceProperties; } @Override protected void doWithPersistentPropertyInternal(PersistentProperty<?> property) { try { if (this.fileReferenceProperties.contains(property.getName())) { byte[] propertyValue = this.fileReferenceProperties.getPropertyValue(property.getName()); fileResourceStorage.save(entity, property, propertyValue); } } catch (IOException e) { throw new RuntimeException(e); } } } private static class FileReferencePropertiesValueEraser extends FileReferencePropertyHandler { private final BeanWrapper beanWrapper; private final FileReferenceProperties fileReferenceProperties; private FileReferencePropertiesValueEraser(Object instance, FileReferenceProperties fileReferenceProperties) { this.beanWrapper = new DirectFieldAccessFallbackBeanWrapper(instance); this.fileReferenceProperties = fileReferenceProperties; } @Override protected void doWithPersistentPropertyInternal(PersistentProperty<?> property) { if (fileReferenceProperties.contains(property.getName())) { beanWrapper.setPropertyValue(property.getName(), "NULL_VALUE"); } } } private static class FileReferenceProperties { private Map<String, byte[]> filePropertyValues = newLinkedHashMap(); public void addPropertyValue(String propertyName, byte[] propertyValue) { this.filePropertyValues.put(propertyName, propertyValue); } public byte[] getPropertyValue(String propertyName) { return this.filePropertyValues.get(propertyName); } public boolean contains(String propertyName) { return filePropertyValues.containsKey(propertyName); } } private static ThreadLocal<FileReferenceProperties> newFileItemsContext() { return new ThreadLocal<FileReferenceProperties>() { protected FileReferenceProperties initialValue() { return new FileReferenceProperties(); } }; } }
2,579
516
<reponame>eltonsandre/intellij-plugin-save-actions /* * The MIT License (MIT) * * Copyright (c) 2020 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.dubreuia.model; import java.util.Arrays; import java.util.Set; import java.util.stream.Stream; import static com.dubreuia.model.ActionType.activation; import static com.dubreuia.model.ActionType.build; import static com.dubreuia.model.ActionType.global; import static com.dubreuia.model.ActionType.java; import static java.util.stream.Collectors.toSet; public enum Action { // Activation activate("Activate save actions on save (before saving each file, performs the configured actions below)", activation, true), activateOnShortcut("Activate save actions on shortcut (default \"CTRL + SHIFT + S\")", activation, false), activateOnBatch("Activate save actions on batch (\"Code > Save Actions > Execute on multiple files\")", activation, false), noActionIfCompileErrors("No action if compile errors (applied per file)", activation, false), // Global organizeImports("Optimize imports", global, true), reformat("Reformat file", global, true), reformatChangedCode("Reformat only changed code (only if VCS configured)", global, false), rearrange("Rearrange fields and methods " + "(configured in \"File > Settings > Editor > Code Style > (...) > Arrangement\")", global, false), // Build compile("[experimental] Compile files (using \"Build > Build Project\")", build, false), reload("[experimental] Reload files in running debugger (using \"Run > Reload Changed Classes\")", build, false), executeAction("[experimental] Execute an action (using quick lists at " + "\"File > Settings > Appearance & Behavior > Quick Lists\")", build, false), // Java fixes fieldCanBeFinal("Add final modifier to field", java, false), localCanBeFinal("Add final modifier to local variable or parameter", java, false), localCanBeFinalExceptImplicit("Add final modifier to local variable or parameter except if it is implicit", java, false), methodMayBeStatic("Add static modifier to methods", java, false), unqualifiedFieldAccess("Add this to field access", java, false), unqualifiedMethodAccess("Add this to method access", java, false), unqualifiedStaticMemberAccess("Add class qualifier to static member access", java, false), customUnqualifiedStaticMemberAccess("Add class qualifier to static member access outside declaring class", java, false), missingOverrideAnnotation("Add missing @Override annotations", java, false), useBlocks("Add blocks to if/while/for statements", java, false), generateSerialVersionUID("Add a serialVersionUID field for Serializable classes", java, false), unnecessaryThis("Remove unnecessary this to field and method", java, false), finalPrivateMethod("Remove final from private method", java, false), unnecessaryFinalOnLocalVariableOrParameter("Remove unnecessary final to local variable or parameter", java, false), explicitTypeCanBeDiamond("Remove explicit generic type for diamond", java, false), suppressAnnotation("Remove unused suppress warning annotation", java, false), unnecessarySemicolon("Remove unnecessary semicolon", java, false), singleStatementInBlock("Remove blocks from if/while/for statements", java, false), accessCanBeTightened("Change visibility of field or method to lower access", java, false), ; private final String text; private final ActionType type; private final boolean defaultValue; Action(String text, ActionType type, boolean defaultValue) { this.text = text; this.type = type; this.defaultValue = defaultValue; } public String getText() { return text; } public ActionType getType() { return type; } public boolean isDefaultValue() { return defaultValue; } public static Set<Action> getDefaults() { return Arrays.stream(Action.values()) .filter(Action::isDefaultValue) .collect(toSet()); } public static Stream<Action> stream() { return Arrays.stream(values()); } public static Stream<Action> stream(ActionType type) { return Arrays.stream(values()).filter(action -> action.type.equals(type)); } }
1,943
496
// // BCMeshContentView.h // BCMeshTransformView // // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface BCMeshContentView : UIView @property (nonatomic, copy) void (^changeBlock)(void); @property (nonatomic, copy) void (^tickBlock)(CADisplayLink *); - (instancetype)initWithFrame:(CGRect)frame changeBlock:(void (^)(void))changeBlock tickBlock:(void (^)(CADisplayLink *))tickBlock; - (void)displayLinkTick:(CADisplayLink *)displayLink; @end
209
312
<reponame>Samsung/ADBI<filename>util/human.h #ifndef HUMAN_H_ #define HUMAN_H_ #define str_fn(what) \ struct what ## _t; \ const char * str_ ## what(const struct what ## _t * what); str_fn(node) str_fn(process) str_fn(thread) str_fn(injection) str_fn(injectable) str_fn(segment) str_fn(tracepoint) const char * str_signal(int signo); const char * str_address(const struct process_t * process, address_t address); #undef str_fn #endif
267
349
<filename>src/nes/wiring/cpu_mmu.h #pragma once #include "common/util.h" #include "nes/cartridge/mapper.h" #include "nes/interfaces/memory.h" // CPU Memory Map (MMU) // NESdoc.pdf // https://wiki.nesdev.com/w/index.php/CPU_memory_map // https://wiki.nesdev.com/w/index.php/2A03 class CPU_MMU final : public Memory { private: // Fixed References (these will never be invalidated) Memory& ram; Memory& ppu; Memory& apu; Memory& joy; // Changing References Mapper* cart; public: CPU_MMU() = delete; CPU_MMU( Memory& ram, Memory& ppu, Memory& apu, Memory& joy ); // <Memory> u8 read(u16 addr) override; u8 peek(u16 addr) const override; void write(u16 addr, u8 val) override; // <Memory/> void loadCartridge(Mapper* cart); void removeCartridge(); };
319
2,151
<reponame>zipated/src<filename>third_party/blink/renderer/core/frame/find_in_page.cc<gh_stars>1000+ /* * Copyright (C) 2009 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 "third_party/blink/renderer/core/frame/find_in_page.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_find_options.h" #include "third_party/blink/public/web/web_frame_client.h" #include "third_party/blink/public/web/web_plugin.h" #include "third_party/blink/public/web/web_plugin_document.h" #include "third_party/blink/renderer/core/editing/finder/text_finder.h" #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" namespace blink { void WebLocalFrameImpl::RequestFind(int identifier, const WebString& search_text, const WebFindOptions& options) { find_in_page_->RequestFind(identifier, search_text, options); } void FindInPage::RequestFind(int identifier, const WebString& search_text, const WebFindOptions& options) { // Send "no results" if this frame has no visible content. if (!frame_->HasVisibleContent() && !options.force) { frame_->Client()->ReportFindInPageMatchCount(identifier, 0 /* count */, true /* finalUpdate */); return; } WebRange current_selection = frame_->SelectionRange(); bool result = false; bool active_now = false; // Search for an active match only if this frame is focused or if this is a // find next request. if (frame_->IsFocused() || options.find_next) { result = frame_->Find(identifier, search_text, options, false /* wrapWithinFrame */, &active_now); } if (result && !options.find_next) { // Indicate that at least one match has been found. 1 here means // possibly more matches could be coming. frame_->Client()->ReportFindInPageMatchCount(identifier, 1 /* count */, false /* finalUpdate */); } // There are three cases in which scoping is needed: // // (1) This is an initial find request (|options.findNext| is false). This // will be the first scoping effort for this find session. // // (2) Something has been selected since the last search. This means that we // cannot just increment the current match ordinal; we need to re-generate // it. // // (3) TextFinder::Find() found what should be the next match (|result| is // true), but was unable to activate it (|activeNow| is false). This means // that the text containing this match was dynamically added since the last // scope of the frame. The frame needs to be re-scoped so that any matches // in the new text can be highlighted and included in the reported number of // matches. // // If none of these cases are true, then we just report the current match // count without scoping. if (/* (1) */ options.find_next && /* (2) */ current_selection.IsNull() && /* (3) */ !(result && !active_now)) { // Force report of the actual count. EnsureTextFinder().IncreaseMatchCount(identifier, 0); return; } // Start a new scoping request. If the scoping function determines that it // needs to scope, it will defer until later. EnsureTextFinder().StartScopingStringMatches(identifier, search_text, options); } bool WebLocalFrameImpl::Find(int identifier, const WebString& search_text, const WebFindOptions& options, bool wrap_within_frame, bool* active_now) { return find_in_page_->Find(identifier, search_text, options, wrap_within_frame, active_now); } bool FindInPage::Find(int identifier, const WebString& search_text, const WebFindOptions& options, bool wrap_within_frame, bool* active_now) { if (!frame_->GetFrame()) return false; // Unlikely, but just in case we try to find-in-page on a detached frame. DCHECK(frame_->GetFrame()->GetPage()); // Up-to-date, clean tree is required for finding text in page, since it // relies on TextIterator to look over the text. frame_->GetFrame() ->GetDocument() ->UpdateStyleAndLayoutIgnorePendingStylesheets(); return EnsureTextFinder().Find(identifier, search_text, options, wrap_within_frame, active_now); } void WebLocalFrameImpl::StopFindingForTesting(mojom::StopFindAction action) { find_in_page_->StopFinding(action); } void FindInPage::StopFinding(mojom::StopFindAction action) { WebPlugin* const plugin = GetWebPluginForFind(); if (plugin) { plugin->StopFind(); return; } const bool clear_selection = action == mojom::StopFindAction::kStopFindActionClearSelection; if (clear_selection) frame_->ExecuteCommand(WebString::FromUTF8("Unselect")); if (GetTextFinder()) { if (!clear_selection) GetTextFinder()->SetFindEndstateFocusAndSelection(); GetTextFinder()->StopFindingAndClearSelection(); } if (action == mojom::StopFindAction::kStopFindActionActivateSelection && frame_->IsFocused()) { WebDocument doc = frame_->GetDocument(); if (!doc.IsNull()) { WebElement element = doc.FocusedElement(); if (!element.IsNull()) element.SimulateClick(); } } } int FindInPage::FindMatchMarkersVersion() const { if (GetTextFinder()) return GetTextFinder()->FindMatchMarkersVersion(); return 0; } WebFloatRect FindInPage::ActiveFindMatchRect() { if (GetTextFinder()) return GetTextFinder()->ActiveFindMatchRect(); return WebFloatRect(); } void FindInPage::ActivateNearestFindResult( const WebFloatPoint& point, ActivateNearestFindResultCallback callback) { WebRect active_match_rect; const int ordinal = EnsureTextFinder().SelectNearestFindMatch(point, &active_match_rect); if (ordinal == -1) { // Something went wrong, so send a no-op reply (force the frame to report // the current match count) in case the host is waiting for a response due // to rate-limiting. int number_of_matches = EnsureTextFinder().TotalMatchCount(); std::move(callback).Run(WebRect(), number_of_matches, -1 /* active_match_ordinal */, !EnsureTextFinder().FrameScoping() || !number_of_matches /* final_reply */); return; } // Call callback with current active match's rect and its ordinal, // and don't update total number of matches. std::move(callback).Run(active_match_rect, -1 /* number_of_matches */, ordinal, true /* final_reply*/); } void FindInPage::GetNearestFindResult(const WebFloatPoint& point, GetNearestFindResultCallback callback) { float distance; EnsureTextFinder().NearestFindMatch(point, &distance); std::move(callback).Run(distance); } void FindInPage::FindMatchRects(int current_version, FindMatchRectsCallback callback) { int rects_version = FindMatchMarkersVersion(); Vector<WebFloatRect> rects; if (current_version != rects_version) rects = EnsureTextFinder().FindMatchRects(); std::move(callback).Run(rects_version, rects, ActiveFindMatchRect()); } void FindInPage::ClearActiveFindMatch() { // TODO(rakina): Do collapse selection as this currently does nothing. frame_->ExecuteCommand(WebString::FromUTF8("CollapseSelection")); EnsureTextFinder().ClearActiveFindMatch(); } void WebLocalFrameImpl::SetTickmarks(const WebVector<WebRect>& tickmarks) { find_in_page_->SetTickmarks(tickmarks); } void FindInPage::SetTickmarks(const WebVector<WebRect>& tickmarks) { if (frame_->GetFrameView()) { Vector<IntRect> tickmarks_converted(tickmarks.size()); for (size_t i = 0; i < tickmarks.size(); ++i) tickmarks_converted[i] = tickmarks[i]; frame_->GetFrameView()->SetTickmarks(tickmarks_converted); } } TextFinder* WebLocalFrameImpl::GetTextFinder() const { return find_in_page_->GetTextFinder(); } TextFinder* FindInPage::GetTextFinder() const { return text_finder_; } TextFinder& WebLocalFrameImpl::EnsureTextFinder() { return find_in_page_->EnsureTextFinder(); } TextFinder& FindInPage::EnsureTextFinder() { if (!text_finder_) text_finder_ = TextFinder::Create(*frame_); return *text_finder_; } void FindInPage::SetPluginFindHandler(WebPluginContainer* plugin) { plugin_find_handler_ = plugin; } WebPluginContainer* FindInPage::PluginFindHandler() const { return plugin_find_handler_; } WebPlugin* WebLocalFrameImpl::GetWebPluginForFind() { return find_in_page_->GetWebPluginForFind(); } WebPlugin* FindInPage::GetWebPluginForFind() { if (frame_->GetDocument().IsPluginDocument()) return frame_->GetDocument().To<WebPluginDocument>().Plugin(); if (plugin_find_handler_) return plugin_find_handler_->Plugin(); return nullptr; } void FindInPage::BindToRequest( mojom::blink::FindInPageAssociatedRequest request) { binding_.Bind(std::move(request)); } void FindInPage::Dispose() { binding_.Close(); } } // namespace blink
3,965
4,606
<filename>examples/docs_snippets_crag/docs_snippets_crag/guides/dagster/graph_job_op/simple_pipeline.py from dagster import pipeline, solid @solid def do_something(): ... @pipeline def do_it_all(): do_something()
90
4,138
<filename>cc/src/main/java/com/billy/cc/core/component/BaseForwardInterceptor.java<gh_stars>1000+ package com.billy.cc.core.component; import android.text.TextUtils; /** * 转发组件调用 <br> * 注:如果需要做成全局拦截器,需要额外实现 {@link IGlobalCCInterceptor}接口 * @author billy.qi * @since 18/9/2 13:40 */ public abstract class BaseForwardInterceptor implements ICCInterceptor { @Override public CCResult intercept(Chain chain) { CC cc = chain.getCC(); String forwardComponentName = shouldForwardCC(cc, cc.getComponentName()); if (!TextUtils.isEmpty(forwardComponentName)) { cc.forwardTo(forwardComponentName); } return chain.proceed(); } /** * 根据当前组件调用对象获取需要转发到的组件名称 * @param cc 当前组件调用对象 * @param componentName 当前调用的组件名称 * @return 转发的目标组件名称(为null则不执行转发) */ protected abstract String shouldForwardCC(CC cc, String componentName); }
516
2,151
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_BOOKMARKS_BOOKMARK_BAR_VIEW_OBSERVER_H_ #define CHROME_BROWSER_UI_VIEWS_BOOKMARKS_BOOKMARK_BAR_VIEW_OBSERVER_H_ class BookmarkBarViewObserver { public: virtual void OnBookmarkBarVisibilityChanged() = 0; protected: ~BookmarkBarViewObserver() {} }; #endif // CHROME_BROWSER_UI_VIEWS_BOOKMARKS_BOOKMARK_BAR_VIEW_OBSERVER_H_
199
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.containerregistry.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** The Active Directory Object that will be used for authenticating the token of a container registry. */ @Fluent public final class ActiveDirectoryObject { @JsonIgnore private final ClientLogger logger = new ClientLogger(ActiveDirectoryObject.class); /* * The user/group/application object ID for Active Directory Object that * will be used for authenticating the token of a container registry. */ @JsonProperty(value = "objectId") private String objectId; /* * The tenant ID of user/group/application object Active Directory Object * that will be used for authenticating the token of a container registry. */ @JsonProperty(value = "tenantId") private String tenantId; /** * Get the objectId property: The user/group/application object ID for Active Directory Object that will be used for * authenticating the token of a container registry. * * @return the objectId value. */ public String objectId() { return this.objectId; } /** * Set the objectId property: The user/group/application object ID for Active Directory Object that will be used for * authenticating the token of a container registry. * * @param objectId the objectId value to set. * @return the ActiveDirectoryObject object itself. */ public ActiveDirectoryObject withObjectId(String objectId) { this.objectId = objectId; return this; } /** * Get the tenantId property: The tenant ID of user/group/application object Active Directory Object that will be * used for authenticating the token of a container registry. * * @return the tenantId value. */ public String tenantId() { return this.tenantId; } /** * Set the tenantId property: The tenant ID of user/group/application object Active Directory Object that will be * used for authenticating the token of a container registry. * * @param tenantId the tenantId value to set. * @return the ActiveDirectoryObject object itself. */ public ActiveDirectoryObject withTenantId(String tenantId) { this.tenantId = tenantId; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
892
435
<reponame>amaajemyfren/data { "copyright_text": "Creative Commons Attribution license (reuse allowed)", "description": "Nous sommes une entreprise de maintenance Informatique.\n\nNous sommes \u00e9galement fain\u00e9ants et enfin nous adorons l'automatisation.\n\nD\u00e9couvrez nos outils de pr\u00e9dilections pour automatiser :\n\n- La configuration de nos serveurs\n- La configuration des clients Windows / Mac / Linux\n\nNous aborderons le design de SaltStack et en quoi cette solution se\ndiff\u00e9rencie de Ansible / Puppet et les autres gestionnaires de\nconfiguration.\n\nDes concepts seront abord\u00e9s sur la puissance offerte par le bazard.\n", "duration": 1735, "language": "fra", "recorded": "2018-10-06", "related_urls": [ { "label": "schedule", "url": "https://www.pycon.fr/2018/program/" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/gfQAFEy_0Nw/maxresdefault.jpg", "title": "Manager un parc avec SaltStack", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=gfQAFEy_0Nw" } ] }
459
10,225
<reponame>CraigMcDonaldCodes/quarkus package io.quarkus.spring.security.deployment; import java.lang.reflect.Modifier; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.FieldInfo; import org.jboss.jandex.IndexView; import org.jboss.jandex.MethodInfo; import io.quarkus.spring.security.runtime.interceptor.SpringSecurityRecorder; final class HasRoleValueUtil { private static final String BEAN_FIELD_REGEX = "@(\\w+)\\.(\\w+)"; private static final Pattern BEAN_FIELD_PATTERN = Pattern.compile(BEAN_FIELD_REGEX); private HasRoleValueUtil() { } static Supplier<String[]> getHasRoleValueProducer(String hasRoleValue, MethodInfo methodInfo, IndexView index, Map<String, DotName> springBeansNameToDotName, Map<String, ClassInfo> springBeansNameToClassInfo, Set<String> beansReferencedInPreAuthorized, SpringSecurityRecorder recorder) { if (hasRoleValue.startsWith("'") && hasRoleValue.endsWith("'")) { return recorder.staticHasRole(hasRoleValue.replace("'", "")); } else if (hasRoleValue.startsWith("@")) { Matcher beanFieldMatcher = BEAN_FIELD_PATTERN.matcher(hasRoleValue); if (!beanFieldMatcher.find()) { throw SpringSecurityProcessorUtil.createGenericMalformedException(methodInfo, hasRoleValue); } String beanName = beanFieldMatcher.group(1); ClassInfo beanClassInfo = SpringSecurityProcessorUtil.getClassInfoFromBeanName(beanName, index, springBeansNameToDotName, springBeansNameToClassInfo, hasRoleValue, methodInfo); String fieldName = beanFieldMatcher.group(2); FieldInfo fieldInfo = beanClassInfo.field(fieldName); //TODO: detect normal scoped beans and throw an exception, as it will read the field from the proxy if ((fieldInfo == null) || !Modifier.isPublic(fieldInfo.flags()) || !DotNames.STRING.equals(fieldInfo.type().name())) { throw new IllegalArgumentException("Bean named '" + beanName + "' found in expression '" + hasRoleValue + "' in the @PreAuthorize annotation on method " + methodInfo.name() + " of class " + methodInfo.declaringClass() + " does not have a public field named '" + fieldName + "' of type String"); } beansReferencedInPreAuthorized.add(fieldInfo.declaringClass().name().toString()); return recorder.fromBeanField(fieldInfo.declaringClass().name().toString(), fieldName); } else { throw SpringSecurityProcessorUtil.createGenericMalformedException(methodInfo, hasRoleValue); } } }
1,182
313
//------------------------------------------------------------------------------ // gb_get_sparsity: determine the sparsity of a matrix result //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, <NAME>, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: GPL-3.0-or-later //------------------------------------------------------------------------------ // gb_get_sparsity determines the sparsity of a result matrix C, which may be // computed from one or two input matrices A and B. The following rules are // used, in order: // (1) GraphBLAS operations of the form C = GrB.method (Cin, ...) use the // sparsity of Cin for the new matrix C. // (2) If the sparsity is determined by the descriptor to the method, then that // determines the sparsity of C. // (3) If both A and B are present and both matrices (not scalars), the // sparsity of C is A_sparsity | B_sparsity // (4) If A is present (and not a scalar), then the sparsity of C is A_sparsity. // (5) If B is present (and not a scalar), then the sparsity of C is B_sparsity. // (6) Otherwise, the global default sparsity is used for C. #include "gb_interface.h" GxB_Format_Value gb_get_sparsity // 0 to 15 ( GrB_Matrix A, // may be NULL GrB_Matrix B, // may be NULL int sparsity_default // may be 0 ) { int sparsity ; int A_sparsity = 0 ; int B_sparsity = 0 ; GrB_Index nrows, ncols ; //-------------------------------------------------------------------------- // get the sparsity of the matrices A and B //-------------------------------------------------------------------------- if (A != NULL) { OK (GrB_Matrix_nrows (&nrows, A)) ; OK (GrB_Matrix_ncols (&ncols, A)) ; if (nrows > 1 || ncols > 1) { // A is a vector or matrix, not a scalar OK (GxB_Matrix_Option_get (A, GxB_SPARSITY_CONTROL, &A_sparsity)) ; } } if (B != NULL) { OK (GrB_Matrix_nrows (&nrows, B)) ; OK (GrB_Matrix_ncols (&ncols, B)) ; if (nrows > 1 || ncols > 1) { // B is a vector or matrix, not a scalar OK (GxB_Matrix_Option_get (B, GxB_SPARSITY_CONTROL, &B_sparsity)) ; } } //-------------------------------------------------------------------------- // determine the sparsity of C //-------------------------------------------------------------------------- if (sparsity_default != 0) { // (2) the sparsity is defined by the descriptor to the method sparsity = sparsity_default ; } else if (A_sparsity > 0 && B_sparsity > 0) { // (3) C is determined by the sparsity of A and B sparsity = A_sparsity | B_sparsity ; } else if (A_sparsity > 0) { // (4) get the sparsity of A sparsity = A_sparsity ; } else if (B_sparsity > 0) { // (5) get the sparsity of B sparsity = B_sparsity ; } else { // (6) use the default sparsity sparsity = GxB_AUTO_SPARSITY ; } return (sparsity) ; }
1,248
1,450
<reponame>jarbus/neural-mmo """ The MIT License (MIT) Copyright (c) 2013 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ """ Camera module ============= In this module base camera class is implemented. """ __all__ = ('Camera', ) import math from kivy.event import EventDispatcher from kivy.properties import NumericProperty, ListProperty, ObjectProperty, \ AliasProperty from kivy.graphics.transformation import Matrix from ..math.vectors import Vector3 class Camera(EventDispatcher): """ Base camera class """ scale = NumericProperty(1.0) up = ObjectProperty(Vector3(0, 1, 0)) def __init__(self): super(Camera, self).__init__() self.projection_matrix = Matrix() self.modelview_matrix = Matrix() self.renderer = None # renderer camera is bound to self._position = Vector3(0, 0, 0) self._position.set_change_cb(self.on_pos_changed) self._look_at = None self.look_at(Vector3(0, 0, -1)) def _set_position(self, val): if isinstance(val, Vector3): self._position = val else: self._position = Vector3(val) self._position.set_change_cb(self.on_pos_changed) self.look_at(self._look_at) self.update() def _get_position(self): return self._position position = AliasProperty(_get_position, _set_position) pos = position # just shortcut def on_pos_changed(self, coord, v): """ Camera position was changed """ self.look_at(self._look_at) self.update() def on_up(self, instance, up): """ Camera up vector was changed """ pass def on_scale(self, instance, scale): """ Handler for change scale parameter event """ def look_at(self, *v): if len(v) == 1: v = v[0] m = Matrix() pos = self._position * -1 m = m.look_at(pos[0], pos[1], pos[2], v[0], v[1], v[2], self.up[0], self.up[1], self.up[2]) self.modelview_matrix = m self._look_at = v self.update() def bind_to(self, renderer): """ Bind this camera to renderer """ self.renderer = renderer def update(self): if self.renderer: self.renderer._update_matrices() def update_projection_matrix(self): """ This function should be overridden in the subclasses """
1,281
1,114
<reponame>HookedBehemoth/libnx #include <string.h> #include <stdlib.h> #include <arm_neon.h> #include "result.h" #include "crypto/aes.h" /* Helper macros to setup for inline AES asm */ #define AES_ENC_DEC_SETUP_VARS() \ uint8x16_t tmp = vld1q_u8((const uint8_t *)src); \ uint8x16_t tmp2 #define AES_ENC_DEC_OUTPUT_VARS() \ [tmp]"+w"(tmp), [tmp2]"=w"(tmp2) #define AES_ENC_DEC_STORE_RESULT() \ vst1q_u8((uint8_t *)dst, tmp) /* Helper macros to do AES encryption, via inline asm. */ #define AES_ENC_ROUND(n) \ "ldr %q[tmp2], %[round_key_" #n "]\n" \ "aese %[tmp].16b, %[tmp2].16b\n" \ "aesmc %[tmp].16b, %[tmp].16b\n" #define AES_ENC_FINAL_ROUND() \ "ldr %q[tmp2], %[round_key_second_last]\n" \ "aese %[tmp].16b, %[tmp2].16b\n" \ "ldr %q[tmp2], %[round_key_last]\n" \ "eor %[tmp].16b, %[tmp].16b, %[tmp2].16b" #define AES_ENC_INPUT_ROUND_KEY(num_rounds, n) \ [round_key_##n]"m"(ctx->round_keys[(n-1)]) #define AES_ENC_INPUT_LAST_ROUND_KEYS(num_rounds) \ [round_key_second_last]"m"(ctx->round_keys[(num_rounds - 1)]), \ [round_key_last]"m"(ctx->round_keys[(num_rounds)]) /* Helper macros to do AES decryption, via inline asm. */ #define AES_DEC_ROUND(n) \ "ldr %q[tmp2], %[round_key_" #n "]\n" \ "aesd %[tmp].16b, %[tmp2].16b\n" \ "aesimc %[tmp].16b, %[tmp].16b\n" #define AES_DEC_FINAL_ROUND() \ "ldr %q[tmp2], %[round_key_second_last]\n" \ "aesd %[tmp].16b, %[tmp2].16b\n" \ "ldr %q[tmp2], %[round_key_last]\n" \ "eor %[tmp].16b, %[tmp].16b, %[tmp2].16b" #define AES_DEC_INPUT_ROUND_KEY(num_rounds, n) \ [round_key_##n]"m"(ctx->round_keys[(num_rounds + 1 - n)]) #define AES_DEC_INPUT_LAST_ROUND_KEYS(num_rounds) \ [round_key_second_last]"m"(ctx->round_keys[1]), \ [round_key_last]"m"(ctx->round_keys[0]) /* Lookup tables for key scheduling. */ static const u8 s_subBytesTable[0x100] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; static const u8 s_rconTable[16] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f }; static inline u32 _subBytes(u32 tmp) { return (s_subBytesTable[(tmp >> 0x00) & 0xFF] << 0x00) | (s_subBytesTable[(tmp >> 0x08) & 0xFF] << 0x08) | (s_subBytesTable[(tmp >> 0x10) & 0xFF] << 0x10) | (s_subBytesTable[(tmp >> 0x18) & 0xFF] << 0x18); } static inline u32 _rotateBytes(u32 tmp) { return (((tmp >> 0x00) & 0xFF) << 0x18) | (((tmp >> 0x08) & 0xFF) << 0x00) | (((tmp >> 0x10) & 0xFF) << 0x08) | (((tmp >> 0x18) & 0xFF) << 0x10); } void aes128ContextCreate(Aes128Context *out, const void *key, bool is_encryptor) { u32 *round_keys_u32 = (u32 *)out->round_keys; /* Copy in first round key. */ memcpy(round_keys_u32, key, AES_128_KEY_SIZE); u32 tmp = round_keys_u32[AES_128_U32_PER_KEY - 1]; /* Do AES key scheduling. */ for (size_t i = AES_128_U32_PER_KEY; i < sizeof(out->round_keys) / sizeof(u32); i++) { /* First word of key needs special handling. */ if (i % AES_128_U32_PER_KEY == 0) { tmp = _rotateBytes(_subBytes(tmp)) ^ (u32)s_rconTable[(i / AES_128_U32_PER_KEY) - 1]; } tmp ^= round_keys_u32[i - AES_128_U32_PER_KEY]; round_keys_u32[i] = tmp; } /* If decryption, calculate inverse mix columns on round keys ahead of time to speed up decryption. */ if (!is_encryptor) { for (size_t i = 1; i < AES_128_NUM_ROUNDS; i++) { uint8x16_t tmp_key = vld1q_u8(out->round_keys[i]); tmp_key = vaesimcq_u8(tmp_key); vst1q_u8(out->round_keys[i], tmp_key); } } } void aes192ContextCreate(Aes192Context *out, const void *key, bool is_encryptor) { u32 *round_keys_u32 = (u32 *)out->round_keys; /* Copy in first round key. */ memcpy(round_keys_u32, key, AES_192_KEY_SIZE); u32 tmp = round_keys_u32[AES_192_U32_PER_KEY - 1]; /* Do AES key scheduling. */ for (size_t i = AES_192_U32_PER_KEY; i < sizeof(out->round_keys) / sizeof(u32); i++) { /* First word of key needs special handling. */ if (i % AES_192_U32_PER_KEY == 0) { tmp = _rotateBytes(_subBytes(tmp)) ^ (u32)s_rconTable[(i / AES_192_U32_PER_KEY) - 1]; } tmp ^= round_keys_u32[i - AES_192_U32_PER_KEY]; round_keys_u32[i] = tmp; } /* If decryption, calculate inverse mix columns on round keys ahead of time to speed up decryption. */ if (!is_encryptor) { for (size_t i = 1; i < AES_192_NUM_ROUNDS; i++) { uint8x16_t tmp_key = vld1q_u8(out->round_keys[i]); tmp_key = vaesimcq_u8(tmp_key); vst1q_u8(out->round_keys[i], tmp_key); } } } void aes256ContextCreate(Aes256Context *out, const void *key, bool is_encryptor) { u32 *round_keys_u32 = (u32 *)out->round_keys; /* Copy in first round key. */ memcpy(round_keys_u32, key, AES_256_KEY_SIZE); u32 tmp = round_keys_u32[AES_256_U32_PER_KEY - 1]; /* Do AES key scheduling. */ for (size_t i = AES_256_U32_PER_KEY; i < sizeof(out->round_keys) / sizeof(u32); i++) { /* First word of key needs special handling. */ if (i % AES_256_U32_PER_KEY == 0) { tmp = _rotateBytes(_subBytes(tmp)) ^ (u32)s_rconTable[(i / AES_256_U32_PER_KEY) - 1]; } else if (i % AES_256_U32_PER_KEY == (AES_256_U32_PER_KEY / 2)) { /* AES-256 does sub bytes on first word of second key */ tmp = _subBytes(tmp); } tmp ^= round_keys_u32[i - AES_256_U32_PER_KEY]; round_keys_u32[i] = tmp; } /* If decryption, calculate inverse mix columns on round keys ahead of time to speed up decryption. */ if (!is_encryptor) { for (size_t i = 1; i < AES_256_NUM_ROUNDS; i++) { uint8x16_t tmp_key = vld1q_u8(out->round_keys[i]); tmp_key = vaesimcq_u8(tmp_key); vst1q_u8(out->round_keys[i], tmp_key); } } } void aes128EncryptBlock(const Aes128Context *ctx, void *dst, const void *src) { /* Setup for asm */ AES_ENC_DEC_SETUP_VARS(); /* Use optimized assembly to do all rounds. */ __asm__ __volatile__ ( AES_ENC_ROUND(1) AES_ENC_ROUND(2) AES_ENC_ROUND(3) AES_ENC_ROUND(4) AES_ENC_ROUND(5) AES_ENC_ROUND(6) AES_ENC_ROUND(7) AES_ENC_ROUND(8) AES_ENC_ROUND(9) AES_ENC_FINAL_ROUND() : AES_ENC_DEC_OUTPUT_VARS() : AES_ENC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 1), AES_ENC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 2), AES_ENC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 3), AES_ENC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 4), AES_ENC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 5), AES_ENC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 6), AES_ENC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 7), AES_ENC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 8), AES_ENC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 9), AES_ENC_INPUT_LAST_ROUND_KEYS(AES_128_NUM_ROUNDS) ); /* Store result. */ AES_ENC_DEC_STORE_RESULT(); } void aes192EncryptBlock(const Aes192Context *ctx, void *dst, const void *src) { /* Setup for asm */ AES_ENC_DEC_SETUP_VARS(); /* Use optimized assembly to do all rounds. */ __asm__ __volatile__ ( AES_ENC_ROUND(1) AES_ENC_ROUND(2) AES_ENC_ROUND(3) AES_ENC_ROUND(4) AES_ENC_ROUND(5) AES_ENC_ROUND(6) AES_ENC_ROUND(7) AES_ENC_ROUND(8) AES_ENC_ROUND(9) AES_ENC_ROUND(10) AES_ENC_ROUND(11) AES_ENC_FINAL_ROUND() : AES_ENC_DEC_OUTPUT_VARS() : AES_ENC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 1), AES_ENC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 2), AES_ENC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 3), AES_ENC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 4), AES_ENC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 5), AES_ENC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 6), AES_ENC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 7), AES_ENC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 8), AES_ENC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 9), AES_ENC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 10), AES_ENC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 11), AES_ENC_INPUT_LAST_ROUND_KEYS(AES_192_NUM_ROUNDS) ); /* Store result. */ AES_ENC_DEC_STORE_RESULT(); } void aes256EncryptBlock(const Aes256Context *ctx, void *dst, const void *src) { /* Setup for asm */ AES_ENC_DEC_SETUP_VARS(); /* Use optimized assembly to do all rounds. */ __asm__ __volatile__ ( AES_ENC_ROUND(1) AES_ENC_ROUND(2) AES_ENC_ROUND(3) AES_ENC_ROUND(4) AES_ENC_ROUND(5) AES_ENC_ROUND(6) AES_ENC_ROUND(7) AES_ENC_ROUND(8) AES_ENC_ROUND(9) AES_ENC_ROUND(10) AES_ENC_ROUND(11) AES_ENC_ROUND(12) AES_ENC_ROUND(13) AES_ENC_FINAL_ROUND() : AES_ENC_DEC_OUTPUT_VARS() : AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 1), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 2), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 3), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 4), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 5), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 6), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 7), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 8), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 9), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 10), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 11), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 12), AES_ENC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 13), AES_ENC_INPUT_LAST_ROUND_KEYS(AES_256_NUM_ROUNDS) ); /* Store result. */ AES_ENC_DEC_STORE_RESULT(); } void aes128DecryptBlock(const Aes128Context *ctx, void *dst, const void *src) { /* Setup for asm */ AES_ENC_DEC_SETUP_VARS(); /* Use optimized assembly to do all rounds. */ __asm__ __volatile__ ( AES_DEC_ROUND(1) AES_DEC_ROUND(2) AES_DEC_ROUND(3) AES_DEC_ROUND(4) AES_DEC_ROUND(5) AES_DEC_ROUND(6) AES_DEC_ROUND(7) AES_DEC_ROUND(8) AES_DEC_ROUND(9) AES_DEC_FINAL_ROUND() : AES_ENC_DEC_OUTPUT_VARS() : AES_DEC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 1), AES_DEC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 2), AES_DEC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 3), AES_DEC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 4), AES_DEC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 5), AES_DEC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 6), AES_DEC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 7), AES_DEC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 8), AES_DEC_INPUT_ROUND_KEY(AES_128_NUM_ROUNDS, 9), AES_DEC_INPUT_LAST_ROUND_KEYS(AES_128_NUM_ROUNDS) ); /* Store result. */ AES_ENC_DEC_STORE_RESULT(); } void aes192DecryptBlock(const Aes192Context *ctx, void *dst, const void *src) { /* Setup for asm */ AES_ENC_DEC_SETUP_VARS(); /* Use optimized assembly to do all rounds. */ __asm__ __volatile__ ( AES_DEC_ROUND(1) AES_DEC_ROUND(2) AES_DEC_ROUND(3) AES_DEC_ROUND(4) AES_DEC_ROUND(5) AES_DEC_ROUND(6) AES_DEC_ROUND(7) AES_DEC_ROUND(8) AES_DEC_ROUND(9) AES_DEC_ROUND(10) AES_DEC_ROUND(11) AES_DEC_FINAL_ROUND() : AES_ENC_DEC_OUTPUT_VARS() : AES_DEC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 1), AES_DEC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 2), AES_DEC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 3), AES_DEC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 4), AES_DEC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 5), AES_DEC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 6), AES_DEC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 7), AES_DEC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 8), AES_DEC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 9), AES_DEC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 10), AES_DEC_INPUT_ROUND_KEY(AES_192_NUM_ROUNDS, 11), AES_DEC_INPUT_LAST_ROUND_KEYS(AES_192_NUM_ROUNDS) ); /* Store result. */ AES_ENC_DEC_STORE_RESULT(); } void aes256DecryptBlock(const Aes256Context *ctx, void *dst, const void *src) { /* Setup for asm */ AES_ENC_DEC_SETUP_VARS(); /* Use optimized assembly to do all rounds. */ __asm__ __volatile__ ( AES_DEC_ROUND(1) AES_DEC_ROUND(2) AES_DEC_ROUND(3) AES_DEC_ROUND(4) AES_DEC_ROUND(5) AES_DEC_ROUND(6) AES_DEC_ROUND(7) AES_DEC_ROUND(8) AES_DEC_ROUND(9) AES_DEC_ROUND(10) AES_DEC_ROUND(11) AES_DEC_ROUND(12) AES_DEC_ROUND(13) AES_DEC_FINAL_ROUND() : AES_ENC_DEC_OUTPUT_VARS() : AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 1), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 2), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 3), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 4), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 5), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 6), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 7), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 8), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 9), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 10), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 11), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 12), AES_DEC_INPUT_ROUND_KEY(AES_256_NUM_ROUNDS, 13), AES_DEC_INPUT_LAST_ROUND_KEYS(AES_256_NUM_ROUNDS) ); /* Store result. */ AES_ENC_DEC_STORE_RESULT(); }
8,615
1,005
<reponame>wes-chen/Adabelief-Optimizer<filename>pypi_packages/adabelief_pytorch0.2.1/adabelief_pytorch/__init__.py from .AdaBelief import AdaBelief __version__='0.2.1'
74
897
<gh_stars>100-1000 import java.util.*; public class CocktailSort { private static void swap(int arr[], int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } private static void cocktailSort(int arr[]) { boolean isSwapped = true; int begin = 0; int last = arr.length-1; while (isSwapped == true) { // set isSwapped to false so that if nothing gets // sorted in this iteration we can break right away isSwapped = false; for(int i = begin; i < last; i++) { // going forward if (arr[i] > arr[i+1]) { swap(arr, i, i+1); isSwapped = true; } } // if nothing swapped then the array is already sorted if (isSwapped == false) break; // else, reset isSwapped to check for next iteration isSwapped = false; // since largest item is now in last. we only need // to check for one place before it last -= 1; for (int i = last; i >= begin; i--) { // going backward if (arr[i] > arr[i+1]) { swap(arr, i, i+1); isSwapped = true; } } // now the smallest number is on first place // so move starting point one position ahead begin++; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); //taking input array System.out.println("Enter size of array:"); int size = sc.nextInt(); int arr[] = new int[size]; System.out.println("Enter array elements:"); for (int i=0; i<size; i++) { arr[i] = sc.nextInt(); } sc.close(); // before sorting System.out.println("Array before Cocktail sort:"); for (int i=0; i<arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); cocktailSort(arr); // after sorting System.out.println("Array after Cocktail sort:"); for (int i=0; i<arr.length; i++) { System.out.print(arr[i] + " "); } } } /** * Sample input/output * Enter size of array: * 10 * Enter array elements: * 88 26 77 49 91 62 33 85 99 11 * Array before Cocktail sort: * 88 26 77 49 91 62 33 85 99 11 * Array after Cocktail sort: * 11 26 33 49 62 77 85 88 91 99 * * Enter size of array: * 7 * Enter array elements: * 5 1 4 2 8 0 2 * Array before Cocktail sort: * 5 1 4 2 8 0 2 * Array after Cocktail sort: * 0 1 2 2 4 5 8 * * Worst case Time complexity = O(n*n) * Best case Time complexity = O(n) when array is already sorted * Auxillary space = O(1) */
1,374
777
// Copyright 2017 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. #ifndef UI_EVENTS_OZONE_EVDEV_SCOPED_INPUT_DEVICE_H_ #define UI_EVENTS_OZONE_EVDEV_SCOPED_INPUT_DEVICE_H_ #include "base/scoped_generic.h" #include "ui/events/ozone/evdev/events_ozone_evdev_export.h" namespace ui { namespace internal { struct EVENTS_OZONE_EVDEV_EXPORT ScopedInputDeviceCloseTraits { static int InvalidValue() { return -1; } static void Free(int fd); }; } // namespace internal typedef base::ScopedGeneric<int, internal::ScopedInputDeviceCloseTraits> ScopedInputDevice; } // namespace ui #endif // UI_EVENTS_OZONE_EVDEV_SCOPED_INPUT_DEVICE_H_
274
599
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 TH<NAME>, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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 datetime import logging import urllib import pytz from dateutil import parser from furl import furl logger = logging.getLogger(__name__) def parse_chart_time(time_string): # 外部输入的 created 出现各种形式 # 1. yaml load 解析出来是 datetime 类型 # 2. 字符串,形如: `2018-02-27T17:49:56.232875637Z` # 3. 字符串,形如: `2018-07-30T14:22:31Z` try: time_value = parser.parse(time_string) except Exception as e: logger.exception("dateutil.parser.parse:%s failed, %s", time_string, e) # if failed, run history implemente if not time_string: raise ValueError(time_string) if isinstance(time_string, datetime.datetime): time_value = time_string.astimezone(pytz.utc) elif isinstance(time_string, str): try: time_value = datetime.datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S.%fZ').astimezone(pytz.utc) except Exception: time_value = datetime.datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%SZ').astimezone(pytz.utc) else: raise ValueError(time_string) return time_value class EmptyVaue(Exception): pass def fix_rancher_value_by_type(value, item_type): result = value if item_type == "boolean": if isinstance(value, bool): result = value else: result = True if value == "true" else False elif item_type == "int": # empty value should be skipped if isinstance(value, str) and not value.strip(): raise EmptyVaue("value is: %s" % value) result = int(value) elif item_type == "float": # empty value should be skipped if isinstance(value, str) and not value.strip(): raise EmptyVaue("value is: %s" % value) result = float(value) elif item_type in ["string", "password"]: result = str(value) else: result = str(value) return result def merge_rancher_answers(answers, customs): parameters = dict() if not isinstance(customs, list): raise ValueError(customs) for item in customs: # TODO 前端需要增加类型支持 parameters[item["name"]] = item["value"] if not isinstance(answers, list): return parameters # raise ValueError(answers) for item in answers: item_type = item.get("type") value = item["value"] try: value = fix_rancher_value_by_type(value, item_type) except EmptyVaue: continue else: parameters[item["name"]] = value return parameters def fix_chart_url(url, repo_url): # 修正urls(chartmuseum默认没有带repo.url) # parameters: # url: charts/chartmuseum-curator-0.9.0.tgz # repo_url: http://charts.bking.com # ==> http://charts.bking.com/charts/chartmuseum-curator-0.9.0.tgz # s-1: path ==> integrated url hostname = urllib.parse.urlparse(repo_url).netloc if hostname not in url: integrated_url = urllib.parse.urljoin(repo_url, url) else: integrated_url = url # s-2: replace '//' with '/' f = furl(integrated_url) f.path.segments = [x for x in f.path.segments if x] return f.url
1,745
634
/* * Copyright 2013-2016 consulo.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.sandboxPlugin.ide.fileEditor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorPolicy; import com.intellij.openapi.fileEditor.FileEditorProvider; import com.intellij.openapi.fileEditor.FileEditorState; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import consulo.ui.annotation.RequiredUIAccess; import org.jdom.Element; import javax.annotation.Nonnull; import consulo.sandboxPlugin.lang.SandFileType; /** * @author VISTALL * @since 30.05.14 */ public class SandFileEditorProvider implements FileEditorProvider { @Override public boolean accept(@Nonnull Project project, @Nonnull VirtualFile file) { return file.getFileType() == SandFileType.INSTANCE; } @RequiredUIAccess @Nonnull @Override public FileEditor createEditor(@Nonnull Project project, @Nonnull VirtualFile file) { return new SandFileEditor(); } @Override public void disposeEditor(@Nonnull FileEditor editor) { } @Nonnull @Override public FileEditorState readState(@Nonnull Element sourceElement, @Nonnull Project project, @Nonnull VirtualFile file) { return FileEditorState.INSTANCE; } @Override public void writeState(@Nonnull FileEditorState state, @Nonnull Project project, @Nonnull Element targetElement) { } @Nonnull @Override public String getEditorTypeId() { return "sand-editor"; } @Nonnull @Override public FileEditorPolicy getPolicy() { return FileEditorPolicy.PLACE_AFTER_DEFAULT_EDITOR; } }
640
335
{ "word": "Hodgepodge", "definitions": [ "A confused mixture; a hotchpotch." ], "parts-of-speech": "Noun" }
64
2,073
/* * 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.mahout.classifier.sgd; import com.google.common.collect.ImmutableMap; import org.apache.mahout.common.MahoutTestCase; import org.apache.mahout.math.DenseVector; import org.apache.mahout.math.Vector; import org.apache.mahout.vectorizer.encoders.Dictionary; import org.junit.Test; public final class CsvRecordFactoryTest extends MahoutTestCase { @Test public void testAddToVector() { RecordFactory csv = new CsvRecordFactory("y", ImmutableMap.of("x1", "n", "x2", "w", "x3", "t")); csv.firstLine("z,x1,y,x2,x3,q"); csv.maxTargetValue(2); Vector v = new DenseVector(2000); int t = csv.processLine("ignore,3.1,yes,tiger, \"this is text\",ignore", v); assertEquals(0, t); // should have 9 values set assertEquals(9.0, v.norm(0), 0); // all should be = 1 except for the 3.1 assertEquals(3.1, v.maxValue(), 0); v.set(v.maxValueIndex(), 0); assertEquals(8.0, v.norm(0), 0); assertEquals(8.0, v.norm(1), 0); assertEquals(1.0, v.maxValue(), 0); v.assign(0); t = csv.processLine("ignore,5.3,no,line, \"and more text and more\",ignore", v); assertEquals(1, t); // should have 9 values set assertEquals(9.0, v.norm(0), 0); // all should be = 1 except for the 3.1 assertEquals(5.3, v.maxValue(), 0); v.set(v.maxValueIndex(), 0); assertEquals(8.0, v.norm(0), 0); assertEquals(10.339850002884626, v.norm(1), 1.0e-6); assertEquals(1.5849625007211563, v.maxValue(), 1.0e-6); v.assign(0); t = csv.processLine("ignore,5.3,invalid,line, \"and more text and more\",ignore", v); assertEquals(1, t); // should have 9 values set assertEquals(9.0, v.norm(0), 0); // all should be = 1 except for the 3.1 assertEquals(5.3, v.maxValue(), 0); v.set(v.maxValueIndex(), 0); assertEquals(8.0, v.norm(0), 0); assertEquals(10.339850002884626, v.norm(1), 1.0e-6); assertEquals(1.5849625007211563, v.maxValue(), 1.0e-6); } @Test public void testDictionaryOrder() { Dictionary dict = new Dictionary(); dict.intern("a"); dict.intern("d"); dict.intern("c"); dict.intern("b"); dict.intern("qrz"); assertEquals("[a, d, c, b, qrz]", dict.values().toString()); Dictionary dict2 = Dictionary.fromList(dict.values()); assertEquals("[a, d, c, b, qrz]", dict2.values().toString()); } }
1,206
672
<gh_stars>100-1000 /* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 "URLFunctions.h" #include "velox/type/Type.h" namespace facebook::velox::functions { bool matchAuthorityAndPath( const boost::cmatch& urlMatch, boost::cmatch& authAndPathMatch, boost::cmatch& authorityMatch, bool& hasAuthority) { static const boost::regex kAuthorityAndPathRegex("//([^/]*)(/.*)?"); auto authorityAndPath = submatch(urlMatch, 2); if (!boost::regex_match( authorityAndPath.begin(), authorityAndPath.end(), authAndPathMatch, kAuthorityAndPathRegex)) { // Does not start with //, doesn't have authority. hasAuthority = false; return true; } static const boost::regex kAuthorityRegex( "(?:([^@:]*)(?::([^@]*))?@)?" // username, password. "(\\[[^\\]]*\\]|[^\\[:]*)" // host (IP-literal (e.g. '['+IPv6+']', // dotted-IPv4, or named host). "(?::(\\d*))?"); // port. const auto authority = authAndPathMatch[1]; if (!boost::regex_match( authority.first, authority.second, authorityMatch, kAuthorityRegex)) { return false; // Invalid URI Authority. } hasAuthority = true; return true; } } // namespace facebook::velox::functions
638
852
#include "CondFormats/L1TObjects/interface/L1TMuonGlobalParams.h" #include "FWCore/Utilities/interface/typelookup.h" TYPELOOKUP_DATA_REG(L1TMuonGlobalParams);
67
1,056
/* * 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.netbeans.modules.java.api.common.queries; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectManager; import org.netbeans.junit.NbTestCase; import org.netbeans.modules.java.api.common.SourceRoots; import org.netbeans.modules.java.api.common.TestProject; import org.netbeans.modules.java.api.common.impl.ModuleTestUtilities; import org.netbeans.modules.java.api.common.project.ProjectProperties; import org.netbeans.spi.java.queries.CompilerOptionsQueryImplementation; import org.netbeans.spi.project.support.ant.AntProjectHelper; import org.netbeans.spi.project.support.ant.EditableProperties; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.test.MockLookup; /** * Test for {@link MultiModuleUnitTestsCompilerOptionsQueryImpl}. * @author <NAME> * Todo: * add/remove module test root * events */ public class MultiModuleUnitTestsCompilerOptionsQueryImplTest extends NbTestCase { //Module Source Path private FileObject src1; //Source Path private FileObject mod1a; // in src1 private FileObject mod1b; // in src1 //Unit tests private FileObject mod1aTests; // in src1 private FileObject mod1bTests; // in src1 private TestProject tp; private SourceRoots modules; private SourceRoots sources; private SourceRoots testModules; private SourceRoots testSources; private ModuleTestUtilities mtu; private CompilerOptionsQueryImplementation query; public MultiModuleUnitTestsCompilerOptionsQueryImplTest(final String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); clearWorkDir(); MockLookup.setInstances(TestProject.createProjectType()); final FileObject wd = FileUtil.toFileObject(FileUtil.normalizeFile(getWorkDir())); src1 = wd.createFolder("src1"); //NOI18N assertNotNull(src1); mod1a = src1.createFolder("lib.common").createFolder("classes"); //NOI18N assertNotNull(mod1a); createModuleInfo(mod1a, "lib.common", "java.base"); mod1b = src1.createFolder("lib.util").createFolder("classes"); //NOI18N assertNotNull(mod1b); createModuleInfo(mod1b, "lib.util", "java.base","java.logging"); //NOI18N mod1aTests = src1.getFileObject("lib.common").createFolder("tests"); //NOI18N assertNotNull(mod1aTests); mod1bTests = src1.getFileObject("lib.util").createFolder("tests"); //NOI18N assertNotNull(mod1bTests); final Project prj = TestProject.createProject(wd, null, null); tp = prj.getLookup().lookup(TestProject.class); assertNotNull(tp); mtu = ModuleTestUtilities.newInstance(tp); assertNotNull(mtu); //Set module roots assertTrue(mtu.updateModuleRoots(false, src1)); modules = mtu.newModuleRoots(false); assertTrue(Arrays.equals(new FileObject[]{src1}, modules.getRoots())); sources = mtu.newSourceRoots(false); assertTrue(mtu.updateModuleRoots(true, src1)); testModules = mtu.newModuleRoots(true); assertTrue(Arrays.equals(new FileObject[]{src1}, testModules.getRoots())); testSources = mtu.newSourceRoots(true); setSourceLevel("9"); //NOI18N query = QuerySupport.createMultiModuleUnitTestsCompilerOptionsQuery(prj, modules, sources, testModules, testSources); } public void testCompilerOptions() { assertNotNull(query); assertNull(query.getOptions(src1)); assertNull(query.getOptions(mod1a)); assertNull(query.getOptions(mod1b)); CompilerOptionsQueryImplementation.Result res = query.getOptions(mod1aTests); assertNotNull(res); assertEquals( newSet( String.format("--patch-module lib.common=%s", FileUtil.toFile(mod1aTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.util=%s", FileUtil.toFile(mod1bTests).getAbsolutePath()), //NOI18N Stream.of(mod1a, mod1b).map(FileObject::getParent).map(FileObject::getNameExt).collect(Collectors.joining(",", "--add-modules ", "")), //NOI18N "--add-reads lib.common=ALL-UNNAMED", //NOI18N "--add-reads lib.util=ALL-UNNAMED"), //NOI18N newPairs(res.getArguments())); res = query.getOptions(mod1bTests); assertNotNull(res); assertEquals( newSet( String.format("--patch-module lib.common=%s", FileUtil.toFile(mod1aTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.util=%s", FileUtil.toFile(mod1bTests).getAbsolutePath()), //NOI18N Stream.of(mod1a, mod1b).map(FileObject::getParent).map(FileObject::getNameExt).collect(Collectors.joining(",", "--add-modules ", "")), //NOI18N "--add-reads lib.common=ALL-UNNAMED", //NOI18N "--add-reads lib.util=ALL-UNNAMED"), //NOI18N newPairs(res.getArguments())); } public void testSourceLevel() { assertNotNull(query); setSourceLevel("1.8"); //NOI18N CompilerOptionsQueryImplementation.Result res = query.getOptions(mod1aTests); assertNotNull(res); res = query.getOptions(mod1bTests); assertNotNull(res); setSourceLevel("9"); //NOI18N res = query.getOptions(mod1aTests); assertNotNull(res); assertEquals( newSet( String.format("--patch-module lib.common=%s", FileUtil.toFile(mod1aTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.util=%s", FileUtil.toFile(mod1bTests).getAbsolutePath()), //NOI18N Stream.of(mod1a, mod1b).map(FileObject::getParent).map(FileObject::getNameExt).collect(Collectors.joining(",", "--add-modules ", "")), //NOI18N "--add-reads lib.common=ALL-UNNAMED", //NOI18N "--add-reads lib.util=ALL-UNNAMED"), //NOI18N newPairs(res.getArguments())); res = query.getOptions(mod1bTests); assertNotNull(res); assertEquals( newSet( String.format("--patch-module lib.common=%s", FileUtil.toFile(mod1aTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.util=%s", FileUtil.toFile(mod1bTests).getAbsolutePath()), //NOI18N Stream.of(mod1a, mod1b).map(FileObject::getParent).map(FileObject::getNameExt).collect(Collectors.joining(",", "--add-modules ", "")), //NOI18N "--add-reads lib.common=ALL-UNNAMED", //NOI18N "--add-reads lib.util=ALL-UNNAMED"), //NOI18N newPairs(res.getArguments())); } public void testModuleSetChanges() throws IOException { assertNotNull(query); CompilerOptionsQueryImplementation.Result res = query.getOptions(mod1aTests); assertNotNull(res); assertEquals( newSet( String.format("--patch-module lib.common=%s", FileUtil.toFile(mod1aTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.util=%s", FileUtil.toFile(mod1bTests).getAbsolutePath()), //NOI18N Stream.of(mod1a, mod1b).map(FileObject::getParent).map(FileObject::getNameExt).collect(Collectors.joining(",", "--add-modules ", "")), //NOI18N "--add-reads lib.common=ALL-UNNAMED", //NOI18N "--add-reads lib.util=ALL-UNNAMED"), //NOI18N newPairs(res.getArguments())); final FileObject mod1c = src1.createFolder("lib.foo").createFolder("classes"); //NOI18N assertNotNull(mod1c); createModuleInfo(mod1c, "lib.foo", "java.base"); final FileObject mod1cTests = src1.getFileObject("lib.foo").createFolder("tests"); //NOI18N assertNotNull(mod1cTests); res = query.getOptions(mod1aTests); assertNotNull(res); assertEquals( newSet( String.format("--patch-module lib.common=%s", FileUtil.toFile(mod1aTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.util=%s", FileUtil.toFile(mod1bTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.foo=%s", FileUtil.toFile(mod1cTests).getAbsolutePath()), //NOI18N Stream.of(mod1a, mod1c, mod1b).map(FileObject::getParent).map(FileObject::getNameExt).collect(Collectors.joining(",", "--add-modules ", "")), //NOI18N "--add-reads lib.common=ALL-UNNAMED", //NOI18N "--add-reads lib.util=ALL-UNNAMED", //NOI18N "--add-reads lib.foo=ALL-UNNAMED"), //NOI18N newPairs(res.getArguments())); res = query.getOptions(mod1cTests); assertNotNull(res); assertEquals( newSet( String.format("--patch-module lib.common=%s", FileUtil.toFile(mod1aTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.util=%s", FileUtil.toFile(mod1bTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.foo=%s", FileUtil.toFile(mod1cTests).getAbsolutePath()), //NOI18N Stream.of(mod1a, mod1c, mod1b).map(FileObject::getParent).map(FileObject::getNameExt).collect(Collectors.joining(",", "--add-modules ", "")), //NOI18N "--add-reads lib.common=ALL-UNNAMED", //NOI18N "--add-reads lib.util=ALL-UNNAMED", //NOI18N "--add-reads lib.foo=ALL-UNNAMED"), //NOI18N newPairs(res.getArguments())); mod1c.getParent().delete(); res = query.getOptions(mod1aTests); assertNotNull(res); assertEquals( newSet( String.format("--patch-module lib.common=%s", FileUtil.toFile(mod1aTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.util=%s", FileUtil.toFile(mod1bTests).getAbsolutePath()), //NOI18N Stream.of(mod1a, mod1b).map(FileObject::getParent).map(FileObject::getNameExt).collect(Collectors.joining(",", "--add-modules ", "")), //NOI18N "--add-reads lib.common=ALL-UNNAMED", //NOI18N "--add-reads lib.util=ALL-UNNAMED"), //NOI18N newPairs(res.getArguments())); } public void testTestModuleInfoChanges() throws IOException { assertNotNull(query); CompilerOptionsQueryImplementation.Result res = query.getOptions(mod1aTests); assertNotNull(res); assertEquals( newSet( String.format("--patch-module lib.common=%s", FileUtil.toFile(mod1aTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.util=%s", FileUtil.toFile(mod1bTests).getAbsolutePath()), //NOI18N Stream.of(mod1a, mod1b).map(FileObject::getParent).map(FileObject::getNameExt).collect(Collectors.joining(",", "--add-modules ", "")), //NOI18N "--add-reads lib.common=ALL-UNNAMED", //NOI18N "--add-reads lib.util=ALL-UNNAMED"), //NOI18N newPairs(res.getArguments())); final FileObject modInfo = createModuleInfo(mod1aTests, "lib.common.tests", "java.base"); res = query.getOptions(mod1aTests); assertNotNull(res); assertEquals( newSet( String.format("--patch-module lib.util=%s", FileUtil.toFile(mod1bTests).getAbsolutePath()), //NOI18N Stream.of(mod1a, mod1b).map(FileObject::getParent).map(FileObject::getNameExt).collect(Collectors.joining(",", "--add-modules ", "")), //NOI18N "--add-reads lib.common=ALL-UNNAMED", //NOI18N "--add-reads lib.util=ALL-UNNAMED"), //NOI18N newPairs(res.getArguments())); modInfo.delete(); res = query.getOptions(mod1aTests); assertNotNull(res); assertEquals( newSet( String.format("--patch-module lib.common=%s", FileUtil.toFile(mod1aTests).getAbsolutePath()), //NOI18N String.format("--patch-module lib.util=%s", FileUtil.toFile(mod1bTests).getAbsolutePath()), //NOI18N Stream.of(mod1a, mod1b).map(FileObject::getParent).map(FileObject::getNameExt).collect(Collectors.joining(",", "--add-modules ", "")), //NOI18N "--add-reads lib.common=ALL-UNNAMED", //NOI18N "--add-reads lib.util=ALL-UNNAMED"), //NOI18N newPairs(res.getArguments())); } private void setSourceLevel(@NonNull final String sl) { ProjectManager.mutex(true, tp).writeAccess(() -> { final EditableProperties ep = tp.getUpdateHelper().getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH); ep.setProperty(ProjectProperties.JAVAC_SOURCE, sl); ep.setProperty(ProjectProperties.JAVAC_TARGET, sl); tp.getUpdateHelper().putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, ep); }); } @NonNull private static Set<String> newSet(@NonNull final String... args) { final Set<String> res = new HashSet<>(); Collections.addAll(res, args); return res; } @NonNull private static Set<String> newPairs(@NonNull final List<? extends String> opts) { final Set<String> res = new HashSet<>(); String f = null; for (String o : opts) { if (f == null) { f = o; } else { res.add(String.format("%s %s", f, o)); f = null; } } return res; } @NonNull private static FileObject createModuleInfo( @NonNull final FileObject root, @NonNull final String moduleName, @NonNull final String... requiredModules) throws IOException { final FileObject moduleInfo = FileUtil.createData(root, "module-info.java"); //NOI18N try(PrintWriter out = new PrintWriter(new OutputStreamWriter(moduleInfo.getOutputStream()))) { out.printf("module %s {%n", moduleName); //NOI18N for (String requiredModule : requiredModules) { out.printf(" requires %s;%n", requiredModule); //NOI18N } out.printf("}"); //NOI18N } return moduleInfo; } }
6,994
370
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright xmuspeech (Author:Snowdar 2019-01-10) # This metric is for ASVspoof Challenge in 2019. import sys # Num of data N_bona_cm=0 N_spoof_cm=0 # Priors Pi_tar=0.9405 Pi_non=0.0095 Pi_spoof=0.05 # ASV costs C_miss_asv=1 C_fa_asv=10 # CM costs C_miss_cm=1 C_fa_cm=10 def load_data(data_path,n): list=[] print("Load data from "+data_path+"...") with open(data_path,'r') as f: content=f.readlines() for line in content: line=line.strip() data_list=line.split() if(n!=len(data_list)): print('[Error] The %s file has no %s fields'%(data_path,n)) exit(1) list.append(data_list) return list def abs(x): if(x<0): return -x else: return x def compute_eer(allScores): numP=0 numN=0 for x in allScores: if(x[1]=="target"): x[1]=1 numP=numP+1 elif(x[1]=="nontarget"): x[1]=0 numN=numN+1 else: print("[Error in compute_eer()] %s is not target or nontarget in score"%(x[1])) exit(1) allScores=sorted(allScores,reverse=False) numFA=numN numFR=0 eer=0.0 threshold=0.0 memory=[] for tuple in allScores: if(tuple[1]==1): numFR=numFR+1 else: numFA=numFA-1 far=numFA*1.0/numN frr=numFR*1.0/numP if(far<=frr): lnow=abs(far-frr) lmemory=abs(memory[0]-memory[1]) if(lnow<=lmemory): eer=(far+frr)/2 threshold=tuple[0] else: eer=(memory[0]+memory[1])/2 threshold=memory[2] return eer,threshold else: memory=[far,frr,tuple[0]] def t_DCF_min(dcf): return min(dcf) def t_DCF_norm(beta,P_miss_cm,P_fa_cm): return beta * P_miss_cm + P_fa_cm def get_rate(x,y): if(y==0): return 0 else: return x*1.0/y def obtain_asv_error_rates(asv_score,asv_threshold): N_tar_asv=0 N_non_asv=0 N_spoof_asv=0 count_tar=0 count_non=0 count_spoof=0 for x in asv_score: if(x[1]=="target"): N_tar_asv=N_tar_asv+1 if(float(x[2])<asv_threshold): count_tar=count_tar+1 elif(x[1]=="nontarget"): N_non_asv=N_non_asv+1 if(float(x[2])>=asv_threshold): count_non=count_non+1 elif(x[1]=="spoof"): N_spoof_asv=N_spoof_asv+1 if(float(x[2])<asv_threshold): count_spoof=count_spoof+1 else: print("[Error in obtain_asv_error_rates()] %s is not target or nontarget or spoof in score"%(x[1])) P_miss_asv=get_rate(count_tar,N_tar_asv) P_fa_asv=get_rate(count_non,N_non_asv) P_miss_spoof_asv=get_rate(count_spoof,N_spoof_asv) return P_miss_asv,P_fa_asv,P_miss_spoof_asv def check(): if(Pi_tar+Pi_non+Pi_spoof!=1): print("[Error in check()] Pi_tar+Pi_non+Pi_spoof != 1 ") exit(1) ## main ## if len(sys.argv)-1 != 2 : print 'usage: '+sys.argv[0]+' [options] <asv-score> <cm-score>' exit(1) """ asv-score format with every line: attack-way target/nontarget/spoof score example: - target 4.23 - nontarget 1.24 VC_1 spoof 2.55 cm-score format with every line: bonafide/spoof score example: bonafide 2.34 spoof -1.2 """ asv_score_path=sys.argv[1] cm_score_path=sys.argv[2] check() #- start -# asv_score_file=load_data(asv_score_path,3) cm_score_file=load_data(cm_score_path,2) #- asv -# asv_score_for_eer=[] for x in asv_score_file: if(x[1]=="target" or x[1]=="nontarget"): asv_score_for_eer.append([float(x[2]),x[1]]) asv_eer,asv_threshold=compute_eer(asv_score_for_eer) P_miss_asv,P_fa_asv,P_miss_spoof_asv=obtain_asv_error_rates(asv_score_file,asv_threshold) #- cm -# cm_score=[] cm_score_for_eer=[] for x in cm_score_file: if(x[0]=="bonafide"): lable=1 text="target" N_bona_cm=N_bona_cm+1 elif(x[0]=="spoof"): lable=0 text="nontarget" N_spoof_cm=N_spoof_cm+1 else: print("[Error in main-cm] the lable %s is not bonafide or spoof"%(x[0])) exit(1) cm_score.append([float(x[1]),lable]) cm_score_for_eer.append([float(x[1]),text]) cm_eer,cm_threshold=compute_eer(cm_score_for_eer) #- t-DCF -# C1=Pi_tar * (C_miss_cm - C_miss_asv * P_miss_asv) - Pi_non * C_fa_asv * P_fa_asv C2=C_fa_cm * Pi_spoof * (1 - P_miss_spoof_asv) beta=C1/C2 cm_score=sorted(cm_score,reverse=False) count_bona=0 count_spoof=N_spoof_cm dcf=[] P_miss_cm=count_bona*1.0/N_bona_cm P_fa_cm=count_spoof*1.0/N_spoof_cm dcf.append(t_DCF_norm(beta,P_miss_cm,P_fa_cm)) for tuple in cm_score: if(tuple[1]==1): count_bona=count_bona+1 else: count_spoof=count_spoof-1 P_miss_cm=count_bona*1.0/N_bona_cm P_fa_cm=count_spoof*1.0/N_spoof_cm dcf.append(t_DCF_norm(beta,P_miss_cm,P_fa_cm)) min_tDCF=t_DCF_min(dcf) #- print -# print("\n[Report]") print("ASV EER=%f%%, threshold=%f"%(asv_eer*100,asv_threshold)) print("ASV Pfa=%f%%, Pmiss=%f%%, 1-Pmiss,spoof=%f%%"%(P_fa_asv*100,P_miss_asv*100,(1-P_miss_spoof_asv)*100)) print("CM EER=%f%%, threshold=%f"%(cm_eer*100,cm_threshold)) print("Final min-tDCF=%f"%(min_tDCF))
3,201
301
<gh_stars>100-1000 package cn.ittiger.video.util; /** * @author: laohu on 2016/8/31 * @site: http://ittiger.cn */ public interface CallbackHandler<T> { void callback(T t); }
74
575
<filename>chrome/browser/file_system_access/chrome_file_system_access_permission_context.h // Copyright 2019 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. #ifndef CHROME_BROWSER_FILE_SYSTEM_ACCESS_CHROME_FILE_SYSTEM_ACCESS_PERMISSION_CONTEXT_H_ #define CHROME_BROWSER_FILE_SYSTEM_ACCESS_CHROME_FILE_SYSTEM_ACCESS_PERMISSION_CONTEXT_H_ #include <map> #include <vector> #include "base/sequence_checker.h" #include "components/content_settings/core/common/content_settings_types.h" #include "components/keyed_service/core/keyed_service.h" #include "components/permissions/permission_util.h" #include "content/public/browser/file_system_access_permission_context.h" #include "third_party/blink/public/mojom/permissions/permission_status.mojom.h" class HostContentSettingsMap; enum ContentSetting; namespace content { class BrowserContext; } // namespace content // Chrome implementation of FileSystemAccessPermissionContext. This class // implements a permission model where permissions are shared across an entire // origin. When the last tab for an origin is closed all permissions for that // origin are revoked. // // All methods must be called on the UI thread. // // This class does not inherit from ChooserContextBase because the model this // API uses doesn't really match what ChooserContextBase has to provide. The // limited lifetime of File System Access permission grants (scoped to the // lifetime of the handles that reference the grants), and the possible // interactions between grants for directories and grants for children of those // directories as well as possible interactions between read and write grants // make it harder to squeeze this into a shape that fits with // ChooserContextBase. class ChromeFileSystemAccessPermissionContext : public content::FileSystemAccessPermissionContext, public KeyedService { public: explicit ChromeFileSystemAccessPermissionContext( content::BrowserContext* context); ~ChromeFileSystemAccessPermissionContext() override; // content::FileSystemAccessPermissionContext: scoped_refptr<content::FileSystemAccessPermissionGrant> GetReadPermissionGrant(const url::Origin& origin, const base::FilePath& path, HandleType handle_type, UserAction user_action) override; scoped_refptr<content::FileSystemAccessPermissionGrant> GetWritePermissionGrant(const url::Origin& origin, const base::FilePath& path, HandleType handle_type, UserAction user_action) override; void ConfirmSensitiveDirectoryAccess( const url::Origin& origin, PathType path_type, const base::FilePath& path, HandleType handle_type, content::GlobalFrameRoutingId frame_id, base::OnceCallback<void(SensitiveDirectoryResult)> callback) override; void PerformAfterWriteChecks( std::unique_ptr<content::FileSystemAccessWriteItem> item, content::GlobalFrameRoutingId frame_id, base::OnceCallback<void(AfterWriteCheckResult)> callback) override; bool CanObtainReadPermission(const url::Origin& origin) override; bool CanObtainWritePermission(const url::Origin& origin) override; void SetLastPickedDirectory(const url::Origin& origin, const std::string& id, const base::FilePath& path, const PathType type) override; PathInfo GetLastPickedDirectory(const url::Origin& origin, const std::string& id) override; base::FilePath GetWellKnownDirectoryPath( blink::mojom::WellKnownDirectory directory) override; ContentSetting GetReadGuardContentSetting(const url::Origin& origin); ContentSetting GetWriteGuardContentSetting(const url::Origin& origin); void SetMaxIdsPerOriginForTesting(unsigned int max_ids) { max_ids_per_origin_ = max_ids; } // Returns a snapshot of the currently granted permissions. // TODO(https://crbug.com/984769): Eliminate process_id and frame_id from this // method when grants stop being scoped to a frame. struct Grants { Grants(); ~Grants(); Grants(Grants&&); Grants& operator=(Grants&&); std::vector<base::FilePath> file_read_grants; std::vector<base::FilePath> file_write_grants; std::vector<base::FilePath> directory_read_grants; std::vector<base::FilePath> directory_write_grants; }; Grants GetPermissionGrants(const url::Origin& origin); // Revokes write access and directory read access for the given origin. void RevokeGrants(const url::Origin& origin); bool OriginHasReadAccess(const url::Origin& origin); bool OriginHasWriteAccess(const url::Origin& origin); // Called by FileSystemAccessTabHelper when a top-level frame was navigated // away from |origin| to some other origin. void NavigatedAwayFromOrigin(const url::Origin& origin); content::BrowserContext* profile() const { return profile_; } void TriggerTimersForTesting(); HostContentSettingsMap* content_settings() { return content_settings_.get(); } protected: SEQUENCE_CHECKER(sequence_checker_); private: class PermissionGrantImpl; void PermissionGrantDestroyed(PermissionGrantImpl* grant); void DidConfirmSensitiveDirectoryAccess( const url::Origin& origin, const base::FilePath& path, HandleType handle_type, content::GlobalFrameRoutingId frame_id, base::OnceCallback<void(SensitiveDirectoryResult)> callback, bool should_block); void MaybeMigrateOriginToNewSchema(const url::Origin& origin); // An origin can only specify up to `max_ids_per_origin_` custom IDs per // origin (not including the default ID). If this limit is exceeded, evict // using LRU. void MaybeEvictEntries(std::unique_ptr<base::Value>& value); // Schedules triggering all open windows to update their File System Access // usage indicator icon. Multiple calls to this method can result in only a // single actual update. void ScheduleUsageIconUpdate(); // Updates the File System Access usage indicator icon in all currently open // windows. void DoUsageIconUpdate(); // Checks if any tabs are open for |origin|, and if not revokes all // permissions for that origin. void MaybeCleanupPermissions(const url::Origin& origin); base::WeakPtr<ChromeFileSystemAccessPermissionContext> GetWeakPtr(); content::BrowserContext* const profile_; // Permission state per origin. struct OriginState; std::map<url::Origin, OriginState> origins_; bool usage_icon_update_scheduled_ = false; scoped_refptr<HostContentSettingsMap> content_settings_; // Number of custom IDs an origin can specify. size_t max_ids_per_origin_ = 32u; base::WeakPtrFactory<ChromeFileSystemAccessPermissionContext> weak_factory_{ this}; DISALLOW_COPY_AND_ASSIGN(ChromeFileSystemAccessPermissionContext); }; #endif // CHROME_BROWSER_FILE_SYSTEM_ACCESS_CHROME_FILE_SYSTEM_ACCESS_PERMISSION_CONTEXT_H_
2,271
3,783
<filename>src/problems/medium/WordLadder.java<gh_stars>1000+ package problems.medium; import java.util.*; /** * Created by sherxon on 2/12/17. */ public class WordLadder { public static void main(String[] args) { System.out.println(); } public int ladderLength(String a, String b, List<String> list) { Map<String, Set<String>> map = new HashMap<>(); map.put(a, new HashSet<>()); Queue<String> q = new LinkedList<>(); for (String s : list) { addVertexAndEdge(s, map); // map.put(s, new HashSet<>()); // for (String key : map.keySet()) { // if (canBeConnected(key, s)) { // map.get(key).add(s); // map.get(s).add(key); // } // } } Set<String> visited = new HashSet<>(list.size()); visited.add(a); q.add(a); Map<String, Integer> d = new HashMap<>(); // distance d.put(a, 1); while (!q.isEmpty()) { String x = q.remove(); for (String s : map.get(x)) { if (!visited.contains(s)) { visited.add(s); d.put(s, d.get(x) + 1); q.add(s); if (s.equals(b)) return d.get(s); } } } return 0; } private void addVertexAndEdge(String s, Map<String, Set<String>> map) { map.put(s, new HashSet<>()); for (String key : map.keySet()) { if (canBeConnected(key, s)) { map.get(key).add(s); map.get(s).add(key); } } } private boolean canBeConnected(String key, String s) { int diff = 0; for (int i = 0; i < key.length(); i++) { if (key.charAt(i) != s.charAt(i)) diff++; if (diff > 1) return false; } return diff == 1; } }
1,085
5,169
{ "name": "WTDB", "version": "1.0.3", "summary": "好想唱情歌 看最美的烟火  在城市中漂泊 我的心为爱颤抖", "description": "男:好想唱情歌 看最美的烟火\n男:娘子\n女:a ha\n男:和你唱情歌 看最美的烟火\n女:你陪我唱情歌 看最美的烟火  在城市中牵手 我的爱为你颤抖  离开多少风雨后 我爱上唱情歌  你是夜的星斗 我真爱的所有\n合唱:是郎给的诱惑 我唱起了情歌  在渴望的天空 有美丽的月色  是郎给的快乐 我风干了寂寞  在幸福的天空 你是我的所有\n男:娘子", "homepage": "https://github.com/weijiewen/WTDB", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "weijiewen": "<EMAIL>" }, "source": { "git": "https://github.com/weijiewen/WTDB.git", "tag": "1.0.3" }, "platforms": { "ios": "9.0" }, "source_files": "WTDB/Classes/**/*", "libraries": "sqlite3" }
608
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/ImageCapture.framework/ImageCapture */ #import <ImageCapture/XXUnknownSuperclass.h> @class NSMutableArray, PTPCameraDeviceManager, MSCameraDeviceManager; @interface ICMasterDeviceBrowser : XXUnknownSuperclass { NSMutableArray *_devices; // 4 = 0x4 NSMutableArray *_browsers; // 8 = 0x8 int _numberOfBrowsingBrowsers; // 12 = 0xc MSCameraDeviceManager *_msDevManager; // 16 = 0x10 PTPCameraDeviceManager *_ptpDevManager; // 20 = 0x14 } @property(readonly, assign) NSMutableArray *devices; // G=0xc459; @synthesize=_devices @property(readonly, assign) NSMutableArray *browsers; // G=0xc46d; @synthesize=_browsers + (id)defaultBrowser; // 0xc5a9 + (BOOL)exists; // 0xc441 - (id)init; // 0xc47d - (void)dealloc; // 0xef71 - (void)finalize; // 0xee75 - (void)addBrowser:(id)browser; // 0xee51 - (void)removeBrowser:(id)browser; // 0xee2d - (int)addPTPCamera:(id)camera; // 0xeaa5 - (void)removePTPCamera:(id)camera; // 0xe36d - (int)addMSCamera:(id)camera; // 0xdcfd - (int)addRemoveMSCamera; // 0xda4d - (void)removeMSCamera:(id)camera; // 0xd325 - (int)start:(id)start; // 0xd019 - (void)stop:(id)stop; // 0xcc55 // declared property getter: - (id)devices; // 0xc459 - (void)handleCommandCompletionNotification:(id)notification; // 0xcbf9 - (void)handleImageCaptureEventNotification:(id)notification; // 0xc6b5 - (id)deviceWithDelegate:(id)delegate; // 0xc5f1 - (void)informBrowserDelegateUsingSelector:(SEL)selector withObject:(id)object; // 0xc469 // declared property getter: - (id)browsers; // 0xc46d @end
634
988
<filename>enterprise/cloud.oracle/src/org/netbeans/modules/cloud/oracle/actions/AbstractPasswordPanel.java<gh_stars>100-1000 /* * 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.netbeans.modules.cloud.oracle.actions; import java.util.Arrays; import java.util.Random; import java.util.function.Consumer; import javax.swing.JPanel; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.openide.DialogDescriptor; /** * * @author <NAME> */ public abstract class AbstractPasswordPanel extends JPanel { private static final String SPECIAL_CHARACTERS = "/!#$^?:.(){}[]~-_."; // NOI18N protected DialogDescriptor descriptor; protected final void setDescriptor(DialogDescriptor descriptor) { if (this.descriptor != null) { throw new IllegalStateException( "DialogDescriptor has been already set."); //NOI18N } this.descriptor = descriptor; descriptor.setValid(false); } static boolean checkPasswordLogic(char[] passwd1, char[] passwd2, Consumer<String> message) { boolean result = false; if (passwd1.length < 8) { message.accept(Bundle.Lenght()); return result; } int nSpecialCharacters = 0; int nLetters = 0; int nDigits = 0; for (int i = 0; i < passwd1.length; i++) { if (Character.isLetter(passwd1[i])) { nLetters++; } else if (Character.isDigit(passwd1[i])) { nDigits++; } else if (SPECIAL_CHARACTERS.indexOf(passwd1[i]) >= 0) { nSpecialCharacters++; } } if (nLetters < 1) { message.accept(Bundle.OneLetter()); } else if (nSpecialCharacters < 1) { message.accept(Bundle.OneSpecial()); } else if (nDigits < 1) { message.accept(Bundle.OneNumber()); } else if (!Arrays.equals(passwd1, passwd2)) { message.accept(Bundle.Match()); } else { message.accept(null); result = true; } return result; } static char[] generatePassword() { Random rnd = new Random(); char[] password = new char[12]; for (int i = 0; i < 4; i++) { password[i] = (char) (65 + rnd.nextInt(25)); } password[4] = SPECIAL_CHARACTERS.charAt(rnd.nextInt(SPECIAL_CHARACTERS.length())); for (int i = 5; i < password.length - 1; i++) { password[i] = (char) (97 + rnd.nextInt(25)); } password[password.length - 1] = (char) (48 + rnd.nextInt(9)); return password; } protected void errorMessage(String message) { if (message == null) { descriptor.getNotificationLineSupport().clearMessages(); descriptor.setValid(true); } else { descriptor.setValid(false); descriptor.getNotificationLineSupport().setErrorMessage(message); } } protected abstract void checkPassword(); protected class PasswordListener implements DocumentListener { @Override public void insertUpdate(DocumentEvent e) { checkPassword(); } @Override public void removeUpdate(DocumentEvent e) { checkPassword(); } @Override public void changedUpdate(DocumentEvent e) { checkPassword(); } } }
1,767
507
<reponame>mjuenema/python-terrascript # terrascript/random/r.py # Automatically generated by tools/makecode.py () import warnings warnings.warn( "using the 'legacy layout' is deprecated", DeprecationWarning, stacklevel=2 ) import terrascript class random_id(terrascript.Resource): pass class random_integer(terrascript.Resource): pass class random_password(terrascript.Resource): pass class random_pet(terrascript.Resource): pass class random_shuffle(terrascript.Resource): pass class random_string(terrascript.Resource): pass class random_uuid(terrascript.Resource): pass
208
1,126
<filename>depth_first_traversal/DepthFirstTraversal.java<gh_stars>1000+ import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Set; import java.util.ArrayList; public class DepthFirstTraversal { // ArrayList for Adjacency List Representation public static ArrayList<LinkedList<Integer>> adj; // Function to add an edge into the DepthFirstTraversal private static void addEdge(int v, int w) { adj.get(v).add(w); } // A function used by DFS private static void depthFirstTraversal(int v, Set<Integer> visited) { // Mark the current node as visited visited.add(v); System.out.println(v); Iterator<Integer> i = adj.get(v).listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited.contains(n)) { depthFirstTraversal(n, visited); } } } public static void dfs(int v) { // false by default in java) Set<Integer> visited = new HashSet<Integer>(); // Call the recursive helper function to print DFS traversal depthFirstTraversal(v, visited); } public static void initEdges(int n) { adj = new ArrayList<LinkedList<Integer>>(); for (int i = 0; i < n; ++i) { adj.add(new LinkedList<Integer>()); } } public static void main(String[] args) { initEdges(4); addEdge(0, 1); addEdge(0, 2); addEdge(1, 2); addEdge(2, 0); addEdge(2, 3); addEdge(3, 0); System.out.println("Depth First Traversal starting from vertex 2"); dfs(2); } }
734
310
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty 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 org.jitsi.impl.neomedia.jmfext.media.renderer.audio; import javax.media.*; import javax.media.format.*; import org.jitsi.impl.neomedia.*; import org.jitsi.impl.neomedia.device.*; import org.jitsi.service.neomedia.*; import org.jitsi.service.neomedia.codec.*; /** * Implements an audio <tt>Renderer</tt> which uses OpenSL ES. * * @author <NAME> */ public class OpenSLESRenderer extends AbstractAudioRenderer<AudioSystem> { /** * The human-readable name of the <tt>OpenSLESRenderer</tt> FMJ plug-in. */ private static final String PLUGIN_NAME = "OpenSL ES Renderer"; /** * The list of input <tt>Format</tt>s supported by <tt>OpenSLESRenderer</tt> * instances. */ private static final Format[] SUPPORTED_INPUT_FORMATS; static { System.loadLibrary("jnopensles"); double[] supportedInputSampleRates = Constants.AUDIO_SAMPLE_RATES; int supportedInputSampleRateCount = supportedInputSampleRates.length; SUPPORTED_INPUT_FORMATS = new Format[supportedInputSampleRateCount]; for (int i = 0; i < supportedInputSampleRateCount; i++) { SUPPORTED_INPUT_FORMATS[i] = new AudioFormat( AudioFormat.LINEAR, supportedInputSampleRates[i], 16 /* sampleSizeInBits */, Format.NOT_SPECIFIED /* channels */, AudioFormat.LITTLE_ENDIAN, AudioFormat.SIGNED, Format.NOT_SPECIFIED /* frameSizeInBits */, Format.NOT_SPECIFIED /* frameRate */, Format.byteArray); } } /** * The <tt>GainControl</tt> through which the volume/gain of rendered media * is controlled. */ private final GainControl gainControl; private long ptr; /** * The indicator which determines whether this <tt>OpenSLESRenderer</tt> * is to set the priority of the thread in which its * {@link #process(Buffer)} method is executed. */ private boolean setThreadPriority = true; /** * Initializes a new <tt>OpenSLESRenderer</tt> instance. */ public OpenSLESRenderer() { this(true); } /** * Initializes a new <tt>OpenSLESRenderer</tt> instance. * * @param enableGainControl <tt>true</tt> to enable controlling the * volume/gain of the rendered media; otherwise, <tt>false</tt> */ public OpenSLESRenderer(boolean enableGainControl) { super(AudioSystem.getAudioSystem( AudioSystem.LOCATOR_PROTOCOL_OPENSLES)); if (enableGainControl) { MediaServiceImpl mediaServiceImpl = NeomediaActivator.getMediaServiceImpl(); gainControl = (mediaServiceImpl == null) ? null : (GainControl) mediaServiceImpl.getOutputVolumeControl(); } else gainControl = null; } /** * Implements {@link PlugIn#close()}. Closes this {@link PlugIn} and * releases its resources. * * @see PlugIn#close() */ public synchronized void close() { if (ptr != 0) { close(ptr); ptr = 0; setThreadPriority = true; } } private static native void close(long ptr); /** * Gets the descriptive/human-readable name of this FMJ plug-in. * * @return the descriptive/human-readable name of this FMJ plug-in */ public String getName() { return PLUGIN_NAME; } /** * Gets the list of input <tt>Format</tt>s supported by this * <tt>OpenSLESRenderer</tt>. * * @return the list of input <tt>Format</tt>s supported by this * <tt>OpenSLESRenderer</tt> */ public Format[] getSupportedInputFormats() { return SUPPORTED_INPUT_FORMATS.clone(); } /** * Implements {@link PlugIn#open()}. Opens this {@link PlugIn} and acquires * the resources that it needs to operate. * * @throws ResourceUnavailableException if any of the required resources * cannot be acquired * @see PlugIn#open() */ public synchronized void open() throws ResourceUnavailableException { if (ptr == 0) { AudioFormat inputFormat = this.inputFormat; int channels = inputFormat.getChannels(); if (channels == Format.NOT_SPECIFIED) channels = 1; /* * Apart from the thread in which #process(Buffer) is executed, use * the thread priority for the thread which will create the * OpenSL ES Audio Player. */ org.jitsi.impl.neomedia.jmfext.media.protocol .audiorecord.DataSource.setThreadPriority(); ptr = open( inputFormat.getEncoding(), inputFormat.getSampleRate(), inputFormat.getSampleSizeInBits(), channels, inputFormat.getEndian(), inputFormat.getSigned(), inputFormat.getDataType()); if (ptr == 0) throw new ResourceUnavailableException(); setThreadPriority = true; } } private static native long open( String encoding, double sampleRate, int sampleSizeInBits, int channels, int endian, int signed, Class<?> dataType) throws ResourceUnavailableException; /** * Implements {@link Renderer#process(Buffer)}. Processes the media data * contained in a specific {@link Buffer} and renders it to the output * device represented by this <tt>Renderer</tt>. * * @param buffer the <tt>Buffer</tt> containing the media data to be * processed and rendered to the output device represented by this * <tt>Renderer</tt> * @return one or a combination of the constants defined in {@link PlugIn} * @see Renderer#process(Buffer) */ public int process(Buffer buffer) { if (setThreadPriority) { setThreadPriority = false; org.jitsi.impl.neomedia.jmfext.media.protocol .audiorecord.DataSource.setThreadPriority(); } Format format = buffer.getFormat(); int processed; if ((format == null) || ((inputFormat != null) && inputFormat.matches(format))) { Object data = buffer.getData(); int length = buffer.getLength(); int offset = buffer.getOffset(); if ((data == null) || (length == 0)) { /* * There is really no actual data to be processed by this * OpenSLESRenderer. */ processed = BUFFER_PROCESSED_OK; } else if ((length < 0) || (offset < 0)) { /* The length and/or the offset of the Buffer are not valid. */ processed = BUFFER_PROCESSED_FAILED; } else { synchronized (this) { if (ptr == 0) { /* * This OpenSLESRenderer is not in a state in which it * can process the data of the Buffer. */ processed = BUFFER_PROCESSED_FAILED; } else { // Apply software gain. if (gainControl != null) { BasicVolumeControl.applyGain( gainControl, (byte[]) data, offset, length); } processed = process(ptr, data, offset, length); } } } } else { /* * This OpenSLESRenderer does not understand the format of the * Buffer. */ processed = BUFFER_PROCESSED_FAILED; } return processed; } private static native int process( long ptr, Object data, int offset, int length); /** * Implements {@link Renderer#start()}. Starts rendering to the output * device represented by this <tt>Renderer</tt>. * * @see Renderer#start() */ public synchronized void start() { if (ptr != 0) { setThreadPriority = true; start(ptr); } } private static native void start(long ptr); /** * Implements {@link Renderer#stop()}. Stops rendering to the output device * represented by this <tt>Renderer</tt>. * * @see Renderer#stop() */ public synchronized void stop() { if (ptr != 0) { stop(ptr); setThreadPriority = true; } } private static native void stop(long ptr); }
4,762
640
<gh_stars>100-1000 /* KernelInjet.H Author: <your name> Last Updated: 2006-02-12 This framework is generated by EasySYS 0.3.0 This template file is copying from QuickSYS 0.3.0 written by <NAME> */ #ifndef _KERNELINJET_H #define _KERNELINJET_H 1 // // Define the various device type values. Note that values used by Microsoft // Corporation are in the range 0-0x7FFF(32767), and 0x8000(32768)-0xFFFF(65535) // are reserved for use by customers. // #define FILE_DEVICE_KERNELINJET 0x8000 // // Macro definition for defining IOCTL and FSCTL function control codes. Note // that function codes 0-0x7FF(2047) are reserved for Microsoft Corporation, // and 0x800(2048)-0xFFF(4095) are reserved for customers. // #define KERNELINJET_IOCTL_BASE 0x800 // // The device driver IOCTLs // #define CTL_CODE_KERNELINJET(i) CTL_CODE(FILE_DEVICE_KERNELINJET, KERNELINJET_IOCTL_BASE+i, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_KERNELINJET_HELLO CTL_CODE_KERNELINJET(0) #define IOCTL_KERNELINJET_TEST CTL_CODE_KERNELINJET(1) // // Name that Win32 front end will use to open the KernelInjet device // #define KERNELINJET_WIN32_DEVICE_NAME_A "\\\\.\\KernelInjet" #define KERNELINJET_WIN32_DEVICE_NAME_W L"\\\\.\\KernelInjet" #define KERNELINJET_DEVICE_NAME_A "\\Device\\KernelInjet" #define KERNELINJET_DEVICE_NAME_W L"\\Device\\KernelInjet" #define KERNELINJET_DOS_DEVICE_NAME_A "\\DosDevices\\KernelInjet" #define KERNELINJET_DOS_DEVICE_NAME_W L"\\DosDevices\\KernelInjet" #ifdef _UNICODE #define KERNELINJET_WIN32_DEVICE_NAME KERNELINJET_WIN32_DEVICE_NAME_W #define KERNELINJET_DEVICE_NAME KERNELINJET_DEVICE_NAME_W #define KERNELINJET_DOS_DEVICE_NAME KERNELINJET_DOS_DEVICE_NAME_W #else #define KERNELINJET_WIN32_DEVICE_NAME KERNELINJET_WIN32_DEVICE_NAME_A #define KERNELINJET_DEVICE_NAME KERNELINJET_DEVICE_NAME_A #define KERNELINJET_DOS_DEVICE_NAME KERNELINJET_DOS_DEVICE_NAME_A #endif #endif
895
2,517
<gh_stars>1000+ // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #define CAF_SUITE dictionary #include "caf/dictionary.hpp" #include "core-test.hpp" using namespace caf; namespace { using int_dict = dictionary<int>; } // namespace CAF_TEST(construction and comparison) { int_dict xs; CAF_CHECK_EQUAL(xs.empty(), true); CAF_CHECK_EQUAL(xs.size(), 0u); int_dict ys{{"foo", 1}, {"bar", 2}}; CAF_CHECK_EQUAL(ys.empty(), false); CAF_CHECK_EQUAL(ys.size(), 2u); CAF_CHECK_NOT_EQUAL(xs, ys); int_dict zs{ys.begin(), ys.end()}; CAF_CHECK_EQUAL(zs.empty(), false); CAF_CHECK_EQUAL(zs.size(), 2u); CAF_CHECK_EQUAL(ys, zs); zs.clear(); CAF_CHECK_EQUAL(zs.empty(), true); CAF_CHECK_EQUAL(zs.size(), 0u); CAF_CHECK_EQUAL(xs, zs); } CAF_TEST(iterators) { using std::equal; using vector_type = std::vector<int_dict::value_type>; int_dict xs{{"a", 1}, {"b", 2}, {"c", 3}}; vector_type ys{{"a", 1}, {"b", 2}, {"c", 3}}; CAF_CHECK(equal(xs.begin(), xs.end(), ys.begin())); CAF_CHECK(equal(xs.cbegin(), xs.cend(), ys.cbegin())); CAF_CHECK(equal(xs.rbegin(), xs.rend(), ys.rbegin())); CAF_CHECK(equal(xs.crbegin(), xs.crend(), ys.crbegin())); } CAF_TEST(swapping) { int_dict xs{{"foo", 1}, {"bar", 2}}; int_dict ys; int_dict zs{{"foo", 1}, {"bar", 2}}; CAF_CHECK_NOT_EQUAL(xs, ys); CAF_CHECK_NOT_EQUAL(ys, zs); CAF_CHECK_EQUAL(xs, zs); xs.swap(ys); CAF_CHECK_NOT_EQUAL(xs, ys); CAF_CHECK_EQUAL(ys, zs); CAF_CHECK_NOT_EQUAL(xs, zs); } CAF_TEST(emplacing) { int_dict xs; CAF_CHECK_EQUAL(xs.emplace("x", 1).second, true); CAF_CHECK_EQUAL(xs.emplace("y", 2).second, true); CAF_CHECK_EQUAL(xs.emplace("y", 3).second, false); } CAF_TEST(insertion) { int_dict xs; CAF_CHECK_EQUAL(xs.insert("a", 1).second, true); CAF_CHECK_EQUAL(xs.insert("b", 2).second, true); CAF_CHECK_EQUAL(xs.insert("c", 3).second, true); CAF_CHECK_EQUAL(xs.insert("c", 4).second, false); int_dict ys; CAF_CHECK_EQUAL(ys.insert_or_assign("a", 1).second, true); CAF_CHECK_EQUAL(ys.insert_or_assign("b", 2).second, true); CAF_CHECK_EQUAL(ys.insert_or_assign("c", 0).second, true); CAF_CHECK_EQUAL(ys.insert_or_assign("c", 3).second, false); CAF_CHECK_EQUAL(xs, ys); } CAF_TEST(insertion with hint) { int_dict xs; auto xs_last = xs.end(); auto xs_insert = [&](string_view key, int val) { xs_last = xs.insert(xs_last, key, val); }; xs_insert("a", 1); xs_insert("c", 3); xs_insert("b", 2); xs_insert("c", 4); int_dict ys; auto ys_last = ys.end(); auto ys_insert_or_assign = [&](string_view key, int val) { ys_last = ys.insert_or_assign(ys_last, key, val); }; ys_insert_or_assign("a", 1); ys_insert_or_assign("c", 0); ys_insert_or_assign("b", 2); ys_insert_or_assign("c", 3); CAF_CHECK_EQUAL(xs, ys); } CAF_TEST(bounds) { int_dict xs{{"a", 1}, {"b", 2}, {"c", 3}, {"d", 4}}; const int_dict& const_xs = xs; CAF_CHECK_EQUAL(xs.lower_bound("c")->first, "c"); CAF_CHECK_EQUAL(xs.upper_bound("c")->first, "d"); CAF_CHECK_EQUAL(const_xs.lower_bound("c")->first, "c"); CAF_CHECK_EQUAL(const_xs.upper_bound("c")->first, "d"); } CAF_TEST(find) { int_dict xs{{"a", 1}, {"b", 2}, {"c", 3}, {"d", 4}}; const int_dict& const_xs = xs; CAF_CHECK_EQUAL(xs.find("e"), xs.end()); CAF_CHECK_EQUAL(xs.find("a")->second, 1); CAF_CHECK_EQUAL(xs.find("c")->second, 3); CAF_CHECK_EQUAL(const_xs.find("e"), xs.end()); CAF_CHECK_EQUAL(const_xs.find("a")->second, 1); CAF_CHECK_EQUAL(const_xs.find("c")->second, 3); } CAF_TEST(element access) { int_dict xs{{"a", 1}, {"b", 2}, {"c", 3}, {"d", 4}}; CAF_CHECK_EQUAL(xs["a"], 1); CAF_CHECK_EQUAL(xs["b"], 2); CAF_CHECK_EQUAL(xs["e"], 0); }
1,833
3,651
<gh_stars>1000+ package com.orientechnologies.orient.server.distributed.impl.lock; import java.util.List; public interface OnLocksAcquired { void execute(List<OLockGuard> guards); }
63
3,428
<gh_stars>1000+ {"id":"01289","group":"spam-2","checksum":{"type":"MD5","value":"2f9168490b8c45e76af4935b4827f702"},"text":"From <EMAIL> Wed Aug 7 08:27:17 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy@<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 6F392440A8\n\tfor <jm@localhost>; Wed, 7 Aug 2002 03:27:12 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 07 Aug 2002 08:27:12 +0100 (IST)\nReceived: from xent.com ([192.168.127.126]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g777RTk15517 for <<EMAIL>>;\n Wed, 7 Aug 2002 08:27:32 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id 785D92940B9; Wed, 7 Aug 2002 00:24:04 -0700 (PDT)\nDelivered-To: <EMAIL>int.<EMAIL>\nReceived: from mail1.epatra.com (unknown [192.168.127.120]) by xent.com\n (Postfix) with ESMTP id D1FCF2940AE for <<EMAIL>>; Wed,\n 7 Aug 2002 00:22:59 -0700 (PDT)\nReceived: from suvi232.pugmarks.net (suvi232.pugmarks.net [64.14.239.232])\n by mail1.epatra.com (8.11.6/8.11.6) with ESMTP id g777av301166 for\n <<EMAIL>>; Wed, 7 Aug 2002 13:06:57 +0530\nReceived: (from www@localhost) by suvi232.pugmarks.net (8.11.6/8.9.3) id\n g75CbW531568; Mon, 5 Aug 2002 18:07:32 +0530\nMessage-Id: <<EMAIL>>\nFrom: <NAME> <<EMAIL>>\nTo: <EMAIL>\nX-Eplanguage: en\nSubject: Business Proposal\nX-Originating-Ip: [207.50.228.120]\nX-Priority: 3\nSender: [email protected]\nErrors-To: [email protected]\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of <NAME> <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Mon, 5 Aug 2002 18:07:32 +0530\nContent-Type: text/html\n\n\nHello\n<br>Dear Sir. \n<br>I got your contact in cause of a seriouse search for a \n<br>reliable foreign partner, which really made me to \n<br>contact you for assistance in transfering my money to \n<br>you for investement purpose. \n<br>I'm Mr <NAME>. the son of a late sierraleonian \n<br>business man Mr <NAME>..Who died two yaers ago \n<br>when the revolutionary united front rebels \n<br>(R.U.F)attacked our residence in Makeni Sierra leone. \n<br>Following the cease fire agreement which was reach \n<br>last year with the help of United Nation peace keeping \n<br>troops,I used the oppoturnity to leave the country \n<br>with a very important document \n<br>of(US$14.500.000m)Fourteen million Five Hundred \n<br>Thounsand U.S Dollars deposited by my late father in \n<br>security company in Dakar Senegal,under my name.this \n<br>money was realised from diamond export. \n<br>Now' I'm searching for a trusted individual or foreing \n<br>firm whom I can invest this money with for I am!\n next \n<br>of kin to these money.However I contact you based on \n<br>your capability and vast knowledge on international \n<br>commercial investement. For your assistance and \n<br>co-opertion I will give you 15%of the total sum \n<br>realised after the sucessfull transfer of this money. \n<br>Please kindly communicate your acceptance of this \n<br>proposal through this my e-mail address so that we can \n<br>discuss the modalities of seeing this transaction \n<br>through.I count on you greately for your assistance. \n<br>Awaiting your earnest response With regards. \n<br>Yours,faithfully. \n<br>MR.Ibrahim.Jallow.\n\n<br>_____________________________________________________________________\n<br><br><font face=\"Arial\" size=\"2\"><b><font color=\"#000080\">Webdunia Quiz Contest</font> - <font color=\"#FF9900\">Limited Time</font> <font color=\"#FF0000\">Unlimited Fun</font></b>.Log on to<b> <font color=\"#0000FF\"><a href=\"http://quiz.webdunia.com\" target=\"_blank\">quiz.webdunia.com</a></font></b><font color=\"#000000\"> and win<b> </b>fabulous prizes.</font></font><br><br>\n<br>India's first multilingual mailing system: Get your Free e-mail account at <a href=\"http://www.epatra.com\" target=\"_blank\">www.epatra.com</a>\n\n\nhttp://xent.com/mailman/listinfo/fork\n\n\n"}
1,667
539
<gh_stars>100-1000 /** * Copyright 2020 The Magma Authors. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * 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. */ #pragma once #include <orc8r/protos/eventd.grpc.pb.h> // for EventService::Stub, EventSe... #include <stdint.h> // for uint32_t #include <functional> // for function #include <memory> // for unique_ptr #include "orc8r/gateway/c/common/async_grpc/GRPCReceiver.hpp" // for GRPCReceiver namespace grpc { class Status; } namespace magma { namespace orc8r { class Event; } } // namespace magma namespace magma { namespace orc8r { class Void; } } // namespace magma using grpc::Status; namespace magma { /** * Base class for interfacing with EventD */ class EventdClient { public: virtual ~EventdClient() = default; virtual void log_event( const orc8r::Event& request, std::function<void(Status status, orc8r::Void)> callback) = 0; }; /** * AsyncEventdClient sends asynchronous calls to EventD * to log events */ class AsyncEventdClient : public GRPCReceiver, public EventdClient { public: AsyncEventdClient(AsyncEventdClient const&) = delete; void operator=(AsyncEventdClient const&) = delete; static AsyncEventdClient& getInstance(); void log_event(const orc8r::Event& request, std::function<void(Status status, orc8r::Void)> callback); private: AsyncEventdClient(); static const uint32_t RESPONSE_TIMEOUT_SEC = 6; std::unique_ptr<orc8r::EventService::Stub> stub_{}; }; } // namespace magma
675
432
/* * Copyright (C) 2020 ActiveJ 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. */ package io.activej.codegen.expression; import io.activej.codegen.Context; import org.objectweb.asm.Label; import org.objectweb.asm.Type; import org.objectweb.asm.commons.GeneratorAdapter; import java.util.function.UnaryOperator; import static org.objectweb.asm.Type.INT_TYPE; import static org.objectweb.asm.Type.VOID_TYPE; final class ExpressionIterate implements Expression { private final Expression from; private final Expression to; private final UnaryOperator<Expression> forVar; ExpressionIterate(Expression from, Expression to, UnaryOperator<Expression> forVar) { this.from = from; this.to = to; this.forVar = forVar; } @Override public Type load(Context ctx) { GeneratorAdapter g = ctx.getGeneratorAdapter(); Label labelLoop = new Label(); Label labelExit = new Label(); VarLocal to = ctx.newLocal(INT_TYPE); this.to.load(ctx); to.store(ctx); from.load(ctx); VarLocal it = ctx.newLocal(INT_TYPE); it.store(ctx); g.mark(labelLoop); it.load(ctx); to.load(ctx); g.ifCmp(INT_TYPE, GeneratorAdapter.GE, labelExit); Type forType = forVar.apply(it).load(ctx); if (forType.getSize() == 1) g.pop(); if (forType.getSize() == 2) g.pop2(); it.load(ctx); g.push(1); g.math(GeneratorAdapter.ADD, INT_TYPE); it.store(ctx); g.goTo(labelLoop); g.mark(labelExit); return VOID_TYPE; } }
676
14,668
// Copyright 2019 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. #ifndef CHROME_BROWSER_ASH_APP_MODE_WEB_APP_MOCK_WEB_KIOSK_APP_LAUNCHER_H_ #define CHROME_BROWSER_ASH_APP_MODE_WEB_APP_MOCK_WEB_KIOSK_APP_LAUNCHER_H_ #include "chrome/browser/ash/app_mode/web_app/web_kiosk_app_launcher.h" #include "components/account_id/account_id.h" #include "testing/gmock/include/gmock/gmock.h" namespace ash { class MockWebKioskAppLauncher : public WebKioskAppLauncher { public: MockWebKioskAppLauncher(); ~MockWebKioskAppLauncher() override; MOCK_METHOD0(Initialize, void()); MOCK_METHOD0(ContinueWithNetworkReady, void()); MOCK_METHOD0(LaunchApp, void()); MOCK_METHOD0(RestartLauncher, void()); }; } // namespace ash // TODO(https://crbug.com/1164001): remove when the //chrome/browser/chromeos // migration is finished. namespace chromeos { using ::ash::MockWebKioskAppLauncher; } #endif // CHROME_BROWSER_ASH_APP_MODE_WEB_APP_MOCK_WEB_KIOSK_APP_LAUNCHER_H_
409
648
{"resourceType":"CodeSystem","id":"concept-property-type","meta":{"lastUpdated":"2019-11-01T09:29:23.356+11:00"},"text":{"status":"generated","div":"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n <h2>PropertyType</h2>\n <div>\n <p>The type of a property value.</p>\n\n </div>\n <p>This code system http://hl7.org/fhir/concept-property-type defines the following codes:</p>\n <table class=\"codes\">\n <tr>\n <td style=\"white-space:nowrap\">\n <b>Code</b>\n </td>\n <td>\n <b>Display</b>\n </td>\n <td>\n <b>Definition</b>\n </td>\n </tr>\n <tr>\n <td style=\"white-space:nowrap\">code\n <a name=\"concept-property-type-code\"> </a>\n </td>\n <td>code (internal reference)</td>\n <td>The property value is a code that identifies a concept defined in the code system.</td>\n </tr>\n <tr>\n <td style=\"white-space:nowrap\">Coding\n <a name=\"concept-property-type-Coding\"> </a>\n </td>\n <td>Coding (external reference)</td>\n <td>The property value is a code defined in an external code system. This may be used for translations, but is not the intent.</td>\n </tr>\n <tr>\n <td style=\"white-space:nowrap\">string\n <a name=\"concept-property-type-string\"> </a>\n </td>\n <td>string</td>\n <td>The property value is a string.</td>\n </tr>\n <tr>\n <td style=\"white-space:nowrap\">integer\n <a name=\"concept-property-type-integer\"> </a>\n </td>\n <td>integer</td>\n <td>The property value is a string (often used to assign ranking values to concepts for supporting score assessments).</td>\n </tr>\n <tr>\n <td style=\"white-space:nowrap\">boolean\n <a name=\"concept-property-type-boolean\"> </a>\n </td>\n <td>boolean</td>\n <td>The property value is a boolean true | false.</td>\n </tr>\n <tr>\n <td style=\"white-space:nowrap\">dateTime\n <a name=\"concept-property-type-dateTime\"> </a>\n </td>\n <td>dateTime</td>\n <td>The property is a date or a date + time.</td>\n </tr>\n <tr>\n <td style=\"white-space:nowrap\">decimal\n <a name=\"concept-property-type-decimal\"> </a>\n </td>\n <td>decimal</td>\n <td>The property value is a decimal number.</td>\n </tr>\n </table>\n </div>"},"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/structuredefinition-wg","valueCode":"vocab"},{"url":"http://hl7.org/fhir/StructureDefinition/structuredefinition-standards-status","valueCode":"normative"},{"url":"http://hl7.org/fhir/StructureDefinition/structuredefinition-normative-version","valueCode":"4.0.0"},{"url":"http://hl7.org/fhir/StructureDefinition/structuredefinition-fmm","valueInteger":5}],"url":"http://hl7.org/fhir/concept-property-type","identifier":[{"system":"urn:ietf:rfc:3986","value":"urn:oid:2.16.840.1.113883.4.642.4.781"}],"version":"4.0.1","name":"PropertyType","title":"PropertyType","status":"active","experimental":false,"date":"2019-11-01T09:29:23+11:00","publisher":"HL7 (FHIR Project)","contact":[{"telecom":[{"system":"url","value":"http://hl7.org/fhir"},{"system":"email","value":"<EMAIL>"}]}],"description":"The type of a property value.","caseSensitive":true,"valueSet":"http://hl7.org/fhir/ValueSet/concept-property-type","content":"complete","concept":[{"code":"code","display":"code (internal reference)","definition":"The property value is a code that identifies a concept defined in the code system."},{"code":"Coding","display":"Coding (external reference)","definition":"The property value is a code defined in an external code system. This may be used for translations, but is not the intent."},{"code":"string","display":"string","definition":"The property value is a string."},{"code":"integer","display":"integer","definition":"The property value is a string (often used to assign ranking values to concepts for supporting score assessments)."},{"code":"boolean","display":"boolean","definition":"The property value is a boolean true | false."},{"code":"dateTime","display":"dateTime","definition":"The property is a date or a date + time."},{"code":"decimal","display":"decimal","definition":"The property value is a decimal number."}]}
2,280
608
// This file is part of VSTGUI. It is subject to the license terms // in the LICENSE file found in the top-level directory of this // distribution and at http://github.com/steinbergmedia/vstgui/LICENSE #include "macglobals.h" #if MAC #include "../../cframe.h" #include "../../ccolor.h" #include "macfactory.h" #include "../iplatformframe.h" #include "../common/fileresourceinputstream.h" #include "../std_unorderedmap.h" #define USE_MAIN_DISPLAY_COLORSPACE 1 namespace VSTGUI { //----------------------------------------------------------------------------- struct ColorHash { size_t operator () (const CColor& c) const { size_t v1 = static_cast<size_t> (c.red | (c.green << 8) | (c.blue << 16) | (c.alpha << 24)); return v1; } }; using CGColorMap = std::unordered_map<CColor, CGColorRef, ColorHash>; //----------------------------------------------------------------------------- class CGColorMapImpl { public: ~CGColorMapImpl () { for (auto& it : map) CFRelease (it.second); } CGColorMap map; }; //----------------------------------------------------------------------------- static CGColorMap& getColorMap () { static CGColorMapImpl colorMap; return colorMap.map; } //----------------------------------------------------------------------------- CGColorRef getCGColor (const CColor& color) { auto& colorMap = getColorMap (); auto it = colorMap.find (color); if (it != colorMap.end ()) { CGColorRef result = it->second; return result; } const CGFloat components[] = {color.normRed<CGFloat> (), color.normGreen<CGFloat> (), color.normBlue<CGFloat> (), color.normAlpha<CGFloat> ()}; CGColorRef result = CGColorCreate (GetCGColorSpace (), components); colorMap.emplace (color, result); return result; } //----------------------------------------------------------------------------- class GenericMacColorSpace { public: GenericMacColorSpace () { colorspace = CreateMainDisplayColorSpace (); } ~GenericMacColorSpace () { CGColorSpaceRelease (colorspace); } static GenericMacColorSpace& instance () { static GenericMacColorSpace gInstance; return gInstance; } //----------------------------------------------------------------------------- static CGColorSpaceRef CreateMainDisplayColorSpace () { #if TARGET_OS_IPHONE return CGColorSpaceCreateDeviceRGB (); #else ColorSyncProfileRef csProfileRef = ColorSyncProfileCreateWithDisplayID (0); if (csProfileRef) { CGColorSpaceRef colorSpace = CGColorSpaceCreateWithPlatformColorSpace (csProfileRef); CFRelease (csProfileRef); return colorSpace; } return nullptr; #endif } CGColorSpaceRef colorspace; }; //----------------------------------------------------------------------------- CGColorSpaceRef GetCGColorSpace () { return GenericMacColorSpace::instance ().colorspace; } } // VSTGUI #endif // MAC
889
724
<filename>vega/networks/pytorch/customs/modnas/contrib/arch_space/activations/torch.py """Torch activation functions.""" import torch.nn from modnas.registry.arch_space import register modules = [ 'ELU', 'Hardshrink', 'Hardtanh', 'LeakyReLU', 'LogSigmoid', 'PReLU', 'ReLU', 'ReLU6', 'RReLU', 'SELU', 'CELU', 'Sigmoid', 'Softplus', 'Softshrink', 'Softsign', 'Tanh', 'Tanhshrink', 'Threshold', ] for name in modules: attr = getattr(torch.nn, name, None) if attr is not None: register(attr)
276
488
<reponame>maurizioabba/rose /*! * \file CPreproc/IfDirectiveContextFinder.cc * * \brief Implements a module to determine the '#if' directive * context surrounding a specified target node. */ // tps (01/14/2010) : Switching from rose.h to sage3. #include "sage3basic.h" #include "IfDirectiveContextFinder.hh" // ======================================================================== using namespace std; // ======================================================================== CPreproc::IfDirectiveContextFinder::IfDirectiveContextFinder (CPreproc::Ifs_t& ifs, const SgLocatedNode* target) : IfDirectiveExtractor (ifs), target_ (target), top_ (0), bottom_ (0) { } void CPreproc::IfDirectiveContextFinder::visitTopDown (SgNode* n) { IfDirectiveExtractor::visitTopDown (n); if (isSgLocatedNode (n) == target_) top_ = getCurrentContext (); } void CPreproc::IfDirectiveContextFinder::visitBottomUp (SgNode* n) { if (isSgLocatedNode (n) == target_) bottom_ = getCurrentContext (); IfDirectiveExtractor::visitBottomUp (n); } CPreproc::If::Case * CPreproc::IfDirectiveContextFinder::getContextTop (void) { return top_; } const CPreproc::If::Case * CPreproc::IfDirectiveContextFinder::getContextTop (void) const { return top_; } CPreproc::If::Case * CPreproc::IfDirectiveContextFinder::getContextBottom (void) { return bottom_; } const CPreproc::If::Case* CPreproc::IfDirectiveContextFinder::getContextBottom (void) const { return bottom_; } // eof
568
778
<filename>modPrecompiled/test/org/aion/precompiled/encoding/AbiEncoder.java<gh_stars>100-1000 package org.aion.precompiled.encoding; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.concurrent.ThreadSafe; import org.aion.precompiled.ExternalCapabilitiesForTesting; import org.aion.precompiled.PrecompiledUtilities; import org.aion.precompiled.util.ByteUtil; @ThreadSafe public class AbiEncoder { private List<BaseTypeFVM> params; private volatile StringBuffer buffer; private String signature; private static ExternalCapabilitiesForTesting capabilities = new ExternalCapabilitiesForTesting(); public AbiEncoder(@Nonnull String signature, @Nonnull BaseTypeFVM... params) { this.params = new ArrayList<>(Arrays.asList(params)); this.signature = signature; } private synchronized void createBuffer() { // represents the offsets until dynamic parameters int offset = 0; final StringBuffer b = new StringBuffer(); b.append(ByteUtil.toHexString(encodeSignature(this.signature))); for (BaseTypeFVM type : this.params) { if (type.isDynamic()) { offset += 16; } else { offset += type.serialize().length; } } // second iteration, go through each element assembling for (BaseTypeFVM type : this.params) { if (type.isDynamic()) { byte[] off = PrecompiledUtilities.pad(BigInteger.valueOf(offset).toByteArray(), 16); b.append(ByteUtil.toHexString(off)); offset += type.serialize().length; } else { b.append(ByteUtil.toHexString(type.serialize())); } } // in the last iteration just iterate through dynamic elements for (BaseTypeFVM type : this.params) { if (type.isDynamic()) { b.append(ByteUtil.toHexString(type.serialize())); } } this.buffer = b; } private String encode() { if (buffer == null) createBuffer(); return "0x" + buffer.toString(); } public byte[] encodeBytes() { encode(); return ByteUtil.hexStringToBytes(buffer.toString()); } @Override public String toString() { return encode(); } private static byte[] encodeSignature(String s) { // encode signature byte[] sig = new byte[4]; System.arraycopy(capabilities.keccak256(s.getBytes()), 0, sig, 0, 4); return sig; } }
1,104
1,523
<filename>fe/src/main/java/org/apache/impala/util/MathUtil.java // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.impala.util; import com.google.common.math.LongMath; public class MathUtil { // Multiply two numbers. If the multiply would overflow, return either Long.MIN_VALUE // (if a xor b is negative) or Long.MAX_VALUE otherwise. The overflow path is not // optimised at all and may be somewhat slow. public static long saturatingMultiply(long a, long b) { try { return LongMath.checkedMultiply(a, b); } catch (ArithmeticException e) { return a < 0 != b < 0 ? Long.MIN_VALUE : Long.MAX_VALUE; } } // Add two numbers. If the add would overflow, return either Long.MAX_VALUE if both are // positive or Long.MIN_VALUE if both are negative. The overflow path is not optimised // at all and may be somewhat slow. public static long saturatingAdd(long a, long b) { try { return LongMath.checkedAdd(a, b); } catch (ArithmeticException e) { return a < 0 ? Long.MIN_VALUE : Long.MAX_VALUE; } } }
544
1,405
package QQPIM; public final class ESoftState { public static final ESoftState ESS_None = new ESoftState(0, 0, "ESS_None"); public static final ESoftState ESS_Offshelf = new ESoftState(1, 1, "ESS_Offshelf"); public static final int _ESS_None = 0; public static final int _ESS_Offshelf = 1; static final /* synthetic */ boolean a = (!ESoftState.class.desiredAssertionStatus()); private static ESoftState[] b = new ESoftState[2]; private int c; private String d = new String(); private ESoftState(int i, int i2, String str) { this.d = str; this.c = i2; b[i] = this; } public static ESoftState convert(int i) { for (int i2 = 0; i2 < b.length; i2++) { if (b[i2].value() == i) { return b[i2]; } } if (a) { return null; } throw new AssertionError(); } public static ESoftState convert(String str) { for (int i = 0; i < b.length; i++) { if (b[i].toString().equals(str)) { return b[i]; } } if (a) { return null; } throw new AssertionError(); } public final String toString() { return this.d; } public final int value() { return this.c; } }
636
428
/** * Copyright 2008 - 2015 The Loon Game Engine 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. * * @project loon * @author cping * @email:<EMAIL> * @version 0.5 */ package loon.action.sprite.effect; import loon.LSystem; import loon.LTexture; import loon.action.map.Config; import loon.action.map.Field2D; import loon.action.sprite.Entity; import loon.geom.RectBox; import loon.geom.Vector2f; import loon.opengl.GLEx; import loon.utils.timer.LTimer; /** * 图片拆分样黑幕过渡效果 */ public class SplitEffect extends Entity implements BaseEffect { private Vector2f movePosOne, movePosTwo; private int halfWidth, halfHeight, multiples, direction; private boolean completed, autoRemoved, special; private RectBox limit; private LTimer timer; public SplitEffect(String fileName, int d) { this(LSystem.loadTexture(fileName), d); } public SplitEffect(LTexture t, int d) { this(t, LSystem.viewSize.getRect(), d); } public SplitEffect(LTexture t, RectBox limit, int d) { this.setRepaint(true); this._image = t; this.setSize(t.width(), t.height()); this.halfWidth = (int) (_width / 2f); this.halfHeight = (int) (_height / 2f); this.multiples = 2; this.direction = d; this.limit = limit; this.timer = new LTimer(10); this.movePosOne = new Vector2f(); this.movePosTwo = new Vector2f(); switch (direction) { case Config.UP: case Config.DOWN: special = true; case Config.TLEFT: case Config.TRIGHT: movePosOne.set(0, 0); movePosTwo.set(halfWidth, 0); break; case Config.LEFT: case Config.RIGHT: special = true; case Config.TUP: case Config.TDOWN: movePosOne.set(0, 0); movePosTwo.set(0, halfHeight); break; } } public void setDelay(long delay) { timer.setDelay(delay); } public long getDelay() { return timer.getDelay(); } @Override public void onUpdate(long elapsedTime) { if (!completed) { if (timer.action(elapsedTime)) { switch (direction) { case Config.LEFT: case Config.RIGHT: case Config.TLEFT: case Config.TRIGHT: movePosOne.move_multiples(Field2D.TLEFT, multiples); movePosTwo.move_multiples(Field2D.TRIGHT, multiples); break; case Config.UP: case Config.DOWN: case Config.TUP: case Config.TDOWN: movePosOne.move_multiples(Field2D.TUP, multiples); movePosTwo.move_multiples(Field2D.TDOWN, multiples); break; } if (special) { if (!limit.intersects(movePosOne.x, movePosOne.y, halfHeight, halfWidth) && !limit.intersects(movePosTwo.x, movePosTwo.y, halfHeight, halfWidth)) { this.completed = true; } } else if (!limit.intersects(movePosOne.x, movePosOne.y, halfWidth, halfHeight) && !limit.intersects(movePosTwo.x, movePosTwo.y, halfWidth, halfHeight)) { this.completed = true; } } } if (this.completed) { if (autoRemoved && getSprites() != null) { getSprites().remove(this); } } } @Override public void repaint(GLEx g, float offsetX, float offsetY) { if (!completed) { final float x1 = movePosOne.x + getX() + offsetX + _offset.x; final float y1 = movePosOne.y + getY() + offsetY + _offset.y; final float x2 = movePosTwo.x + getX() + offsetX + _offset.x; final float y2 = movePosTwo.y + getY() + offsetY + _offset.y; switch (direction) { case Config.LEFT: case Config.RIGHT: case Config.TUP: case Config.TDOWN: g.draw(_image, x1, y1, _width, halfHeight, 0, 0, _width, halfHeight); g.draw(_image, x2, y2, _width, halfHeight, 0, halfHeight, _width, _height - halfHeight); break; case Config.UP: case Config.DOWN: case Config.TLEFT: case Config.TRIGHT: g.draw(_image, x1, y1, halfWidth, _height, 0, 0, halfWidth, _height); g.draw(_image, x2, y2, halfWidth, _height, halfWidth, 0, _width - halfWidth, _height); break; } } } @Override public boolean isCompleted() { return completed; } public int getMultiples() { return multiples; } public void setMultiples(int multiples) { this.multiples = multiples; } public boolean isAutoRemoved() { return autoRemoved; } public SplitEffect setAutoRemoved(boolean autoRemoved) { this.autoRemoved = autoRemoved; return this; } @Override public void close() { super.close(); completed = true; } }
1,904
875
<reponame>GENGXIANQIU653/jeewx-boot package com.jeecg.p3.baseApi.util; import com.alibaba.fastjson.JSONObject; import org.jeecgframework.p3.base.vo.WeixinDto; import org.jeecgframework.p3.core.util.WeiXinHttpUtil; import org.jeecgframework.p3.core.utils.common.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WeixinUserUtil { private static Logger logger= LoggerFactory.getLogger(WeixinUserUtil.class); /** * 微信获取个人信息util * * @param weixinDto * @return 获取头像 Map两个键headimgurl,fxheadimgurl */ public static void setWeixinDto(WeixinDto weixinDto, String utoken) { logger.info("setWeixinDto parameter weixinDto={}", new Object[] { weixinDto }); try { if (weixinDto.getOpenid() != null) { JSONObject jsonObj =null; if(StringUtils.isEmpty(utoken)){ jsonObj = WeiXinHttpUtil.getGzUserInfo(weixinDto.getOpenid(), weixinDto.getJwid()); }else{ jsonObj = WeiXinHttpUtil.getGzUserInfo2(weixinDto.getOpenid(), weixinDto.getJwid(),utoken); } logger.info("setWeixinDto Openid getGzUserInfo jsonObj={}", new Object[] { jsonObj }); if (jsonObj != null && jsonObj.containsKey("subscribe")) { weixinDto.setSubscribe(jsonObj.getString("subscribe")); } else { weixinDto.setSubscribe("0"); } if (jsonObj != null && jsonObj.containsKey("nickname")) { weixinDto.setNickname(jsonObj.getString("nickname")); } else { weixinDto.setNickname("匿名"); } if (jsonObj != null && jsonObj.containsKey("headimgurl")) { weixinDto.setHeadimgurl(jsonObj.getString("headimgurl")); } else { weixinDto.setHeadimgurl("http://static.h5huodong.com/upload/common/defaultHeadImg.png"); } } if (StringUtils.isNotEmpty(weixinDto.getFxOpenid())) { JSONObject jsonObj =null; if(StringUtils.isEmpty(utoken)){ jsonObj = WeiXinHttpUtil.getGzUserInfo(weixinDto.getFxOpenid(), weixinDto.getJwid()); }else{ jsonObj = WeiXinHttpUtil.getGzUserInfo2(weixinDto.getFxOpenid(),weixinDto.getJwid(),utoken); } logger.info("setWeixinDto FxOpenid getGzUserInfo jsonObj={}", new Object[] { jsonObj }); if (jsonObj != null && jsonObj.containsKey("nickname")) { weixinDto.setFxNickname(jsonObj.getString("nickname")); } else { weixinDto.setFxNickname("匿名"); } if (jsonObj != null && jsonObj.containsKey("headimgurl")) { weixinDto.setFxHeadimgurl(jsonObj.getString("headimgurl")); } else { weixinDto.setFxHeadimgurl("http://static.h5huodong.com/upload/common/defaultHeadImg.png"); } } } catch (Exception e) { logger.error("setWeixinDto e={}", new Object[] { e }); } } /** * 获取用户信息 * @param weixinDto * @return */ public static void setWeixinDtoAuthToken(WeixinDto weixinDto, String webAuthToken) { logger.info("setWeixinDto parameter weixinDto={}",new Object[] { weixinDto }); try { if (weixinDto.getOpenid() != null) { JSONObject jsonObj = null; if(StringUtils.isNotEmpty(webAuthToken)){ jsonObj=WebAuthWeixinApi.getWebAuthUserInfo(weixinDto.getOpenid(), webAuthToken); logger.info("===========================主动授权获取用户信息=============================="); }else{ jsonObj=WeiXinHttpUtil.getGzUserInfo(weixinDto.getOpenid(), weixinDto.getJwid()); logger.info("===========================静默授权获取用户信息=============================="); } logger.info("setWeixinDto Openid getGzUserInfo jsonObj={}",new Object[] { jsonObj }); if (jsonObj != null && jsonObj.containsKey("subscribe")) { weixinDto.setSubscribe(jsonObj.getString("subscribe")); } else { weixinDto.setSubscribe("0"); } if (jsonObj != null && jsonObj.containsKey("nickname")) { weixinDto.setNickname(jsonObj.getString("nickname")); } else { weixinDto.setNickname("匿名"); } if (jsonObj != null && jsonObj.containsKey("headimgurl")) { weixinDto.setHeadimgurl(jsonObj.getString("headimgurl")); } else { weixinDto.setHeadimgurl("http://static.h5huodong.com/upload/common/defaultHeadImg.png"); } } if (StringUtils.isNotEmpty(weixinDto.getFxOpenid())) { JSONObject jsonObj = WeiXinHttpUtil.getGzUserInfo(weixinDto.getFxOpenid(), weixinDto.getJwid()); logger.info("setWeixinDto FxOpenid getGzUserInfo jsonObj={}",new Object[] { jsonObj }); if (jsonObj != null && jsonObj.containsKey("nickname")) { weixinDto.setFxNickname(jsonObj.getString("nickname")); } else { weixinDto.setFxNickname("匿名"); } if (jsonObj != null && jsonObj.containsKey("headimgurl")) { weixinDto.setFxHeadimgurl(jsonObj.getString("headimgurl")); } else { weixinDto.setFxHeadimgurl("http://static.h5huodong.com/upload/common/defaultHeadImg.png"); } } } catch (Exception e) { e.printStackTrace(); logger.error("setWeixinDto e={}", new Object[] { e }); } } }
3,409
451
// File Automatically generated by eLiSe #include "StdAfx.h" #include "cEqAppui_TerFix_M2CCamBilin.h" cEqAppui_TerFix_M2CCamBilin::cEqAppui_TerFix_M2CCamBilin(): cElCompiledFonc(2) { AddIntRef (cIncIntervale("Bil0_0",3,5)); AddIntRef (cIncIntervale("Bil0_1",7,9)); AddIntRef (cIncIntervale("Bil1_0",5,7)); AddIntRef (cIncIntervale("Bil1_1",9,11)); AddIntRef (cIncIntervale("Intr",0,3)); AddIntRef (cIncIntervale("Orient",11,17)); Close(false); } void cEqAppui_TerFix_M2CCamBilin::ComputeVal() { double tmp0_ = mCompCoord[11]; double tmp1_ = mCompCoord[12]; double tmp2_ = cos(tmp1_); double tmp3_ = sin(tmp0_); double tmp4_ = cos(tmp0_); double tmp5_ = sin(tmp1_); double tmp6_ = mCompCoord[13]; double tmp7_ = mCompCoord[14]; double tmp8_ = mLocXTer-tmp7_; double tmp9_ = sin(tmp6_); double tmp10_ = -(tmp9_); double tmp11_ = -(tmp5_); double tmp12_ = cos(tmp6_); double tmp13_ = mCompCoord[15]; double tmp14_ = mLocYTer-tmp13_; double tmp15_ = mCompCoord[16]; double tmp16_ = mLocZTer-tmp15_; double tmp17_ = -(tmp3_); double tmp18_ = tmp4_*tmp11_; double tmp19_ = tmp3_*tmp11_; double tmp20_ = mCompCoord[0]; double tmp21_ = tmp17_*tmp10_; double tmp22_ = tmp18_*tmp12_; double tmp23_ = tmp21_+tmp22_; double tmp24_ = (tmp23_)*(tmp8_); double tmp25_ = tmp4_*tmp10_; double tmp26_ = tmp19_*tmp12_; double tmp27_ = tmp25_+tmp26_; double tmp28_ = (tmp27_)*(tmp14_); double tmp29_ = tmp24_+tmp28_; double tmp30_ = tmp2_*tmp12_; double tmp31_ = tmp30_*(tmp16_); double tmp32_ = tmp29_+tmp31_; double tmp33_ = tmp20_/(tmp32_); double tmp34_ = tmp4_*tmp2_; double tmp35_ = tmp34_*(tmp8_); double tmp36_ = tmp3_*tmp2_; double tmp37_ = tmp36_*(tmp14_); double tmp38_ = tmp35_+tmp37_; double tmp39_ = tmp5_*(tmp16_); double tmp40_ = tmp38_+tmp39_; double tmp41_ = (tmp40_)*(tmp33_); double tmp42_ = mCompCoord[1]; double tmp43_ = tmp41_+tmp42_; double tmp44_ = mLocPts1_x-(tmp43_); double tmp45_ = mLocPts1_x-mLocPts0_x; double tmp46_ = (tmp44_)/(tmp45_); double tmp47_ = tmp17_*tmp12_; double tmp48_ = tmp18_*tmp9_; double tmp49_ = tmp47_+tmp48_; double tmp50_ = (tmp49_)*(tmp8_); double tmp51_ = tmp4_*tmp12_; double tmp52_ = tmp19_*tmp9_; double tmp53_ = tmp51_+tmp52_; double tmp54_ = (tmp53_)*(tmp14_); double tmp55_ = tmp50_+tmp54_; double tmp56_ = tmp2_*tmp9_; double tmp57_ = tmp56_*(tmp16_); double tmp58_ = tmp55_+tmp57_; double tmp59_ = (tmp58_)*(tmp33_); double tmp60_ = mCompCoord[2]; double tmp61_ = tmp59_+tmp60_; double tmp62_ = mLocPts2_y-(tmp61_); double tmp63_ = mLocPts2_y-mLocPts0_y; double tmp64_ = (tmp62_)/(tmp63_); double tmp65_ = 1-tmp46_; double tmp66_ = 1-tmp64_; double tmp67_ = (tmp46_)*(tmp64_); double tmp68_ = (tmp65_)*(tmp64_); double tmp69_ = (tmp46_)*(tmp66_); double tmp70_ = (tmp65_)*(tmp66_); mVal[0] = ((mCompCoord[3]*tmp67_+mCompCoord[5]*tmp68_+mCompCoord[7]*tmp69_+mCompCoord[9]*tmp70_)-mLocXIm)*mLocScNorm; mVal[1] = ((mCompCoord[4]*tmp67_+mCompCoord[6]*tmp68_+mCompCoord[8]*tmp69_+mCompCoord[10]*tmp70_)-mLocYIm)*mLocScNorm; } void cEqAppui_TerFix_M2CCamBilin::ComputeValDeriv() { double tmp0_ = mCompCoord[11]; double tmp1_ = mCompCoord[12]; double tmp2_ = cos(tmp1_); double tmp3_ = sin(tmp0_); double tmp4_ = cos(tmp0_); double tmp5_ = sin(tmp1_); double tmp6_ = mCompCoord[13]; double tmp7_ = mCompCoord[14]; double tmp8_ = mLocXTer-tmp7_; double tmp9_ = sin(tmp6_); double tmp10_ = -(tmp9_); double tmp11_ = -(tmp5_); double tmp12_ = cos(tmp6_); double tmp13_ = mCompCoord[15]; double tmp14_ = mLocYTer-tmp13_; double tmp15_ = mCompCoord[16]; double tmp16_ = mLocZTer-tmp15_; double tmp17_ = -(tmp3_); double tmp18_ = tmp4_*tmp11_; double tmp19_ = tmp3_*tmp11_; double tmp20_ = mCompCoord[0]; double tmp21_ = tmp17_*tmp10_; double tmp22_ = tmp18_*tmp12_; double tmp23_ = tmp21_+tmp22_; double tmp24_ = (tmp23_)*(tmp8_); double tmp25_ = tmp4_*tmp10_; double tmp26_ = tmp19_*tmp12_; double tmp27_ = tmp25_+tmp26_; double tmp28_ = (tmp27_)*(tmp14_); double tmp29_ = tmp24_+tmp28_; double tmp30_ = tmp2_*tmp12_; double tmp31_ = tmp30_*(tmp16_); double tmp32_ = tmp29_+tmp31_; double tmp33_ = tmp20_/(tmp32_); double tmp34_ = tmp4_*tmp2_; double tmp35_ = tmp34_*(tmp8_); double tmp36_ = tmp3_*tmp2_; double tmp37_ = tmp36_*(tmp14_); double tmp38_ = tmp35_+tmp37_; double tmp39_ = tmp5_*(tmp16_); double tmp40_ = tmp38_+tmp39_; double tmp41_ = (tmp40_)*(tmp33_); double tmp42_ = mCompCoord[1]; double tmp43_ = tmp41_+tmp42_; double tmp44_ = mLocPts1_x-(tmp43_); double tmp45_ = mLocPts1_x-mLocPts0_x; double tmp46_ = (tmp44_)/(tmp45_); double tmp47_ = tmp17_*tmp12_; double tmp48_ = tmp18_*tmp9_; double tmp49_ = tmp47_+tmp48_; double tmp50_ = (tmp49_)*(tmp8_); double tmp51_ = tmp4_*tmp12_; double tmp52_ = tmp19_*tmp9_; double tmp53_ = tmp51_+tmp52_; double tmp54_ = (tmp53_)*(tmp14_); double tmp55_ = tmp50_+tmp54_; double tmp56_ = tmp2_*tmp9_; double tmp57_ = tmp56_*(tmp16_); double tmp58_ = tmp55_+tmp57_; double tmp59_ = (tmp58_)*(tmp33_); double tmp60_ = mCompCoord[2]; double tmp61_ = tmp59_+tmp60_; double tmp62_ = mLocPts2_y-(tmp61_); double tmp63_ = mLocPts2_y-mLocPts0_y; double tmp64_ = (tmp62_)/(tmp63_); double tmp65_ = 1-tmp46_; double tmp66_ = 1-tmp64_; double tmp67_ = ElSquare(tmp32_); double tmp68_ = (tmp32_)/tmp67_; double tmp69_ = mCompCoord[3]; double tmp70_ = (tmp68_)*(tmp40_); double tmp71_ = -(tmp70_); double tmp72_ = tmp71_*(tmp45_); double tmp73_ = ElSquare(tmp45_); double tmp74_ = (tmp72_)/tmp73_; double tmp75_ = (tmp68_)*(tmp58_); double tmp76_ = -(tmp75_); double tmp77_ = tmp76_*(tmp63_); double tmp78_ = ElSquare(tmp63_); double tmp79_ = (tmp77_)/tmp78_; double tmp80_ = mCompCoord[5]; double tmp81_ = mCompCoord[7]; double tmp82_ = -(tmp74_); double tmp83_ = -(tmp79_); double tmp84_ = mCompCoord[9]; double tmp85_ = -(1); double tmp86_ = tmp85_*(tmp45_); double tmp87_ = (tmp86_)/tmp73_; double tmp88_ = -(tmp87_); double tmp89_ = tmp85_*(tmp63_); double tmp90_ = (tmp89_)/tmp78_; double tmp91_ = -(tmp90_); double tmp92_ = (tmp46_)*(tmp64_); double tmp93_ = (tmp65_)*(tmp64_); double tmp94_ = (tmp46_)*(tmp66_); double tmp95_ = (tmp65_)*(tmp66_); double tmp96_ = tmp85_*tmp3_; double tmp97_ = -(tmp4_); double tmp98_ = tmp96_*tmp11_; double tmp99_ = tmp97_*tmp10_; double tmp100_ = tmp98_*tmp12_; double tmp101_ = tmp99_+tmp100_; double tmp102_ = (tmp101_)*(tmp8_); double tmp103_ = tmp96_*tmp10_; double tmp104_ = tmp103_+tmp22_; double tmp105_ = (tmp104_)*(tmp14_); double tmp106_ = tmp102_+tmp105_; double tmp107_ = tmp20_*(tmp106_); double tmp108_ = -(tmp107_); double tmp109_ = tmp108_/tmp67_; double tmp110_ = tmp96_*tmp2_; double tmp111_ = tmp110_*(tmp8_); double tmp112_ = tmp34_*(tmp14_); double tmp113_ = tmp111_+tmp112_; double tmp114_ = (tmp113_)*(tmp33_); double tmp115_ = (tmp109_)*(tmp40_); double tmp116_ = tmp114_+tmp115_; double tmp117_ = -(tmp116_); double tmp118_ = tmp117_*(tmp45_); double tmp119_ = (tmp118_)/tmp73_; double tmp120_ = tmp97_*tmp12_; double tmp121_ = tmp98_*tmp9_; double tmp122_ = tmp120_+tmp121_; double tmp123_ = (tmp122_)*(tmp8_); double tmp124_ = tmp96_*tmp12_; double tmp125_ = tmp124_+tmp48_; double tmp126_ = (tmp125_)*(tmp14_); double tmp127_ = tmp123_+tmp126_; double tmp128_ = (tmp127_)*(tmp33_); double tmp129_ = (tmp109_)*(tmp58_); double tmp130_ = tmp128_+tmp129_; double tmp131_ = -(tmp130_); double tmp132_ = tmp131_*(tmp63_); double tmp133_ = (tmp132_)/tmp78_; double tmp134_ = -(tmp119_); double tmp135_ = -(tmp133_); double tmp136_ = tmp85_*tmp5_; double tmp137_ = -(tmp2_); double tmp138_ = tmp137_*tmp4_; double tmp139_ = tmp137_*tmp3_; double tmp140_ = tmp138_*tmp12_; double tmp141_ = tmp140_*(tmp8_); double tmp142_ = tmp139_*tmp12_; double tmp143_ = tmp142_*(tmp14_); double tmp144_ = tmp141_+tmp143_; double tmp145_ = tmp136_*tmp12_; double tmp146_ = tmp145_*(tmp16_); double tmp147_ = tmp144_+tmp146_; double tmp148_ = tmp20_*(tmp147_); double tmp149_ = -(tmp148_); double tmp150_ = tmp149_/tmp67_; double tmp151_ = tmp136_*tmp4_; double tmp152_ = tmp151_*(tmp8_); double tmp153_ = tmp136_*tmp3_; double tmp154_ = tmp153_*(tmp14_); double tmp155_ = tmp152_+tmp154_; double tmp156_ = tmp2_*(tmp16_); double tmp157_ = tmp155_+tmp156_; double tmp158_ = (tmp157_)*(tmp33_); double tmp159_ = (tmp150_)*(tmp40_); double tmp160_ = tmp158_+tmp159_; double tmp161_ = -(tmp160_); double tmp162_ = tmp161_*(tmp45_); double tmp163_ = (tmp162_)/tmp73_; double tmp164_ = tmp138_*tmp9_; double tmp165_ = tmp164_*(tmp8_); double tmp166_ = tmp139_*tmp9_; double tmp167_ = tmp166_*(tmp14_); double tmp168_ = tmp165_+tmp167_; double tmp169_ = tmp136_*tmp9_; double tmp170_ = tmp169_*(tmp16_); double tmp171_ = tmp168_+tmp170_; double tmp172_ = (tmp171_)*(tmp33_); double tmp173_ = (tmp150_)*(tmp58_); double tmp174_ = tmp172_+tmp173_; double tmp175_ = -(tmp174_); double tmp176_ = tmp175_*(tmp63_); double tmp177_ = (tmp176_)/tmp78_; double tmp178_ = -(tmp163_); double tmp179_ = -(tmp177_); double tmp180_ = -(tmp12_); double tmp181_ = tmp85_*tmp9_; double tmp182_ = tmp180_*tmp17_; double tmp183_ = tmp181_*tmp18_; double tmp184_ = tmp182_+tmp183_; double tmp185_ = (tmp184_)*(tmp8_); double tmp186_ = tmp180_*tmp4_; double tmp187_ = tmp181_*tmp19_; double tmp188_ = tmp186_+tmp187_; double tmp189_ = (tmp188_)*(tmp14_); double tmp190_ = tmp185_+tmp189_; double tmp191_ = tmp181_*tmp2_; double tmp192_ = tmp191_*(tmp16_); double tmp193_ = tmp190_+tmp192_; double tmp194_ = tmp20_*(tmp193_); double tmp195_ = -(tmp194_); double tmp196_ = tmp195_/tmp67_; double tmp197_ = (tmp196_)*(tmp40_); double tmp198_ = -(tmp197_); double tmp199_ = tmp198_*(tmp45_); double tmp200_ = (tmp199_)/tmp73_; double tmp201_ = tmp181_*tmp17_; double tmp202_ = tmp12_*tmp18_; double tmp203_ = tmp201_+tmp202_; double tmp204_ = (tmp203_)*(tmp8_); double tmp205_ = tmp181_*tmp4_; double tmp206_ = tmp12_*tmp19_; double tmp207_ = tmp205_+tmp206_; double tmp208_ = (tmp207_)*(tmp14_); double tmp209_ = tmp204_+tmp208_; double tmp210_ = tmp12_*tmp2_; double tmp211_ = tmp210_*(tmp16_); double tmp212_ = tmp209_+tmp211_; double tmp213_ = (tmp212_)*(tmp33_); double tmp214_ = (tmp196_)*(tmp58_); double tmp215_ = tmp213_+tmp214_; double tmp216_ = -(tmp215_); double tmp217_ = tmp216_*(tmp63_); double tmp218_ = (tmp217_)/tmp78_; double tmp219_ = -(tmp200_); double tmp220_ = -(tmp218_); double tmp221_ = tmp85_*(tmp23_); double tmp222_ = tmp20_*tmp221_; double tmp223_ = -(tmp222_); double tmp224_ = tmp223_/tmp67_; double tmp225_ = tmp85_*tmp34_; double tmp226_ = tmp225_*(tmp33_); double tmp227_ = (tmp224_)*(tmp40_); double tmp228_ = tmp226_+tmp227_; double tmp229_ = -(tmp228_); double tmp230_ = tmp229_*(tmp45_); double tmp231_ = (tmp230_)/tmp73_; double tmp232_ = tmp85_*(tmp49_); double tmp233_ = tmp232_*(tmp33_); double tmp234_ = (tmp224_)*(tmp58_); double tmp235_ = tmp233_+tmp234_; double tmp236_ = -(tmp235_); double tmp237_ = tmp236_*(tmp63_); double tmp238_ = (tmp237_)/tmp78_; double tmp239_ = -(tmp231_); double tmp240_ = -(tmp238_); double tmp241_ = tmp85_*(tmp27_); double tmp242_ = tmp20_*tmp241_; double tmp243_ = -(tmp242_); double tmp244_ = tmp243_/tmp67_; double tmp245_ = tmp85_*tmp36_; double tmp246_ = tmp245_*(tmp33_); double tmp247_ = (tmp244_)*(tmp40_); double tmp248_ = tmp246_+tmp247_; double tmp249_ = -(tmp248_); double tmp250_ = tmp249_*(tmp45_); double tmp251_ = (tmp250_)/tmp73_; double tmp252_ = tmp85_*(tmp53_); double tmp253_ = tmp252_*(tmp33_); double tmp254_ = (tmp244_)*(tmp58_); double tmp255_ = tmp253_+tmp254_; double tmp256_ = -(tmp255_); double tmp257_ = tmp256_*(tmp63_); double tmp258_ = (tmp257_)/tmp78_; double tmp259_ = -(tmp251_); double tmp260_ = -(tmp258_); double tmp261_ = tmp85_*tmp30_; double tmp262_ = tmp20_*tmp261_; double tmp263_ = -(tmp262_); double tmp264_ = tmp263_/tmp67_; double tmp265_ = tmp136_*(tmp33_); double tmp266_ = (tmp264_)*(tmp40_); double tmp267_ = tmp265_+tmp266_; double tmp268_ = -(tmp267_); double tmp269_ = tmp268_*(tmp45_); double tmp270_ = (tmp269_)/tmp73_; double tmp271_ = tmp85_*tmp56_; double tmp272_ = tmp271_*(tmp33_); double tmp273_ = (tmp264_)*(tmp58_); double tmp274_ = tmp272_+tmp273_; double tmp275_ = -(tmp274_); double tmp276_ = tmp275_*(tmp63_); double tmp277_ = (tmp276_)/tmp78_; double tmp278_ = -(tmp270_); double tmp279_ = -(tmp277_); double tmp280_ = (tmp74_)*(tmp64_); double tmp281_ = (tmp79_)*(tmp46_); double tmp282_ = tmp280_+tmp281_; double tmp283_ = mCompCoord[4]; double tmp284_ = tmp82_*(tmp64_); double tmp285_ = (tmp79_)*(tmp65_); double tmp286_ = tmp284_+tmp285_; double tmp287_ = mCompCoord[6]; double tmp288_ = (tmp74_)*(tmp66_); double tmp289_ = tmp83_*(tmp46_); double tmp290_ = tmp288_+tmp289_; double tmp291_ = mCompCoord[8]; double tmp292_ = tmp82_*(tmp66_); double tmp293_ = tmp83_*(tmp65_); double tmp294_ = tmp292_+tmp293_; double tmp295_ = mCompCoord[10]; double tmp296_ = (tmp87_)*(tmp64_); double tmp297_ = tmp88_*(tmp64_); double tmp298_ = (tmp87_)*(tmp66_); double tmp299_ = tmp88_*(tmp66_); double tmp300_ = (tmp90_)*(tmp46_); double tmp301_ = (tmp90_)*(tmp65_); double tmp302_ = tmp91_*(tmp46_); double tmp303_ = tmp91_*(tmp65_); double tmp304_ = tmp92_*mLocScNorm; double tmp305_ = tmp93_*mLocScNorm; double tmp306_ = tmp94_*mLocScNorm; double tmp307_ = tmp95_*mLocScNorm; double tmp308_ = (tmp119_)*(tmp64_); double tmp309_ = (tmp133_)*(tmp46_); double tmp310_ = tmp308_+tmp309_; double tmp311_ = tmp134_*(tmp64_); double tmp312_ = (tmp133_)*(tmp65_); double tmp313_ = tmp311_+tmp312_; double tmp314_ = (tmp119_)*(tmp66_); double tmp315_ = tmp135_*(tmp46_); double tmp316_ = tmp314_+tmp315_; double tmp317_ = tmp134_*(tmp66_); double tmp318_ = tmp135_*(tmp65_); double tmp319_ = tmp317_+tmp318_; double tmp320_ = (tmp163_)*(tmp64_); double tmp321_ = (tmp177_)*(tmp46_); double tmp322_ = tmp320_+tmp321_; double tmp323_ = tmp178_*(tmp64_); double tmp324_ = (tmp177_)*(tmp65_); double tmp325_ = tmp323_+tmp324_; double tmp326_ = (tmp163_)*(tmp66_); double tmp327_ = tmp179_*(tmp46_); double tmp328_ = tmp326_+tmp327_; double tmp329_ = tmp178_*(tmp66_); double tmp330_ = tmp179_*(tmp65_); double tmp331_ = tmp329_+tmp330_; double tmp332_ = (tmp200_)*(tmp64_); double tmp333_ = (tmp218_)*(tmp46_); double tmp334_ = tmp332_+tmp333_; double tmp335_ = tmp219_*(tmp64_); double tmp336_ = (tmp218_)*(tmp65_); double tmp337_ = tmp335_+tmp336_; double tmp338_ = (tmp200_)*(tmp66_); double tmp339_ = tmp220_*(tmp46_); double tmp340_ = tmp338_+tmp339_; double tmp341_ = tmp219_*(tmp66_); double tmp342_ = tmp220_*(tmp65_); double tmp343_ = tmp341_+tmp342_; double tmp344_ = (tmp231_)*(tmp64_); double tmp345_ = (tmp238_)*(tmp46_); double tmp346_ = tmp344_+tmp345_; double tmp347_ = tmp239_*(tmp64_); double tmp348_ = (tmp238_)*(tmp65_); double tmp349_ = tmp347_+tmp348_; double tmp350_ = (tmp231_)*(tmp66_); double tmp351_ = tmp240_*(tmp46_); double tmp352_ = tmp350_+tmp351_; double tmp353_ = tmp239_*(tmp66_); double tmp354_ = tmp240_*(tmp65_); double tmp355_ = tmp353_+tmp354_; double tmp356_ = (tmp251_)*(tmp64_); double tmp357_ = (tmp258_)*(tmp46_); double tmp358_ = tmp356_+tmp357_; double tmp359_ = tmp259_*(tmp64_); double tmp360_ = (tmp258_)*(tmp65_); double tmp361_ = tmp359_+tmp360_; double tmp362_ = (tmp251_)*(tmp66_); double tmp363_ = tmp260_*(tmp46_); double tmp364_ = tmp362_+tmp363_; double tmp365_ = tmp259_*(tmp66_); double tmp366_ = tmp260_*(tmp65_); double tmp367_ = tmp365_+tmp366_; double tmp368_ = (tmp270_)*(tmp64_); double tmp369_ = (tmp277_)*(tmp46_); double tmp370_ = tmp368_+tmp369_; double tmp371_ = tmp278_*(tmp64_); double tmp372_ = (tmp277_)*(tmp65_); double tmp373_ = tmp371_+tmp372_; double tmp374_ = (tmp270_)*(tmp66_); double tmp375_ = tmp279_*(tmp46_); double tmp376_ = tmp374_+tmp375_; double tmp377_ = tmp278_*(tmp66_); double tmp378_ = tmp279_*(tmp65_); double tmp379_ = tmp377_+tmp378_; mVal[0] = ((tmp69_*tmp92_+tmp80_*tmp93_+tmp81_*tmp94_+tmp84_*tmp95_)-mLocXIm)*mLocScNorm; mCompDer[0][0] = ((tmp282_)*tmp69_+(tmp286_)*tmp80_+(tmp290_)*tmp81_+(tmp294_)*tmp84_)*mLocScNorm; mCompDer[0][1] = (tmp296_*tmp69_+tmp297_*tmp80_+tmp298_*tmp81_+tmp299_*tmp84_)*mLocScNorm; mCompDer[0][2] = (tmp300_*tmp69_+tmp301_*tmp80_+tmp302_*tmp81_+tmp303_*tmp84_)*mLocScNorm; mCompDer[0][3] = tmp304_; mCompDer[0][4] = 0; mCompDer[0][5] = tmp305_; mCompDer[0][6] = 0; mCompDer[0][7] = tmp306_; mCompDer[0][8] = 0; mCompDer[0][9] = tmp307_; mCompDer[0][10] = 0; mCompDer[0][11] = ((tmp310_)*tmp69_+(tmp313_)*tmp80_+(tmp316_)*tmp81_+(tmp319_)*tmp84_)*mLocScNorm; mCompDer[0][12] = ((tmp322_)*tmp69_+(tmp325_)*tmp80_+(tmp328_)*tmp81_+(tmp331_)*tmp84_)*mLocScNorm; mCompDer[0][13] = ((tmp334_)*tmp69_+(tmp337_)*tmp80_+(tmp340_)*tmp81_+(tmp343_)*tmp84_)*mLocScNorm; mCompDer[0][14] = ((tmp346_)*tmp69_+(tmp349_)*tmp80_+(tmp352_)*tmp81_+(tmp355_)*tmp84_)*mLocScNorm; mCompDer[0][15] = ((tmp358_)*tmp69_+(tmp361_)*tmp80_+(tmp364_)*tmp81_+(tmp367_)*tmp84_)*mLocScNorm; mCompDer[0][16] = ((tmp370_)*tmp69_+(tmp373_)*tmp80_+(tmp376_)*tmp81_+(tmp379_)*tmp84_)*mLocScNorm; mVal[1] = ((tmp283_*tmp92_+tmp287_*tmp93_+tmp291_*tmp94_+tmp295_*tmp95_)-mLocYIm)*mLocScNorm; mCompDer[1][0] = ((tmp282_)*tmp283_+(tmp286_)*tmp287_+(tmp290_)*tmp291_+(tmp294_)*tmp295_)*mLocScNorm; mCompDer[1][1] = (tmp296_*tmp283_+tmp297_*tmp287_+tmp298_*tmp291_+tmp299_*tmp295_)*mLocScNorm; mCompDer[1][2] = (tmp300_*tmp283_+tmp301_*tmp287_+tmp302_*tmp291_+tmp303_*tmp295_)*mLocScNorm; mCompDer[1][3] = 0; mCompDer[1][4] = tmp304_; mCompDer[1][5] = 0; mCompDer[1][6] = tmp305_; mCompDer[1][7] = 0; mCompDer[1][8] = tmp306_; mCompDer[1][9] = 0; mCompDer[1][10] = tmp307_; mCompDer[1][11] = ((tmp310_)*tmp283_+(tmp313_)*tmp287_+(tmp316_)*tmp291_+(tmp319_)*tmp295_)*mLocScNorm; mCompDer[1][12] = ((tmp322_)*tmp283_+(tmp325_)*tmp287_+(tmp328_)*tmp291_+(tmp331_)*tmp295_)*mLocScNorm; mCompDer[1][13] = ((tmp334_)*tmp283_+(tmp337_)*tmp287_+(tmp340_)*tmp291_+(tmp343_)*tmp295_)*mLocScNorm; mCompDer[1][14] = ((tmp346_)*tmp283_+(tmp349_)*tmp287_+(tmp352_)*tmp291_+(tmp355_)*tmp295_)*mLocScNorm; mCompDer[1][15] = ((tmp358_)*tmp283_+(tmp361_)*tmp287_+(tmp364_)*tmp291_+(tmp367_)*tmp295_)*mLocScNorm; mCompDer[1][16] = ((tmp370_)*tmp283_+(tmp373_)*tmp287_+(tmp376_)*tmp291_+(tmp379_)*tmp295_)*mLocScNorm; } void cEqAppui_TerFix_M2CCamBilin::ComputeValDerivHessian() { ELISE_ASSERT(false,"Foncteur cEqAppui_TerFix_M2CCamBilin Has no Der Sec"); } void cEqAppui_TerFix_M2CCamBilin::SetPts0_x(double aVal){ mLocPts0_x = aVal;} void cEqAppui_TerFix_M2CCamBilin::SetPts0_y(double aVal){ mLocPts0_y = aVal;} void cEqAppui_TerFix_M2CCamBilin::SetPts1_x(double aVal){ mLocPts1_x = aVal;} void cEqAppui_TerFix_M2CCamBilin::SetPts2_y(double aVal){ mLocPts2_y = aVal;} void cEqAppui_TerFix_M2CCamBilin::SetScNorm(double aVal){ mLocScNorm = aVal;} void cEqAppui_TerFix_M2CCamBilin::SetXIm(double aVal){ mLocXIm = aVal;} void cEqAppui_TerFix_M2CCamBilin::SetXTer(double aVal){ mLocXTer = aVal;} void cEqAppui_TerFix_M2CCamBilin::SetYIm(double aVal){ mLocYIm = aVal;} void cEqAppui_TerFix_M2CCamBilin::SetYTer(double aVal){ mLocYTer = aVal;} void cEqAppui_TerFix_M2CCamBilin::SetZTer(double aVal){ mLocZTer = aVal;} double * cEqAppui_TerFix_M2CCamBilin::AdrVarLocFromString(const std::string & aName) { if (aName == "Pts0_x") return & mLocPts0_x; if (aName == "Pts0_y") return & mLocPts0_y; if (aName == "Pts1_x") return & mLocPts1_x; if (aName == "Pts2_y") return & mLocPts2_y; if (aName == "ScNorm") return & mLocScNorm; if (aName == "XIm") return & mLocXIm; if (aName == "XTer") return & mLocXTer; if (aName == "YIm") return & mLocYIm; if (aName == "YTer") return & mLocYTer; if (aName == "ZTer") return & mLocZTer; return 0; } cElCompiledFonc::cAutoAddEntry cEqAppui_TerFix_M2CCamBilin::mTheAuto("cEqAppui_TerFix_M2CCamBilin",cEqAppui_TerFix_M2CCamBilin::Alloc); cElCompiledFonc * cEqAppui_TerFix_M2CCamBilin::Alloc() { return new cEqAppui_TerFix_M2CCamBilin(); }
9,851
507
<gh_stars>100-1000 // // Copyright 2019 Autodesk // // 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 <mayaUsd/fileio/importData.h> #include <mayaUsdUI/ui/IMayaMQtUtil.h> #include <mayaUsdUI/ui/USDImportDialog.h> #include <pxr/usd/usd/stagePopulationMask.h> #include <QtCore/QProcessEnvironment> #include <QtWidgets/QApplication> #include <QtWidgets/QStyle> #include <iostream> #include <string> class TestUIQtUtil : public MayaUsd::IMayaMQtUtil { public: ~TestUIQtUtil() override = default; int dpiScale(int size) const override; float dpiScale(float size) const override; QPixmap* createPixmap(const std::string& imageName) const override; }; int TestUIQtUtil::dpiScale(int size) const { return size; } float TestUIQtUtil::dpiScale(float size) const { return size; } QPixmap* TestUIQtUtil::createPixmap(const std::string& imageName) const { QString resName(":/"); resName += imageName.c_str(); return new QPixmap(resName); } int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " <filename> <rootPrimPath> <primVarSelection>" << std::endl; std::cout << std::endl; std::cout << " Ex: " << argv[0] << "\"/Kitchen_set/Props_grp/DiningTable_grp/ChairB_2\" " "\"/Kitchen_set/Props_grp/North_grp/NorthWall_grp/NailA_1:modelingVariant=NailB\"" << std::endl; exit(EXIT_FAILURE); } if (QProcessEnvironment::systemEnvironment().contains("MAYA_LOCATION")) { QString mayaLoc = QProcessEnvironment::systemEnvironment().value("MAYA_LOCATION"); QCoreApplication::addLibraryPath(mayaLoc + "\\plugins"); } QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); // Create the Qt Application QApplication app(argc, argv); app.setStyle("adskdarkflatui"); std::string usdFile = argv[1]; // Set some import data for testing. MayaUsd::ImportData importData(usdFile); if (argc >= 3) { std::string strRootPrimPath = argv[2]; importData.setRootPrimPath(strRootPrimPath); } if (argc >= 4) { std::string strPrimVarSel = argv[3]; std::string::size_type pos1 = strPrimVarSel.find(':'); if (pos1 != std::string::npos) { std::string strPrimPath = strPrimVarSel.substr(0, pos1); std::string::size_type pos2 = strPrimVarSel.find('=', pos1); if (pos2 != std::string::npos) { std::string strVarName = strPrimVarSel.substr(pos1 + 1, pos2 - pos1 - 1); std::string strVarSel = strPrimVarSel.substr(pos2 + 1); MayaUsd::ImportData::PrimVariantSelections primVarSels; SdfVariantSelectionMap varSel; varSel[strVarName] = strVarSel; primVarSels[SdfPath(strPrimPath)] = varSel; importData.setPrimVariantSelections(primVarSels); } } } // Create and show the ImportUI TestUIQtUtil uiQtUtil; MayaUsd::USDImportDialog usdImportDialog(usdFile, &importData, uiQtUtil); // Give the dialog the Maya dark style. QStyle* adsk = app.style(); usdImportDialog.setStyle(adsk); QPalette newPal(adsk->standardPalette()); newPal.setBrush( QPalette::Active, QPalette::AlternateBase, newPal.color(QPalette::Active, QPalette::Base).lighter(130)); usdImportDialog.setPalette(newPal); usdImportDialog.show(); auto ret = app.exec(); std::string rootPrimPath = usdImportDialog.rootPrimPath(); UsdStagePopulationMask popMask = usdImportDialog.stagePopulationMask(); MayaUsd::ImportData::PrimVariantSelections varSel = usdImportDialog.primVariantSelections(); return ret; }
1,927