max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
346
<filename>Language Skills/Python/Unit 05 Lists & Dictionaries/02 A Day at the Supermarket/Owning a Store/9-Something of value.py prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3, } stock = { "banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15, } for key in prices: print key print "price: %s" % prices[key] print "stock: %s" % stock[key] total = 0 for n in stock: total = total + (stock[n] * prices[n]) print total
221
1,853
int main() { struct S { int v{676}; int v2 = 828; }; }
52
580
<gh_stars>100-1000 #include<bits/stdc++.h> #define ll long long int #define watch(x) cout << (#x) << " is " << (x) << endl //watch function print variable and value for debugging #define count_ones __builtin_popcountll // count_ones(9) is equal to 2 valid for ll also #define MOD 1000000007 #define pb push_back #define fo(i,n) for(ll i=0;i<n;i++) using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t, x,tem,tem2; cin>>t; while(t--) { tem = 0;; cin >> x; if (x % 2 != 0) { cout << x << endl; continue; } while (x != 0) { tem = tem << 1; tem = tem + (x & 1); x = x >> 1; } cout << tem << endl; } return 0; }
369
1,091
<reponame>meodaiduoi/onos /* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.vpls.config; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableSet; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.onosproject.net.EncapsulationType; import org.onosproject.net.config.ConfigApplyDelegate; import org.onosproject.net.config.NetworkConfigEvent; import org.onosproject.net.config.NetworkConfigRegistryAdapter; import org.onosproject.vpls.VplsTest; import org.onosproject.vpls.api.VplsData; import java.io.IOException; import java.util.Collection; import static org.junit.Assert.*; public class VplsConfigManagerTest extends VplsTest { VplsConfigManager vplsConfigManager; @Before public void setup() { vplsConfigManager = new VplsConfigManager(); vplsConfigManager.configService = new TestConfigService(); vplsConfigManager.coreService = new TestCoreService(); vplsConfigManager.interfaceService = new TestInterfaceService(); vplsConfigManager.registry = new NetworkConfigRegistryAdapter(); vplsConfigManager.vpls = new TestVpls(); vplsConfigManager.leadershipService = new TestLeadershipService(); vplsConfigManager.activate(); } @After public void tearDown() { vplsConfigManager.deactivate(); } /** * Reloads network configuration by sending a network config event. */ @Test public void testReloadConfig() { NetworkConfigEvent event = new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_ADDED, null, VplsAppConfig.class); ((TestConfigService) vplsConfigManager.configService).sendEvent(event); Collection<VplsData> vplss = vplsConfigManager.vpls.getAllVpls(); assertEquals(2, vplss.size()); VplsData expect = VplsData.of(VPLS1); expect.addInterfaces(ImmutableSet.of(V100H1, V100H2)); expect.state(VplsData.VplsState.ADDED); assertTrue(vplss.contains(expect)); expect = VplsData.of(VPLS2, EncapsulationType.VLAN); expect.addInterfaces(ImmutableSet.of(V200H1, V200H2)); expect.state(VplsData.VplsState.ADDED); System.out.println(vplss); assertTrue(vplss.contains(expect)); } /** * Sends a network config event with null network config. */ @Test public void testReloadNullConfig() { ((TestConfigService) vplsConfigManager.configService).setConfig(null); NetworkConfigEvent event = new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_ADDED, null, VplsAppConfig.class); ((TestConfigService) vplsConfigManager.configService).sendEvent(event); Collection<VplsData> vplss = vplsConfigManager.vpls.getAllVpls(); assertEquals(0, vplss.size()); } /** * Updates VPLSs by sending new VPLS config. */ @Test public void testReloadConfigUpdateVpls() { ((TestVpls) vplsConfigManager.vpls).initSampleData(); VplsAppConfig vplsAppConfig = new VplsAppConfig(); final ObjectMapper mapper = new ObjectMapper(); final ConfigApplyDelegate delegate = new VplsAppConfigTest.MockCfgDelegate(); JsonNode tree = null; try { tree = new ObjectMapper().readTree(TestConfigService.EMPTY_JSON_TREE); } catch (IOException e) { e.printStackTrace(); } vplsAppConfig.init(APPID, APP_NAME, tree, mapper, delegate); VplsConfig vplsConfig = new VplsConfig(VPLS1, ImmutableSet.of(V100H1.name()), EncapsulationType.MPLS); vplsAppConfig.addVpls(vplsConfig); ((TestConfigService) vplsConfigManager.configService).setConfig(vplsAppConfig); NetworkConfigEvent event = new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_ADDED, null, VplsAppConfig.class); ((TestConfigService) vplsConfigManager.configService).sendEvent(event); Collection<VplsData> vplss = vplsConfigManager.vpls.getAllVpls(); assertEquals(1, vplss.size()); VplsData expect = VplsData.of(VPLS1, EncapsulationType.MPLS); expect.addInterfaces(ImmutableSet.of(V100H1)); expect.state(VplsData.VplsState.ADDED); assertTrue(vplss.contains(expect)); } /** * Remvoes all VPLS by sending CONFIG_REMOVED event. */ @Test public void testRemoveConfig() { NetworkConfigEvent event = new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_REMOVED, null, VplsAppConfig.class); ((TestConfigService) vplsConfigManager.configService).sendEvent(event); Collection<VplsData> vplss = vplsConfigManager.vpls.getAllVpls(); assertEquals(0, vplss.size()); } }
2,627
317
<filename>mxnet/image_train.hpp<gh_stars>100-1000 /*! * Copyright (c) 2016 by Contributors */ #ifndef __H2O_IMAGE_TRAIN_H__ #define __H2O_IMAGE_TRAIN_H__ #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <network_def.hpp> class ImageTrain{ private: void setClassificationDimensions(int num_classes, int batch_size); void setOptimizer(); void initializeState(); public: explicit ImageTrain(int w = 0, int h = 0, int c = 0, int device = 0, int seed = 0, bool gpu = true); void buildNet(int num_classes, int batch_size, char * net_name, int num_hidden=0, int *hidden=nullptr, char**activations=nullptr, double input_dropout=0, double *hidden_dropout=nullptr); void setSeed(int seed); void loadModel(char * model_path); void saveModel(char * model_path); void loadParam(char * param_path); void saveParam(char * param_path); const char * toJson(); std::vector<float> loadMeanImage(const char * file_path); void setLR(float lr) {learning_rate = lr;} void setWD(float wd) {weight_decay = wd;} void setMomentum(float m) { momentum = m; if (opt.get() != nullptr) opt->SetParam("momentum", momentum); } void setClipGradient(float c) { clip_gradient = c; if (opt.get() != nullptr) opt->SetParam("clip_gradient", clip_gradient); } //train/predict on a mini-batch std::vector<float> train(float * data, float * label); std::vector<float> predict(float * data, float * label); std::vector<float> predict(float * data); std::vector<float> extractLayer(float * image_data, const char * output_key); const char * listAllLayers(); private: int width, height, channels; int batch_size, num_classes; float learning_rate, weight_decay, momentum, clip_gradient; std::map<std::string, mxnet::cpp::NDArray> args_map; std::map<std::string, mxnet::cpp::NDArray> aux_map; mxnet::cpp::Symbol mxnet_sym; std::unique_ptr<mxnet::cpp::Executor> exec; std::unique_ptr<mxnet::cpp::Optimizer> opt; bool is_built; mxnet::cpp::Context ctx_dev; std::vector<float> execute(float * data, float * label, bool is_train); // prediction probs std::vector<float> preds; mxnet::cpp::Shape shape; }; #endif
885
1,204
<reponame>DiegoEliasCosta/gs-collections<gh_stars>1000+ /* * Copyright 2014 <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. */ package com.gs.collections.impl.lazy.parallel; import java.util.Comparator; import com.gs.collections.api.ParallelIterable; import com.gs.collections.api.RichIterable; import com.gs.collections.api.bag.MutableBag; import com.gs.collections.api.bag.sorted.MutableSortedBag; import com.gs.collections.api.block.function.Function; import com.gs.collections.api.block.function.Function0; import com.gs.collections.api.block.function.Function2; import com.gs.collections.api.block.function.primitive.DoubleFunction; import com.gs.collections.api.block.function.primitive.FloatFunction; import com.gs.collections.api.block.function.primitive.IntFunction; import com.gs.collections.api.block.function.primitive.LongFunction; import com.gs.collections.api.block.predicate.Predicate; import com.gs.collections.api.block.predicate.Predicate2; import com.gs.collections.api.block.procedure.Procedure; import com.gs.collections.api.block.procedure.Procedure2; import com.gs.collections.api.list.MutableList; import com.gs.collections.api.map.MapIterable; import com.gs.collections.api.map.MutableMap; import com.gs.collections.api.map.sorted.MutableSortedMap; import com.gs.collections.api.set.MutableSet; import com.gs.collections.api.set.sorted.MutableSortedSet; public abstract class NonParallelIterable<T, RI extends RichIterable<T>> implements ParallelIterable<T> { protected final RI delegate; protected NonParallelIterable(RI delegate) { this.delegate = delegate; } public void forEach(Procedure<? super T> procedure) { this.delegate.forEach(procedure); } public <P> void forEachWith(Procedure2<? super T, ? super P> procedure, P parameter) { this.delegate.forEachWith(procedure, parameter); } public T detect(Predicate<? super T> predicate) { return this.delegate.detect(predicate); } public <P> T detectWith(Predicate2<? super T, ? super P> predicate, P parameter) { return this.delegate.detectWith(predicate, parameter); } public T detectIfNone(Predicate<? super T> predicate, Function0<? extends T> function) { return this.delegate.detectIfNone(predicate, function); } public <P> T detectWithIfNone(Predicate2<? super T, ? super P> predicate, P parameter, Function0<? extends T> function) { return this.delegate.detectWithIfNone(predicate, parameter, function); } public int count(Predicate<? super T> predicate) { return this.delegate.count(predicate); } public <P> int countWith(Predicate2<? super T, ? super P> predicate, P parameter) { return this.delegate.countWith(predicate, parameter); } public boolean anySatisfy(Predicate<? super T> predicate) { return this.delegate.anySatisfy(predicate); } public <P> boolean anySatisfyWith(Predicate2<? super T, ? super P> predicate, P parameter) { return this.delegate.anySatisfyWith(predicate, parameter); } public boolean allSatisfy(Predicate<? super T> predicate) { return this.delegate.allSatisfy(predicate); } public <P> boolean allSatisfyWith(Predicate2<? super T, ? super P> predicate, P parameter) { return this.delegate.allSatisfyWith(predicate, parameter); } public boolean noneSatisfy(Predicate<? super T> predicate) { return this.delegate.noneSatisfy(predicate); } public <P> boolean noneSatisfyWith(Predicate2<? super T, ? super P> predicate, P parameter) { return this.delegate.noneSatisfyWith(predicate, parameter); } public MutableList<T> toList() { return this.delegate.toList(); } public MutableList<T> toSortedList() { return this.delegate.toSortedList(); } public MutableList<T> toSortedList(Comparator<? super T> comparator) { return this.delegate.toSortedList(comparator); } public <V extends Comparable<? super V>> MutableList<T> toSortedListBy(Function<? super T, ? extends V> function) { return this.delegate.toSortedListBy(function); } public MutableSet<T> toSet() { return this.delegate.toSet(); } public MutableSortedSet<T> toSortedSet() { return this.delegate.toSortedSet(); } public MutableSortedSet<T> toSortedSet(Comparator<? super T> comparator) { return this.delegate.toSortedSet(comparator); } public <V extends Comparable<? super V>> MutableSortedSet<T> toSortedSetBy(Function<? super T, ? extends V> function) { return this.delegate.toSortedSetBy(function); } public MutableBag<T> toBag() { return this.delegate.toBag(); } public MutableSortedBag<T> toSortedBag() { return this.delegate.toSortedBag(); } public MutableSortedBag<T> toSortedBag(Comparator<? super T> comparator) { return this.delegate.toSortedBag(comparator); } public <V extends Comparable<? super V>> MutableSortedBag<T> toSortedBagBy(Function<? super T, ? extends V> function) { return this.delegate.toSortedBagBy(function); } public <NK, NV> MutableMap<NK, NV> toMap(Function<? super T, ? extends NK> keyFunction, Function<? super T, ? extends NV> valueFunction) { return this.delegate.toMap(keyFunction, valueFunction); } public <NK, NV> MutableSortedMap<NK, NV> toSortedMap(Function<? super T, ? extends NK> keyFunction, Function<? super T, ? extends NV> valueFunction) { return this.delegate.toSortedMap(keyFunction, valueFunction); } public <NK, NV> MutableSortedMap<NK, NV> toSortedMap(Comparator<? super NK> comparator, Function<? super T, ? extends NK> keyFunction, Function<? super T, ? extends NV> valueFunction) { return this.delegate.toSortedMap(comparator, keyFunction, valueFunction); } public Object[] toArray() { return this.delegate.toArray(); } public <T1> T1[] toArray(T1[] target) { return this.delegate.toArray(target); } public T min(Comparator<? super T> comparator) { return this.delegate.min(comparator); } public T max(Comparator<? super T> comparator) { return this.delegate.max(comparator); } public T min() { return this.delegate.min(); } public T max() { return this.delegate.max(); } public <V extends Comparable<? super V>> T minBy(Function<? super T, ? extends V> function) { return this.delegate.minBy(function); } public <V extends Comparable<? super V>> T maxBy(Function<? super T, ? extends V> function) { return this.delegate.maxBy(function); } public long sumOfInt(IntFunction<? super T> function) { return this.delegate.sumOfInt(function); } public double sumOfFloat(FloatFunction<? super T> function) { return this.delegate.sumOfFloat(function); } public long sumOfLong(LongFunction<? super T> function) { return this.delegate.sumOfLong(function); } public double sumOfDouble(DoubleFunction<? super T> function) { return this.delegate.sumOfDouble(function); } @Override public String toString() { return this.delegate.toString(); } public String makeString() { return this.delegate.makeString(); } public String makeString(String separator) { return this.delegate.makeString(separator); } public String makeString(String start, String separator, String end) { return this.delegate.makeString(start, separator, end); } public void appendString(Appendable appendable) { this.delegate.appendString(appendable); } public void appendString(Appendable appendable, String separator) { this.delegate.appendString(appendable, separator); } public void appendString(Appendable appendable, String start, String separator, String end) { this.delegate.appendString(appendable, start, separator, end); } public <V> MapIterable<V, T> groupByUniqueKey(Function<? super T, ? extends V> function) { return this.delegate.groupByUniqueKey(function); } public <K, V> MapIterable<K, V> aggregateInPlaceBy(Function<? super T, ? extends K> groupBy, Function0<? extends V> zeroValueFactory, Procedure2<? super V, ? super T> mutatingAggregator) { return this.delegate.aggregateInPlaceBy(groupBy, zeroValueFactory, mutatingAggregator); } public <K, V> MapIterable<K, V> aggregateBy(Function<? super T, ? extends K> groupBy, Function0<? extends V> zeroValueFactory, Function2<? super V, ? super T, ? extends V> nonMutatingAggregator) { return this.delegate.aggregateBy(groupBy, zeroValueFactory, nonMutatingAggregator); } }
3,579
1,338
<reponame>Kirishikesan/haiku /* * Copyright 2008-2011, Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * <NAME>, <EMAIL> */ #include "DeviceSCSI.h" #include <scsi.h> #include <sstream> #include <stdlib.h> #include <Catalog.h> #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "DeviceSCSI" // standard SCSI device types const char* SCSITypeMap[] = { B_TRANSLATE("Disk Drive"), // 0x00 B_TRANSLATE("Tape Drive"), // 0x01 B_TRANSLATE("Printer"), // 0x02 B_TRANSLATE("Processor"), // 0x03 B_TRANSLATE("Worm"), // 0x04 B_TRANSLATE("CD-ROM"), // 0x05 B_TRANSLATE("Scanner"), // 0x06 B_TRANSLATE("Optical Drive"), // 0x07 B_TRANSLATE("Changer"), // 0x08 B_TRANSLATE("Communications"), // 0x09 B_TRANSLATE("Graphics Peripheral"), // 0x0A B_TRANSLATE("Graphics Peripheral"), // 0x0B B_TRANSLATE("Array"), // 0x0C B_TRANSLATE("Enclosure"), // 0x0D B_TRANSLATE("RBC"), // 0x0E B_TRANSLATE("Card Reader"), // 0x0F B_TRANSLATE("Bridge"), // 0x10 B_TRANSLATE("Other") // 0x11 }; DeviceSCSI::DeviceSCSI(Device* parent) : Device(parent) { } DeviceSCSI::~DeviceSCSI() { } void DeviceSCSI::InitFromAttributes() { BString nodeVendor(GetAttribute("scsi/vendor").fValue); BString nodeProduct(GetAttribute("scsi/product").fValue); fCategory = (Category)CAT_MASS; uint32 nodeTypeID = atoi(GetAttribute("scsi/type").fValue); SetAttribute(B_TRANSLATE("Device name"), nodeProduct.String()); SetAttribute(B_TRANSLATE("Manufacturer"), nodeVendor.String()); SetAttribute(B_TRANSLATE("Device class"), SCSITypeMap[nodeTypeID]); BString listName; listName << "SCSI " << SCSITypeMap[nodeTypeID] << " (" << nodeProduct << ")"; SetText(listName.String()); } Attributes DeviceSCSI::GetBusAttributes() { // Push back things that matter for SCSI devices Attributes attributes; attributes.push_back(GetAttribute(B_TRANSLATE("Device class"))); attributes.push_back(GetAttribute(B_TRANSLATE("Device name"))); attributes.push_back(GetAttribute(B_TRANSLATE("Manufacturer"))); attributes.push_back(GetAttribute("scsi/revision")); attributes.push_back(GetAttribute("scsi/target_id")); attributes.push_back(GetAttribute("scsi/target_lun")); return attributes; } BString DeviceSCSI::GetBusStrings() { BString str(B_TRANSLATE("Class Info:\t\t\t\t: %classInfo%")); str.ReplaceFirst("%classInfo%", fAttributeMap["Class Info"]); return str; } BString DeviceSCSI::GetBusTabName() { return B_TRANSLATE("SCSI Information"); }
1,039
551
@interface MIMEAddress : NSObject @property (nonatomic, retain, readonly) NSString *name; @end
31
332
<filename>java/org/cef/network/CefWebPluginInfo.java // Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. package org.cef.network; /** * Information about a specific web plugin. */ public interface CefWebPluginInfo { /** * Returns the plugin name (i.e. Flash). */ public String getName(); /** * Returns the plugin file path (DLL/bundle/library). */ public String getPath(); /** * Returns the version of the plugin (may be OS-specific). */ public String getVersion(); /** * Returns a description of the plugin from the version information. */ public String getDescription(); }
255
438
# Copyright 2014, Sandia Corporation. Under the terms of Contract # DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain # rights in this software. """Provides the top-level :ref:`convenience-api`, which allows you to create many plots using a single compact statement. """ import logging import sys if sys.version_info.major < 3: raise RuntimeError("As of version 0.19, Toyplot requires Python 3. For Python 2 support, use Toyplot version 0.18") from toyplot.canvas import Canvas __version__ = "0.20.0-dev" log = logging.getLogger(__name__) log.setLevel(logging.WARNING) log.addHandler(logging.NullHandler()) class DeprecationWarning(Warning): """Used with :func:`warnings.warn` to mark deprecated API.""" pass def bars( a, b=None, c=None, along="x", baseline="stacked", color=None, filename=None, height=None, hyperlink=None, label=None, margin=50, opacity=1.0, padding=10, show=True, style=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale="linear", xshow=True, ylabel=None, ymax=None, ymin=None, yscale="linear", yshow=True, ): """Convenience function for creating a bar plot in a single call. See :meth:`toyplot.coordinates.Cartesian.bars`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.BarMagnitudes` or :class:`toyplot.mark.BarBoundaries` The new bar mark. """ canvas = Canvas(width=width, height=height) axes = canvas.cartesian( label=label, margin=margin, padding=padding, show=show, xlabel=xlabel, xmax=xmax, xmin=xmin, xscale=xscale, xshow=xshow, ylabel=ylabel, ymax=ymax, ymin=ymin, yscale=yscale, yshow=yshow, ) mark = axes.bars( a=a, b=b, c=c, along=along, baseline=baseline, color=color, filename=filename, hyperlink=hyperlink, opacity=opacity, style=style, title=title, ) return canvas, axes, mark def fill( a, b=None, c=None, along="x", baseline=None, color=None, filename=None, height=None, label=None, margin=50, opacity=1.0, padding=10, show=True, style=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale="linear", xshow=True, ylabel=None, ymax=None, ymin=None, yscale="linear", yshow=True, ): """Convenience function for creating a fill plot in a single call. See :meth:`toyplot.coordinates.Cartesian.fill`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.FillBoundaries` or :class:`toyplot.mark.FillMagnitudes` The new fill mark. """ canvas = Canvas( height=height, width=width, ) axes = canvas.cartesian( label=label, margin=margin, padding=padding, show=show, xlabel=xlabel, xmax=xmax, xmin=xmin, xscale=xscale, xshow=xshow, ylabel=ylabel, ymax=ymax, ymin=ymin, yscale=yscale, yshow=yshow, ) mark = axes.fill( a=a, b=b, c=c, along=along, baseline=baseline, color=color, filename=filename, opacity=opacity, style=style, title=title, ) return canvas, axes, mark def graph( a, b=None, c=None, along="x", ecolor=None, eopacity=1.0, estyle=None, ewidth=1.0, height=None, hmarker=None, layout=None, margin=50, mmarker=None, mposition=0.5, olayout=None, padding=20, tmarker=None, varea=None, vcolor=None, vcoordinates=None, vlabel=None, vlshow=True, vlstyle=None, vmarker="o", vopacity=1.0, vsize=None, vstyle=None, vtitle=None, width=None, ): # pragma: no cover """Convenience function for creating a graph plot in a single call. See :meth:`toyplot.coordinates.Cartesian.graph`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.Graph` The new graph mark. """ canvas = Canvas( height=height, width=width, ) axes = canvas.cartesian( aspect="fit-range", margin=margin, padding=padding, show=False, ) mark = axes.graph( a=a, b=b, c=c, along=along, ecolor=ecolor, eopacity=eopacity, estyle=estyle, ewidth=ewidth, hmarker=hmarker, layout=layout, mmarker=mmarker, mposition=mposition, olayout=olayout, tmarker=tmarker, varea=varea, vcolor=vcolor, vcoordinates=vcoordinates, vlabel=vlabel, vlshow=vlshow, vlstyle=vlstyle, vmarker=vmarker, vopacity=vopacity, vsize=vsize, vstyle=vstyle, vtitle=vtitle, ) return canvas, axes, mark def image( data, height=None, margin=0, width=None, ): # pragma: no cover """Convenience function for displaying an image in a single call. See :meth:`toyplot.canvas.Canvas.image`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. mark: :class:`toyplot.mark.Image` The new image mark. """ canvas = Canvas( height=height, width=width, ) mark = canvas.image( data=data, margin=margin, ) return canvas, mark def matrix( data, blabel=None, blocator=None, bshow=None, colorshow=False, filename=None, height=None, label=None, llabel=None, llocator=None, lshow=None, margin=50, rlabel=None, rlocator=None, rshow=None, step=1, tlabel=None, tlocator=None, tshow=None, width=None, ): """Convenience function to create a matrix visualization in a single call. See :meth:`toyplot.canvas.Canvas.matrix`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. table: :class:`toyplot.coordinates.Table` A new set of table axes that fill the canvas. """ canvas = Canvas( height=height, width=width, ) axes = canvas.matrix( blabel=blabel, blocator=blocator, bshow=bshow, colorshow=colorshow, data=data, filename=filename, label=label, llabel=llabel, llocator=llocator, lshow=lshow, margin=margin, rlabel=rlabel, rlocator=rlocator, rshow=rshow, step=step, tlabel=tlabel, tlocator=tlocator, tshow=tshow, ) return canvas, axes def plot( a, b=None, along="x", area=None, aspect=None, color=None, filename=None, height=None, label=None, margin=50, marker=None, mfill=None, mlstyle=None, mopacity=1.0, mstyle=None, mtitle=None, opacity=1.0, padding=10, show=True, size=None, stroke_width=2.0, style=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale="linear", xshow=True, ylabel=None, ymax=None, ymin=None, yscale="linear", yshow=True, ): """Convenience function for creating a line plot in a single call. See :meth:`toyplot.coordinates.Cartesian.plot`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.Plot` The new plot mark. """ canvas = Canvas( height=height, width=width, ) axes = canvas.cartesian( aspect=aspect, label=label, margin=margin, padding=padding, show=show, xlabel=xlabel, xmax=xmax, xmin=xmin, xscale=xscale, xshow=xshow, ylabel=ylabel, ymax=ymax, ymin=ymin, yscale=yscale, yshow=yshow, ) mark = axes.plot( a=a, b=b, along=along, area=area, color=color, filename=filename, marker=marker, mfill=mfill, mlstyle=mlstyle, mopacity=mopacity, mstyle=mstyle, mtitle=mtitle, opacity=opacity, size=size, stroke_width=stroke_width, style=style, title=title, ) return canvas, axes, mark def scatterplot( a, b=None, along="x", area=None, aspect=None, color=None, filename=None, height=None, hyperlink=None, label=None, margin=50, marker="o", mlstyle=None, mstyle=None, opacity=1.0, padding=10, show=True, size=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale="linear", xshow=True, ylabel=None, ymax=None, ymin=None, yscale="linear", yshow=True, ): """Convenience function for creating a scatter plot in a single call. See :meth:`toyplot.coordinates.Cartesian.scatterplot`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.Point` The new scatterplot mark. """ canvas = Canvas( height=height, width=width, ) axes = canvas.cartesian( aspect=aspect, label=label, margin=margin, padding=padding, show=show, xlabel=xlabel, xmax=xmax, xmin=xmin, xscale=xscale, xshow=xshow, ylabel=ylabel, ymax=ymax, ymin=ymin, yscale=yscale, yshow=yshow, ) mark = axes.scatterplot( a=a, b=b, along=along, area=area, color=color, filename=filename, hyperlink=hyperlink, marker=marker, mlstyle=mlstyle, mstyle=mstyle, opacity=opacity, size=size, title=title, ) return canvas, axes, mark def table( data=None, brows=None, columns=None, filename=None, height=None, label=None, lcolumns=None, margin=50, rcolumns=None, rows=None, trows=None, width=None, ): """Convenience function to create a table visualization in a single call. See :meth:`toyplot.canvas.Canvas.table`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. table: :class:`toyplot.coordinates.Table` A new set of table axes that fill the canvas. """ canvas = Canvas( height=height, width=width, ) axes = canvas.table( brows=brows, columns=columns, data=data, filename=filename, label=label, lcolumns=lcolumns, margin=margin, rcolumns=rcolumns, rows=rows, trows=trows, ) return canvas, axes
6,969
1,611
""" Cluster Agent for Cloud Foundry tasks """ import os from invoke import task from .build_tags import get_default_build_tags from .cluster_agent_helpers import build_common, clean_common, refresh_assets_common, version_common # constants BIN_PATH = os.path.join(".", "bin", "datadog-cluster-agent-cloudfoundry") @task def build(ctx, rebuild=False, build_include=None, build_exclude=None, race=False, development=True, skip_assets=False): """ Build Cluster Agent for Cloud Foundry Example invokation: inv cluster-agent-cloudfoundry.build """ build_common( ctx, BIN_PATH, get_default_build_tags(build="cluster-agent-cloudfoundry"), "-cloudfoundry", rebuild, build_include, build_exclude, race, development, skip_assets, ) @task def refresh_assets(ctx, development=True): """ Clean up and refresh cluster agent's assets and config files """ refresh_assets_common(ctx, BIN_PATH, [], development) @task def integration_tests(ctx, install_deps=False, race=False, remote_docker=False): # noqa: U100 """ Run integration tests for cluster-agent-cloudfoundry """ pass # TODO @task def clean(ctx): """ Remove temporary objects and binary artifacts """ clean_common(ctx, "datadog-cluster-agent") @task def version(ctx, url_safe=False, git_sha_length=7): """ Get the agent version. url_safe: get the version that is able to be addressed as a url git_sha_length: different versions of git have a different short sha length, use this to explicitly set the version (the windows builder and the default ubuntu version have such an incompatibility) """ version_common(ctx, url_safe, git_sha_length)
684
2,542
<reponame>AnthonyM/service-fabric<filename>src/prod/src/ServiceModel/management/FileStoreService/StoreFileVersion.cpp // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace Management::FileStoreService; INITIALIZE_SIZE_ESTIMATION(StoreFileVersion) StoreFileVersion StoreFileVersion::Default = StoreFileVersion(); StoreFileVersion::StoreFileVersion() : epochDataLossNumber_(0) , epochConfigurationNumber_(-1) , versionNumber_(0) { } StoreFileVersion::StoreFileVersion( int64 const epochDataLossNumber, int64 const epochConfigurationNumber, uint64 const versionNumber) : epochDataLossNumber_(epochDataLossNumber) , epochConfigurationNumber_(epochConfigurationNumber) , versionNumber_(versionNumber) { } StoreFileVersion const & StoreFileVersion::operator = (StoreFileVersion const & other) { if (this != &other) { this->epochDataLossNumber_ = other.epochDataLossNumber_; this->epochConfigurationNumber_ = other.epochConfigurationNumber_; this->versionNumber_ = other.versionNumber_; } return *this; } StoreFileVersion const & StoreFileVersion::operator = (StoreFileVersion && other) { if (this != &other) { this->epochDataLossNumber_ = other.epochDataLossNumber_; this->epochConfigurationNumber_ = other.epochConfigurationNumber_; this->versionNumber_ = other.versionNumber_; } return *this; } bool StoreFileVersion::operator == (StoreFileVersion const & other) const { bool equals = true; equals = this->epochDataLossNumber_ == other.epochDataLossNumber_; if (!equals) { return equals; } equals = this->epochConfigurationNumber_ == other.epochConfigurationNumber_; if(!equals) { return equals; } equals = this->versionNumber_ == other.versionNumber_; if (!equals) { return equals; } return equals; } bool StoreFileVersion::operator != (StoreFileVersion const & other) const { return !(*this == other); } void StoreFileVersion::WriteTo(TextWriter & w, FormatOptions const &) const { w.Write(ToString()); } wstring StoreFileVersion::ToString() const { if(this->epochConfigurationNumber_ == -1) { return wformatString("{0}_{1}", this->epochDataLossNumber_, this->versionNumber_); } else { return wformatString("{0}_{1}_{2}", this->epochDataLossNumber_, this->epochConfigurationNumber_, this->versionNumber_); } } bool StoreFileVersion::IsStoreFileVersion(std::wstring const & stringValue) { vector<wstring> tokens; StringUtility::Split<wstring>(stringValue, tokens, L"_", true); int64 value; uint64 unsignedValue; if(tokens.size() == 2) { if(!TryParseInt64(tokens[0], value)) { return false; } if(!TryParseUInt64(tokens[1], unsignedValue)) { return false; } return true; } else if(tokens.size() == 3) { if(!TryParseInt64(tokens[0], value)) { return false; } if(!TryParseInt64(tokens[1], value)) { return false; } if(!TryParseUInt64(tokens[2], unsignedValue)) { return false; } return true; } else { return false; } }
1,240
338
package com.tvd12.ezyfoxserver.nio.handler; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import com.tvd12.ezyfox.callback.EzyCallback; import com.tvd12.ezyfox.codec.EzyByteToObjectDecoder; import com.tvd12.ezyfox.codec.EzyMessage; import com.tvd12.ezyfox.codec.EzyMessageDataDecoder; import com.tvd12.ezyfox.codec.EzyMessageHeader; import com.tvd12.ezyfox.codec.EzySimpleMessageDataDecoder; import com.tvd12.ezyfoxserver.socket.EzyPacket; import com.tvd12.ezyfoxserver.socket.EzySimpleSocketStream; import com.tvd12.ezyfoxserver.socket.EzySocketStream; public class EzySimpleNioHandlerGroup extends EzyAbstractHandlerGroup<EzyMessageDataDecoder> implements EzyNioHandlerGroup { private final EzyCallback<EzyMessage> decodeBytesCallback; public EzySimpleNioHandlerGroup(Builder builder) { super(builder); this.decodeBytesCallback = m -> this.executeHandleReceivedMessage(m); } @Override protected EzyMessageDataDecoder newDecoder(Object decoder) { return new EzySimpleMessageDataDecoder((EzyByteToObjectDecoder)decoder); } @Override public void fireBytesReceived(byte[] bytes) throws Exception { handleReceivedBytes(bytes); } @Override public void fireMessageReceived(EzyMessage message) throws Exception { handleReceivedMesssage(message); } private void handleReceivedBytes(byte[] bytes) { try { decoder.decode(bytes, decodeBytesCallback); } catch(Exception throwable) { fireExceptionCaught(throwable); } } private void executeHandleReceivedMessage(EzyMessage message) { handleReceivedMesssage(message); } private void handleReceivedMesssage(EzyMessage message) { try { EzyMessageHeader header = message.getHeader(); if(header.isRawBytes()) { boolean sessionStreamingEnable = session.isStreamingEnable(); if(!streamingEnable || !sessionStreamingEnable) { return; } byte[] rawBytes = message.getContent(); EzySocketStream stream = new EzySimpleSocketStream(session, rawBytes); streamQueue.add(stream); } else { Object data = decodeMessage(message); int dataSize = message.getByteCount(); handleReceivedData(data, dataSize); } } catch (Exception e) { fireExceptionCaught(e); } finally { executeAddReadBytes(message.getByteCount()); } } private Object decodeMessage(EzyMessage message) throws Exception { Object answer = decoder.decode(message, session.getSessionKey()); return answer; } @Override protected void sendPacketNow0(EzyPacket packet) { ByteBuffer writeBuffer = ByteBuffer.allocate(packet.getSize()); executeSendingPacket(packet, writeBuffer); } @Override protected int writePacketToSocket(EzyPacket packet, Object writeBuffer) throws Exception { byte[] bytes = getBytesToWrite(packet); int bytesToWrite = bytes.length; ByteBuffer buffer = getWriteBuffer((ByteBuffer)writeBuffer, bytesToWrite); buffer.clear(); buffer.put(bytes); buffer.flip(); int bytesWritten = channel.write(buffer, packet.isBinary()); if (bytesWritten < bytesToWrite) { byte[] remainBytes = getPacketFragment(buffer); packet.setFragment(remainBytes); SelectionKey selectionKey = session.getSelectionKey(); if(selectionKey != null && selectionKey.isValid()) { selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } else { logger.warn("selection key invalid, wrriten bytes: {}, session: {}", bytesWritten, session); } } else { packet.release(); } return bytesWritten; } private byte[] getPacketFragment(ByteBuffer buffer) { byte[] remainBytes = new byte[buffer.remaining()]; buffer.get(remainBytes); return remainBytes; } public static Builder builder() { return new Builder(); } public static class Builder extends EzyAbstractHandlerGroup.Builder { @Override public EzyNioHandlerGroup build() { return new EzySimpleNioHandlerGroup(this); } } }
1,382
831
<filename>room/src/com/android/tools/idea/room/migrations/json/PrimaryKeyBundle.java /* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.room.migrations.json; import com.google.gson.annotations.SerializedName; import java.util.List; /** * This was copied from the Room Migration project. It is only a temporary solution and in the future we will try to use the real classes. */ public class PrimaryKeyBundle implements SchemaEquality<PrimaryKeyBundle> { @SerializedName("columnNames") private List<String> mColumnNames; @SerializedName("autoGenerate") private boolean mAutoGenerate; public PrimaryKeyBundle(boolean autoGenerate, List<String> columnNames) { mColumnNames = columnNames; mAutoGenerate = autoGenerate; } public List<String> getColumnNames() { return mColumnNames; } public boolean isAutoGenerate() { return mAutoGenerate; } @Override public boolean isSchemaEqual(PrimaryKeyBundle other) { return mColumnNames.equals(other.mColumnNames) && mAutoGenerate == other.mAutoGenerate; } }
482
427
<gh_stars>100-1000 //===- BuildKey.h -----------------------------------------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #ifndef LLBUILD_BUILDSYSTEM_BUILDKEY_H #define LLBUILD_BUILDSYSTEM_BUILDKEY_H #include "llbuild/Basic/Compiler.h" #include "llbuild/Basic/LLVM.h" #include "llbuild/Core/BuildEngine.h" #include "llbuild/BuildSystem/BuildDescription.h" #include "llvm/ADT/StringRef.h" namespace llbuild { namespace buildsystem { /// The BuildKey encodes the key space used by the BuildSystem when using the /// core BuildEngine. class BuildKey { using KeyType = core::KeyType; public: enum class Kind { /// A key used to identify a command. Command, /// A key used to identify a custom task. CustomTask, /// A key used to identify directory contents. DirectoryContents, /// A key used to identify the signature of a complete directory tree. DirectoryTreeSignature, /// A key used to identify a node. Node, /// A key used to identify a target. Target, /// An invalid key kind. Unknown, }; static StringRef stringForKind(Kind); private: /// The actual key data. KeyType key; private: BuildKey(const KeyType& key) : key(key) {} BuildKey(char kindCode, StringRef str) { key.reserve(1 + str.size()); key.push_back(kindCode); key.append(str.begin(), str.end()); } BuildKey(char kindCode, StringRef name, StringRef data) { // FIXME: We need good support infrastructure for binary encoding. uint32_t nameSize = name.size(); uint32_t dataSize = data.size(); key.resize(1 + sizeof(uint32_t) + nameSize + dataSize); uint32_t pos = 0; key[pos] = kindCode; pos += 1; memcpy(&key[pos], &nameSize, sizeof(uint32_t)); pos += sizeof(uint32_t); memcpy(&key[pos], name.data(), nameSize); pos += nameSize; memcpy(&key[pos], data.data(), dataSize); pos += dataSize; assert(key.size() == pos); } public: /// @name Construction Functions /// @{ /// Create a key for computing a command result. static BuildKey makeCommand(StringRef name) { return BuildKey('C', name); } /// Create a key for computing a custom task (manged by a particular command). static BuildKey makeCustomTask(StringRef name, StringRef taskData) { return BuildKey('X', name, taskData); } /// Create a key for computing the contents of a directory. static BuildKey makeDirectoryContents(StringRef path) { return BuildKey('D', path); } /// Create a key for computing the contents of a directory. static BuildKey makeDirectoryTreeSignature(StringRef path) { return BuildKey('S', path); } /// Create a key for computing a node result. static BuildKey makeNode(StringRef path) { return BuildKey('N', path); } /// Create a key for computing a node result. static BuildKey makeNode(const Node* node) { return BuildKey('N', node->getName()); } /// Createa a key for computing a target. static BuildKey makeTarget(StringRef name) { return BuildKey('T', name); } /// @} /// @name Accessors /// @{ const KeyType& getKeyData() const { return key; } Kind getKind() const { switch (key[0]) { case 'C': return Kind::Command; case 'D': return Kind::DirectoryContents; case 'N': return Kind::Node; case 'S': return Kind::DirectoryTreeSignature; case 'T': return Kind::Target; case 'X': return Kind::CustomTask; default: return Kind::Unknown; } } bool isCommand() const { return getKind() == Kind::Command; } bool isCustomTask() const { return getKind() == Kind::CustomTask; } bool isDirectoryContents() const { return getKind() == Kind::DirectoryContents; } bool isDirectoryTreeSignature() const { return getKind() == Kind::DirectoryTreeSignature; } bool isNode() const { return getKind() == Kind::Node; } bool isTarget() const { return getKind() == Kind::Target; } StringRef getCommandName() const { assert(isCommand()); return StringRef(key.data()+1, key.size()-1); } StringRef getCustomTaskName() const { assert(isCustomTask()); uint32_t nameSize; memcpy(&nameSize, &key[1], sizeof(uint32_t)); return StringRef(&key[1 + sizeof(uint32_t)], nameSize); } StringRef getCustomTaskData() const { assert(isCustomTask()); uint32_t nameSize; memcpy(&nameSize, &key[1], sizeof(uint32_t)); uint32_t dataSize = key.size() - 1 - sizeof(uint32_t) - nameSize; return StringRef(&key[1 + sizeof(uint32_t) + nameSize], dataSize); } StringRef getDirectoryContentsPath() const { assert(isDirectoryContents()); return StringRef(key.data()+1, key.size()-1); } StringRef getDirectoryTreeSignaturePath() const { assert(isDirectoryTreeSignature()); return StringRef(key.data()+1, key.size()-1); } StringRef getNodeName() const { assert(isNode()); return StringRef(key.data()+1, key.size()-1); } StringRef getTargetName() const { assert(isTarget()); return StringRef(key.data()+1, key.size()-1); } /// @} /// @name Conversion to core ValueType. /// @{ static BuildKey fromData(const KeyType& key) { auto result = BuildKey(key); assert(result.getKind() != Kind::Unknown && "invalid key"); return result; } const core::KeyType toData() const { return getKeyData(); } /// @} /// @name Debug Support /// @{ void dump(raw_ostream& OS) const; /// @} }; } } #endif
1,971
435
<filename>pydata-new-york-city-2019/videos/samuel-rochette-quantifying-uncertainty-in-machine-learning-models-pydata-new-york-2019.json { "copyright_text": null, "description": "Many models give a lot more information during the inference process that we usually know. We will begin with an intrinsic estimation of all the distribution with random forest algorithm. Then we will extend those 'prediction intervals' to almost every regression models thanks to the quantile loss. Eventually we will discuss about probability calibration to measure uncertainty in classification.", "duration": 1962, "language": "eng", "recorded": "2019-11-04", "related_urls": [ { "label": "Conference schedule", "url": "https://pydata.org/nyc2019/schedule/" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/yk5cmVW3EA0/maxresdefault.jpg", "title": "Quantifying uncertainty in machine learning models", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=yk5cmVW3EA0" } ] }
361
5,168
<filename>dnn/src/cuda/convolution/backward_data/matmul.cpp /** * \file dnn/src/cuda/convolution/backward_data/matmul.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. */ #include "./algo.h" #include "src/common/algo_base.h" #include "src/cuda/convolution/helper.h" #include "src/cuda/convolution/im2col.cuh" #include "src/cuda/matrix_mul/opr_impl.h" #include "src/cuda/utils.h" using namespace megdnn; using namespace cuda; namespace { std::pair<TensorLayoutArray, MatrixMulForward::Param> sub_opr_config( const ConvolutionBackwardDataImpl::CanonizedFilterMeta& fm, const TensorLayout& filter_layout, const TensorLayout& diff_layout, const TensorLayout& grad_layout, const ConvolutionBackwardDataImpl* opr) { size_t N = grad_layout.shape[0], IC = fm.icpg, OC = fm.ocpg, OH = diff_layout.shape[2], OW = diff_layout.shape[3], FH = fm.spatial[0], FW = fm.spatial[1]; megdnn_assert(filter_layout.dtype.enumv() == diff_layout.dtype.enumv()); TensorLayout Al({OC, IC * FH * FW}, filter_layout.dtype), Bl({IC * FH * FW, OH * OW * N}, filter_layout.dtype), Cl({OC, OH * OW * N}, filter_layout.dtype); MatrixMulForward::Param param; if (opr->param().compute_mode == param::Convolution::ComputeMode::FLOAT32) { param.compute_mode = param::MatrixMul::ComputeMode::FLOAT32; } param.transposeA = true; return {{Al, Cl, Bl}, param}; } std::pair<TensorLayoutArray, std::unique_ptr<MatrixMulForward>> prepare_sub_opr( const ConvolutionBackwardDataImpl::AlgoBase::SizeArgs& args) { auto matmul_opr = args.handle->create_operator<MatrixMulForward>(); set_execution_policy<ConvolutionBackwardData, MatrixMulForward*>( args.opr, matmul_opr.get()); auto&& config = sub_opr_config( args.filter_meta, *args.filter_layout, *args.diff_layout, *args.grad_layout, args.opr); matmul_opr->param() = config.second; return {config.first, std::move(matmul_opr)}; } } // namespace std::vector<Algorithm::SearchItem> ConvolutionBackwardDataImpl::AlgoMatmul:: get_subopr_list( const TensorLayoutArray& layouts, const OperatorBase* opr) const { const ConvolutionBackwardDataImpl* conv_backward_data_opr = static_cast<const ConvolutionBackwardDataImpl*>(opr); CanonizedFilterMeta fm = conv_backward_data_opr->make_canonized_filter_meta( layouts[2].ndim, layouts[0]); auto&& config = sub_opr_config( fm, layouts[0], layouts[1], layouts[2], conv_backward_data_opr); std::string param_str; Algorithm::serialize_write_pod(config.second, param_str); return {{Algorithm::OprType::MATRIX_MUL_FORWARD, param_str, config.first}}; } bool ConvolutionBackwardDataImpl::AlgoMatmul::is_available(const SizeArgs& args) const { if (args.diff_layout->dtype == args.filter_layout->dtype && args.diff_layout->dtype == dtype::BFloat16()) { return false; } auto&& fm = args.filter_meta; return args.filter_meta.format == Param::Format::NCHW && args.diff_layout->dtype.category() == DTypeCategory::FLOAT && fm.group == 1 && fm.spatial_ndim == 2; } size_t ConvolutionBackwardDataImpl::AlgoMatmul::get_workspace_in_bytes( const SizeArgs& args) const { auto config = prepare_sub_opr(args); auto&& sizes = matmul_get_workspace_bundle(args.as_fwd_args()); sizes.push_back(config.second->get_workspace_in_bytes( config.first[0], config.first[1], config.first[2])); return WorkspaceBundle(nullptr, sizes).total_size_in_bytes(); } void ConvolutionBackwardDataImpl::AlgoMatmul::exec(const ExecArgs& args) const { #define cb(DType) \ if (args.diff_layout->dtype == DType()) { \ using ctype = typename DTypeTrait<DType>::ctype; \ exec_internal<ctype>(args); \ return; \ } MEGDNN_FOREACH_COMPUTING_DTYPE_FLOAT(cb) #undef cb megdnn_assert_internal(0); } template <typename T> void ConvolutionBackwardDataImpl::AlgoMatmul::exec_internal(const ExecArgs& args) { auto&& fm = args.filter_meta; size_t N = args.grad_layout->shape[0], IC = fm.icpg, IH = args.grad_layout->shape[2], IW = args.grad_layout->shape[3], OC = fm.ocpg, OH = args.diff_layout->shape[2], OW = args.diff_layout->shape[3], FH = fm.spatial[0], FW = fm.spatial[1], PH = fm.padding[0], PW = fm.padding[1], SH = fm.stride[0], SW = fm.stride[1], DH = fm.dilation[0], DW = fm.dilation[1]; auto stream = cuda_stream(args.handle); auto config = prepare_sub_opr(args); auto&& sizes = matmul_get_workspace_bundle(args.as_fwd_args()); sizes.push_back(config.second->get_workspace_in_bytes( config.first[0], config.first[1], config.first[2])); auto wbundle = WorkspaceBundle(args.workspace.raw_ptr, sizes); T* diff_t = static_cast<T*>(wbundle.get(0)); T* col = static_cast<T*>(wbundle.get(1)); { // transpose diff TensorLayout froml({N, OC * OH * OW}, typename DTypeTrait<T>::dtype()), tol(froml); froml.stride[0] = args.diff_layout->stride[0]; tol.stride[0] = 1; tol.stride[1] = N; TensorND from(args.diff_tensor->ptr<T>(), froml), to(diff_t, tol); args.handle->relayout_opr()->exec(from, to); } { // take gemm grad TensorLayout Al({OC, IC * FH * FW}, typename DTypeTrait<T>::dtype()), Bl({IC * FH * FW, OH * OW * N}, typename DTypeTrait<T>::dtype()), Cl({OC, OH * OW * N}, typename DTypeTrait<T>::dtype()); TensorND A(args.filter_tensor->ptr<T>(), Al), B(col, Bl), C(diff_t, Cl); if (fm.should_flip) { convolution::flip_filter( args.as_fwd_args(), wbundle.get_workspace(2), A.raw_ptr); config.second->exec(A, C, B, wbundle.get_workspace(3)); } else { config.second->exec(A, C, B, wbundle.get_workspace(2)); } } { // col2im convolution::col2im<T>( col, args.grad_tensor->ptr<T>(), N, args.grad_layout->stride[0], IC, IH, IW, FH, FW, OH, OW, PH, PW, SH, SW, DH, DW, stream); } } // vim: syntax=cpp.doxygen
3,037
342
package com.edlplan.framework.support.timing; public interface IRunnableHandler { void post(Runnable r); void post(Runnable r, double delayMS); }
55
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-mwx3-cc72-hfg4", "modified": "2022-05-13T01:13:47Z", "published": "2022-05-13T01:13:47Z", "aliases": [ "CVE-2018-20662" ], "details": "In Poppler 0.72.0, PDFDoc::setup in PDFDoc.cc allows attackers to cause a denial-of-service (application crash caused by Object.h SIGABRT, because of a wrong return value from PDFDoc::setup) by crafting a PDF file in which an xref data structure is mishandled during extractPDFSubtype processing.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-20662" }, { "type": "WEB", "url": "https://access.redhat.com/errata/RHSA-2019:2022" }, { "type": "WEB", "url": "https://access.redhat.com/errata/RHSA-2019:2713" }, { "type": "WEB", "url": "https://gitlab.freedesktop.org/poppler/poppler/commit/9fd5ec0e6e5f763b190f2a55ceb5427cfe851d5f" }, { "type": "WEB", "url": "https://gitlab.freedesktop.org/poppler/poppler/issues/706" }, { "type": "WEB", "url": "https://lists.debian.org/debian-lts-announce/2019/03/msg00008.html" }, { "type": "WEB", "url": "https://lists.debian.org/debian-lts-announce/2020/11/msg00014.html" }, { "type": "WEB", "url": "https://lists.fedoraproject.org/archives/list/[email protected]/message/6OSCOYM3AMFFBJWSBWY6VJVLNE5JD7YS/" }, { "type": "WEB", "url": "https://lists.fedoraproject.org/archives/list/[email protected]/message/BI7NLDN2HUEU4ZW3D7XPHOAEGT2CKDRO/" }, { "type": "WEB", "url": "https://lists.fedoraproject.org/archives/list/[email protected]/message/JQ6RABASMSIMMWMDZTP6ZWUWZPTBSVB5/" }, { "type": "WEB", "url": "https://lists.fedoraproject.org/archives/list/[email protected]/message/ZWP5XSUG6GNRI75NYKF53KIB2CZY6QQ6/" }, { "type": "WEB", "url": "https://usn.ubuntu.com/4042-1/" } ], "database_specific": { "cwe_ids": [ "CWE-20" ], "severity": "MODERATE", "github_reviewed": false } }
1,187
765
/* * Copyright (c) 2021 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: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __MEM_PORT_TERMINATOR_HH__ #define __MEM_PORT_TERMINATOR_HH__ /** * @file port_terminator.hh * Contains the description of the class PortTerminator. It is useful for cases * where you do not need to connect all of the ports in your system, but the * simulator is complaining about orphan ports. For example if you have * configured a cache hierarchy and want to test its performance using * PyTrafficGen, you will end up with an icache that is not connected to any * other component in the system. In this case you can just connect that port * to this object. This object will not issue any request or respond to any * request. It is neccessary to make sure the ports that are connected to * a PortTerminator are never going to be used in your system. */ #include <vector> #include "mem/port.hh" #include "params/PortTerminator.hh" #include "sim/sim_object.hh" namespace gem5 { class PortTerminator : public SimObject { private: /** * @brief definition of the ReqPort class. It is of type RequestPort * It will always return true when it receives a timing response. However, * it should never become useful if PortTerminator is used correctly in * your system (since it is a pure virtual function it should be * implemented for any class that inherits from RequestPort). It will never * send request retires, nor it will need to keep track of address ranges * of its peer port. */ class ReqPort : public RequestPort { public: ReqPort(const std::string &name, PortTerminator *owner): RequestPort(name, owner) {} protected: bool recvTimingResp(PacketPtr pkt) override { panic("Received an unexpected response. RequestPorts on a " "PortTerminator never issue any requests. Therefore, they should " "never receive a response.\n"); } void recvReqRetry() override { return; } void recvRangeChange() override { return; } }; /** * @brief definition of the RespPort class. It is of type ResponsePort * It is a ReponsePort that should never receive a request. If this is not * true in the system you configured, probably you should not use * PortTerminator for the port connected to PortTerminator. */ class RespPort : public ResponsePort { public: RespPort(const std::string &name, PortTerminator *owner): ResponsePort(name, owner) {} }; std::vector<ReqPort> reqPorts; std::vector<RespPort> respPorts; public: PortTerminator(const PortTerminatorParams &params); Port &getPort(const std::string &if_name, PortID idx = InvalidPortID) override; }; } #endif // __MEM_PORT_TERMINATOR_HH__
1,420
2,208
__author__ = '<NAME>, <EMAIL>' from .environment import Environment class GraphicalEnvironment(Environment): """ Special type of environment that has graphical output and therefore needs a renderer. """ def __init__(self): self.renderer = None def setRenderer(self, renderer): """ set the renderer, which is an object of or inherited from class Renderer. :key renderer: The renderer that should display the Environment :type renderer: L{Renderer} :see: Renderer """ self.renderer = renderer def getRenderer(self): """ returns the current renderer. :return: the current renderer :rtype: L{Renderer} """ return self.renderer def hasRenderer(self): """ tells you whether or not a Renderer has been set previously :return: True if a renderer was set, False otherwise :rtype: Boolean """ return (self.getRenderer() != None)
404
14,668
// 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 Chromium LICENSE file. #include "qcmsint.h" #include <math.h> typedef struct _qcms_coords { float x; float y; } qcms_coords; typedef struct _qcms_triangle { qcms_coords verticies[3]; } qcms_triangle; #define NTSC_1953_GAMUT_SIZE 0.1582 static qcms_triangle get_profile_triangle(qcms_profile *profile) { float sumRed = s15Fixed16Number_to_float(profile->redColorant.X) + s15Fixed16Number_to_float(profile->redColorant.Y) + s15Fixed16Number_to_float(profile->redColorant.Z); float xRed = s15Fixed16Number_to_float(profile->redColorant.X) / sumRed; float yRed = s15Fixed16Number_to_float(profile->redColorant.Y) / sumRed; float sumGreen = s15Fixed16Number_to_float(profile->greenColorant.X) + s15Fixed16Number_to_float(profile->greenColorant.Y) + s15Fixed16Number_to_float(profile->greenColorant.Z); float xGreen = s15Fixed16Number_to_float(profile->greenColorant.X) / sumGreen; float yGreen = s15Fixed16Number_to_float(profile->greenColorant.Y) / sumGreen; float sumBlue = s15Fixed16Number_to_float(profile->blueColorant.X) + s15Fixed16Number_to_float(profile->blueColorant.Y) + s15Fixed16Number_to_float(profile->blueColorant.Z); float xBlue = s15Fixed16Number_to_float(profile->blueColorant.X) / sumBlue; float yBlue = s15Fixed16Number_to_float(profile->blueColorant.Y) / sumBlue; qcms_triangle triangle = {{{xRed, yRed}, {xGreen, yGreen}, {xBlue, yBlue}}}; return triangle; } static float get_triangle_area(const qcms_triangle candidate) { float xRed = candidate.verticies[0].x; float yRed = candidate.verticies[0].y; float xGreen = candidate.verticies[1].x; float yGreen = candidate.verticies[1].y; float xBlue = candidate.verticies[2].x; float yBlue = candidate.verticies[2].y; float area = fabs((xRed - xBlue) * (yGreen - yBlue) - (xGreen - xBlue) * (yRed - yBlue)) / 2; return area; } static float get_ntsc_gamut_metric_area(const qcms_triangle candidate) { float area = get_triangle_area(candidate); return area * 100 / NTSC_1953_GAMUT_SIZE; } float qcms_profile_ntsc_relative_gamut_size(qcms_profile *profile) { qcms_triangle triangle = get_profile_triangle(profile); return get_ntsc_gamut_metric_area(triangle); }
1,034
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/GMM.framework/GMM */ #import <GMM/XXUnknownSuperclass.h> __attribute__((visibility("hidden"))) @interface GMMDirectionsOptionValue : XXUnknownSuperclass { int _optionID; // 4 = 0x4 BOOL _hasValue; // 8 = 0x8 int _value; // 12 = 0xc } @property(assign, nonatomic) int value; // G=0x1e53d; S=0x1e261; @synthesize=_value @property(assign, nonatomic) BOOL hasValue; // G=0x1e51d; S=0x1e52d; @synthesize=_hasValue @property(assign, nonatomic) int optionID; // G=0x1e4fd; S=0x1e50d; @synthesize=_optionID // declared property getter: - (int)value; // 0x1e53d // declared property setter: - (void)setHasValue:(BOOL)value; // 0x1e52d // declared property getter: - (BOOL)hasValue; // 0x1e51d // declared property setter: - (void)setOptionID:(int)anId; // 0x1e50d // declared property getter: - (int)optionID; // 0x1e4fd - (void)writeTo:(id)to; // 0x1e4a5 - (BOOL)readFrom:(id)from; // 0x1e3b1 - (id)dictionaryRepresentation; // 0x1e2f5 - (id)description; // 0x1e285 // declared property setter: - (void)setValue:(int)value; // 0x1e261 - (void)dealloc; // 0x1e235 @end
495
2,151
/* * Copyright 2013 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can * be found in the LICENSE file. */ // DO NOT EDIT: GENERATED CODE #ifndef NACL_TRUSTED_BUT_NOT_TCB #error This file is not meant for use in the TCB #endif #include "gtest/gtest.h" #include "native_client/src/trusted/validator_arm/actual_vs_baseline.h" #include "native_client/src/trusted/validator_arm/arm_helpers.h" #include "native_client/src/trusted/validator_arm/gen/arm32_decode_named_bases.h" using nacl_arm_dec::Instruction; using nacl_arm_dec::ClassDecoder; using nacl_arm_dec::Register; using nacl_arm_dec::RegisterList; namespace nacl_arm_test { // The following classes are derived class decoder testers that // add row pattern constraints and decoder restrictions to each tester. // This is done so that it can be used to make sure that the // corresponding pattern is not tested for cases that would be excluded // due to row checks, or restrictions specified by the row restrictions. // op(22:21)=00 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QADD_cccc00010000nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010000nnnndddd00000101mmmm, // rule: QADD, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} class QADD_cccc00010000nnnndddd00000101mmmm_case_0TesterCase0 : public Arm32DecoderTester { public: QADD_cccc00010000nnnndddd00000101mmmm_case_0TesterCase0(const NamedClassDecoder& decoder) : Arm32DecoderTester(decoder) {} virtual bool PassesParsePreconditions( nacl_arm_dec::Instruction inst, const NamedClassDecoder& decoder); }; bool QADD_cccc00010000nnnndddd00000101mmmm_case_0TesterCase0 ::PassesParsePreconditions( nacl_arm_dec::Instruction inst, const NamedClassDecoder& decoder) { // Check that row patterns apply to pattern being checked.' // op(22:21)=~00 if ((inst.Bits() & 0x00600000) != 0x00000000) return false; // $pattern(31:0)=~xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx if ((inst.Bits() & 0x00000F00) != 0x00000000) return false; // if cond(31:28)=1111, don't test instruction. if ((inst.Bits() & 0xF0000000) == 0xF0000000) return false; // Check other preconditions defined for the base decoder. return Arm32DecoderTester:: PassesParsePreconditions(inst, decoder); } // op(22:21)=01 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QSUB_cccc00010010nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010010nnnndddd00000101mmmm, // rule: QSUB, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} class QSUB_cccc00010010nnnndddd00000101mmmm_case_0TesterCase1 : public Arm32DecoderTester { public: QSUB_cccc00010010nnnndddd00000101mmmm_case_0TesterCase1(const NamedClassDecoder& decoder) : Arm32DecoderTester(decoder) {} virtual bool PassesParsePreconditions( nacl_arm_dec::Instruction inst, const NamedClassDecoder& decoder); }; bool QSUB_cccc00010010nnnndddd00000101mmmm_case_0TesterCase1 ::PassesParsePreconditions( nacl_arm_dec::Instruction inst, const NamedClassDecoder& decoder) { // Check that row patterns apply to pattern being checked.' // op(22:21)=~01 if ((inst.Bits() & 0x00600000) != 0x00200000) return false; // $pattern(31:0)=~xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx if ((inst.Bits() & 0x00000F00) != 0x00000000) return false; // if cond(31:28)=1111, don't test instruction. if ((inst.Bits() & 0xF0000000) == 0xF0000000) return false; // Check other preconditions defined for the base decoder. return Arm32DecoderTester:: PassesParsePreconditions(inst, decoder); } // op(22:21)=10 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QDADD_cccc00010100nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010100nnnndddd00000101mmmm, // rule: QDADD, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} class QDADD_cccc00010100nnnndddd00000101mmmm_case_0TesterCase2 : public Arm32DecoderTester { public: QDADD_cccc00010100nnnndddd00000101mmmm_case_0TesterCase2(const NamedClassDecoder& decoder) : Arm32DecoderTester(decoder) {} virtual bool PassesParsePreconditions( nacl_arm_dec::Instruction inst, const NamedClassDecoder& decoder); }; bool QDADD_cccc00010100nnnndddd00000101mmmm_case_0TesterCase2 ::PassesParsePreconditions( nacl_arm_dec::Instruction inst, const NamedClassDecoder& decoder) { // Check that row patterns apply to pattern being checked.' // op(22:21)=~10 if ((inst.Bits() & 0x00600000) != 0x00400000) return false; // $pattern(31:0)=~xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx if ((inst.Bits() & 0x00000F00) != 0x00000000) return false; // if cond(31:28)=1111, don't test instruction. if ((inst.Bits() & 0xF0000000) == 0xF0000000) return false; // Check other preconditions defined for the base decoder. return Arm32DecoderTester:: PassesParsePreconditions(inst, decoder); } // op(22:21)=11 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QDSUB_cccc00010110nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010110nnnndddd00000101mmmm, // rule: QDSUB, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} class QDSUB_cccc00010110nnnndddd00000101mmmm_case_0TesterCase3 : public Arm32DecoderTester { public: QDSUB_cccc00010110nnnndddd00000101mmmm_case_0TesterCase3(const NamedClassDecoder& decoder) : Arm32DecoderTester(decoder) {} virtual bool PassesParsePreconditions( nacl_arm_dec::Instruction inst, const NamedClassDecoder& decoder); }; bool QDSUB_cccc00010110nnnndddd00000101mmmm_case_0TesterCase3 ::PassesParsePreconditions( nacl_arm_dec::Instruction inst, const NamedClassDecoder& decoder) { // Check that row patterns apply to pattern being checked.' // op(22:21)=~11 if ((inst.Bits() & 0x00600000) != 0x00600000) return false; // $pattern(31:0)=~xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx if ((inst.Bits() & 0x00000F00) != 0x00000000) return false; // if cond(31:28)=1111, don't test instruction. if ((inst.Bits() & 0xF0000000) == 0xF0000000) return false; // Check other preconditions defined for the base decoder. return Arm32DecoderTester:: PassesParsePreconditions(inst, decoder); } // The following are derived class decoder testers for decoder actions // associated with a pattern of an action. These derived classes introduce // a default constructor that automatically initializes the expected decoder // to the corresponding instance in the generated DecoderState. // op(22:21)=00 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QADD_cccc00010000nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010000nnnndddd00000101mmmm, // rule: QADD, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} class QADD_cccc00010000nnnndddd00000101mmmm_case_0Tester_Case0 : public QADD_cccc00010000nnnndddd00000101mmmm_case_0TesterCase0 { public: QADD_cccc00010000nnnndddd00000101mmmm_case_0Tester_Case0() : QADD_cccc00010000nnnndddd00000101mmmm_case_0TesterCase0( state_.QADD_cccc00010000nnnndddd00000101mmmm_case_0_QADD_instance_) {} }; // op(22:21)=01 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QSUB_cccc00010010nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010010nnnndddd00000101mmmm, // rule: QSUB, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} class QSUB_cccc00010010nnnndddd00000101mmmm_case_0Tester_Case1 : public QSUB_cccc00010010nnnndddd00000101mmmm_case_0TesterCase1 { public: QSUB_cccc00010010nnnndddd00000101mmmm_case_0Tester_Case1() : QSUB_cccc00010010nnnndddd00000101mmmm_case_0TesterCase1( state_.QSUB_cccc00010010nnnndddd00000101mmmm_case_0_QSUB_instance_) {} }; // op(22:21)=10 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QDADD_cccc00010100nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010100nnnndddd00000101mmmm, // rule: QDADD, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} class QDADD_cccc00010100nnnndddd00000101mmmm_case_0Tester_Case2 : public QDADD_cccc00010100nnnndddd00000101mmmm_case_0TesterCase2 { public: QDADD_cccc00010100nnnndddd00000101mmmm_case_0Tester_Case2() : QDADD_cccc00010100nnnndddd00000101mmmm_case_0TesterCase2( state_.QDADD_cccc00010100nnnndddd00000101mmmm_case_0_QDADD_instance_) {} }; // op(22:21)=11 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QDSUB_cccc00010110nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010110nnnndddd00000101mmmm, // rule: QDSUB, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} class QDSUB_cccc00010110nnnndddd00000101mmmm_case_0Tester_Case3 : public QDSUB_cccc00010110nnnndddd00000101mmmm_case_0TesterCase3 { public: QDSUB_cccc00010110nnnndddd00000101mmmm_case_0Tester_Case3() : QDSUB_cccc00010110nnnndddd00000101mmmm_case_0TesterCase3( state_.QDSUB_cccc00010110nnnndddd00000101mmmm_case_0_QDSUB_instance_) {} }; // Defines a gtest testing harness for tests. class Arm32DecoderStateTests : public ::testing::Test { protected: Arm32DecoderStateTests() {} }; // The following functions test each pattern specified in parse // decoder tables. // op(22:21)=00 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QADD_cccc00010000nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010000nnnndddd00000101mmmm, // rule: QADD, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} TEST_F(Arm32DecoderStateTests, QADD_cccc00010000nnnndddd00000101mmmm_case_0Tester_Case0_TestCase0) { QADD_cccc00010000nnnndddd00000101mmmm_case_0Tester_Case0 baseline_tester; NamedActual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1_QADD actual; ActualVsBaselineTester a_vs_b_tester(actual, baseline_tester); a_vs_b_tester.Test("cccc00010000nnnndddd00000101mmmm"); } // op(22:21)=01 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QSUB_cccc00010010nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010010nnnndddd00000101mmmm, // rule: QSUB, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} TEST_F(Arm32DecoderStateTests, QSUB_cccc00010010nnnndddd00000101mmmm_case_0Tester_Case1_TestCase1) { QSUB_cccc00010010nnnndddd00000101mmmm_case_0Tester_Case1 baseline_tester; NamedActual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1_QSUB actual; ActualVsBaselineTester a_vs_b_tester(actual, baseline_tester); a_vs_b_tester.Test("cccc00010010nnnndddd00000101mmmm"); } // op(22:21)=10 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QDADD_cccc00010100nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010100nnnndddd00000101mmmm, // rule: QDADD, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} TEST_F(Arm32DecoderStateTests, QDADD_cccc00010100nnnndddd00000101mmmm_case_0Tester_Case2_TestCase2) { QDADD_cccc00010100nnnndddd00000101mmmm_case_0Tester_Case2 baseline_tester; NamedActual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1_QDADD actual; ActualVsBaselineTester a_vs_b_tester(actual, baseline_tester); a_vs_b_tester.Test("cccc00010100nnnndddd00000101mmmm"); } // op(22:21)=11 & $pattern(31:0)=xxxxxxxxxxxxxxxxxxxx0000xxxxxxxx // = {Pc: 15, // Rd: Rd(15:12), // Rm: Rm(3:0), // Rn: Rn(19:16), // actual: Actual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1, // baseline: QDSUB_cccc00010110nnnndddd00000101mmmm_case_0, // defs: {Rd}, // fields: [Rn(19:16), Rd(15:12), Rm(3:0)], // pattern: cccc00010110nnnndddd00000101mmmm, // rule: QDSUB, // safety: [Pc in {Rd, Rn, Rm} => UNPREDICTABLE], // uses: {Rn, Rm}} TEST_F(Arm32DecoderStateTests, QDSUB_cccc00010110nnnndddd00000101mmmm_case_0Tester_Case3_TestCase3) { QDSUB_cccc00010110nnnndddd00000101mmmm_case_0Tester_Case3 baseline_tester; NamedActual_PKH_cccc01101000nnnnddddiiiiit01mmmm_case_1_QDSUB actual; ActualVsBaselineTester a_vs_b_tester(actual, baseline_tester); a_vs_b_tester.Test("cccc00010110nnnndddd00000101mmmm"); } } // namespace nacl_arm_test int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
6,940
1,137
<filename>Tests/test_types.py import os import types def test_subclassdict(): """Test that a subclass of dict can be merged into a static dict""" out = {**os.environ, 'foo': 'bar'} assert 'foo' in out def test_change_method(): class A: def foo(self): return 1 def bar(self): return 2 a = A() def _f(): return a.foo() assert _f() == 1 a.foo = a.bar assert _f() == 2 def test_resolve_bases(): class A: pass class B: pass class C: def __mro_entries__(self, bases): if A in bases: return () return (A,) c = C() assert types.resolve_bases(()) == () assert types.resolve_bases((c,)) == (A,) assert types.resolve_bases((C,)) == (C,) assert types.resolve_bases((A, C)) == (A, C) assert types.resolve_bases((c, A)) == (A,) assert types.resolve_bases((A, c)) == (A,) x = (A,) y = (C,) z = (A, C) t = (A, C, B) for bases in [x, y, z, t]: assert types.resolve_bases(bases) is bases
521
335
<filename>O/Oread_noun.json { "word": "Oread", "definitions": [ "A nymph believed to inhabit mountains." ], "parts-of-speech": "Noun" }
73
3,066
<reponame>skofra0/crate /* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.expression.scalar.geo; import static io.crate.metadata.functions.Signature.scalar; import java.util.Arrays; import java.util.List; import org.apache.lucene.document.LatLonPoint; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; import org.elasticsearch.common.geo.GeoUtils; import org.elasticsearch.common.lucene.search.Queries; import org.locationtech.spatial4j.shape.Point; import io.crate.data.Input; import io.crate.expression.operator.EqOperator; import io.crate.expression.operator.GtOperator; import io.crate.expression.operator.GteOperator; import io.crate.expression.operator.LtOperator; import io.crate.expression.operator.LteOperator; import io.crate.expression.scalar.ScalarFunctionModule; import io.crate.expression.symbol.Function; import io.crate.expression.symbol.Literal; import io.crate.expression.symbol.Symbol; import io.crate.lucene.LuceneQueryBuilder; import io.crate.lucene.LuceneQueryBuilder.Context; import io.crate.metadata.NodeContext; import io.crate.metadata.Reference; import io.crate.metadata.Scalar; import io.crate.metadata.TransactionContext; import io.crate.metadata.functions.Signature; import io.crate.types.DataTypes; public class DistanceFunction extends Scalar<Double, Point> { public static final String NAME = "distance"; public static void register(ScalarFunctionModule module) { module.register( scalar( NAME, DataTypes.GEO_POINT.getTypeSignature(), DataTypes.GEO_POINT.getTypeSignature(), DataTypes.DOUBLE.getTypeSignature() ), DistanceFunction::new ); } private final Signature signature; private final Signature boundSignature; private DistanceFunction(Signature signature, Signature boundSignature) { this.signature = signature; this.boundSignature = boundSignature; } @Override public Signature signature() { return signature; } @Override public Signature boundSignature() { return boundSignature; } @Override public Double evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Point>[] args) { assert args.length == 2 : "number of args must be 2"; return evaluate(args[0], args[1]); } public static Double evaluate(Input<Point> arg1, Input<Point> arg2) { Point value1 = arg1.value(); if (value1 == null) { return null; } Point value2 = arg2.value(); if (value2 == null) { return null; } return GeoUtils.arcDistance(value1.getY(), value1.getX(), value2.getY(), value2.getX()); } @Override public Symbol normalizeSymbol(Function symbol, TransactionContext txnCtx, NodeContext nodeCtx) { Symbol arg1 = symbol.arguments().get(0); Symbol arg2 = symbol.arguments().get(1); boolean arg1IsReference = true; short numLiterals = 0; if (arg1.symbolType().isValueSymbol()) { numLiterals++; arg1IsReference = false; } if (arg2.symbolType().isValueSymbol()) { numLiterals++; } if (numLiterals == 2) { return Literal.of(evaluate((Input) arg1, (Input) arg2)); } // ensure reference is the first argument. if (!arg1IsReference) { return new Function(signature, Arrays.asList(arg2, arg1), signature.getReturnType().createType()); } return symbol; } @Override public Query toQuery(Function parent, Function inner, Context context) { assert inner.name().equals(DistanceFunction.NAME) : "function must be " + DistanceFunction.NAME; // ┌─► pointLiteral // │ // distance(p, 'POINT (1 2)') = 10 // │ │ // └► pointRef │ // ^^^^^^^^^^^^^^^^^^^^^^^^^^ └► parentRhs // inner // // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // parent // List<Symbol> innerArgs = inner.arguments(); if (!(innerArgs.get(0) instanceof Reference pointRef && innerArgs.get(1) instanceof Literal<?> pointLiteral)) { // can't use distance filter without literal, fallback to genericFunction return null; } List<Symbol> parentArgs = parent.arguments(); if (!(parentArgs.get(1) instanceof Literal<?> parentRhs)) { // must be something like cmp(distance(..), non-literal) - fallback to genericFunction return null; } Double distance = DataTypes.DOUBLE.implicitCast(parentRhs.value()); String parentName = parent.name(); Point pointValue = (Point) pointLiteral.value(); String fieldName = pointRef.column().fqn(); return esV5DistanceQuery(parent, context, parentName, fieldName, distance, pointValue); } /** * Create a LatLonPoint distance query. * * * <pre> * , - ~ ~ ~ - , * , ' ' , * , , X = lonLat coordinates * , , * , [distance] , * , p<------------>X * , ^ , * , | , * , [columnName] , * , point , ' * ' - , _ _ _ , ' * * lt and lte -> match everything WITHIN distance * gt and gte -> match everything OUTSIDE distance * * eq distance ~ 0 -> match everything within distance + tolerance * * eq distance > 0 -> build two circles, one slightly smaller, one slightly larger * distance must not be within the smaller distance but within the larger. * </pre> */ private static Query esV5DistanceQuery(Function parentFunction, LuceneQueryBuilder.Context context, String parentOperatorName, String columnName, Double distance, Point lonLat) { switch (parentOperatorName) { // We documented that using distance in the WHERE clause utilizes the index which isn't precise so treating // lte & lt the same should be acceptable case LteOperator.NAME: case LtOperator.NAME: return LatLonPoint.newDistanceQuery(columnName, lonLat.getY(), lonLat.getX(), distance); case GteOperator.NAME: if (distance - GeoUtils.TOLERANCE <= 0.0d) { return Queries.newMatchAllQuery(); } // fall through case GtOperator.NAME: return Queries.not(LatLonPoint.newDistanceQuery(columnName, lonLat.getY(), lonLat.getX(), distance)); case EqOperator.NAME: return eqDistance(parentFunction, context, columnName, distance, lonLat); default: return null; } } private static Query eqDistance(Function parentFunction, LuceneQueryBuilder.Context context, String columnName, Double distance, Point lonLat) { double smallDistance = distance * 0.99; if (smallDistance <= 0.0) { return LatLonPoint.newDistanceQuery(columnName, lonLat.getY(), lonLat.getX(), 0); } Query withinSmallCircle = LatLonPoint.newDistanceQuery(columnName, lonLat.getY(), lonLat.getX(), smallDistance); Query withinLargeCircle = LatLonPoint.newDistanceQuery(columnName, lonLat.getY(), lonLat.getX(), distance * 1.01); return new BooleanQuery.Builder() .add(withinLargeCircle, BooleanClause.Occur.MUST) .add(withinSmallCircle, BooleanClause.Occur.MUST_NOT) .add(LuceneQueryBuilder.genericFunctionFilter(parentFunction, context), BooleanClause.Occur.FILTER) .build(); } }
4,072
1,056
<reponame>arusinha/incubator-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.mycompany.installer.wizard.components.panels; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.Insets; import java.io.File; import java.util.List; import org.netbeans.installer.product.Registry; import org.netbeans.installer.product.components.Product; import org.netbeans.installer.utils.ErrorManager; import org.netbeans.installer.utils.LogManager; import org.netbeans.installer.utils.ResourceUtils; import org.netbeans.installer.utils.StringUtils; import org.netbeans.installer.utils.SystemUtils; import org.netbeans.installer.utils.exceptions.InitializationException; import org.netbeans.installer.utils.helper.Platform; import org.netbeans.installer.utils.helper.swing.NbiPanel; import org.netbeans.installer.utils.helper.swing.NbiTextPane; import org.netbeans.installer.wizard.components.panels.ErrorMessagePanel; import org.netbeans.installer.wizard.components.panels.ErrorMessagePanel.ErrorMessagePanelSwingUi; import org.netbeans.installer.wizard.components.panels.ErrorMessagePanel.ErrorMessagePanelUi; import org.netbeans.installer.wizard.containers.SwingContainer; import org.netbeans.installer.wizard.ui.SwingUi; import org.netbeans.installer.wizard.ui.WizardUi; public class WelcomePanel extends ErrorMessagePanel { ///////////////////////////////////////////////////////////////////////////////// private Registry bundledRegistry; private Registry defaultRegistry; public WelcomePanel() { setProperty(TITLE_PROPERTY, DEFAULT_TITLE); setProperty(DESCRIPTION_PROPERTY, DEFAULT_DESCRIPTION); setProperty(WELCOME_TEXT_PROPERTY, DEFAULT_WELCOME_TEXT); setProperty(WELCOME_ALREADY_INSTALLED_TEXT_PROPERTY, DEFAULT_WELCOME_ALREADY_INSTALLED_TEXT); setProperty(WELCOME_ALREADY_INSTALLED_NEXT_BUTTON_TEXT_PROPERTY, DEFAULT_WELCOME_ALREADY_INSTALLED_NEXT_BUTTON_TEXT); try { defaultRegistry = Registry.getInstance(); bundledRegistry = new Registry(); final String bundledRegistryUri = System.getProperty( Registry.BUNDLED_PRODUCT_REGISTRY_URI_PROPERTY); if (bundledRegistryUri != null) { bundledRegistry.loadProductRegistry(bundledRegistryUri); } else { bundledRegistry.loadProductRegistry( Registry.DEFAULT_BUNDLED_PRODUCT_REGISTRY_URI); } } catch (InitializationException e) { ErrorManager.notifyError("Cannot load bundled registry", e); } } Registry getBundledRegistry() { return bundledRegistry; } @Override public WizardUi getWizardUi() { if (wizardUi == null) { wizardUi = new WelcomePanelUi(this); } return wizardUi; } @Override public boolean canExecuteForward() { return canExecute(); } @Override public boolean canExecuteBackward() { return canExecute(); } // private ////////////////////////////////////////////////////////////////////// private boolean canExecute() { return bundledRegistry.getNodes().size() > 1; } ///////////////////////////////////////////////////////////////////////////////// // Inner Classes public static class WelcomePanelUi extends ErrorMessagePanelUi { protected WelcomePanel component; public WelcomePanelUi(WelcomePanel component) { super(component); this.component = component; } @Override public SwingUi getSwingUi(SwingContainer container) { if (swingUi == null) { swingUi = new WelcomePanelSwingUi(component, container); } return super.getSwingUi(container); } } public static class WelcomePanelSwingUi extends ErrorMessagePanelSwingUi { protected WelcomePanel panel; private NbiTextPane textPane; private NbiPanel leftImagePanel; ValidatingThread validatingThread; public WelcomePanelSwingUi( final WelcomePanel component, final SwingContainer container) { super(component, container); this.panel = component; initComponents(); } @Override public String getTitle() { return null; // the welcome page does not have a title } // protected //////////////////////////////////////////////////////////////// @Override protected void initializeContainer() { super.initializeContainer(); container.getBackButton().setVisible(false); } @Override protected void initialize() { textPane.setContentType("text/html"); textPane.setText(StringUtils.format(panel.getProperty(WELCOME_TEXT_PROPERTY))); List<Product> toInstall = Registry.getInstance().getProductsToInstall(); if(toInstall.isEmpty()) { List <Product> list = panel.getBundledRegistry().getProducts(); if(list.size() == 1) { if(SystemUtils.getCurrentPlatform().isCompatibleWith(list.get(0).getPlatforms())) { File installationLocation = list.get(0).getInstallationLocation(); textPane.setText( StringUtils.format( panel.getProperty(WELCOME_ALREADY_INSTALLED_TEXT_PROPERTY), list.get(0).getDisplayName(), installationLocation.getAbsolutePath())); } else { textPane.setText( StringUtils.format( WELCOME_INCOMPATIBLE_PLATFORM_TEXT, list.get(0).getDisplayName())); } container.getCancelButton().setVisible(false); container.getNextButton().setText(panel.getProperty( WELCOME_ALREADY_INSTALLED_NEXT_BUTTON_TEXT_PROPERTY)); } } super.initialize(); } // private ////////////////////////////////////////////////////////////////// private void initComponents() { // textPane ///////////////////////////////////////////////////////////// textPane = new NbiTextPane(); leftImagePanel = new NbiPanel(); int width = 0; int height = 0; final String topLeftImage = SystemUtils.resolveString( System.getProperty( WELCOME_PAGE_LEFT_TOP_IMAGE_PROPERTY)); final String bottomLeftImage = SystemUtils.resolveString( System.getProperty( WELCOME_PAGE_LEFT_BOTTOM_IMAGE_PROPERTY)); int bottomAnchor = NbiPanel.ANCHOR_BOTTOM_LEFT; if (topLeftImage != null) { leftImagePanel.setBackgroundImage(topLeftImage, ANCHOR_TOP_LEFT); width = leftImagePanel.getBackgroundImage(NbiPanel.ANCHOR_TOP_LEFT).getIconWidth(); height += leftImagePanel.getBackgroundImage(NbiPanel.ANCHOR_TOP_LEFT).getIconHeight(); } if (bottomLeftImage != null) { leftImagePanel.setBackgroundImage(bottomLeftImage, bottomAnchor); width = leftImagePanel.getBackgroundImage(bottomAnchor).getIconWidth(); height += leftImagePanel.getBackgroundImage(bottomAnchor).getIconHeight(); } leftImagePanel.setPreferredSize(new Dimension(width, height)); leftImagePanel.setMaximumSize(new Dimension(width, height)); leftImagePanel.setMinimumSize(new Dimension(width, 0)); leftImagePanel.setSize(new Dimension(width, height)); leftImagePanel.setOpaque(false); // this ///////////////////////////////////////////////////////////////// int dy = 0; add(leftImagePanel, new GridBagConstraints( 0, 0, // x, y 1, 100, // width, height 0.0, 1.0, // weight-x, weight-y GridBagConstraints.WEST, // anchor GridBagConstraints.VERTICAL, // fill new Insets(0, 0, 0, 0), // padding 0, 0)); // padx, pady - ??? add(textPane, new GridBagConstraints( 1, dy++, // x, y 4, 1, // width, height 1.0, 0.0, // weight-x, weight-y GridBagConstraints.LINE_START, // anchor GridBagConstraints.HORIZONTAL, // fill new Insets(10, 11, 11, 11), // padding 0, 0)); // padx, pady - ??? NbiTextPane separatorPane = new NbiTextPane(); separatorPane = new NbiTextPane(); add(separatorPane, new GridBagConstraints( 3, dy, // x, y 1, 1, // width, height 1.0, 0.0, // weight-x, weight-y GridBagConstraints.CENTER, // anchor GridBagConstraints.BOTH, // fill new Insets(0, 0, 0, 0), // padding 0, 0)); // padx, pady - ??? // move error label after the left welcome image Component errorLabel = getComponent(0); getLayout().removeLayoutComponent(errorLabel); add(errorLabel, new GridBagConstraints( 1, 99, // x, y 99, 1, // width, height 1.0, 0.0, // weight-x, weight-y GridBagConstraints.CENTER, // anchor GridBagConstraints.HORIZONTAL, // fill new Insets(4, 11, 4, 0), // padding 0, 0)); // ??? (padx, pady) } } ///////////////////////////////////////////////////////////////////////////////// // Constants public static final String DEFAULT_TITLE = ResourceUtils.getString(WelcomePanel.class, "WP.title"); public static final String DEFAULT_DESCRIPTION = ResourceUtils.getString(WelcomePanel.class, "WP.description"); // NOI18N public static final String WELCOME_TEXT_PROPERTY = "welcome.text"; // NOI18N public static final String WELCOME_ALREADY_INSTALLED_TEXT_PROPERTY = "welcome.already.installed.text"; // NOI18N public static final String WELCOME_ALREADY_INSTALLED_NEXT_BUTTON_TEXT_PROPERTY = "welcome.already.installed.next.button.text";//NOI18N public static final String WELCOME_INCOMPATIBLE_PLATFORM_TEXT = ResourceUtils.getString(WelcomePanel.class, "WP.incompatible.platform.text");//NOI18N public static final String DEFAULT_WELCOME_ALREADY_INSTALLED_NEXT_BUTTON_TEXT = ResourceUtils.getString(WelcomePanel.class, "WP.already.installed.next.button.text");//NOI18N public static final String DEFAULT_WELCOME_TEXT = ResourceUtils.getString(WelcomePanel.class, "WP.welcome.text"); // NOI18N public static final String DEFAULT_WELCOME_ALREADY_INSTALLED_TEXT = ResourceUtils.getString(WelcomePanel.class, "WP.already.installed.text"); // NOI18N public static final String WELCOME_PAGE_LEFT_TOP_IMAGE_PROPERTY = "nbi.wizard.ui.swing.welcome.left.top.image";//NOI18N public static final String WELCOME_PAGE_LEFT_BOTTOM_IMAGE_PROPERTY = "nbi.wizard.ui.swing.welcome.left.bottom.image";//NOI18N }
5,769
347
<reponame>hbraha/ovirt-engine<filename>backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/irsbroker/GetImageInfoVDSCommand.java package org.ovirt.engine.core.vdsbroker.irsbroker; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.GetVolumeInfoVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GetImageInfoVDSCommand<P extends GetImageInfoVDSCommandParameters> extends IrsBrokerCommand<P> { private static final Logger log = LoggerFactory.getLogger(GetImageInfoVDSCommand.class); public GetImageInfoVDSCommand(P parameters) { super(parameters); } @Override protected void executeIrsBrokerCommand() { GetVolumeInfoVDSCommandParameters p = new GetVolumeInfoVDSCommandParameters(getCurrentIrsProxy() .getCurrentVdsId(), getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), getParameters().getImageGroupId(), getParameters().getImageId()); DiskImage di = (DiskImage) resourceManager.runVdsCommand(VDSCommandType.GetVolumeInfo, p).getReturnValue(); // if couldn't parse image then succeeded should be false getVDSReturnValue().setSucceeded(di != null); if (!getVDSReturnValue().getSucceeded()) { log.error("Failed to get the volume information, marking as FAILED"); } setReturnValue(di); } }
584
1,666
<reponame>madanagopaltcomcast/pxCore #include <node.h> #include <v8.h> namespace { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Object; using v8::Promise; using v8::String; using v8::Value; static void ThrowError(Isolate* isolate, const char* err_msg) { Local<String> str = String::NewFromOneByte( isolate, reinterpret_cast<const uint8_t*>(err_msg), NewStringType::kNormal).ToLocalChecked(); isolate->ThrowException(str); } static void GetPromiseField(const FunctionCallbackInfo<Value>& args) { auto isolate = args.GetIsolate(); if (!args[0]->IsPromise()) return ThrowError(isolate, "arg is not an Promise"); auto p = args[0].As<Promise>(); if (p->InternalFieldCount() < 1) return ThrowError(isolate, "Promise has no internal field"); auto l = p->GetInternalField(0); args.GetReturnValue().Set(l); } inline void Initialize(v8::Local<v8::Object> binding) { NODE_SET_METHOD(binding, "getPromiseField", GetPromiseField); } NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) } // anonymous namespace
404
666
import sys sys.path.append("../") from appJar import gui import random val = 0 def press(btn): print(btn) def updateMeter(): global val val = random.randint(0,100) app.setMeter("m1", (val, val)) # val += 1 app=gui() app.startTabbedFrame("One") app.startTab("Two") app.addDualMeter("m1") #app.setDualMeterFill("m1", ["yellow","blue"]) #app.setMeterFg("m1", "white") #app.setMeterBg("m1", "red") app.registerEvent(updateMeter) app.addRadioButton("song", "Song 1") app.addRadioButton("song", "Song 2") app.addRadioButton("song2", "Song 3") app.setRadioButtonBg("song", "green") app.setRadioButtonFg("song", "red") app.setRadioButtonBg("song2", "green") app.addListBox("list", [1, 2, 3]) app.setListBoxRows("list", 3) app.addListBox("list2", [1, 2, 3]) app.setListBoxBg("list", "yellow") app.setListBoxFg("list", "orange") app.setListBoxBg("list2", "green") app.addRadioButton("rb1", "Button1") app.addRadioButton("rb2", "Button2") app.addRadioButton("rb3", "Button3") app.setRadioButtonBg("rb1", "purple") app.setRadioButtonBg("rb2", "orange") app.setRadioButtonFg("rb2", "pink") app.addButton("B1", press) app.addButton("B2", press) app.addButton("B3", press) app.addButton("B4", press) app.setButtonBg("B1", "green") app.stopTab() app.stopTabbedFrame() app.go()
548
1,475
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.util; import java.util.Collection; import java.util.List; import org.apache.geode.annotations.Immutable; import org.apache.geode.internal.util.redaction.StringRedaction; public class ArgumentRedactor { @Immutable private static final StringRedaction DELEGATE = new StringRedaction(); private ArgumentRedactor() { // do not instantiate } /** * Parse a string to find key/value pairs and redact the values if identified as sensitive. * * <p> * The following format is expected:<br> * - Each key/value pair should be separated by spaces.<br> * - The key must be preceded by '--', '-D', or '--J=-D'.<br> * - The value may optionally be wrapped in quotation marks.<br> * - The value is assigned to a key with '=', '=' padded with any number of optional spaces, or * any number of spaces without '='.<br> * - The value must not contain spaces without being wrapped in quotation marks.<br> * - The value may contain spaces or any other symbols when wrapped in quotation marks. * * <p> * Examples: * <ol> * <li>"--password=<PASSWORD>" * <li>"--user me --password <PASSWORD>" * <li>"-Dflag -Dopt=arg" * <li>"--classpath=." * <li>"password=secret" * </ol> * * @param string The string input to be parsed * * @return A string that has sensitive data redacted. */ public static String redact(String string) { return DELEGATE.redact(string); } public static String redact(Iterable<String> strings) { return DELEGATE.redact(strings); } /** * Return the redacted value string if the provided key is identified as sensitive, otherwise * return the original value. * * @param key A string such as a system property, java option, or command-line key. * @param value The string value for the key. * * @return The redacted string if the key is identified as sensitive, otherwise the original * value. */ public static String redactArgumentIfNecessary(String key, String value) { return DELEGATE.redactArgumentIfNecessary(key, value); } public static List<String> redactEachInList(Collection<String> strings) { return DELEGATE.redactEachInList(strings); } /** * Returns true if a string identifies sensitive data. For example, a string containing * the word "password" identifies data that is sensitive and should be secured. * * @param key The string to be evaluated. * * @return true if the string identifies sensitive data. */ public static boolean isSensitive(String key) { return DELEGATE.isSensitive(key); } public static String getRedacted() { return DELEGATE.getRedacted(); } }
1,047
460
#include "../../src/dbus/qdbuserror.h"
19
32,544
package com.baeldung.ex.beancreationexception.spring; import com.baeldung.ex.beancreationexception.cause9.BeanB; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration @ComponentScan("com.baeldung.ex.beancreationexception.cause9") @ImportResource("classpath:beancreationexception_cause9.xml") public class Cause9ContextWithJavaConfig { @Autowired BeanFactory beanFactory; public Cause9ContextWithJavaConfig() { super(); } // beans @Bean public BeanB beanB() { beanFactory.getBean("beanA"); return new BeanB(); } }
305
2,542
<gh_stars>1000+ // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ // CRC values are verified with http://www.sunshine2k.de/coding/javascript/crc/crc_js.html #include "stdafx.h" #include <boost/test/unit_test.hpp> #include "Common/boost-taef.h" using namespace std; namespace Common { BOOST_AUTO_TEST_SUITE2(crctest) BOOST_AUTO_TEST_CASE(basic32) { ENTER; string s1("this is a test string"); crc32 c1; c1.AddData(s1.c_str(), s1.length()); Trace.WriteInfo(TraceType, "c1 = {0:x}", c1.Value()); VERIFY_IS_TRUE(c1.Value() == 0xFC86D6B5); crc32 c1_2(s1.c_str(), s1.length()); Trace.WriteInfo(TraceType, "c1_2 = {0:x}", c1_2.Value()); VERIFY_IS_TRUE(c1.Value() == c1_2.Value()); string s2("this is a test strinf"); // s1 and s2 differs by a single bit crc32 c2(s2.c_str(), s2.length()); Trace.WriteInfo(TraceType, "c2 = {0:x}", c2.Value()); VERIFY_IS_TRUE(c1.Value() != c2.Value()); VERIFY_IS_TRUE(c2.Value() == 0x8B81E623); string s3("Garbled data@34@!@%@#"); // s3 is very different from s1 and s2 crc32 c3; c3.AddData(s3.c_str(), s3.length()); Trace.WriteInfo(TraceType, "c3 = {0:x}", c3.Value()); VERIFY_IS_TRUE(c1.Value() != c3.Value()); VERIFY_IS_TRUE(c2.Value() != c3.Value()); VERIFY_IS_TRUE(c3.Value() == 0x582D102A); string s1_part2("this is a part 2 of s1"); c1.AddData(s1_part2.c_str(), s1_part2.length()); Trace.WriteInfo(TraceType, "c1 = {0:x}", c1.Value()); VERIFY_IS_TRUE(c1.Value() != c1_2.Value()); VERIFY_IS_TRUE(c1.Value() == 0x36AF107A); c1_2.AddData(s1_part2.c_str(), s1_part2.length()); Trace.WriteInfo(TraceType, "c1_2 = {0:x}", c1_2.Value()); VERIFY_IS_TRUE(c1.Value() == c1_2.Value()); string s4 = s1 + s1_part2; crc32 c4; c4.AddData(s4.c_str(), s4.length()); Trace.WriteInfo(TraceType, "c4 = {0:x}", c4.Value()); VERIFY_IS_TRUE(c1.Value() == c4.Value()); string s5 = s2 + s1_part2; // s5 and s4 differs by a single bit crc32 c5; c5.AddData(s5.c_str(), s5.length()); Trace.WriteInfo(TraceType, "c5 = {0:x}", c5.Value()); VERIFY_IS_TRUE(c1.Value() != c5.Value()); VERIFY_IS_TRUE(c5.Value() == 0xADDCFAAE); LEAVE; } BOOST_AUTO_TEST_CASE(basic8) { ENTER; string s1("this is a test string"); crc8 c1; c1.AddData(s1.c_str(), s1.length()); Trace.WriteInfo(TraceType, "c1 = {0:x}", c1.Value()); VERIFY_IS_TRUE(c1.Value() == 0x17); crc8 c1_2(s1.c_str(), s1.length()); Trace.WriteInfo(TraceType, "c1_2 = {0:x}", c1_2.Value()); VERIFY_IS_TRUE(c1.Value() == c1_2.Value()); string s2("this is a test strinf"); // s1 and s2 differs by a single bit crc8 c2(s2.c_str(), s2.length()); Trace.WriteInfo(TraceType, "c2 = {0:x}", c2.Value()); VERIFY_IS_TRUE(c1.Value() != c2.Value()); VERIFY_IS_TRUE(c2.Value() == 0x10); string s3("Garbled data@34@!@%@#"); // s3 is very different from s1 and s2 crc8 c3; c3.AddData(s3.c_str(), s3.length()); Trace.WriteInfo(TraceType, "c3 = {0:x}", c3.Value()); VERIFY_IS_TRUE(c1.Value() != c3.Value()); VERIFY_IS_TRUE(c2.Value() != c3.Value()); VERIFY_IS_TRUE(c3.Value() == 0x9f); string s1_part2("this is a part 2 of s1"); c1.AddData(s1_part2.c_str(), s1_part2.length()); Trace.WriteInfo(TraceType, "c1 = {0:x}", c1.Value()); VERIFY_IS_TRUE(c1.Value() != c1_2.Value()); VERIFY_IS_TRUE(c1.Value() == 0x7C); c1_2.AddData(s1_part2.c_str(), s1_part2.length()); Trace.WriteInfo(TraceType, "c1_2 = {0:x}", c1_2.Value()); VERIFY_IS_TRUE(c1.Value() == c1_2.Value()); string s4 = s1 + s1_part2; crc8 c4; c4.AddData(s4.c_str(), s4.length()); Trace.WriteInfo(TraceType, "c4 = {0:x}", c4.Value()); VERIFY_IS_TRUE(c1.Value() == c4.Value()); string s5 = s2 + s1_part2; // s5 and s4 differs by a single bit crc8 c5; c5.AddData(s5.c_str(), s5.length()); Trace.WriteInfo(TraceType, "c5 = {0:x}", c5.Value()); VERIFY_IS_TRUE(c1.Value() != c5.Value()); VERIFY_IS_TRUE(c5.Value() == 0xC5); LEAVE; } BOOST_AUTO_TEST_SUITE_END() }
2,454
2,151
<reponame>Keneral/aframeworks /* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v4.graphics; import android.graphics.Bitmap; /** * Helper for accessing features in {@link android.graphics.Bitmap} * introduced after API level 4 in a backwards compatible fashion. */ public final class BitmapCompat { /** * Interface for the full API. */ interface BitmapImpl { public boolean hasMipMap(Bitmap bitmap); public void setHasMipMap(Bitmap bitmap, boolean hasMipMap); public int getAllocationByteCount(Bitmap bitmap); } static class BaseBitmapImpl implements BitmapImpl { @Override public boolean hasMipMap(Bitmap bitmap) { return false; } @Override public void setHasMipMap(Bitmap bitmap, boolean hasMipMap) { } @Override public int getAllocationByteCount(Bitmap bitmap) { return bitmap.getRowBytes() * bitmap.getHeight(); } } static class HcMr1BitmapCompatImpl extends BaseBitmapImpl { @Override public int getAllocationByteCount(Bitmap bitmap) { return BitmapCompatHoneycombMr1.getAllocationByteCount(bitmap); } } static class JbMr2BitmapCompatImpl extends HcMr1BitmapCompatImpl { @Override public boolean hasMipMap(Bitmap bitmap){ return BitmapCompatJellybeanMR2.hasMipMap(bitmap); } @Override public void setHasMipMap(Bitmap bitmap, boolean hasMipMap) { BitmapCompatJellybeanMR2.setHasMipMap(bitmap, hasMipMap); } } static class KitKatBitmapCompatImpl extends JbMr2BitmapCompatImpl { @Override public int getAllocationByteCount(Bitmap bitmap) { return BitmapCompatKitKat.getAllocationByteCount(bitmap); } } /** * Select the correct implementation to use for the current platform. */ static final BitmapImpl IMPL; static { final int version = android.os.Build.VERSION.SDK_INT; if (version >= 19) { IMPL = new KitKatBitmapCompatImpl(); } else if (version >= 18) { IMPL = new JbMr2BitmapCompatImpl(); } else if (version >= 12) { IMPL = new HcMr1BitmapCompatImpl(); } else { IMPL = new BaseBitmapImpl(); } } public static boolean hasMipMap(Bitmap bitmap) { return IMPL.hasMipMap(bitmap); } public static void setHasMipMap(Bitmap bitmap, boolean hasMipMap) { IMPL.setHasMipMap(bitmap, hasMipMap); } /** * Returns the size of the allocated memory used to store this bitmap's pixels in a backwards * compatible way. * * @param bitmap the bitmap in which to return it's allocation size * @return the allocation size in bytes */ public static int getAllocationByteCount(Bitmap bitmap) { return IMPL.getAllocationByteCount(bitmap); } private BitmapCompat() {} }
1,385
409
#ifndef MONITORDATA_H #define MONITORDATA_H /** * MonitorData 类 * 监控数据的容器类 * 类中实现一些基本判断 * 如:是否有cookie,请求的文档类是什么等 * @author Tapir * @date 2012-02-03 */ #include <QObject> #include <QDebug> #include <QString> class MonitorData: public QObject { Q_OBJECT private: public: explicit MonitorData(); // http 数据 int StatusCode; QString ReasonPhrase; bool FromCache; QString ServerIPAddress; QString RequestURL; // 请求大小 qint64 ResponseSize; // 请求实际执行时间 qint64 ResponseDuration; // 请求等待时间 qint64 ResponseWaitingDuration; // 数据下载时间 qint64 ResponseDownloadDuration; // DNS 查找时间 qint64 ResponseDNSLookupDuration; // 请求开始时间 qint64 RequestStartTime; // 请求结束时间 qint64 RequestEndTime; QString ResponseMethod; QString UserAgent; QString Accept; QString AcceptRanges; QString Referer; QString Age; QString AccessControlAllowOrigin; QString CacheControl; QString Connection; QString ContentType; uint ContentLength; QString ContentLanguage; QString ContentEncoding; QString Cookie; QString Date; QString ETag; QString Expires; QString IfModifiedSince; QString Location; QString LastModified; QString Server; QString SetCookie; QString P3P; QString Vary; QString TransferEncoding; QString Via; QString XVia; QString XDEBUGIDC; QString XPoweredBy; QString XCache; QString XCacheLookup; QString XCacheVarnish; QString PoweredByChinaCache; QString SINALB; QMap<QString, QString> other; bool hasKeepAlive(); bool hasGZip(); bool hasCookie(); bool hasCache(); bool hasExpires(); bool isImgFile(); bool isPng(); bool isJpg(); bool isGif(); bool isIco(); bool isSvg(); bool isCssFile(); bool isJsFile(); bool isDocFile(); bool isAudioFile(); bool isVideoFile(); bool isFontFile(); bool isOtherFile(); bool isHttp200(); bool isHttp301(); bool isHttp302(); bool isHttp304(); bool isHttp404(); bool isFromCDN(); }; #endif // MONITORDATA_H
1,022
3,294
<gh_stars>1000+ //<snippet1> // PInvokeLib.cpp : Defines the entry point for the DLL application. // #define PINVOKELIB_EXPORTS #include "PInvokeLib.h" #include <strsafe.h> #include <objbase.h> #include <stdio.h> #pragma comment(lib,"ole32.lib") BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } //****************************************************************** // This is the constructor of a class that has been exported. CTestClass::CTestClass() { m_member = 1; } int CTestClass::DoSomething( int i ) { return i*i + m_member; } PINVOKELIB_API CTestClass* CreateTestClass() { return new CTestClass(); } PINVOKELIB_API void DeleteTestClass( CTestClass* instance ) { delete instance; } //****************************************************************** PINVOKELIB_API int TestArrayOfInts( int* pArray, int size ) { int result = 0; for ( int i = 0; i < size; i++ ) { result += pArray[ i ]; pArray[i] += 100; } return result; } //****************************************************************** PINVOKELIB_API int TestRefArrayOfInts( int** ppArray, int* pSize ) { int result = 0; // CoTaskMemAlloc must be used instead of the new operator // because code on the managed side will call Marshal.FreeCoTaskMem // to free this memory. int* newArray = (int*)CoTaskMemAlloc( sizeof(int) * 5 ); for ( int i = 0; i < *pSize; i++ ) { result += (*ppArray)[i]; } for ( int j = 0; j < 5; j++ ) { newArray[j] = (*ppArray)[j] + 100; } CoTaskMemFree( *ppArray ); *ppArray = newArray; *pSize = 5; return result; } //****************************************************************** PINVOKELIB_API int TestMatrixOfInts( int pMatrix[][COL_DIM], int row ) { int result = 0; for ( int i = 0; i < row; i++ ) { for ( int j = 0; j < COL_DIM; j++ ) { result += pMatrix[i][j]; pMatrix[i][j] += 100; } } return result; } //****************************************************************** PINVOKELIB_API int TestArrayOfStrings( char* ppStrArray[], int count ) { int result = 0; STRSAFE_LPSTR temp; size_t len; const size_t alloc_size = sizeof(char) * 10; for ( int i = 0; i < count; i++ ) { len = 0; StringCchLengthA( ppStrArray[i], STRSAFE_MAX_CCH, &len ); result += len; temp = (STRSAFE_LPSTR)CoTaskMemAlloc( alloc_size ); StringCchCopyA( temp, alloc_size, (STRSAFE_LPCSTR)"123456789" ); // CoTaskMemFree must be used instead of delete to free memory. CoTaskMemFree( ppStrArray[i] ); ppStrArray[i] = (char *) temp; } return result; } //****************************************************************** PINVOKELIB_API int TestArrayOfStructs( MYPOINT* pPointArray, int size ) { int result = 0; MYPOINT* pCur = pPointArray; for ( int i = 0; i < size; i++ ) { result += pCur->x + pCur->y; pCur->y = 0; pCur++; } return result; } //****************************************************************** PINVOKELIB_API int TestStructInStruct( MYPERSON2* pPerson2 ) { size_t len = 0; StringCchLengthA( pPerson2->person->last, STRSAFE_MAX_CCH, &len ); len = sizeof(char) * ( len + 2 ) + 1; STRSAFE_LPSTR temp = (STRSAFE_LPSTR)CoTaskMemAlloc( len ); StringCchCopyA( temp, len, (STRSAFE_LPSTR)"Mc" ); StringCbCatA( temp, len, (STRSAFE_LPSTR)pPerson2->person->last ); CoTaskMemFree( pPerson2->person->last ); pPerson2->person->last = (char *)temp; return pPerson2->age; } //****************************************************************** PINVOKELIB_API int TestArrayOfStructs2( MYPERSON* pPersonArray, int size ) { int result = 0; MYPERSON* pCur = pPersonArray; STRSAFE_LPSTR temp; size_t len; for ( int i = 0; i < size; i++ ) { len = 0; StringCchLengthA( pCur->first, STRSAFE_MAX_CCH, &len ); len++; result += len; len = 0; StringCchLengthA( pCur->last, STRSAFE_MAX_CCH, &len ); len++; result += len; len = sizeof(char) * ( len + 2 ); temp = (STRSAFE_LPSTR)CoTaskMemAlloc( len ); StringCchCopyA( temp, len, (STRSAFE_LPCSTR)"Mc" ); StringCbCatA( temp, len, (STRSAFE_LPCSTR)pCur->last ); result += 2; // CoTaskMemFree must be used instead of delete to free memory. CoTaskMemFree( pCur->last ); pCur->last = (char *)temp; pCur++; } return result; } //****************************************************************** PINVOKELIB_API void TestStructInStruct3( MYPERSON3 person3 ) { printf( "\n\nperson passed by value:\n" ); printf( "first = %s last = %s age = %i\n\n", person3.person.first, person3.person.last, person3.age ); } //********************************************************************* PINVOKELIB_API void TestUnion( MYUNION u, int type ) { if ( ( type != 1 ) && ( type != 2 ) ) { return; } if ( type == 1 ) { printf( "\n\ninteger passed: %i", u.i ); } else if ( type == 2 ) { printf( "\n\ndouble passed: %f", u.d ); } } //****************************************************************** PINVOKELIB_API void TestUnion2( MYUNION2 u, int type ) { if ( ( type != 1 ) && ( type != 2 ) ) { return; } if ( type == 1 ) { printf( "\n\ninteger passed: %i", u.i ); } else if ( type == 2 ) { printf( "\n\nstring passed: %s", u.str ); } } //****************************************************************** PINVOKELIB_API void TestCallBack( FPTR pf, int value ) { printf( "\nReceived value: %i", value ); printf( "\nPassing to callback..." ); bool res = (*pf)(value); if ( res ) { printf( "Callback returned true.\n" ); } else { printf( "Callback returned false.\n" ); } } //****************************************************************** PINVOKELIB_API void TestCallBack2( FPTR2 pf2, char* value ) { printf( "\nReceived value: %s", value ); printf( "\nPassing to callback..." ); bool res = (*pf2)(value); if ( res ) { printf( "Callback2 returned true.\n" ); } else { printf( "Callback2 returned false.\n" ); } } //****************************************************************** PINVOKELIB_API void TestStringInStruct( MYSTRSTRUCT* pStruct ) { wprintf( L"\nUnicode buffer content: %s\n", pStruct->buffer ); // Assuming that the buffer is big enough. StringCbCatW( pStruct->buffer, pStruct->size, (STRSAFE_LPWSTR)L"++" ); } //****************************************************************** PINVOKELIB_API void TestStringInStructAnsi( MYSTRSTRUCT2* pStruct ) { printf( "\nAnsi buffer content: %s\n", pStruct->buffer ); // Assuming that the buffer is big enough. StringCbCatA( (STRSAFE_LPSTR) pStruct->buffer, pStruct->size, (STRSAFE_LPSTR)"++" ); } //****************************************************************** PINVOKELIB_API void TestOutArrayOfStructs( int* pSize, MYSTRSTRUCT2** ppStruct ) { const int cArraySize = 5; *pSize = 0; *ppStruct = (MYSTRSTRUCT2*)CoTaskMemAlloc( cArraySize * sizeof( MYSTRSTRUCT2 )); if ( ppStruct != NULL ) { MYSTRSTRUCT2* pCurStruct = *ppStruct; LPSTR buffer; *pSize = cArraySize; STRSAFE_LPCSTR teststr = "***"; size_t len = 0; StringCchLengthA(teststr, STRSAFE_MAX_CCH, &len); len++; for ( int i = 0; i < cArraySize; i++, pCurStruct++ ) { pCurStruct->size = len; buffer = (LPSTR)CoTaskMemAlloc( len ); StringCchCopyA( buffer, len, teststr ); pCurStruct->buffer = (char *)buffer; } } } //************************************************************************ PINVOKELIB_API char * TestStringAsResult() { const size_t alloc_size = 64; STRSAFE_LPSTR result = (STRSAFE_LPSTR)CoTaskMemAlloc( alloc_size ); STRSAFE_LPCSTR teststr = "This is return value"; StringCchCopyA( result, alloc_size, teststr ); return (char *) result; } //************************************************************************ PINVOKELIB_API void SetData( DataType typ, void* object ) { switch ( typ ) { case DT_I2: printf( "Short %i\n", *((short*)object) ); break; case DT_I4: printf( "Long %i\n", *((long*)object) ); break; case DT_R4: printf( "Float %f\n", *((float*)object) ); break; case DT_R8: printf( "Double %f\n", *((double*)object) ); break; case DT_STR: printf( "String %s\n", (char*)object ); break; default: printf( "Unknown type" ); break; } } //************************************************************************ PINVOKELIB_API void TestArrayInStruct( MYARRAYSTRUCT* pStruct ) { pStruct->flag = true; pStruct->vals[0] += 100; pStruct->vals[1] += 100; pStruct->vals[2] += 100; } //</snippet1>
3,841
3,680
#!/pxrpythonsubst # # Copyright 2020 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # # Remove any unwanted visuals from the view. def _modifySettings(appController): appController._dataModel.viewSettings.showBBoxes = False appController._dataModel.viewSettings.showHUD = False # Set the camera and refresh the view. def _setCamera(appController, path): stage = appController._dataModel.stage prim = stage.GetPrimAtPath(path) appController._stageView.cameraPrim = prim appController._stageView.updateGL() def _testPerspectiveCamera(appController): _setCamera(appController, '/main_cam') appController._takeShot("perspective.png") def _testOrthoCamera(appController): _setCamera(appController, '/OrthoCam') appController._takeShot("ortho.png") def testUsdviewInputFunction(appController): _modifySettings(appController) _testPerspectiveCamera(appController) _testOrthoCamera(appController)
556
375
{ "logo0": "music.bmp", "logo1": "obs.bmp", "logo2": "firefox.bmp", "logo3": "mail.bmp", "logo4": "youtube.bmp", "logo5": "settings.bmp" }
82
854
__________________________________________________________________________________________________ class Solution { public: bool canWin(string s) { for (int i = 1; i < s.size(); ++i) { if (s[i] == '+' && s[i - 1] == '+' && !canWin(s.substr(0, i - 1) + "--" + s.substr(i + 1))) { return true; } } return false; } }; __________________________________________________________________________________________________ class Solution { public: bool canWin(string s) { for (int i = -1; (i = s.find("++", i + 1)) >= 0;) { if (!canWin(s.substr(0, i) + "--" + s.substr(i + 2))) { return true; } } return false; } }; __________________________________________________________________________________________________
332
311
#include <stdio.h> int main() { int num = 1414942034; printf("%02X:%02X:%02X:%02X", ((unsigned char *)(&num))[0],((unsigned char *)(&num))[1], ((unsigned char *)(&num))[2], ((unsigned char *)(&num))[3]); return 0; }
112
545
<filename>src/samples/debug/sio/main.c /* * PSP Software Development Kit - https://github.com/pspdev * ----------------------------------------------------------------------- * Licensed under the BSD license, see LICENSE in PSPSDK root for details. * * main.c - Basic sample to demonstrate the remote port sio. * * Copyright (c) 2005 <NAME> <<EMAIL>> * */ #include <pspkernel.h> #include <pspdebug.h> #include <pspdisplay.h> #include <pspsdk.h> #include <pspctrl.h> #include <stdio.h> #include <string.h> PSP_MODULE_INFO("REMOTE", 0x1000, 1, 1); /* Define the main thread's attribute value (optional) */ PSP_MAIN_THREAD_ATTR(0); int main(void) { pspDebugScreenInit(); sceCtrlSetSamplingCycle(0); sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG); /* Initialise SIO and install a kprintf handler */ pspDebugSioInit(); pspDebugSioInstallKprintf(); /* Install a stdout handler */ pspDebugInstallStdoutHandler(pspDebugSioPutData); Kprintf("Hi from %s!\n", "Kprintf"); printf("Also hi from stdio\r\n"); pspDebugScreenPrintf("Press X to exit, tap away on your terminal to echo\n"); sceDisplayWaitVblankStart(); while(1) { SceCtrlData pad; int ch; sceCtrlReadBufferPositive(&pad, 1); if(pad.Buttons & PSP_CTRL_CROSS) { break; } ch = pspDebugSioGetchar(); if(ch >= 0) { pspDebugScreenPrintf("Received %d\n", ch); if(ch == '\r') { pspDebugSioPutchar('\r'); pspDebugSioPutchar('\n'); } else { pspDebugSioPutchar(ch); } } sceDisplayWaitVblankStart(); } sceKernelExitGame(); return 0; }
633
312
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ [ { "namespace": "contentScripts", "types": [ { "id": "RegisteredContentScriptOptions", "type": "object", "description": "Details of a content script registered programmatically", "properties": { "matches": { "type": "array", "optional": false, "minItems": 1, "items": { "$ref": "manifest.MatchPattern" } }, "excludeMatches": { "type": "array", "optional": true, "minItems": 1, "items": { "$ref": "manifest.MatchPattern" } }, "includeGlobs": { "type": "array", "optional": true, "items": { "type": "string" } }, "excludeGlobs": { "type": "array", "optional": true, "items": { "type": "string" } }, "css": { "type": "array", "optional": true, "description": "The list of CSS files to inject", "items": { "$ref": "extensionTypes.ExtensionFileOrCode" } }, "js": { "type": "array", "optional": true, "description": "The list of JS files to inject", "items": { "$ref": "extensionTypes.ExtensionFileOrCode" } }, "allFrames": {"type": "boolean", "optional": true, "description": "If allFrames is <code>true</code>, implies that the JavaScript or CSS should be injected into all frames of current page. By default, it's <code>false</code> and is only injected into the top frame."}, "matchAboutBlank": {"type": "boolean", "optional": true, "description": "If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is <code>false</code>."}, "runAt": { "$ref": "extensionTypes.RunAt", "optional": true, "description": "The soonest that the JavaScript or CSS will be injected into the tab. Defaults to \"document_idle\"." } } }, { "id": "RegisteredContentScript", "type": "object", "description": "An object that represents a content script registered programmatically", "functions": [ { "name": "unregister", "type": "function", "description": "Unregister a content script registered programmatically", "async": true, "parameters": [] } ] } ], "functions": [ { "name": "register", "type": "function", "description": "Register a content script programmatically", "async": true, "parameters": [ { "name": "contentScriptOptions", "$ref": "RegisteredContentScriptOptions" } ] } ] } ]
1,459
3,680
<filename>pxr/usd/usdMedia/testenv/testUsdMediaSpatialAudio.py #!/pxrpythonsubst # # Copyright 2019 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. from pxr import Sdf, Usd, UsdMedia import unittest, math class TestUsdMediaSpatialAudio(unittest.TestCase): def test_TimeAttrs(self): # Create layer and stage with a SpatialAudio prim that we will reference refLayer = Sdf.Layer.CreateAnonymous() refStage = Usd.Stage.Open(refLayer) refAudio = UsdMedia.SpatialAudio.Define(refStage, '/RefAudio') # Create a new and SpatialAudio prim that references the above prim. # The reference has a layer offset of scale=2.0, offset=10.0 stage = Usd.Stage.CreateInMemory() audio = UsdMedia.SpatialAudio.Define(stage, '/Audio') refs = audio.GetPrim().GetReferences() refs.AddReference(refLayer.identifier, Sdf.Path("/RefAudio"), layerOffset=Sdf.LayerOffset(scale=2.0, offset=10.0)) self.assertEqual(refAudio.GetStartTimeAttr().Get(), Sdf.TimeCode(0)) self.assertEqual(refAudio.GetEndTimeAttr().Get(), Sdf.TimeCode(0)) self.assertEqual(refAudio.GetMediaOffsetAttr().Get(), 0.0) self.assertEqual(audio.GetStartTimeAttr().Get(), Sdf.TimeCode(0)) self.assertEqual(audio.GetEndTimeAttr().Get(), Sdf.TimeCode(0)) self.assertEqual(audio.GetMediaOffsetAttr().Get(), 0) refAudio.CreateStartTimeAttr().Set(Sdf.TimeCode(10.0)) refAudio.CreateEndTimeAttr().Set(Sdf.TimeCode(200.0)) refAudio.CreateMediaOffsetAttr().Set(5.0) self.assertEqual(refAudio.GetStartTimeAttr().Get(), Sdf.TimeCode(10)) self.assertEqual(refAudio.GetEndTimeAttr().Get(), Sdf.TimeCode(200)) self.assertEqual(refAudio.GetMediaOffsetAttr().Get(), 5.0) self.assertEqual(audio.GetStartTimeAttr().Get(), Sdf.TimeCode(30)) self.assertEqual(audio.GetEndTimeAttr().Get(), Sdf.TimeCode(410)) self.assertEqual(audio.GetMediaOffsetAttr().Get(), 5.0) if __name__ == '__main__': unittest.main()
1,115
407
<filename>paas/appmanager/tesla-appmanager-domain/src/main/java/com/alibaba/tesla/appmanager/domain/core/CustomWorkloadResource.java package com.alibaba.tesla.appmanager.domain.core; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.alibaba.tesla.appmanager.domain.schema.CustomAddonWorkloadSpec; import lombok.Data; /** * @ClassName: CustomWorkloadResource * @Author: dyj * @DATE: 2020-12-23 * @Description: **/ @Data public class CustomWorkloadResource implements Serializable { private static final long serialVersionUID = 7881942127685889587L; /** * API 版本号 */ private String apiVersion; /** * 类型 */ private String kind; /** * 元信息 */ private WorkloadResource.MetaData metadata; /** * 定义描述文件 */ private CustomAddonWorkloadSpec spec; /** * 数据输出列表 */ private List<WorkloadResource.DataOutput> dataOutputs = new ArrayList<>(); }
406
1,537
<gh_stars>1000+ # Copyright (c) 2016, Xilinx, 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: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pytest from pynq import Overlay from pynq.lib.pmod import Pmod_OLED from pynq.lib.pmod import PMODA from pynq.lib.pmod import PMODB from pynq.tests.util import user_answer_yes from pynq.tests.util import get_interface_id __author__ = "<NAME>, <NAME>" __copyright__ = "Copyright 2016, Xilinx" __email__ = "<EMAIL>" try: _ = Overlay('base.bit', download=False) flag0 = True except IOError: flag0 = False flag1 = user_answer_yes("\nPmod OLED attached to the board?") if flag1: oled_id = eval(get_interface_id('Pmod OLED', options=['PMODA', 'PMODB'])) flag = flag0 and flag1 @pytest.mark.skipif(not flag, reason="need OLED attached to the base overlay") def test_write_string(): """Test for the OLED Pmod. Writes on the OLED the string 'Welcome to PYNQ.' and asks the user to confirm if it is shown on the OLED. After that, it clears the screen. This test can be skipped. """ Overlay('base.bit').download() oled = Pmod_OLED(oled_id) oled.draw_line(0, 0, 255, 0) oled.draw_line(0, 2, 255, 2) oled.write('Welcome to PYNQ.', 0, 1) oled.draw_line(0, 20, 255, 20) oled.draw_line(0, 22, 255, 22) assert user_answer_yes("\nWelcome message shown on the OLED?") oled.clear() assert user_answer_yes("OLED screen clear now?") del oled
1,063
1,775
/** * CodeBaseTest简单描述Java SecurityManager的使用 * * AttackTest尝试以多种方式去对Java SecurityManager进行绕过,越权执行操作 * * * @author xuanyh */ package com.threedr3am.bug.security.manager;
105
368
package org.nem.core.model.observers; import org.hamcrest.MatcherAssert; import org.hamcrest.core.IsEqual; import org.junit.*; import org.nem.core.model.*; import org.nem.core.test.Utils; public class MultisigMinCosignatoriesModificationNotificationTest { @Test public void canCreateNotification() { // Act: final Account multisig = Utils.generateRandomAccount(); final MultisigMinCosignatoriesModification modification = new MultisigMinCosignatoriesModification(3); final MultisigMinCosignatoriesModificationNotification notification = new MultisigMinCosignatoriesModificationNotification(multisig, modification); // Assert: MatcherAssert.assertThat(notification.getType(), IsEqual.equalTo(NotificationType.MinCosignatoriesModification)); MatcherAssert.assertThat(notification.getMultisigAccount(), IsEqual.equalTo(multisig)); MatcherAssert.assertThat(notification.getModification(), IsEqual.equalTo(modification)); } }
301
348
<gh_stars>100-1000 {"nom":"Gouaux-de-Larboust","circ":"8ème circonscription","dpt":"Haute-Garonne","inscrits":90,"abs":24,"votants":66,"blancs":3,"nuls":1,"exp":62,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":33},{"nuance":"SOC","nom":"<NAME>","voix":29}]}
110
309
<gh_stars>100-1000 #include <vtkSmartPointer.h> #include <vtkSurfaceReconstructionFilter.h> #include <cmath> #include <vtkCamera.h> #include <vtkContourFilter.h> #include <vtkMath.h> #include <vtkNamedColors.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProgrammableSource.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkReverseSense.h> #include <vtkTransform.h> #include <vtkTransformPolyDataFilter.h> #include <vtkSphereSource.h> #include <vtkXMLPolyDataReader.h> namespace { static vtkSmartPointer<vtkPolyData> transform_back(vtkSmartPointer<vtkPoints> pt, vtkSmartPointer<vtkPolyData> pd); } int main(int argc, char* argv[]) { auto namedColors = vtkSmartPointer<vtkNamedColors>::New(); vtkSmartPointer<vtkPolyData> input; if (argc > 1) { auto reader = vtkSmartPointer<vtkXMLPolyDataReader>::New(); reader->SetFileName(argv[1]); reader->Update(); input = reader->GetOutput(); } else { auto sphereSource = vtkSmartPointer<vtkSphereSource>::New(); sphereSource->Update(); input = sphereSource->GetOutput(); } // Read some points //auto points = vtkSmartPointer<vtkPoints>::New(); auto polydata = vtkSmartPointer<vtkPolyData>::New(); polydata->SetPoints(input->GetPoints()); // Construct the surface and create isosurface. auto surf = vtkSmartPointer<vtkSurfaceReconstructionFilter>::New(); surf->SetInputData(polydata); auto contourFilter = vtkSmartPointer<vtkContourFilter>::New(); contourFilter->SetInputConnection(surf->GetOutputPort()); contourFilter->SetValue(0, 0.0); // Sometimes the contouring algorithm can create a volume whose gradient // vector and ordering of polygon (using the right hand rule) are // inconsistent. vtkReverseSense cures this problem. auto reverse = vtkSmartPointer<vtkReverseSense>::New(); reverse->SetInputConnection(contourFilter->GetOutputPort()); reverse->ReverseCellsOn(); reverse->ReverseNormalsOn(); reverse->Update(); //auto newSurf = transform_back(points, reverse->GetOutput()); auto map = vtkSmartPointer<vtkPolyDataMapper>::New(); map->SetInputConnection(reverse->GetOutputPort()); map->ScalarVisibilityOff(); auto surfaceActor = vtkSmartPointer<vtkActor>::New(); surfaceActor->SetMapper(map); surfaceActor->GetProperty()->SetDiffuseColor( namedColors->GetColor3d("Tomato").GetData()); surfaceActor->GetProperty()->SetSpecularColor( namedColors->GetColor3d("Seashell").GetData()); surfaceActor->GetProperty()->SetSpecular(.4); surfaceActor->GetProperty()->SetSpecularPower(50); // Create the RenderWindow, Renderer and both Actors auto renderer = vtkSmartPointer<vtkRenderer>::New(); auto renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); auto interactor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); interactor->SetRenderWindow(renderWindow); // Add the actors to the renderer, set the background and size renderer->AddActor(surfaceActor); renderer->SetBackground(namedColors->GetColor3d("Burlywood").GetData()); renderWindow->SetSize(640, 480); interactor->Initialize(); renderWindow->Render(); interactor->Start(); return EXIT_SUCCESS; } namespace { vtkSmartPointer<vtkPolyData> transform_back(vtkSmartPointer<vtkPoints> pt, vtkSmartPointer<vtkPolyData> pd) { // The reconstructed surface is transformed back to where the // original points are. (Hopefully) it is only a similarity // transformation. // 1. Get bounding box of pt, get its minimum corner (left, bottom, least-z), // at c0, pt_bounds // 2. Get bounding box of surface pd, get its minimum corner (left, bottom, // least-z), at c1, pd_bounds // 3. compute scale as: // scale = (pt_bounds[1] - pt_bounds[0])/(pd_bounds[1] - pd_bounds[0]); // 4. transform the surface by T := T(pt_bounds[0], [2], // [4]).S(scale).T(-pd_bounds[0], -[2], -[4]) // 1. double pt_bounds[6]; // (xmin,xmax, ymin,ymax, zmin,zmax) pt->GetBounds(pt_bounds); // 2. double pd_bounds[6]; // (xmin,xmax, ymin,ymax, zmin,zmax) pd->GetBounds(pd_bounds); // // test, make sure it is isotropic // std::cout<<(pt_bounds[1] - pt_bounds[0])/(pd_bounds[1] - // pd_bounds[0])<<std::endl; std::cout<<(pt_bounds[3] - // pt_bounds[2])/(pd_bounds[3] - pd_bounds[2])<<std::endl; // std::cout<<(pt_bounds[5] - pt_bounds[4])/(pd_bounds[5] - // pd_bounds[4])<<std::endl; // // TEST // 3 double scale = (pt_bounds[1] - pt_bounds[0]) / (pd_bounds[1] - pd_bounds[0]); // 4. auto transp = vtkSmartPointer<vtkTransform>::New(); transp->Translate(pt_bounds[0], pt_bounds[2], pt_bounds[4]); transp->Scale(scale, scale, scale); transp->Translate(-pd_bounds[0], -pd_bounds[2], -pd_bounds[4]); auto tpd = vtkSmartPointer<vtkTransformPolyDataFilter>::New(); tpd->SetInputData(pd); tpd->SetTransform(transp); tpd->Update(); return tpd->GetOutput(); } } // namespace
1,915
660
/* * Copyright (c) 2020, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ //! //! \file render_copy.h //! \brief header file of render copy base functions //! \details define render copy basic API //! #ifndef __MEDIA_RENDER_COPY_H__ #define __MEDIA_RENDER_COPY_H__ #include "media_copy.h" #include "vphal_render_common.h" const VphalSseuSetting VpDefaultSSEUTable[baseKernelMaxNumID] = { // Slice Sub-Slice EU Rsvd(freq) {2, 3, 8, 0}, }; class RenderCopyState { public: RenderCopyState(PMOS_INTERFACE osInterface, MhwInterfaces *mhwInterfaces); virtual ~RenderCopyState(); //! //! \brief RenderCopyState initialize //! \details Initialize the RenderCopyState, create BLT context. //! \return MOS_STATUS //! Return MOS_STATUS_SUCCESS if successful, otherwise failed //! virtual MOS_STATUS Initialize(); protected: //! //! \brief Submit command //! \details Submit render command //! \return MOS_STATUS //! Return MOS_STATUS_SUCCESS if successful, otherwise failed //! virtual MOS_STATUS SubmitCMD( ); public: PMOS_INTERFACE m_osInterface = nullptr; MhwInterfaces *m_mhwInterfaces = nullptr; MhwRenderInterface *m_renderInterface = nullptr; RENDERHAL_INTERFACE *m_renderHal = nullptr; MhwCpInterface *m_cpInterface = nullptr; }; #endif // __MEDIA_RENDER_COPY_H__
952
1,587
<gh_stars>1000+ package io.pratik.springcloudrds; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SpringcloudrdsApplicationTests { @Autowired private SystemRepository systemRepository; @Test void testCurrentDate() { String currentDate = systemRepository.getCurrentDate(); System.out.println("currentDate "+currentDate); } }
154
1,209
<reponame>JJPowelly/u8glib<gh_stars>1000+ /* Fontname: -Adobe-Symbol-Medium-R-Normal--17-120-100-100-P-95-Adobe-FontSpecific Copyright: Copyright (c) 1984, 1987 Adobe Systems Incorporated. All Rights Reserved. Copyright (c) 1988, 1991 Digital Equipment Corporation. All Rights Reserved. Capital A Height: 11, '1' Height: 12 Calculated Max Values w=13 h=17 x= 7 y=12 dx=14 dy= 0 ascent=13 len=26 Font Bounding box w=20 h=17 x=-3 y=-4 Calculated Min Values x=-1 y=-4 dx= 0 dy= 0 Pure Font ascent =11 descent=-4 X Font ascent =12 descent=-4 Max Font ascent =13 descent=-4 */ #include "u8g.h" const u8g_fntpgm_uint8_t u8g_font_symb12r[1985] U8G_FONT_SECTION("u8g_font_symb12r") = { 0,20,17,253,252,11,2,70,5,85,32,127,252,13,252,12, 252,0,0,0,4,0,1,3,11,11,5,1,0,64,224,224, 224,64,64,64,0,64,224,64,11,12,24,11,0,0,128,32, 128,32,64,64,64,64,63,128,32,128,17,0,17,0,10,0, 10,0,4,0,4,0,8,11,11,8,0,0,18,18,18,127, 36,36,36,254,72,72,72,7,12,12,9,0,0,254,2,2, 2,2,126,2,2,2,2,2,254,11,12,24,13,1,255,48, 64,111,128,201,0,201,0,154,0,148,192,101,160,11,32,11, 32,18,96,34,64,33,128,12,11,22,13,0,0,14,0,25, 0,17,0,26,0,12,240,56,64,76,128,198,128,131,0,197, 144,120,224,5,8,8,7,1,0,224,16,24,120,24,24,16, 224,4,14,14,5,0,254,16,32,64,64,128,128,128,128,128, 128,64,64,32,16,4,14,14,5,0,254,128,64,32,32,16, 16,16,16,16,16,32,32,64,128,5,5,5,8,1,3,32, 168,112,168,32,9,9,18,9,0,0,8,0,8,0,8,0, 8,0,255,128,8,0,8,0,8,0,8,0,3,5,5,4, 1,254,64,224,96,64,128,9,1,2,9,0,4,255,128,3, 3,3,4,1,0,64,224,64,5,11,11,5,255,0,8,8, 16,16,32,32,32,64,64,128,128,7,12,12,8,0,0,56, 108,68,198,130,130,130,130,198,68,108,56,5,12,12,8,1, 0,32,96,160,32,32,32,32,32,32,32,32,248,7,12,12, 8,0,0,56,76,134,2,2,4,4,8,16,34,126,252,6, 12,12,8,1,0,56,76,132,4,8,56,12,4,4,4,200, 112,7,12,12,8,0,0,4,4,12,20,20,36,68,68,254, 4,4,4,7,12,12,8,0,0,62,60,64,64,240,248,12, 4,4,4,200,240,6,12,12,8,1,0,12,48,96,64,248, 204,132,132,132,132,76,56,6,12,12,8,1,0,252,252,136, 8,8,16,16,16,16,32,32,32,6,12,12,8,1,0,48, 72,132,196,104,48,88,140,132,132,72,48,6,12,12,8,1, 0,112,200,132,132,132,132,204,124,8,24,48,192,3,8,8, 4,1,0,64,224,64,0,0,64,224,64,3,10,10,4,1, 254,64,224,64,0,0,64,224,96,64,128,8,9,9,9,0, 0,1,6,24,96,128,96,24,6,1,9,4,8,9,0,2, 255,128,0,0,0,0,255,128,8,9,9,9,0,0,128,96, 24,6,1,6,24,96,128,6,11,11,7,0,0,120,156,140, 12,24,16,32,0,32,112,32,8,8,8,9,0,0,113,142, 0,0,255,0,0,255,11,11,22,12,0,0,4,0,4,0, 14,0,14,0,19,0,19,0,33,128,63,128,65,192,64,192, 225,224,9,11,22,11,1,0,254,0,99,0,97,128,97,128, 99,0,126,0,99,0,97,128,97,128,99,0,254,0,10,11, 22,12,0,0,241,192,96,128,49,0,26,0,26,0,12,0, 22,0,19,0,35,0,65,128,227,192,10,11,22,10,0,0, 4,0,4,0,14,0,14,0,19,0,19,0,35,0,33,128, 65,128,64,192,255,192,8,11,11,10,1,0,255,97,96,96, 98,126,98,96,96,97,255,12,11,22,12,0,0,15,0,6, 0,63,192,102,96,198,48,198,48,198,48,102,96,63,192,6, 0,15,0,9,11,22,10,1,0,255,128,97,128,96,0,96, 0,96,0,96,0,96,0,96,0,96,0,96,0,240,0,11, 11,22,12,0,0,241,224,96,192,96,192,96,192,96,192,127, 192,96,192,96,192,96,192,96,192,241,224,4,11,11,6,1, 0,240,96,96,96,96,96,96,96,96,96,240,9,12,24,10, 0,0,12,0,18,0,17,0,9,0,69,0,163,0,33,128, 33,0,33,0,33,0,34,0,28,0,10,11,22,12,1,0, 243,192,97,0,98,0,100,0,104,0,120,0,108,0,102,0, 99,0,97,128,243,192,11,11,22,11,0,0,4,0,4,0, 14,0,14,0,19,0,19,0,33,128,33,128,64,192,64,192, 225,224,13,11,22,14,1,0,224,56,96,112,112,112,112,176, 88,176,89,48,77,48,78,48,70,48,68,48,224,120,10,11, 22,11,1,0,225,192,112,128,112,128,88,128,92,128,78,128, 70,128,67,128,67,128,65,128,224,128,11,11,22,12,0,0, 31,0,113,192,96,192,192,96,192,96,192,96,192,96,192,96, 96,192,113,192,31,0,11,11,22,12,1,0,255,224,96,192, 96,192,96,192,96,192,96,192,96,192,96,192,96,192,96,192, 241,224,11,11,22,12,0,0,31,0,113,192,96,192,192,96, 209,96,223,96,209,96,192,96,96,192,113,192,31,0,8,11, 11,9,1,0,252,102,99,99,102,124,96,96,96,96,240,9, 11,22,10,0,0,255,128,96,128,48,0,24,0,12,0,12, 0,8,0,16,128,32,128,127,128,255,128,10,11,22,10,0, 0,255,192,140,64,140,64,12,0,12,0,12,0,12,0,12, 0,12,0,12,0,30,0,10,11,22,11,1,0,241,192,96, 128,49,0,49,0,26,0,12,0,12,0,12,0,12,0,12, 0,30,0,7,12,12,8,0,252,60,76,128,128,128,128,124, 62,2,2,60,56,12,12,24,12,0,0,31,128,112,224,96, 96,192,48,192,48,192,48,192,48,96,96,48,192,137,16,249, 240,249,240,9,11,22,11,0,0,255,128,255,128,128,128,0, 0,34,0,62,0,34,0,0,0,128,128,255,128,255,128,12, 11,22,13,0,0,207,48,102,96,102,96,102,96,102,96,63, 192,6,0,6,0,6,0,6,0,15,0,8,11,11,10,1, 0,255,131,134,12,12,24,48,48,97,193,255,3,14,14,6, 1,254,224,128,128,128,128,128,128,128,128,128,128,128,128,224, 9,8,16,14,2,0,8,0,28,0,8,0,0,0,0,0, 65,0,227,128,65,0,3,14,14,5,0,254,224,32,32,32, 32,32,32,32,32,32,32,32,32,224,9,11,22,11,1,0, 8,0,8,0,8,0,8,0,8,0,8,0,8,0,8,0, 8,0,8,0,255,128,8,1,1,8,0,253,255,10,1,2, 8,7,12,255,192,10,9,18,11,0,0,57,128,101,128,195, 0,195,0,195,0,194,0,198,64,101,64,56,128,8,17,17, 9,0,252,60,70,66,66,70,92,70,67,67,65,65,99,94, 64,64,64,192,8,12,12,9,0,253,99,162,150,20,28,24, 24,56,40,105,69,198,7,12,12,8,0,0,120,140,64,48, 24,44,70,194,130,194,68,56,7,9,9,7,0,0,56,68, 192,192,120,192,192,66,60,7,14,14,9,1,253,16,16,56, 84,214,146,146,146,214,84,56,16,16,16,8,13,13,7,255, 252,97,161,146,18,20,20,8,8,16,16,48,48,48,9,12, 24,10,0,253,110,0,177,0,33,0,33,0,33,0,33,0, 33,0,33,0,33,0,1,0,1,0,1,128,6,9,9,5, 255,0,32,96,160,32,32,32,32,52,24,9,12,24,10,0, 253,39,0,73,128,201,128,136,128,136,128,136,128,201,128,73, 0,62,0,8,0,8,0,8,0,8,9,9,9,0,0,70, 206,80,80,120,76,76,70,79,9,13,26,9,0,0,96,0, 208,0,144,0,16,0,8,0,24,0,24,0,56,0,40,0, 36,0,100,128,68,128,195,0,8,13,13,9,1,252,132,132, 132,132,132,132,132,205,182,128,128,128,128,9,9,18,8,255, 0,225,128,33,128,49,0,51,0,18,0,26,0,12,0,12, 0,8,0,7,9,9,9,1,0,56,68,198,130,130,130,198, 68,56,8,9,9,9,0,0,127,255,164,36,36,36,37,103, 102,7,12,12,9,1,0,56,108,68,198,130,254,130,130,198, 68,108,56,7,13,13,9,1,252,56,76,134,134,130,130,198, 196,184,128,128,128,128,9,9,18,10,1,0,31,128,116,0, 194,0,195,0,129,0,193,0,65,0,99,0,30,0,7,9, 9,7,0,0,60,124,144,16,16,16,18,30,12,8,9,9, 9,1,0,68,226,161,33,33,33,33,50,28,10,10,20,11, 0,0,127,192,155,0,32,128,100,192,68,64,68,64,68,64, 68,64,100,192,59,128,9,9,18,11,1,0,54,0,65,0, 201,128,136,128,136,128,136,128,136,128,201,128,119,0,7,17, 17,8,0,252,64,88,48,64,92,60,64,128,128,128,128,124, 62,2,2,60,56,11,13,26,11,0,252,196,96,100,192,36, 128,36,128,36,128,36,128,36,128,53,128,31,0,4,0,4, 0,4,0,4,0,7,17,17,8,1,252,32,76,60,32,64, 64,128,128,128,128,128,124,62,2,2,60,56,5,14,14,8, 1,254,24,32,32,32,32,32,192,32,32,32,32,32,32,24, 1,14,14,3,1,253,128,128,128,128,128,128,128,128,128,128, 128,128,128,128,5,14,14,8,1,254,192,32,32,32,32,32, 24,32,32,32,32,32,32,192,8,2,2,9,0,3,113,142, 255};
4,511
1,405
package tms; import android.os.RemoteException; import com.tencent.tmsecure.module.permission.IDummyService; import com.tencent.tmsecure.module.permission.PermissionTableItem; import tms.es; /* access modifiers changed from: package-private */ public final class du implements es.a { final /* synthetic */ int a; final /* synthetic */ int b; final /* synthetic */ int c; final /* synthetic */ es d; du(es esVar, int i, int i2, int i3) { this.d = esVar; this.a = i; this.b = i2; this.c = i3; } @Override // tms.es.a public final void a() throws RemoteException { PermissionTableItem itemByUid = this.d.g.getItemByUid(this.a); if (itemByUid != null) { itemByUid.mRids[this.b] = this.c; } } @Override // tms.es.a public final void a(IDummyService iDummyService) throws RemoteException { iDummyService.updatePermissionTable(this.a, this.b, this.c); } @Override // tms.es.a public final void b() throws RemoteException { this.d.g.update(this.a, this.b, this.c); } }
464
2,151
// 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 THIRD_PARTY_BLINK_RENDERER_MODULES_PAYMENTS_PAYMENT_APP_SERVICE_WORKER_GLOBAL_SCOPE_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_PAYMENTS_PAYMENT_APP_SERVICE_WORKER_GLOBAL_SCOPE_H_ #include "third_party/blink/renderer/core/dom/events/event_target.h" #include "third_party/blink/renderer/platform/wtf/allocator.h" namespace blink { class PaymentAppServiceWorkerGlobalScope { STATIC_ONLY(PaymentAppServiceWorkerGlobalScope); public: DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(abortpayment); DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(canmakepayment); DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(paymentrequest); }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PAYMENTS_PAYMENT_APP_SERVICE_WORKER_GLOBAL_SCOPE_H_
353
332
// Autogenerated from vk-api-schema. Please don't edit it manually. package com.vk.api.sdk.objects.groups; import com.google.gson.annotations.SerializedName; import com.vk.api.sdk.queries.EnumParam; /** * Type of online status of group */ public enum OnlineStatusType implements EnumParam { @SerializedName("none") NONE("none"), @SerializedName("online") ONLINE("online"), @SerializedName("answer_mark") ANSWER_MARK("answer_mark"); private final String value; OnlineStatusType(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return value.toLowerCase(); } }
270
1,253
<reponame>oliviertassinari/validator /* * Copyright (c) 2008 Mozilla Foundation * * 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 nu.validator.servlet.imagereview; import org.xml.sax.Locator; public class Image implements Locator { private final String src; private final String alt; private final String lang; private final boolean rtl; private final int width; private final int height; private final boolean linked; private final String systemId; private final String publicId; private final int column; private final int line; /** * @param src * @param alt * @param width * @param height * @param locator */ public Image(String src, String alt, String lang, boolean rtl, int width, int height, boolean linked, Locator locator) { this.src = src; this.alt = alt; this.lang = lang; this.rtl = rtl; this.width = width; this.height = height; this.linked = linked; this.systemId = locator.getSystemId(); this.publicId = locator.getPublicId(); this.column = locator.getColumnNumber(); this.line = locator.getLineNumber(); } /** * Returns the src. * * @return the src */ public String getSrc() { return src; } /** * Returns the alt. * * @return the alt */ public String getAlt() { return alt; } /** * Returns the width. * * @return the width */ public int getWidth() { return width; } /** * Returns the height. * * @return the height */ public int getHeight() { return height; } /** * Returns the lang. * * @return the lang */ public String getLang() { return lang; } /** * Returns the linked. * * @return the linked */ public boolean isLinked() { return linked; } @Override public int getColumnNumber() { return column; } @Override public int getLineNumber() { return line; } @Override public String getPublicId() { return publicId; } @Override public String getSystemId() { return systemId; } /** * Returns the rtl. * * @return the rtl */ public boolean isRtl() { return rtl; } }
1,337
1,073
// RUN: %clang -### -working-directory /no/such/dir/ input 2>&1 | FileCheck %s //CHECK: no such file or directory: '/no/such/dir/input'
50
9,516
import torch import torch.nn as nn import torch.nn.functional as F class MLP(nn.Module): def __init__( self, in_feats, n_classes, n_layers, n_hidden, activation, dropout=0.0, input_drop=0.0, residual=False, ): super().__init__() self.n_layers = n_layers self.n_hidden = n_hidden self.n_classes = n_classes self.linears = nn.ModuleList() self.norms = nn.ModuleList() for i in range(n_layers): in_hidden = n_hidden if i > 0 else in_feats out_hidden = n_hidden if i < n_layers - 1 else n_classes self.linears.append(nn.Linear(in_hidden, out_hidden)) if i < n_layers - 1: self.norms.append(nn.BatchNorm1d(out_hidden)) self.activation = activation self.input_drop = nn.Dropout(input_drop) self.dropout = nn.Dropout(dropout) self.residual = residual def forward(self, h): h = self.input_drop(h) h_last = None for i in range(self.n_layers): h = self.linears[i](h) if self.residual and 0 < i < self.n_layers - 1: h += h_last h_last = h if i < self.n_layers - 1: h = self.norms[i](h) h = self.activation(h, inplace=True) h = self.dropout(h) return h
709
361
<filename>tern/formats/spdx/spdxtagvalue/file_helpers.py # -*- coding: utf-8 -*- # # Copyright (c) 2020 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2-Clause """ File level helpers for SPDX tag-value document generator """ from tern.formats.spdx import spdx_common def get_file_comment(filedata): '''Return a formatted comment string with all file level notices. Return an empty string if no notices are present''' comment = '' for origin in filedata.origins.origins: comment = comment + '{}:'.format(origin.origin_str) + '\n' for notice in origin.notices: comment = comment + \ '{}: {}'.format(notice.level, notice.message) + '\n' return comment # formatting functions def get_license_info_block(filedata): '''The SPDX spec asks to list of SPDX license identifiers or license reference IDs using the format: LicenseInfoInFile: <license ref>. In this case, we do not know if we are collecting SPDX license identifiers or license strings or something else. So we will create license refs here. If the licenses list is empty we will report NONE''' block = '' if not filedata.licenses: block = 'LicenseInfoInFile: NONE\n' else: for lic in spdx_common.get_file_licenses(filedata): block = block + 'LicenseInfoInFile: {}'.format( spdx_common.get_license_ref(lic)) + '\n' return block def get_file_contributor_block(filedata): '''The SPDX spec allows for an optional block listing file contributors. If there are any authors found in the file, return a formatted SPDX text block with the list of authors. If empty, return an empty string''' block = '' for author in filedata.authors: block = block + 'FileContributor: {}'.format(author) + '\n' return block # full file block def get_file_block(filedata, template, layer_id): '''Given a FileData object, and the SPDX template mapping, return a SPDX document block for the file. The mapping should have only FileName and FileType keys. A layer id is used to distinguish copies of the same file occuring in different places in the image''' block = '' mapping = filedata.to_dict(template) # File Name block = block + 'FileName: {}'.format(mapping['FileName']) + '\n' # SPDX ID block = block + 'SPDXID: {}'.format( spdx_common.get_file_spdxref(filedata, layer_id)) + '\n' # File Type block = block + 'FileType: {}'.format(mapping['FileType']) + '\n' # File checksum block = block + 'FileChecksum: {}'.format( spdx_common.get_file_checksum(filedata)) + '\n' # Concluded license - we won't provide this block = block + 'LicenseConcluded: NOASSERTION' + '\n' # License info in file block = block + get_license_info_block(filedata) # File copyright text - we don't know this block = block + 'FileCopyrightText: NOASSERTION' + '\n' # File comment - we add this only if there is a comment comment = spdx_common.get_file_comment(filedata) if comment: block = block + 'FileComment: <text>\n' + comment + '</text>' + '\n' # File Notice - we add this only if there is a notice notice = spdx_common.get_file_notice(filedata) if notice: block = block + 'FileNotice: <text>\n' + notice + '</text>' + '\n' # File Contributor - we add this only if there are contributors contributors = get_file_contributor_block(filedata) if contributors: block = block + contributors return block
1,291
343
#include "stdafx.h" RH_C_SHARED_ENUM_PARSE_FILE("../../../opennurbs/opennurbs_text.h") //-------------------------------------------------------- // ON_Text //-------------------------------------------------------- RH_C_FUNCTION ON::AnnotationType ON_V6_Annotation_AnnotationType(const ON_Annotation* annotationptr) { if (annotationptr) return annotationptr->Type(); return ON::AnnotationType::Unset; } RH_C_FUNCTION void ON_V6_Annotation_GetPlane(const ON_Annotation* constPtrAnnotation, ON_PLANE_STRUCT* plane) { if (constPtrAnnotation && plane) { ON_Plane pl = constPtrAnnotation->Plane(); CopyToPlaneStruct(*plane, pl); } } RH_C_FUNCTION void ON_V6_Annotation_SetPlane(ON_Annotation* ptrAnnotation, ON_PLANE_STRUCT plane) { if (ptrAnnotation) { ON_Plane pl = FromPlaneStruct(plane); ptrAnnotation->SetPlane(pl); } } RH_C_FUNCTION ON_UUID ON_V6_Annotation_GetDimstyleId(const ON_Annotation* constPtrAnnotation) { if (constPtrAnnotation) return constPtrAnnotation->DimensionStyleId(); return ON_nil_uuid; } RH_C_FUNCTION void ON_V6_Annotation_SetDimstyleId(ON_Annotation* ptrAnnotation, ON_UUID id) { if (ptrAnnotation) ptrAnnotation->SetDimensionStyleId(id); } RH_C_FUNCTION const ON_DimStyle* ON_Annotation_DimensionStyle(const ON_Annotation* constAnnotation, const ON_DimStyle* constParentDimStyle) { if (constAnnotation) { const ON_DimStyle& parent = ON_DimStyle::DimStyleOrDefault(constParentDimStyle); const ON_DimStyle& ds = constAnnotation->DimensionStyle(parent); return &ds; } return nullptr; } RH_C_FUNCTION ON_DimStyle* ON_V6_Annotation_DimensionStyle(const ON_Annotation* constAnnotation, const ON_DimStyle* constParentDimStyle) { if (constAnnotation) { const ON_DimStyle& parent = ON_DimStyle::DimStyleOrDefault(constParentDimStyle); const ON_DimStyle& ds = constAnnotation->DimensionStyle(parent); return new ON_DimStyle(ds); } return nullptr; } RH_C_FUNCTION bool ON_V6_Annotation_SetOverrideDimstyle(ON_Annotation* ptrAnnotation, const ON_DimStyle* ptrDimStyle) { if (ptrAnnotation && ptrDimStyle) { ON_DimStyle* overrides = new ON_DimStyle(*ptrDimStyle); return ptrAnnotation->SetOverrideDimensionStyle(overrides); } return false; } RH_C_FUNCTION bool ON_V6_Annotation_ClearOverrideDimstyle(ON_Annotation* ptrAnnotation) { if (ptrAnnotation) { ON_DimStyle* dimstyle = nullptr; return ptrAnnotation->SetOverrideDimensionStyle(dimstyle); } return false; } RH_C_FUNCTION bool ON_V6_Annotation_HasOverrideDimstyle(const ON_Annotation* ptrAnnotation) { if (ptrAnnotation) return ptrAnnotation->HasDimensionStyleOverrides(); return false; } RH_C_FUNCTION void ON_V6_Annotation_GetTextString(const ON_Annotation* constAnnotation, ON_wString* wstring, bool rich) { if (nullptr != wstring) { if (constAnnotation) { if (rich) { const ON_TextContent* text_content = constAnnotation->Text(); if(nullptr != text_content) (*wstring) = text_content->PlatformRichTextFromRuns(); } else (*wstring) = constAnnotation->PlainText(); } else *wstring = ON_wString::EmptyString; } } RH_C_FUNCTION void ON_V6_Annotation_GetPlainTextWithFields(const ON_Annotation* constAnnotation, ON_wString* wstring) { if (constAnnotation && wstring) { (*wstring) = constAnnotation->PlainTextWithFields(); } } RH_C_FUNCTION void ON_V6_Annotation_GetPlainTextWithRunMap(const ON_Annotation* constAnnotation, ON_wString* wstring, ON_SimpleArray<int>* intrunmap) { if (constAnnotation && wstring && intrunmap) { ON_SimpleArray<ON_3dex> runmap; (*wstring) = constAnnotation->PlainTextWithFields(&runmap); int count = runmap.Count(); for(int i = 0; i < count; i++) intrunmap->Append(3, &runmap[i].i); } } RH_C_FUNCTION double ON_V6_Annotation_GetFormatWidth(const ON_Annotation* constAnnotation) { if (constAnnotation) return constAnnotation->FormattingRectangleWidth(); return 0.0; } RH_C_FUNCTION void ON_V6_Annotation_SetFormatWidth(ON_Annotation* annotation, double width) { if (annotation) annotation->SetFormattingRectangleWidth(width); } RH_C_FUNCTION void ON_V6_Annotation_WrapText(ON_Annotation* annotation) { if (nullptr != annotation) { double width = annotation->FormattingRectangleWidth(); if (width == width && width > 0.0) { ON_TextContent* text = annotation->Text(); if (nullptr != text) { text->WrapText(width); } } } } RH_C_FUNCTION void ON_V6_Annotation_SetTextIsWrapped(ON_Annotation* annotation, bool wrapped) { if (nullptr != annotation) { ON_TextContent* pText = annotation->Text(); if (nullptr != pText) pText->SetTextIsWrapped(wrapped); } } RH_C_FUNCTION bool ON_V6_Annotation_TextIsWrapped(const ON_Annotation* constAnnotation) { if (nullptr != constAnnotation) { const ON_TextContent* pText = constAnnotation->Text(); if (nullptr != pText) return pText->TextIsWrapped(); } return false; } RH_C_FUNCTION double ON_V6_Annotation_GetTextRotationRadians(const ON_Annotation* constPtrTextObject) { double rotation = 0.0; if (constPtrTextObject) rotation = constPtrTextObject->TextRotationRadians(); return rotation; } RH_C_FUNCTION void ON_V6_Annotation_SetTextRotationRadians(ON_Annotation* constPtrTextObject, double rotation_radians) { if (constPtrTextObject) constPtrTextObject->SetTextRotationRadians(rotation_radians); } RH_C_FUNCTION void ON_V6_Annotation_SetTextString(ON_Annotation* annotation, const RHMONO_STRING* str, const ON_DimStyle* constDimstyle) { if (annotation) { INPUTSTRINGCOERCE(_str, str); annotation->ReplaceTextString(_str, constDimstyle); } } RH_C_FUNCTION bool ON_V6_Annotation_RunReplace(ON_Annotation* annotation, const ON_DimStyle* parent_style, const RHMONO_STRING* repl_str, int start_run_idx, int start_run_pos, int end_run_idx, int end_run_pos) { bool rc = false; if (annotation) { INPUTSTRINGCOERCE(_str, repl_str); rc = annotation->RunReplaceString(parent_style, _str, start_run_idx, start_run_pos, end_run_idx, end_run_pos); } return rc; } RH_C_FUNCTION void ON_V6_Annotation_ClearPropertyOverride(ON_Annotation* annotation, ON_DimStyle::field field) { if (nullptr != annotation) annotation->ClearFieldOverride(field); } RH_C_FUNCTION bool ON_V6_Annotation_FieldIsOverridden(const ON_Annotation* annotation, ON_DimStyle::field field) { if (nullptr != annotation) return annotation->FieldIsOverridden(field); else return false; } RH_C_FUNCTION double ON_V6_Annotation_ExtensionLineExtension(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ExtensionLineExtension(parent_style); return ON_DimStyle::Default.ExtExtension(); } RH_C_FUNCTION void ON_V6_Annotation_SetExtensionLineExtension(ON_Annotation* annotation, const ON_DimStyle* parent_style, double d) { if (nullptr != annotation) annotation->SetExtensionLineExtension(parent_style, d); } RH_C_FUNCTION double ON_V6_Annotation_ExtensionLineOffset(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ExtensionLineOffset(parent_style); else return ON_DimStyle::Default.ExtOffset(); } RH_C_FUNCTION void ON_V6_Annotation_SetExtensionLineOffset(ON_Annotation* annotation, const ON_DimStyle* parent_style, double d) { if (nullptr != annotation) annotation->SetExtensionLineOffset(parent_style, d); } RH_C_FUNCTION double ON_V6_Annotation_ArrowSize(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ArrowSize(parent_style); return ON_DimStyle::Default.ArrowSize(); } RH_C_FUNCTION void ON_V6_Annotation_SetArrowSize(ON_Annotation* annotation, const ON_DimStyle* parent_style, double d) { if (nullptr != annotation) annotation->SetArrowSize(parent_style, d); } RH_C_FUNCTION double ON_V6_Annotation_LeaderArrowSize(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LeaderArrowSize(parent_style); else return ON_DimStyle::Default.LeaderArrowSize(); } RH_C_FUNCTION void ON_V6_Annotation_SetLeaderArrowSize(ON_Annotation* annotation, const ON_DimStyle* parent_style, double d) { if (nullptr != annotation) annotation->SetLeaderArrowSize(parent_style, d); } RH_C_FUNCTION double ON_V6_Annotation_CenterMarkSize(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->CenterMarkSize(parent_style); else return ON_DimStyle::Default.CenterMark(); } RH_C_FUNCTION void ON_V6_Annotation_SetCenterMarkSize(ON_Annotation* annotation, const ON_DimStyle* parent_style, double d) { if (nullptr != annotation) annotation->SetCenterMarkSize(parent_style, d); } RH_C_FUNCTION ON_DimStyle::centermark_style ON_V6_Annotation_CenterMarkStyle(ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->CenterMarkStyle(parent_style); else return ON_DimStyle::Default.CenterMarkStyle(); } RH_C_FUNCTION void ON_V6_Annotation_SetCenterMarkStyle(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::centermark_style style) { if (nullptr != annotation) annotation->SetCenterMarkStyle(parent_style, style); } RH_C_FUNCTION /*ON_DimStyle::TextLocation*/ int ON_V6_Annotation_TextAlignment(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { const ON_DimStyle::TextLocation dim_text_location = (nullptr != annotation) ? annotation->DimTextLocation(parent_style) : ON_DimStyle::Default.DimTextLocation(); return (int)static_cast<unsigned int>(dim_text_location); } RH_C_FUNCTION void ON_V6_Annotation_SetTextAlignment(ON_Annotation* annotation, const ON_DimStyle* parent_style, /*ON_DimStyle::TextLocation*/int m) { if (nullptr != annotation) { const ON_DimStyle::TextLocation dim_text_location = ON_DimStyle::TextLocationFromUnsigned((unsigned int)m); if (((unsigned int)m) == static_cast<unsigned int>(dim_text_location)) annotation->SetDimTextLocation(parent_style, dim_text_location); } } RH_C_FUNCTION ON_DimStyle::angle_format ON_V6_Annotation_AngleFormat(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->AngleFormat(parent_style); else return ON_DimStyle::Default.AngleFormat(); } RH_C_FUNCTION void ON_V6_Annotation_SetAngleFormat(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::angle_format format) { if (nullptr != annotation) annotation->SetAngleFormat(parent_style, format); } RH_C_FUNCTION int ON_V6_Annotation_LengthResolution(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LengthResolution(parent_style); else return ON_DimStyle::Default.LengthResolution(); } RH_C_FUNCTION void ON_V6_Annotation_SetLengthResolution(ON_Annotation* annotation, const ON_DimStyle* parent_style, int r) { if (nullptr != annotation) annotation->SetLengthResolution(parent_style, r); } RH_C_FUNCTION int ON_V6_Annotation_AngleResolution(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->AngleResolution(parent_style); else return ON_DimStyle::Default.AngleResolution(); } RH_C_FUNCTION void ON_V6_Annotation_SetAngleResolution(ON_Annotation* annotation, const ON_DimStyle* parent_style, int r) { if (nullptr != annotation) annotation->SetAngleResolution(parent_style, r); } RH_C_FUNCTION double ON_V6_Annotation_TextGap(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->TextGap(parent_style); else return ON_DimStyle::Default.TextGap(); } RH_C_FUNCTION void ON_V6_Annotation_SetTextGap(ON_Annotation* annotation, const ON_DimStyle* parent_style, double gap) { if (nullptr != annotation) annotation->SetTextGap(parent_style, gap); } RH_C_FUNCTION double ON_V6_Annotation_TextHeight(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (annotation) return annotation->TextHeight(parent_style); return ON_DimStyle::Default.TextHeight(); } RH_C_FUNCTION void ON_V6_Annotation_SetTextHeight(ON_Annotation* annotation, const ON_DimStyle* parent_style, double height) { if (annotation) { annotation->SetTextHeight(parent_style, height); } } RH_C_FUNCTION double ON_V6_Annotation_LengthFactor(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LengthFactor(parent_style); else return ON_DimStyle::Default.LengthFactor(); } RH_C_FUNCTION void ON_V6_Annotation_SetLengthFactor(ON_Annotation* annotation, const ON_DimStyle* parent_style, double d) { if (nullptr != annotation) annotation->SetLengthFactor(parent_style, d); } RH_C_FUNCTION bool ON_V6_Annotation_Alternate(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->Alternate(parent_style); else return ON_DimStyle::Default.Alternate(); } RH_C_FUNCTION void ON_V6_Annotation_SetAlternate(ON_Annotation* annotation, const ON_DimStyle* parent_style, bool b) { if (nullptr != annotation) annotation->SetAlternate(parent_style, b); } RH_C_FUNCTION double ON_V6_Annotation_AlternateLengthFactor(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->AlternateLengthFactor(parent_style); else return ON_DimStyle::Default.AlternateLengthFactor(); } RH_C_FUNCTION void ON_V6_Annotation_SetAlternateLengthFactor(ON_Annotation* annotation, const ON_DimStyle* parent_style, double d) { if (nullptr != annotation) annotation->SetAlternateLengthFactor(parent_style, d); } RH_C_FUNCTION int ON_V6_Annotation_AlternateLengthResolution(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->AlternateLengthResolution(parent_style); else return ON_DimStyle::Default.AlternateLengthResolution(); } RH_C_FUNCTION void ON_V6_Annotation_SetAlternateLengthResolution(ON_Annotation* annotation, const ON_DimStyle* parent_style, int r) { if (nullptr != annotation) annotation->SetAlternateLengthResolution(parent_style, r); } RH_C_FUNCTION void ON_V6_Annotation_Prefix(const ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_wString* wstring) { if (nullptr != annotation && nullptr != wstring) *wstring = annotation->Prefix(parent_style); else *wstring = ON_wString::EmptyString; } RH_C_FUNCTION void ON_V6_Annotation_SetPrefix(ON_Annotation* annotation, const ON_DimStyle* parent_style, const RHMONO_STRING* str) { if (nullptr != annotation && nullptr != str) { INPUTSTRINGCOERCE(prefix, str); annotation->SetPrefix(parent_style, prefix); } } RH_C_FUNCTION void ON_V6_Annotation_Suffix(const ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_wString* wstring) { if (nullptr != annotation && nullptr != wstring) *wstring = annotation->Suffix(parent_style); else *wstring = ON_wString::EmptyString; } RH_C_FUNCTION void ON_V6_Annotation_SetSuffix(ON_Annotation* annotation, const ON_DimStyle* parent_style, const RHMONO_STRING* str) { if (nullptr != annotation) { INPUTSTRINGCOERCE(suffix, str); annotation->SetSuffix(parent_style, suffix); } } RH_C_FUNCTION void ON_V6_Annotation_AlternatePrefix(const ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_wString* wstring) { if (nullptr != annotation && nullptr != wstring) *wstring = annotation->AlternatePrefix(parent_style); else *wstring = ON_wString::EmptyString; } RH_C_FUNCTION void ON_V6_Annotation_SetAlternatePrefix(ON_Annotation* annotation, const ON_DimStyle* parent_style, const RHMONO_STRING* str) { if (nullptr != annotation) { INPUTSTRINGCOERCE(prefix, str); annotation->SetAlternatePrefix(parent_style, prefix); } } RH_C_FUNCTION void ON_V6_Annotation_AlternateSuffix(const ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_wString* wstring) { if (nullptr != annotation && nullptr != wstring) *wstring = annotation->AlternateSuffix(parent_style); else *wstring = ON_wString::EmptyString; } RH_C_FUNCTION void ON_V6_Annotation_SetAlternateSuffix(ON_Annotation* annotation, const ON_DimStyle* parent_style, const RHMONO_STRING* str) { if (nullptr != annotation) { INPUTSTRINGCOERCE(suffix, str); annotation->SetAlternateSuffix(parent_style, suffix); } } RH_C_FUNCTION bool ON_V6_Annotation_SuppressExtension1(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->SuppressExtension1(parent_style); else return ON_DimStyle::Default.SuppressExtension1(); } RH_C_FUNCTION void ON_V6_Annotation_SetSuppressExtension1(ON_Annotation* annotation, const ON_DimStyle* parent_style, bool b) { if (nullptr != annotation) annotation->SetSuppressExtension1(parent_style, b); } RH_C_FUNCTION bool ON_V6_Annotation_SuppressExtension2(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->SuppressExtension2(parent_style); else return ON_DimStyle::Default.SuppressExtension2(); } RH_C_FUNCTION void ON_V6_Annotation_SetSuppressExtension2(ON_Annotation* annotation, const ON_DimStyle* parent_style, bool b) { if (nullptr != annotation) annotation->SetSuppressExtension2(parent_style, b); } RH_C_FUNCTION double ON_V6_Annotation_DimExtension(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->DimExtension(parent_style); else return ON_DimStyle::Default.DimExtension(); } RH_C_FUNCTION void ON_V6_Annotation_SetDimExtension(ON_Annotation* annotation, const ON_DimStyle* parent_style, const double e) { if (nullptr != annotation) annotation->SetDimExtension(parent_style, e); } RH_C_FUNCTION ON_DimStyle::tolerance_format ON_V6_Annotation_ToleranceFormat(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ToleranceFormat(parent_style); else return ON_DimStyle::Default.ToleranceFormat(); } RH_C_FUNCTION void ON_V6_Annotation_SetToleranceFormat(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::tolerance_format format) { if (nullptr != annotation) annotation->SetToleranceFormat(parent_style, format); } RH_C_FUNCTION int ON_V6_Annotation_ToleranceResolution(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ToleranceResolution(parent_style); else return ON_DimStyle::Default.ToleranceResolution(); } RH_C_FUNCTION void ON_V6_Annotation_SetToleranceResolution(ON_Annotation* annotation, const ON_DimStyle* parent_style, int r) { if (nullptr != annotation) annotation->SetToleranceResolution(parent_style, r); } RH_C_FUNCTION double ON_V6_Annotation_ToleranceUpperValue(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ToleranceUpperValue(parent_style); else return ON_DimStyle::Default.ToleranceUpperValue(); } RH_C_FUNCTION void ON_V6_Annotation_SetToleranceUpperValue(ON_Annotation* annotation, const ON_DimStyle* parent_style, double v) { if (nullptr != annotation) annotation->SetToleranceUpperValue(parent_style, v); } RH_C_FUNCTION double ON_V6_Annotation_ToleranceLowerValue(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ToleranceLowerValue(parent_style); else return ON_DimStyle::Default.ToleranceLowerValue(); } RH_C_FUNCTION void ON_V6_Annotation_SetToleranceLowerValue(ON_Annotation* annotation, const ON_DimStyle* parent_style, double v) { if (nullptr != annotation) annotation->SetToleranceLowerValue(parent_style, v); } RH_C_FUNCTION double ON_V6_Annotation_ToleranceHeightScale(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ToleranceHeightScale(parent_style); else return ON_DimStyle::Default.ToleranceHeightScale(); } RH_C_FUNCTION void ON_V6_Annotation_SetToleranceHeightScale(ON_Annotation* annotation, const ON_DimStyle* parent_style, double scale) { if (nullptr != annotation) annotation->SetToleranceHeightScale(parent_style, scale); } RH_C_FUNCTION double ON_V6_Annotation_BaselineSpacing(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->BaselineSpacing(parent_style); else return ON_DimStyle::Default.BaselineSpacing(); } RH_C_FUNCTION void ON_V6_Annotation_SetBaselineSpacing(ON_Annotation* annotation, const ON_DimStyle* parent_style, double spacing) { if (nullptr != annotation) annotation->SetBaselineSpacing(parent_style, spacing); } RH_C_FUNCTION bool ON_V6_Annotation_DrawTextMask(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->DrawTextMask(parent_style); else return ON_DimStyle::Default.DrawTextMask(); } RH_C_FUNCTION void ON_V6_Annotation_SetDrawTextMask(ON_Annotation* annotation, const ON_DimStyle* parent_style, bool bDraw) { if (nullptr != annotation) annotation->SetDrawTextMask(parent_style, bDraw); } RH_C_FUNCTION ON_TextMask::MaskType ON_V6_Annotation_MaskFillType(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->MaskFillType(parent_style); else return ON_DimStyle::Default.MaskFillType(); } RH_C_FUNCTION void ON_V6_Annotation_SetMaskFillType(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_TextMask::MaskType source) { if (nullptr != annotation) annotation->SetMaskFillType(parent_style, source); } RH_C_FUNCTION ON_TextMask::MaskFrame ON_V6_Annotation_MaskFrameType(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->MaskFrameType(parent_style); else return ON_DimStyle::Default.MaskFrameType(); } RH_C_FUNCTION void ON_V6_Annotation_SetMaskFrameType(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_TextMask::MaskFrame source) { if (nullptr != annotation) annotation->SetMaskFrameType(parent_style, source); } RH_C_FUNCTION int ON_V6_Annotation_MaskColor(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { ON_Color on_color = ON_Color::Black; if (nullptr != annotation) on_color = annotation->MaskColor(parent_style); else on_color = ON_DimStyle::Default.MaskColor(); return ABGR_to_ARGB(on_color); } RH_C_FUNCTION void ON_V6_Annotation_SetMaskColor(ON_Annotation* annotation, const ON_DimStyle* parent_style, int rgb_color) { if (nullptr != annotation) { ON_Color on_color = ARGB_to_ABGR(rgb_color); annotation->SetMaskColor(parent_style, on_color); } } RH_C_FUNCTION double ON_V6_Annotation_MaskBorder(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->MaskBorder(parent_style); else return ON_DimStyle::Default.MaskBorder(); } RH_C_FUNCTION void ON_V6_Annotation_SetMaskBorder(ON_Annotation* annotation, const ON_DimStyle* parent_style, double offset) { if (nullptr != annotation) annotation->SetMaskBorder(parent_style, offset); } //RH_C_FUNCTION const ON_TextMask* ON_V6_Annotation_TextMask(const ON_Annotation* annotation, const ON_DimStyle* parent_style) //{ // if (nullptr != annotation) // return &annotation->TextMask(parent_style); // else // return &ON_DimStyle::Default.TextMask(); //} // //RH_C_FUNCTION void ON_V6_Annotation_SetTextMask(ON_Annotation* annotation, const ON_TextMask* text_mask) //{ // if (nullptr != annotation) // annotation->SetTextMask(*text_mask); //} // RH_C_FUNCTION double ON_V6_Annotation_FixedExtensionLength(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->FixedExtensionLength(parent_style); else return ON_DimStyle::Default.FixedExtensionLen(); } RH_C_FUNCTION void ON_V6_Annotation_SetFixedExtensionLength(ON_Annotation* annotation, const ON_DimStyle* parent_style, double l) { if (nullptr != annotation) annotation->SetFixedExtensionLength(parent_style, l); } RH_C_FUNCTION bool ON_V6_Annotation_FixedExtensionLengthOn(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->FixedExtensionLengthOn(parent_style); else return ON_DimStyle::Default.FixedExtensionLenOn(); } RH_C_FUNCTION void ON_V6_Annotation_SetFixedExtensionLengthOn(ON_Annotation* annotation, const ON_DimStyle* parent_style, bool b) { if (nullptr != annotation) annotation->SetFixedExtensionLengthOn(parent_style, b); } RH_C_FUNCTION int ON_V6_Annotation_AlternateToleranceResolution(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->AlternateToleranceResolution(parent_style); else return ON_DimStyle::Default.AlternateToleranceResolution(); } RH_C_FUNCTION void ON_V6_Annotation_SetAlternateToleranceResolution(ON_Annotation* annotation, const ON_DimStyle* parent_style, int r) { if (nullptr != annotation) annotation->SetAlternateToleranceResolution(parent_style, r); } RH_C_FUNCTION bool ON_V6_Annotation_SuppressArrow1(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->SuppressArrow1(parent_style); else return ON_DimStyle::Default.SuppressArrow1(); } RH_C_FUNCTION void ON_V6_Annotation_SetSuppressArrow1(ON_Annotation* annotation, const ON_DimStyle* parent_style, bool s) { if (nullptr != annotation) annotation->SetSuppressArrow1(parent_style, s); } RH_C_FUNCTION bool ON_V6_Annotation_SuppressArrow2(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->SuppressArrow2(parent_style); else return ON_DimStyle::Default.SuppressArrow2(); } RH_C_FUNCTION void ON_V6_Annotation_SetSuppressArrow2(ON_Annotation* annotation, const ON_DimStyle* parent_style, bool s) { if (nullptr != annotation) annotation->SetSuppressArrow2(parent_style, s); } RH_C_FUNCTION int ON_V6_Annotation_TextMoveLeader(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->TextMoveLeader(parent_style); else return ON_DimStyle::Default.TextMoveLeader(); } RH_C_FUNCTION void ON_V6_Annotation_SetTextMoveLeader(ON_Annotation* annotation, const ON_DimStyle* parent_style, int m) { if (nullptr != annotation) annotation->SetTextMoveLeader(parent_style, m); } RH_C_FUNCTION int ON_V6_Annotation_ArcLengthSymbol(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ArcLengthSymbol(parent_style); else return ON_DimStyle::Default.ArcLengthSymbol(); } RH_C_FUNCTION void ON_V6_Annotation_SetArcLengthSymbol(ON_Annotation* annotation, const ON_DimStyle* parent_style, int m) { if (nullptr != annotation) annotation->SetArcLengthSymbol(parent_style, m); } RH_C_FUNCTION ON_DimStyle::stack_format ON_V6_Annotation_StackFractionFormat(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->StackFractionFormat(parent_style); else return ON_DimStyle::Default.StackFractionFormat(); } RH_C_FUNCTION void ON_V6_Annotation_SetStackFractionFormat(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::stack_format f) { if (nullptr != annotation) annotation->SetStackFractionFormat(parent_style, f); } RH_C_FUNCTION double ON_V6_Annotation_StackHeightScale(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->StackHeightScale(parent_style); else return ON_DimStyle::Default.StackHeightScale(); } RH_C_FUNCTION void ON_V6_Annotation_SetStackHeightScale(ON_Annotation* annotation, const ON_DimStyle* parent_style, double f) { if (nullptr != annotation) annotation->SetStackHeightScale(parent_style, f); } RH_C_FUNCTION double ON_V6_Annotation_RoundOff(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->RoundOff(parent_style); else return ON_DimStyle::Default.RoundOff(); } RH_C_FUNCTION void ON_V6_Annotation_SetRoundOff(ON_Annotation* annotation, const ON_DimStyle* parent_style, double r) { if (nullptr != annotation) annotation->SetRoundOff(parent_style, r); } RH_C_FUNCTION double ON_V6_Annotation_AlternateRoundOff(ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->AlternateRoundOff(parent_style); else return ON_DimStyle::Default.AlternateRoundOff(); } RH_C_FUNCTION void ON_V6_Annotation_SetAlternateRoundOff(ON_Annotation* annotation, const ON_DimStyle* parent_style, double r) { if (nullptr != annotation) annotation->SetAlternateRoundOff(parent_style, r); } RH_C_FUNCTION double ON_V6_Annotation_AngleRoundOff(ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->AngleRoundOff(parent_style); else return ON_DimStyle::Default.AngleRoundOff(); } RH_C_FUNCTION void ON_V6_Annotation_SetAngleRoundOff(ON_Annotation* annotation, const ON_DimStyle* parent_style, double r) { if (nullptr != annotation) annotation->SetAngleRoundOff(parent_style, r); } RH_C_FUNCTION ON_DimStyle::suppress_zero ON_V6_Annotation_ZeroSuppress(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ZeroSuppress(parent_style); else return ON_DimStyle::Default.ZeroSuppress(); } RH_C_FUNCTION void ON_V6_Annotation_SetZeroSuppress(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::suppress_zero s) { if (nullptr != annotation) annotation->SetZeroSuppress(parent_style, s); } RH_C_FUNCTION ON_DimStyle::suppress_zero ON_V6_Annotation_AlternateZeroSuppress(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->AlternateZeroSuppress(parent_style); else return ON_DimStyle::Default.AlternateZeroSuppress(); } RH_C_FUNCTION void ON_V6_Annotation_SetAlternateZeroSuppress(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::suppress_zero s) { if (nullptr != annotation) annotation->SetAlternateZeroSuppress(parent_style, s); } RH_C_FUNCTION ON_DimStyle::suppress_zero ON_V6_Annotation_ToleranceZeroSuppress(ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ToleranceZeroSuppress(parent_style); else return ON_DimStyle::Default.ToleranceZeroSuppress(); } RH_C_FUNCTION void ON_V6_Annotation_SetToleranceZeroSuppress(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::suppress_zero s) { if (nullptr != annotation) annotation->SetToleranceZeroSuppress(parent_style, s); } RH_C_FUNCTION ON_DimStyle::suppress_zero ON_V6_Annotation_AngleZeroSuppress(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->AngleZeroSuppress(parent_style); else return ON_DimStyle::Default.AngleZeroSuppress(); } RH_C_FUNCTION void ON_V6_Annotation_SetAngleZeroSuppress(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::suppress_zero s) { if (nullptr != annotation) annotation->SetAngleZeroSuppress(parent_style, s); } RH_C_FUNCTION bool ON_V6_Annotation_AlternateBelow(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->AlternateBelow(parent_style); else return ON_DimStyle::Default.AlternateBelow(); } RH_C_FUNCTION void ON_V6_Annotation_SetAlternateBelow(ON_Annotation* annotation, const ON_DimStyle* parent_style, bool b) { if (nullptr != annotation) annotation->SetAlternateBelow(parent_style, b); } RH_C_FUNCTION ON_Arrowhead::arrow_type ON_V6_Annotation_ArrowType1(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ArrowType1(parent_style); else return ON_DimStyle::Default.ArrowType1(); } RH_C_FUNCTION void ON_V6_Annotation_SetArrowType1(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_Arrowhead::arrow_type t) { if (nullptr != annotation) annotation->SetArrowType1(parent_style, t); } RH_C_FUNCTION ON_Arrowhead::arrow_type ON_V6_Annotation_ArrowType2(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ArrowType2(parent_style); else return ON_DimStyle::Default.ArrowType2(); } RH_C_FUNCTION void ON_V6_Annotation_SetArrowType2(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_Arrowhead::arrow_type t) { if (nullptr != annotation) annotation->SetArrowType2(parent_style, t); } RH_C_FUNCTION void ON_V6_Annotation_SetArrowType1And2(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_Arrowhead::arrow_type t) { if (nullptr != annotation) annotation->SetArrowType1And2(parent_style, t); } RH_C_FUNCTION ON_Arrowhead::arrow_type ON_V6_Annotation_LeaderArrowType(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LeaderArrowType(parent_style); else return ON_DimStyle::Default.LeaderArrowType(); } RH_C_FUNCTION void ON_V6_Annotation_SetLeaderArrowType(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_Arrowhead::arrow_type t) { if (nullptr != annotation) annotation->SetLeaderArrowType(parent_style, t); } RH_C_FUNCTION ON_UUID ON_V6_Annotation_ArrowBlockId1(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ArrowBlockId1(parent_style); else return ON_DimStyle::Default.ArrowBlockId1(); } RH_C_FUNCTION void ON_V6_Annotation_SetArrowBlockId1(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_UUID id) { if (nullptr != annotation) annotation->SetArrowBlockId1(parent_style, id); } RH_C_FUNCTION ON_UUID ON_V6_Annotation_ArrowBlockId2(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->ArrowBlockId2(parent_style); else return ON_DimStyle::Default.ArrowBlockId2(); } RH_C_FUNCTION void ON_V6_Annotation_SetArrowBlockId2(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_UUID id) { if (nullptr != annotation) annotation->SetArrowBlockId2(parent_style, id); } RH_C_FUNCTION ON_UUID ON_V6_Annotation_LeaderArrowBlockId(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LeaderArrowBlockId(parent_style); else return ON_DimStyle::Default.LeaderArrowBlockId(); } RH_C_FUNCTION void ON_V6_Annotation_SetLeaderArrowBlockId(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_UUID id) { if (nullptr != annotation) annotation->SetLeaderArrowBlockId(parent_style, id); } RH_C_FUNCTION ON::TextVerticalAlignment ON_V6_Annotation_TextVerticalAlignment(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->TextVerticalAlignment(parent_style); else return ON_DimStyle::Default.TextVerticalAlignment(); } RH_C_FUNCTION void ON_V6_Annotation_SetTextVerticalAlignment(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON::TextVerticalAlignment style) { if (nullptr != annotation) annotation->SetTextVerticalAlignment(parent_style, style); } RH_C_FUNCTION ON::TextVerticalAlignment ON_V6_Annotation_LeaderTextVerticalAlignment(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LeaderTextVerticalAlignment(parent_style); else return ON_DimStyle::Default.LeaderTextVerticalAlignment(); } RH_C_FUNCTION void ON_V6_Annotation_SetLeaderTextVerticalAlignment(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON::TextVerticalAlignment style) { if (nullptr != annotation) annotation->SetLeaderTextVerticalAlignment(parent_style, style); } RH_C_FUNCTION ON_DimStyle::ContentAngleStyle ON_V6_Annotation_LeaderContentAngleStyle(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LeaderContentAngleStyle(parent_style); else return ON_DimStyle::Default.LeaderContentAngleStyle(); } RH_C_FUNCTION void ON_V6_Annotation_SetLeaderContentAngleStyle(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::ContentAngleStyle style) { if (nullptr != annotation) annotation->SetLeaderContentAngleStyle(parent_style, style); } RH_C_FUNCTION ON_DimStyle::leader_curve_type ON_V6_Annotation_LeaderCurveType(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LeaderCurveType(parent_style); else return ON_DimStyle::Default.LeaderCurveType(); } RH_C_FUNCTION void ON_V6_Annotation_SetLeaderCurveType(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::leader_curve_type type) { if (nullptr != annotation) annotation->SetLeaderCurveType(parent_style, type); } RH_C_FUNCTION bool ON_V6_Annotation_LeaderHasLanding(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LeaderHasLanding(parent_style); else return ON_DimStyle::Default.LeaderHasLanding(); } RH_C_FUNCTION void ON_V6_Annotation_SetLeaderHasLanding(ON_Annotation* annotation, const ON_DimStyle* parent_style, bool b) { if (nullptr != annotation) annotation->SetLeaderHasLanding(parent_style, b); } RH_C_FUNCTION double ON_V6_Annotation_LeaderLandingLength(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LeaderLandingLength(parent_style); else return ON_DimStyle::Default.LeaderLandingLength(); } RH_C_FUNCTION void ON_V6_Annotation_SetLeaderLandingLength(ON_Annotation* annotation, const ON_DimStyle* parent_style, double l) { if (nullptr != annotation) annotation->SetLeaderLandingLength(parent_style, l); } RH_C_FUNCTION double ON_V6_Annotation_LeaderContentAngleRadians(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LeaderContentAngleRadians(parent_style); else return ON_DimStyle::Default.LeaderContentAngleRadians(); } RH_C_FUNCTION void ON_V6_Annotation_SetLeaderContentAngleRadians(ON_Annotation* annotation, const ON_DimStyle* parent_style, double r) { if (nullptr != annotation) annotation->SetLeaderContentAngleRadians(parent_style, r); } RH_C_FUNCTION double ON_V6_Annotation_LeaderContentAngleDegrees(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LeaderContentAngleDegrees(parent_style); else return ON_DimStyle::Default.LeaderContentAngleDegrees(); } RH_C_FUNCTION void ON_V6_Annotation_SetLeaderContentAngleDegrees(ON_Annotation* annotation, const ON_DimStyle* parent_style, double d) { if (nullptr != annotation) annotation->SetLeaderContentAngleDegrees(parent_style, d); } RH_C_FUNCTION ON::TextHorizontalAlignment ON_V6_Annotation_TextHorizontalAlignment(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->TextHorizontalAlignment(parent_style); else return ON_DimStyle::Default.TextHorizontalAlignment(); } RH_C_FUNCTION void ON_V6_Annotation_SetTextHorizontalAlignment(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON::TextHorizontalAlignment halign) { if (nullptr != annotation) annotation->SetTextHorizontalAlignment(parent_style, halign); } RH_C_FUNCTION ON::TextHorizontalAlignment ON_V6_Annotation_LeaderTextHorizontalAlignment(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->LeaderTextHorizontalAlignment(parent_style); else return ON_DimStyle::Default.LeaderTextHorizontalAlignment(); } RH_C_FUNCTION void ON_V6_Annotation_SetLeaderTextHorizontalAlignment(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON::TextHorizontalAlignment h) { if (nullptr != annotation) annotation->SetLeaderTextHorizontalAlignment(parent_style, h); } RH_C_FUNCTION bool ON_V6_Annotation_DrawForward(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->DrawForward(parent_style); else return ON_DimStyle::Default.DrawForward(); } RH_C_FUNCTION void ON_V6_Annotation_SetDrawForward(ON_Annotation* annotation, const ON_DimStyle* parent_style, bool drawforward) { if (nullptr != annotation) annotation->SetDrawForward(parent_style, drawforward); } RH_C_FUNCTION bool ON_V6_Annotation_SignedOrdinate(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->SignedOrdinate(parent_style); else return ON_DimStyle::Default.SignedOrdinate(); } RH_C_FUNCTION void ON_V6_Annotation_SetSignedOrdinate(ON_Annotation* annotation, const ON_DimStyle* parent_style, bool allowsigned) { if (nullptr != annotation) annotation->SetSignedOrdinate(parent_style, allowsigned); } #if !defined(RHINO3DM_BUILD) //in rhino.exe RH_C_FUNCTION double ON_V6_Annotation_GetDimScale(unsigned int doc_sn, const ON_DimStyle* dimstyle, const CRhinoViewport* vport) { double scale = 1.0; CRhinoDoc* doc = CRhinoDoc::FromRuntimeSerialNumber(doc_sn); if (nullptr != doc && nullptr != dimstyle && nullptr != vport) { scale = CRhinoAnnotation::GetAnnotationScale(doc, dimstyle, vport); } return scale; } #endif RH_C_FUNCTION double ON_V6_Annotation_DimScale(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return annotation->DimScale(parent_style); else return ON_DimStyle::Default.DimScale(); } RH_C_FUNCTION void ON_V6_Annotation_SetDimScale(ON_Annotation* annotation, const ON_DimStyle* parent_style, double scale) { if (nullptr != annotation) annotation->SetDimScale(parent_style, scale); } RH_C_FUNCTION const ON_Font* ON_V6_Annotation_Font(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { if (nullptr != annotation) return &annotation->Font(parent_style); else return &ON_DimStyle::Default.Font(); } RH_C_FUNCTION ON_DimStyle::LengthDisplay ON_V6_Annotation_GetDimensionLengthDisplay(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { ON_DimStyle::LengthDisplay display = ON_DimStyle::LengthDisplay::ModelUnits; if (nullptr != annotation) display = annotation->DimensionLengthDisplay(parent_style); return display; } RH_C_FUNCTION ON_DimStyle::LengthDisplay ON_V6_Annotation_GetAlternateDimensionLengthDisplay(const ON_Annotation* annotation, const ON_DimStyle* parent_style) { ON_DimStyle::LengthDisplay display = ON_DimStyle::LengthDisplay::ModelUnits; if (nullptr != annotation) display = annotation->AlternateDimensionLengthDisplay(parent_style); return display; } RH_C_FUNCTION void ON_V6_Annotation_SetDimensionLengthDisplay(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::LengthDisplay display) { if (nullptr != annotation) annotation->SetDimensionLengthDisplay(parent_style, display); } RH_C_FUNCTION void ON_V6_Annotation_SetAlternateDimensionLengthDisplay(ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_DimStyle::LengthDisplay display) { if (nullptr != annotation) annotation->SetAlternateDimensionLengthDisplay(parent_style, display); } RH_C_FUNCTION ON::TextHorizontalAlignment ON_V6_Annotation_GetHAlignment(const ON_Annotation* constAnnotation) { ON::TextHorizontalAlignment h = ON::TextHorizontalAlignment::Left; ON::TextVerticalAlignment v; if (constAnnotation) constAnnotation->GetAlignment(h, v); return h; } RH_C_FUNCTION void ON_V6_Annotation_SetHAlignment(ON_Annotation* annotation, unsigned int h_align) { if (annotation) { ON::TextHorizontalAlignment h; ON::TextVerticalAlignment v; annotation->GetAlignment(h, v); ON::TextHorizontalAlignment h1 = ON::TextHorizontalAlignmentFromUnsigned(h_align); annotation->SetAlignment(h1, v); } } RH_C_FUNCTION void ON_V6_Annotation_FormatRtfString(const RHMONO_STRING* rtfstr_in, ON_wString* rtfstr_out, bool clear_bold, bool set_bold, bool clear_italic, bool set_italic, bool clear_underline, bool set_underline, bool clear_facename, bool set_facename, const RHMONO_STRING* facename) { INPUTSTRINGCOERCE(str, rtfstr_in); INPUTSTRINGCOERCE(str1, facename); *rtfstr_out = ON_TextContext::FormatRtfString(str, nullptr, clear_bold, set_bold, clear_italic, set_italic, clear_underline, set_underline, clear_facename, set_facename, str1); } RH_C_FUNCTION bool ON_V6_Annotation_DecimalSeparator(const ON_Annotation* annotation, const ON_DimStyle* parent_style, ON_wString* pString) { if (pString) { wchar_t s = ON_wString::DecimalAsPeriod; if (annotation) s = annotation->DecimalSeparator(parent_style); (*pString) += s; return true; } return false; } RH_C_FUNCTION void ON_V6_Annotation_SetDecimalSeparator(ON_Annotation* annotation, const ON_DimStyle* parent_style, const RHMONO_STRING* str) { if (annotation && str) { INPUTSTRINGCOERCE(_str, str); if (_str && _str[0]) annotation->SetDecimalSeparator(parent_style, _str[0]); } } RH_C_FUNCTION ON::TextVerticalAlignment ON_Text_GetTextVerticalAlignment(const ON_Text* text, const ON_DimStyle* parent_style) { if (text && parent_style) return text->TextVerticalAlignment(parent_style); return ON::TextVerticalAlignment::Top; } RH_C_FUNCTION void ON_Text_SetTextVerticalAlignment(ON_Text* text, const ON_DimStyle* parent_style, ON::TextVerticalAlignment v_alignment) { if (text && parent_style) { text->SetTextVerticalAlignment(parent_style, v_alignment); } } RH_C_FUNCTION ON::TextVerticalAlignment ON_Leader_GetLeaderTextVerticalAlignment(const ON_Leader* dim, const ON_DimStyle* parent_style) { if (dim && parent_style) return dim->LeaderTextVerticalAlignment(parent_style); return ON::TextVerticalAlignment::Top; } RH_C_FUNCTION void ON_Leader_SetLeaderTextVerticalAlignment(ON_Leader* dim, const ON_DimStyle* parent_style, ON::TextVerticalAlignment v_alignment) { if (dim && parent_style) { dim->SetLeaderTextVerticalAlignment(parent_style, v_alignment); } } RH_C_FUNCTION ON::TextHorizontalAlignment ON_Text_GetTextHorizontalAlignment(const ON_Text* text, const ON_DimStyle* parent_style) { if (text && parent_style) return text->TextHorizontalAlignment(parent_style); return ON::TextHorizontalAlignment::Left; } RH_C_FUNCTION void ON_Text_SetTextHorizontalAlignment(ON_Text* text, const ON_DimStyle* parent_style, ON::TextHorizontalAlignment h_alignment) { if (text && parent_style) { text->SetTextHorizontalAlignment(parent_style, h_alignment); } } RH_C_FUNCTION ON::TextHorizontalAlignment ON_Leader_GetLeaderTextHorizontalAlignment(const ON_Leader* dim, const ON_DimStyle* parent_style) { if (dim && parent_style) return dim->LeaderTextHorizontalAlignment(parent_style); return ON::TextHorizontalAlignment::Left; } RH_C_FUNCTION void ON_Leader_SetLeaderTextHorizontalAlignment(ON_Leader* dim, const ON_DimStyle* parent_style, ON::TextHorizontalAlignment h_alignment) { if (dim && parent_style) { dim->SetLeaderTextHorizontalAlignment(parent_style, h_alignment); } } RH_C_FUNCTION ON_DimStyle::TextLocation ON_Dim_GetDimTextocation(const ON_Dimension* dim, const ON_DimStyle* parent_style) { if (dim && parent_style) return dim->DimTextLocation(parent_style); return ON_DimStyle::TextLocation::AboveDimLine; } RH_C_FUNCTION void ON_Dim_SetDimTextLocation(ON_Dimension* dim, const ON_DimStyle* parent_style, ON_DimStyle::TextLocation loc) { if (dim && parent_style) { dim->SetDimTextLocation(parent_style, loc); } } RH_C_FUNCTION ON_DimStyle::TextLocation ON_Dim_GetDimRadialTextocation(const ON_Dimension* dim, const ON_DimStyle* parent_style) { if (dim && parent_style) return dim->DimRadialTextLocation(parent_style); return ON_DimStyle::TextLocation::InDimLine; } RH_C_FUNCTION void ON_Dim_SetDimRadialTextLocation(ON_Dimension* dim, const ON_DimStyle* parent_style, ON_DimStyle::TextLocation loc) { if (dim && parent_style) { dim->SetDimRadialTextLocation(parent_style, loc); } } RH_C_FUNCTION ON_DimStyle::ContentAngleStyle ON_Leader_GetLeaderContentAngleStyle(const ON_Leader* dim, const ON_DimStyle* parent_style) { if (dim && parent_style) return dim->LeaderContentAngleStyle(parent_style); return ON_DimStyle::ContentAngleStyle::Horizontal; } RH_C_FUNCTION void ON_Leader_SetLeaderContentAngleStyle(ON_Leader* dim, const ON_DimStyle* parent_style, ON_DimStyle::ContentAngleStyle angle_style) { if (dim && parent_style) { dim->SetLeaderContentAngleStyle(parent_style, angle_style); } } RH_C_FUNCTION ON_DimStyle::ContentAngleStyle ON_Dim_GetDimTextAngleStyle(const ON_Dimension* dim, const ON_DimStyle* parent_style) { if (dim && parent_style) return dim->DimTextAngleStyle(parent_style); return ON_DimStyle::ContentAngleStyle::Aligned; } RH_C_FUNCTION void ON_Dim_SetDimTextAngleStyle(ON_Dimension* dim, const ON_DimStyle* parent_style, ON_DimStyle::ContentAngleStyle angle_style) { if (dim && parent_style) { dim->SetDimTextAngleStyle(parent_style, angle_style); } } RH_C_FUNCTION ON_DimStyle::ContentAngleStyle ON_Dim_GetDimRadialTextAngleStyle(const ON_Dimension* dim, const ON_DimStyle* parent_style) { if (dim && parent_style) return dim->DimRadialTextAngleStyle(parent_style); return ON_DimStyle::ContentAngleStyle::Horizontal; } RH_C_FUNCTION void ON_Leader_SetDimRadialTextAngleStyle(ON_Dimension* dim, const ON_DimStyle* parent_style, ON_DimStyle::ContentAngleStyle angle_style) { if (dim && parent_style) { dim->SetDimRadialTextAngleStyle(parent_style, angle_style); } } RH_C_FUNCTION ON::TextOrientation ON_Text_GetTextOrientation(const ON_Text* text, const ON_DimStyle* parent_style) { if (text && parent_style) return text->TextOrientation(parent_style); return ON::TextOrientation::InPlane; } RH_C_FUNCTION void ON_Text_SetTextOrientation(ON_Text* text, const ON_DimStyle* parent_style, ON::TextOrientation orientation) { if (text && parent_style) { text->SetTextOrientation(parent_style, orientation); } } RH_C_FUNCTION ON::TextOrientation ON_Leader_GetTextOrientation(const ON_Leader* dim, const ON_DimStyle* parent_style) { if (dim && parent_style) return dim->LeaderTextOrientation(parent_style); return ON::TextOrientation::InPlane; } RH_C_FUNCTION void ON_Leader_SetTextOrientation(ON_Leader* dim, const ON_DimStyle* parent_style, ON::TextOrientation orientation) { if (dim && parent_style) { dim->SetLeaderTextOrientation(parent_style, orientation); } } RH_C_FUNCTION ON::TextOrientation ON_Dim_GetDimTextOrientation(const ON_Dimension* dim, const ON_DimStyle* parent_style) { if (dim && parent_style) return dim->DimTextOrientation(parent_style); return ON::TextOrientation::InPlane; } RH_C_FUNCTION void ON_Dim_SetDimTextOrientation(ON_Dimension* dim, const ON_DimStyle* parent_style, ON::TextOrientation orientation) { if (dim && parent_style) { dim->SetDimTextOrientation(parent_style, orientation); } } RH_C_FUNCTION ON::TextOrientation ON_Dim_GetDimRadialTextOrientation(const ON_Dimension* dim, const ON_DimStyle* parent_style) { if (dim && parent_style) return dim->DimRadialTextOrientation(parent_style); return ON::TextOrientation::InPlane; } RH_C_FUNCTION void ON_Dim_SetDimRadialTextOrientation(ON_Dimension* dim, const ON_DimStyle* parent_style, ON::TextOrientation orientation) { if (dim && parent_style) { dim->SetDimRadialTextOrientation(parent_style, orientation); } } RH_C_FUNCTION bool ON_Annotation_GetTextUnderlined(const ON_Annotation* anno, const ON_DimStyle* parent_style) { if (anno && parent_style) return anno->TextUnderlined(parent_style); return false; } RH_C_FUNCTION void ON_Dim_SetTextUnderlined(ON_Annotation* anno, const ON_DimStyle* parent_style, bool underlined) { if (anno && parent_style) { anno->SetTextUnderlined(parent_style, underlined); } } RH_C_FUNCTION void ON_V6_DimLinear_GetDisplayText(const ON_DimLinear* dimptr, ON::LengthUnitSystem units, const ON_DimStyle* dimstyle, ON_wString* wstring) { if (dimptr && wstring) { if (!dimptr->GetDistanceDisplayText(units, dimstyle, *wstring)) *wstring = ON_wString::EmptyString; } } RH_C_FUNCTION void ON_V6_DimRadial_GetDisplayText(const ON_DimRadial* dimptr, ON::LengthUnitSystem units, const ON_DimStyle* dimstyle, ON_wString* wstring) { if (dimptr && wstring) { if (!dimptr->GetDistanceDisplayText(units, dimstyle, *wstring)) *wstring = ON_wString::EmptyString; } } RH_C_FUNCTION void ON_V6_DimOrdinate_GetDisplayText(const ON_DimOrdinate* dimptr, ON::LengthUnitSystem units, const ON_DimStyle* dimstyle, ON_wString* wstring) { if (dimptr && wstring) { if (!dimptr->GetDistanceDisplayText(units, dimstyle, *wstring)) *wstring = ON_wString::EmptyString; } } RH_C_FUNCTION void ON_V6_DimAngular_GetDisplayText(const ON_DimAngular* dimptr, const ON_DimStyle* dimstyle, ON_wString* wstring) { if (dimptr && wstring) { if (!dimptr->GetAngleDisplayText(dimstyle, *wstring)) *wstring = ON_wString::EmptyString; } } RH_C_FUNCTION ON_Text* ON_V6_TextObject_New() { return new ON_Text(); } RH_C_FUNCTION ON_Text* ON_V6_TextObject_Create(const RHMONO_STRING* rtfstr, const ON_PLANE_STRUCT plane, const ON_DimStyle* style, bool wrapped, double rect_width, double rotation) { ON_Text* rc = new ON_Text(); INPUTSTRINGCOERCE(_rtfstr, rtfstr); if (!rc->Create(_rtfstr, style, FromPlaneStruct(plane), wrapped, rect_width, rotation)) { delete rc; rc = nullptr; } return rc; } RH_C_FUNCTION bool ON_V6_TextObject_Transform(ON_Text* ptrTextObject, const ON_Xform* constaPtrXform, const ON_DimStyle* dimstyle) { if (ptrTextObject == nullptr || constaPtrXform == nullptr) return false; return dimstyle ? ptrTextObject->Transform(*constaPtrXform, dimstyle) : ptrTextObject->Transform(*constaPtrXform); } RH_C_FUNCTION bool ON_V6_TextObject_GetTextXform(const ON_Text* constPtrTextObject, const ON_DimStyle* dimstyle, double scale, ON_Xform* xform_out) { bool rc = false; if (constPtrTextObject && xform_out) { rc = constPtrTextObject->GetTextXform(nullptr, dimstyle, scale, *xform_out) ? true : false; } return rc; } // set the whole text string to bold or not bold RH_C_FUNCTION bool ON_Annotation_SetBold(ON_Annotation* anno, bool set_on, const ON_DimStyle* style) { bool rc = false; if (anno) { rc = anno->SetAnnotationBold(set_on, style); } return rc; } // set the whole text string to italic or not italic RH_C_FUNCTION bool ON_Annotation_SetItalic(ON_Annotation* anno, bool set_on, const ON_DimStyle* style) { bool rc = false; if (anno) { rc = anno->SetAnnotationItalic(set_on, style); } return rc; } // set the whole text string to underlined or not underlined RH_C_FUNCTION bool ON_Annotation_SetUnderline(ON_Annotation* anno, bool set_on, const ON_DimStyle* style) { bool rc = false; if (anno) { rc = anno->SetAnnotationUnderline(set_on, style); } return rc; } // set the facename whole text string RH_C_FUNCTION bool ON_Annotation_SetFacename(ON_Annotation* anno, bool set_on, const RHMONO_STRING* facename, const ON_DimStyle* style) { bool rc = false; if (anno) { INPUTSTRINGCOERCE(str, facename); rc = anno->SetAnnotationFacename(set_on, str, style); } return rc; } RH_C_FUNCTION void ON_Annotation_SetFont(ON_Annotation* annotation, const ON_DimStyle* parent_style, const class ON_Font* font) { if (nullptr != annotation && nullptr != font) { annotation->SetAnnotationFont(font, parent_style); } } RH_C_FUNCTION int ON_Annotation_FirstCharTextProperties(const RHMONO_STRING* rtfstr_in, ON_wString* facename) { INPUTSTRINGCOERCE(str, rtfstr_in); int answer = 0; { bool bold = false, italic = false, underline = false; ON_wString wstr; if (nullptr != facename) wstr = *facename; bool rc = ON_Annotation::FirstCharTextProperties(str, bold, italic, underline, wstr); if (rc) { answer = 1; if (bold) answer |= 2; if (italic) answer |= 4; if (underline) answer |= 8; if (nullptr != facename) *facename = wstr; } } return answer; } RH_C_FUNCTION const ON_Font* ON_Annotation_FirstCharFont(const ON_Annotation* ptr) { if(nullptr != ptr && nullptr != ptr->Text()) return ptr->Text()->FirstCharFont(); return &ON_Font::Default; } RH_C_FUNCTION bool ON_Annotation_GetAnnotationBoundingBox(const ON_Annotation* constAnnotation, const ON_DimStyle* constParentDimstyle, ON_BoundingBox* bbox) { bool rc = false; if (constAnnotation && bbox) { const ON_DimStyle* dimstyle = nullptr; if (constParentDimstyle) dimstyle = &(constAnnotation->DimensionStyle(*constParentDimstyle)); if (nullptr == dimstyle) { // 19 July 2018 <NAME> (RH-44507) // I have no idea why the annotation bounding box calculation purely relies on // a dimstyle height, but it appears to work for the most part in Rhino. In the // case where an annotation with no associated dimstyle is created in RhinoCommon, // just use a temp dimstyle to ensure the correct text height is used during the // bounding box calculation. const double height = constAnnotation->TextHeight(nullptr); if (fabs(height - 1) > 0.0001) { ON_DimStyle tempDimStyle = ON_DimStyle::Default; tempDimStyle.SetTextHeight(height); dimstyle = &tempDimStyle; return constAnnotation->GetAnnotationBoundingBox(nullptr, dimstyle, 1.0, &bbox->m_min.x, &bbox->m_max.x, false); } } rc = constAnnotation->GetAnnotationBoundingBox(nullptr, dimstyle, 1.0, &bbox->m_min.x, &bbox->m_max.x, false); } return rc; } RH_C_FUNCTION bool ON_Annotation_IsAllBold(const ON_Annotation* ptr) { if (nullptr != ptr) return ptr->IsAllBold(); return false; } RH_C_FUNCTION bool ON_Annotation_IsAllItalic(const ON_Annotation* ptr) { if (nullptr != ptr) return ptr->IsAllItalic(); return false; } RH_C_FUNCTION bool ON_Annotation_IsAllUnderlined(const ON_Annotation* ptr) { if (nullptr != ptr) return ptr->IsAllUnderlined(); return false; } // ON_TextRun //--------------------------------------------------------------------- enum TextRunTypeConsts : int { rtNone = 0, rtText = 1, rtNewline = 2, rtParagraph = 3, rtColumn = 4, rtField = 5, rtFontdef = 6, rtHeader = 7 }; //TextRunTypeConsts TextRunType(int rti) //{ // TextRunTypeConsts type = rtNone; // ON_TextRun::RunType rt = (ON_TextRun::RunType)rti; // switch (rt) // { // case ON_TextRun::RunType::kText: type = rtText; break; // case ON_TextRun::RunType::kNewline: type = rtNewline; break; // case ON_TextRun::RunType::kParagraph: type = rtParagraph; break; // case ON_TextRun::RunType::kColumn: type = rtNewline; break; // case ON_TextRun::RunType::kField: type = rtField; break; // case ON_TextRun::RunType::kFontdef: type = rtFontdef; break; // case ON_TextRun::RunType::kHeader: type = rtHeader; break; // } // return type; //} int TextRunType(TextRunTypeConsts rt) { int type = (int)ON_TextRun::RunType::kNone; switch (rt) { case rtText: type = (int)ON_TextRun::RunType::kText; break; case rtNewline: type = (int)ON_TextRun::RunType::kNewline; break; case rtParagraph: type = (int)ON_TextRun::RunType::kParagraph; break; case rtColumn: type = (int)ON_TextRun::RunType::kNewline; break; case rtField: type = (int)ON_TextRun::RunType::kField; break; case rtFontdef: type = (int)ON_TextRun::RunType::kFontdef; break; case rtHeader: type = (int)ON_TextRun::RunType::kHeader; break; } return type; } //RH_C_FUNCTION ON_TextRun* ON_TextRun_New(const ON_TextRun* sourcePointer) //{ // ON_TextRun* result = ON_TextRun::GetManagedTextRun(); // if (result && sourcePointer) // *result = *sourcePointer; // return result; //} // //RH_C_FUNCTION void ON_TextRun_Delete(ON_TextRun* ptrTextRun) //{ // ON_TextRun::ReturnManagedTextRun(ptrTextRun); //} RH_C_FUNCTION TextRunTypeConsts ON_TextRun_Type(const ON_TextRun* constPtrTextRun) { TextRunTypeConsts rt = rtNone; if (constPtrTextRun) rt = static_cast < TextRunTypeConsts > (constPtrTextRun->Type()); return rt; } RH_C_FUNCTION void ON_TextRun_SetType(ON_TextRun* ptrTextRun, TextRunTypeConsts rt) { if (ptrTextRun) ptrTextRun->SetType(static_cast< ON_TextRun::RunType >(TextRunType(rt))); } //RH_C_FUNCTION double ON_TextRun_Height(const ON_TextRun* constPtrTextRun) //{ // if (constPtrTextRun) // return constPtrTextRun->Height(); // return 1.0; //} // //RH_C_FUNCTION void ON_TextRun_SetHeight(ON_TextRun* ptrTextRun, double h) //{ // if (ptrTextRun) // ptrTextRun->SetHeight(h); //} // //RH_C_FUNCTION unsigned int ON_TextRun_Color(const ON_TextRun* constPtrTextRun) //{ // unsigned int argb = 0; // if (constPtrTextRun) // { // unsigned int color = (unsigned int)constPtrTextRun->Color(); // argb = ABGR_to_ARGB(color); // } // return argb; //} // //RH_C_FUNCTION void ON_TextRun_SetColor(ON_TextRun* ptrTextRun, unsigned int argb) //{ // unsigned int abgr = ARGB_to_ABGR(argb); // ON_Color color(abgr); // if(ptrTextRun) // ptrTextRun->SetColor(color); //} // //RH_C_FUNCTION void ON_TextRun_SetTextStyle(ON_TextRun* ptrTextRun, const ON_Font* style) //{ // if (ptrTextRun) // ptrTextRun->SetFont(style); //} // //RH_C_FUNCTION const ON_Font* ON_TextRun_TextStyle(const ON_TextRun* constPtrTextRun) //{ // if (constPtrTextRun) // return constPtrTextRun->Font(); // return nullptr; //} // //RH_C_FUNCTION void ON_TextRun_BoundingBox(const ON_TextRun* constPtrTextRun, ON_BoundingBox* bbox) //{ // if (constPtrTextRun && bbox) // *bbox = constPtrTextRun->BoundingBox(); //} // //RH_C_FUNCTION void ON_TextRun_SetBoundingBox(ON_TextRun* ptrTextRun, ON_2DPOINT_STRUCT pmin, ON_2DPOINT_STRUCT pmax) //{ // if (ptrTextRun) // { // ON_2dPoint pt_min(pmin.val); // ON_2dPoint pt_max(pmax.val); // ptrTextRun->SetBoundingBox(pt_min, pt_max); // } //} // //RH_C_FUNCTION void ON_TextRun_Offset(const ON_TextRun* constPtrTextRun, ON_2dVector* vector) //{ // if (constPtrTextRun && vector) // *vector = constPtrTextRun->Offset(); //} // //RH_C_FUNCTION void ON_TextRun_SetOffset(ON_TextRun* ptrTextRun, ON_2DVECTOR_STRUCT offset) //{ // if (ptrTextRun) // { // ON_2dVector _offset(offset.val); // ptrTextRun->SetOffset(_offset); // } //} // //RH_C_FUNCTION void ON_TextRun_Advance(const ON_TextRun* constPtrTextRun, ON_2dVector* advance) //{ // if (constPtrTextRun && advance) // *advance = constPtrTextRun->Advance(); //} // //RH_C_FUNCTION void ON_TextRun_SetAdvance(ON_TextRun* ptrTextRun, ON_2DVECTOR_STRUCT advance) //{ // if (ptrTextRun) // { // ON_2dVector _advance(advance.val); // ptrTextRun->SetAdvance(_advance); // } //} // //RH_C_FUNCTION double ON_TextRun_HeightScale(const ON_TextRun* constPtrTextRun, const ON_Font* style) //{ // if (constPtrTextRun) // return constPtrTextRun->HeightScale(style); // else // return 1.0; //} // //RH_C_FUNCTION void ON_TextRun_GetCodepoints(const ON_TextRun* constPtrTextRun, int count, /*ARRAY*/unsigned int* cpOut) //{ // if (constPtrTextRun && count >= ON_TextRun::CodepointCount(constPtrTextRun->UnicodeString()) && cpOut) // { // for (int i = 0; i < count; i++) // cpOut[i] = constPtrTextRun->UnicodeString()[i]; // } //} // //RH_C_FUNCTION void ON_TextRun_SetCodepoints(ON_TextRun* ptrTextRun, int count, /*ARRAY*/const unsigned int* cp) //{ // if (ptrTextRun) // ptrTextRun->SetUnicodeString(count, cp); //} // //RH_C_FUNCTION int ON_TextRun_CodepointCount(const ON_TextRun* constPtrTextRun) //{ // if (constPtrTextRun) // return (int)ON_TextRun::CodepointCount(constPtrTextRun->UnicodeString()); // return 0; //} // RH_C_FUNCTION bool ON_TextContext_FormatDistanceAndTolerance(double distance, ON::LengthUnitSystem units_in, const ON_DimStyle* dimstyle, bool alternate, ON_wString* formatted_string) { if (formatted_string) return ON_TextContent::FormatDistanceAndTolerance(distance, units_in, dimstyle, alternate, *formatted_string); return false; } RH_C_FUNCTION bool ON_TextContext_FormatArea(double area, ON::LengthUnitSystem units_in, const ON_DimStyle* dimstyle, bool alternate, ON_wString* formatted_string) { if (formatted_string) return ON_TextContent::FormatArea(area, units_in, dimstyle, alternate, *formatted_string); return false; } RH_C_FUNCTION bool ON_TextContext_FormatVolume(double volume, ON::LengthUnitSystem units_in, const ON_DimStyle* dimstyle, bool alternate, ON_wString* formatted_string) { if (formatted_string) return ON_TextContent::FormatVolume(volume, units_in, dimstyle, alternate, *formatted_string); return false; }
23,936
2,058
from functools import lru_cache, partial from collections import OrderedDict from contextlib import contextmanager import html from itertools import count import os import signal import subprocess import sys import time import threading import traceback import sublime MYPY = False if MYPY: from typing import Callable, Dict, Iterator, Tuple, Type @contextmanager def print_runtime(message): # type: (str) -> Iterator[None] start_time = time.perf_counter() yield end_time = time.perf_counter() duration = round((end_time - start_time) * 1000) thread_name = threading.current_thread().name[0] print('{} took {}ms [{}]'.format(message, duration, thread_name)) def measure_runtime(): # type: () -> Callable[[str], None] start_time = time.perf_counter() def print_mark(message): # type: (str) -> None end_time = time.perf_counter() duration = round((end_time - start_time) * 1000) thread_name = threading.current_thread().name[0] print('{} after {}ms [{}]'.format(message, duration, thread_name)) return print_mark class timer: def __init__(self): self._start_time = time.perf_counter() def passed(self, ms): # type: (int) -> bool cur_time = time.perf_counter() duration = (cur_time - self._start_time) * 1000 return duration > ms @contextmanager def eat_but_log_errors(exception=Exception): # type: (Type[Exception]) -> Iterator[None] try: yield except exception: traceback.print_exc() def hprint(msg): # type: (str) -> None """Print help message for e.g. a failed action""" # Note this does a plain and boring print. We use it to # mark some usages of print throughout the code-base. # We later might find better ways to show these help # messages to the user. print(msg) def flash(view, message): # type: (sublime.View, str) -> None """ Flash status message on view's window. """ window = view.window() if window: window.status_message(message) IDS = partial(next, count()) # type: Callable[[], int] # type: ignore[assignment] HIDE_POPUP_TIMERS = {} # type: Dict[sublime.ViewId, int] POPUPS = {} # type: Dict[sublime.ViewId, Tuple] DEFAULT_TIMEOUT = 2500 # [ms] DEFAULT_STYLE = { 'background': 'transparent', 'foreground': 'var(--foreground)' } def show_toast(view, message, timeout=DEFAULT_TIMEOUT, style=DEFAULT_STYLE): # type: (sublime.View, str, int, Dict[str, str]) -> Callable[[], None] """Show a toast popup at the bottom of the view. A timeout of -1 makes a "sticky" toast. """ messages_by_line = escape_text(message).splitlines() content = style_message("<br />".join(messages_by_line), style) # Order can matter here. If we calc width *after* visible_region we get # different results! width, _ = view.viewport_extent() visible_region = view.visible_region() last_row, _ = view.rowcol(visible_region.end()) line_start = view.text_point(last_row - 4 - len(messages_by_line), 0) vid = view.id() key = IDS() def on_hide(vid, key): if HIDE_POPUP_TIMERS.get(vid) == key: HIDE_POPUP_TIMERS.pop(vid, None) def __hide_popup(vid, key, sink): if HIDE_POPUP_TIMERS.get(vid) == key: HIDE_POPUP_TIMERS.pop(vid, None) sink() inner_hide_popup = show_popup( view, content, max_width=width * 2 / 3, location=line_start, on_hide=partial(on_hide, vid, key) ) HIDE_POPUP_TIMERS[vid] = key hide_popup = partial(__hide_popup, vid, key, inner_hide_popup) if timeout > 0: sublime.set_timeout(hide_popup, timeout) return hide_popup def show_popup(view, content, max_width, location, on_hide=None): vid = view.id() inner_hide_popup = view.hide_popup actual_key = (int(max_width), location) if POPUPS.get(vid) == actual_key: view.update_popup(content) else: def __on_hide(vid, key): if POPUPS.get(vid) == key: POPUPS.pop(vid, None) if on_hide: on_hide() view.show_popup( content, max_width=max_width, location=location, on_hide=partial(__on_hide, vid, actual_key) ) POPUPS[vid] = actual_key def __hide_popup(vid, key, sink): if POPUPS.get(vid) == key: POPUPS.pop(vid, None) sink() return partial(__hide_popup, vid, actual_key, inner_hide_popup) def style_message(message, style): # type: (str, Dict[str, str]) -> str return """ <div style="padding: 1rem; background-color: {background}; color: {foreground}" >{message}</div> """.format(message=message, **style) def escape_text(text): # type: (str) -> str return html.escape(text, quote=False).replace(" ", "&nbsp;") MYPY = False if MYPY: from typing import Iterable, Sequence, NamedTuple Action = NamedTuple("Action", [("description", str), ("action", Callable[[], None])]) ActionType = Tuple[str, Callable[[], None]] QuickPanelItems = Iterable[str] else: from collections import namedtuple Action = namedtuple("Action", "description action") def show_panel( window, # type: sublime.Window items, # type: QuickPanelItems on_done, # type: Callable[[int], None] on_cancel=lambda: None, # type: Callable[[], None] on_highlight=lambda _: None, # type: Callable[[int], None] selected_index=-1, # type: int flags=sublime.MONOSPACE_FONT ): # (...) -> None def _on_done(idx): # type: (int) -> None if idx == -1: on_cancel() else: on_done(idx) # `on_highlight` also gets called `on_done`. We # reduce the side-effects here using `lru_cache`. @lru_cache(1) def _on_highlight(idx): # type: (int) -> None on_highlight(idx) window.show_quick_panel( list(items), _on_done, on_highlight=_on_highlight, selected_index=selected_index, flags=flags ) def show_actions_panel(window, actions, select=-1): # type: (sublime.Window, Sequence[ActionType], int) -> None def on_selection(idx): # type: (int) -> None description, action = actions[idx] action() show_panel( window, (action[0] for action in actions), on_selection, selected_index=select ) def noop(description): # type: (str) -> ActionType return Action(description, lambda: None) def focus_view(view): # type: (sublime.View) -> None window = view.window() if not window: return group, _ = window.get_view_index(view) window.focus_group(group) window.focus_view(view) if int(sublime.version()) < 4000: from Default import history_list # type: ignore[import] def add_selection_to_jump_history(view): history_list.get_jump_history_for_view(view).push_selection(view) else: def add_selection_to_jump_history(view): view.run_command("add_jump_record", { "selection": [(r.a, r.b) for r in view.sel()] }) def line_indentation(line): # type: (str) -> int return len(line) - len(line.lstrip()) def kill_proc(proc): if sys.platform == "win32": # terminate would not kill process opened by the shell cmd.exe, # it will only kill cmd.exe leaving the child running startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW subprocess.Popen( "taskkill /PID %d /T /F" % proc.pid, startupinfo=startupinfo) else: os.killpg(proc.pid, signal.SIGTERM) proc.terminate() # `realpath` also supports `bytes` and we don't, hence the indirection def _resolve_path(path): # type: (str) -> str return os.path.realpath(path) if ( os.name == "nt" and sys.getwindowsversion()[:2] >= (6, 0) and sys.version_info[:2] < (3, 8) ): try: from nt import _getfinalpathname # type: ignore[import] except ImportError: resolve_path = _resolve_path else: def resolve_path(path): # type: (str) -> str rpath = _getfinalpathname(path) if rpath.startswith("\\\\?\\"): rpath = rpath[4:] if rpath.startswith("UNC\\"): rpath = "\\" + rpath[3:] return rpath else: resolve_path = _resolve_path def paths_upwards(path): # type: (str) -> Iterator[str] while True: yield path path, name = os.path.split(path) if not name or path == "/": break class Cache(OrderedDict): def __init__(self, maxsize=128): assert maxsize > 0 self.maxsize = maxsize super().__init__() def __getitem__(self, key): value = super().__getitem__(key) self.move_to_end(key) return value def __setitem__(self, key, value): if key in self: self.move_to_end(key) super().__setitem__(key, value) if len(self) > self.maxsize: self.popitem(last=False)
4,082
812
import json from nose import SkipTest from tests.test_stack import TestConfig, app_from_config from tg.support.paginate import Page from tg.controllers.util import _urlencode from tg import json_encode from tg.util.webtest import test_context def setup_noDB(): base_config = TestConfig(folder='rendering', values={ 'use_sqlalchemy': False, 'use_toscawidgets': False, 'use_toscawidgets2': False }) return app_from_config(base_config) _pager = ('<div id="pager"><span class="pager_curpage">1</span>' ' <a href="%(url)s?page=2">2</a>' ' <a href="%(url)s?page=3">3</a>' ' <span class="pager_dotdot">..</span>' ' <a href="%(url)s?page=5">5</a></div>') _data = '<ul id="data">%s</ul>' % ''.join( '<li>%d</li>' % i for i in range(10)) class TestPagination: def setup(self): self.app = setup_noDB() def test_basic_pagination(self): url = '/paginated/42' page = self.app.get(url) assert _pager % locals() in page, page assert _data in page, page url = '/paginated/42?page=2' page = self.app.get(url) assert '<li>0</li>' not in page assert '<li>10</li>' in page def test_pagination_negative(self): url = '/paginated/42?page=-1' page = self.app.get(url) assert '<li>0</li>' in page def test_pagination_items_per_page(self): url = '/paginated/42?items_per_page=20' page = self.app.get(url) assert '<li>0</li>' in page assert '<li>19</li>' in page def test_pagination_items_per_page_negative(self): url = '/paginated/42?items_per_page=-1' page = self.app.get(url) assert '<li>0</li>' in page assert '<li>10</li>' not in page def test_pagination_non_paginable(self): url = '/paginated_text' page = self.app.get(url) assert 'Some Text' in page def test_pagination_with_validation(self): url = '/paginated_validated/42' page = self.app.get(url) assert _pager % locals() in page, page assert _data in page, page url = '/paginated_validated/42?page=2' page = self.app.get(url) assert '<li>0</li>' not in page assert '<li>10</li>' in page def test_validation_with_pagination(self): url = '/validated_paginated/42' page = self.app.get(url) assert _pager % locals() in page, page assert _data in page, page url = '/validated_paginated/42?page=2' page = self.app.get(url) assert '<li>0</li>' not in page assert '<li>10</li>' in page def test_pagination_with_link_args(self): url = '/paginate_with_params/42' page = self.app.get(url) assert 'param1=hi' in page assert 'param2=man' in page assert 'partial' not in page assert '/fake_url' in page url = '/paginate_with_params/42?page=2' page = self.app.get(url) assert '<li>0</li>' not in page assert '<li>10</li>' in page def test_multiple_paginators(self): url = '/multiple_paginators/42' try: from collections import OrderedDict params = (('testdata_page', 2), ('testdata2_page', 2)) reverse_params = OrderedDict(reversed(params)) params = OrderedDict(params) except ImportError: reverse_params = params = {'testdata2_page': 2, 'testdata_page': 2} goto_page2_link = url + '?' + _urlencode(params) goto_page2_reverse_link = url + '?' + _urlencode(reverse_params) page = self.app.get(url) assert '/multiple_paginators/42?testdata2_page=2' in page, str(page) assert '/multiple_paginators/42?testdata_page=2' in page, str(page) url = '/multiple_paginators/42?testdata_page=2' page = self.app.get(url) assert ( goto_page2_link in page or goto_page2_reverse_link in page ), str(page) assert '/multiple_paginators/42?testdata_page=4' in page, str(page) assert '<li>0</li>' not in page assert '<li>10</li>' in page assert '<li>142</li>' in page assert '<li>151</li>' in page url = '/multiple_paginators/42?testdata2_page=2' page = self.app.get(url) assert ( goto_page2_link in page or goto_page2_reverse_link in page ), str(page) assert '/multiple_paginators/42?testdata2_page=4' in page, str(page) assert '<li>0</li>' in page assert '<li>9</li>' in page assert '<li>151</li>' not in page assert '<li>161</li>' in page def test_json_pagination(self): url = '/paginated/42.json' page = self.app.get(url) assert '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]' in page url = '/paginated/42.json?page=2' page = self.app.get(url) assert '[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]' in page class TestPage(object): def test_not_a_number_page(self): p = Page(range(100), items_per_page=10, page='A') sec = list(p) assert sec[-1] == 9, sec def test_empty_list(self): p = Page([], items_per_page=10, page=1) assert list(p) == [] def test_page_out_of_bound(self): p = Page(range(100), items_per_page=10, page=10000) sec = list(p) assert sec[-1] == 99, sec def test_page_out_of_lower_bound(self): p = Page(range(100), items_per_page=10, page=-5) sec = list(p) assert sec[-1] == 9, sec def test_navigator_one_page(self): with test_context(None, '/'): p = Page(range(10), items_per_page=10, page=10) assert p.pager() == '' def test_navigator_middle_page(self): with test_context(None, '/'): p = Page(range(100), items_per_page=10, page=5) pager = p.pager() assert '?page=1' in pager assert '?page=4' in pager assert '?page=6' in pager assert '?page=10' in pager def test_navigator_ajax(self): with test_context(None, '/'): p = Page(range(100), items_per_page=10, page=5) pager = p.pager(onclick='goto($page)') assert 'goto(1)' in pager assert 'goto(4)' in pager assert 'goto(6)' in pager assert 'goto(10)' in pager try: import sqlite3 except: import pysqlite2 from sqlalchemy import (MetaData, Table, Column, ForeignKey, Integer, String) from sqlalchemy.orm import create_session, mapper, relation metadata = MetaData('sqlite:///:memory:') test1 = Table('test1', metadata, Column('id', Integer, primary_key=True), Column('val', String(8))) test2 = Table('test2', metadata, Column('id', Integer, primary_key=True), Column('test1id', Integer, ForeignKey('test1.id')), Column('val', String(8))) test3 = Table('test3', metadata, Column('id', Integer, primary_key=True), Column('val', String(8))) test4 = Table('test4', metadata, Column('id', Integer, primary_key=True), Column('val', String(8))) metadata.create_all() class Test2(object): pass mapper(Test2, test2) class Test1(object): pass mapper(Test1, test1, properties={'test2s': relation(Test2)}) class Test3(object): pass mapper(Test3, test3) class Test4(object): pass mapper(Test4, test4) test1.insert().execute({'id': 1, 'val': 'bob'}) test2.insert().execute({'id': 1, 'test1id': 1, 'val': 'fred'}) test2.insert().execute({'id': 2, 'test1id': 1, 'val': 'alice'}) test3.insert().execute({'id': 1, 'val': 'bob'}) test4.insert().execute({'id': 1, 'val': 'alberto'}) class TestPageSQLA(object): def setup(self): self.s = create_session() def test_relationship(self): t = self.s.query(Test1).get(1) p = Page(t.test2s, items_per_page=1, page=1) assert len(list(p)) == 1 assert list(p)[0].val == 'fred', list(p) def test_query(self): q = self.s.query(Test2) p = Page(q, items_per_page=1, page=1) assert len(list(p)) == 1 assert list(p)[0].val == 'fred', list(p) def test_json_query(self): q = self.s.query(Test2) p = Page(q, items_per_page=1, page=1) res = json.loads(json_encode(p)) assert len(res['entries']) == 1 assert res['total'] == 2 assert res['entries'][0]['val'] == 'fred' try: import ming from ming import create_datastore, Session, schema, ASCENDING from ming.odm import ODMSession, FieldProperty, ForeignIdProperty, RelationProperty, Mapper from ming.odm.declarative import MappedClass except ImportError: ming = None class TestPageMing(object): @classmethod def setupClass(cls): if ming is None: raise SkipTest('Ming not available...') cls.basic_session = Session(create_datastore('mim:///testdb')) cls.s = ODMSession(cls.basic_session) class Author(MappedClass): class __mongometa__: session = cls.s name = 'wiki_author' _id = FieldProperty(schema.ObjectId) name = FieldProperty(str) pages = RelationProperty('WikiPage') class WikiPage(MappedClass): class __mongometa__: session = cls.s name = 'wiki_page' _id = FieldProperty(schema.ObjectId) title = FieldProperty(str) text = FieldProperty(str) order = FieldProperty(int) author_id = ForeignIdProperty(Author) author = RelationProperty(Author) cls.Author = Author cls.WikiPage = WikiPage Mapper.compile_all() cls.author = Author(name='author1') author2 = Author(name='author2') WikiPage(title='Hello', text='Text', order=1, author=cls.author) WikiPage(title='Another', text='Text', order=2, author=cls.author) WikiPage(title='ThirdOne', text='Text', order=3, author=author2) cls.s.flush() cls.s.clear() def teardown(self): self.s.clear() def test_query(self): q = self.WikiPage.query.find().sort([('order', ASCENDING)]) p = Page(q, items_per_page=1, page=1) assert len(list(p)) == 1 assert list(p)[0].title == 'Hello', list(p) def test_json_query(self): q = self.WikiPage.query.find().sort([('order', ASCENDING)]) p = Page(q, items_per_page=1, page=1) res = json.loads(json_encode(p)) assert len(res['entries']) == 1 assert res['total'] == 3 assert res['entries'][0]['title'] == 'Hello', res['entries'] assert res['entries'][0]['author_id'] == str(self.author._id), res['entries'] def test_relation(self): a = self.Author.query.find({'name': 'author1'}).first() p = Page(a.pages, items_per_page=1, page=1) assert len(list(p)) == 1 assert list(p)[0].title in ('Hello', 'Another'), list(p)
5,190
362
package net.ripe.db.whois.update.domain; import net.ripe.db.whois.update.keycert.X509CertificateWrapper; import java.security.cert.X509Certificate; import java.util.Objects; public class ClientCertificateCredential implements Credential { private final X509Certificate x509Certificate; private final String fingerprint; public ClientCertificateCredential(final X509CertificateWrapper x509CertificateWrapper) { this.x509Certificate = x509CertificateWrapper.getCertificate(); this.fingerprint = x509CertificateWrapper.getFingerprint(); } public static Credential createOfferedCredential(X509CertificateWrapper x509CertificateWrapper) { return new ClientCertificateCredential(x509CertificateWrapper); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final ClientCertificateCredential that = (ClientCertificateCredential) o; return Objects.equals(x509Certificate, that.x509Certificate); } @Override public int hashCode() { return Objects.hash(x509Certificate); } @Override public String toString() { return "ClientCertificateCredential"; } public String getFingerprint() { return fingerprint; } }
473
450
/* * Copyright (c) 2004, 2005 TADA AB - Taby Sweden * Distributed under the terms shown in the file COPYRIGHT * found in the root folder of this project or at * http://eng.tada.se/osprojects/COPYRIGHT.html */ package org.postgresql.pljava.example.annotation; import org.postgresql.pljava.annotation.Function; import java.io.IOException; import java.io.InputStream; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.logging.Logger; import org.postgresql.pljava.ResultSetProvider; /** * @author <NAME> */ public class UsingProperties implements ResultSetProvider { private static Logger s_logger = Logger.getAnonymousLogger(); private final Iterator m_propertyIterator; public UsingProperties() throws IOException { Properties v = new Properties(); InputStream propStream = this.getClass().getResourceAsStream("example.properties"); if(propStream == null) { s_logger.fine("example.properties was null"); m_propertyIterator = Collections.EMPTY_SET.iterator(); } else { v.load(propStream); propStream.close(); s_logger.fine("example.properties has " + v.size() + " entries"); m_propertyIterator = v.entrySet().iterator(); } } public boolean assignRowValues(ResultSet receiver, int currentRow) throws SQLException { if(!m_propertyIterator.hasNext()) { s_logger.fine("no more rows, returning false"); return false; } Map.Entry propEntry = (Map.Entry)m_propertyIterator.next(); receiver.updateString(1, (String)propEntry.getKey()); receiver.updateString(2, (String)propEntry.getValue()); // s_logger.fine("next row created, returning true"); return true; } @Function( complexType = "javatest._properties") public static ResultSetProvider getProperties() throws SQLException { try { return new UsingProperties(); } catch(IOException e) { throw new SQLException("Error reading properties", e.getMessage()); } } public void close() { } }
712
351
<filename>samples/aci-show-tenants-in-multisite-orchestrator.py # Sample code accessing the Cisco Multisite Orchestrator from requests import Session # Replace the following variables with the correct values for your deployment. username = 'admin' password = 'password' mso_ip = '10.10.10.10' def show_tenants(): # Login to Multisite Orchestrator session = Session() data = {'username': username, 'password': password} resp = session.post('https://%s/api/v1/auth/login' % mso_ip, json=data, verify=False) if not resp.ok: print('Could not login to Multisite Orchestrator') return # Get the tenants headers = {"Authorization": "Bearer %s" % resp.json()['token']} resp = session.get('https://%s/api/v1/tenants' % mso_ip, headers=headers) if not resp.ok: print('Could not get tenants from Multisite Orchestrator') return # Print the result print('Tenants') print('-' * len('Tenants')) for tenant in resp.json()['tenants']: print(tenant['displayName']) if __name__ == '__main__': show_tenants()
396
349
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015-2021 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #pragma once #include <modules/openglqt/openglqtmoduledefine.h> #include <inviwo/core/util/canvas.h> #include <warn/push> #include <warn/ignore/all> #include <QSurfaceFormat> #include <warn/pop> #include <string_view> class QOffscreenSurface; class QOpenGLContext; // Include causes: warning qopenglfunctions.h is not compatible with GLEW, // GLEW defines will be undefined namespace inviwo { /* * Convenience class for creating an QOffscreenSurface with an QOpenGLContext. * * This class can be used for concurrent OpenGL operations in background threads. * The class must be created in the main thread. * initializeGL must be called before use, but can be called in a different thread. * * @note Most Canvas overriden functions are non-functional except HiddenCanvasQt::activate() */ class IVW_MODULE_OPENGLQT_API HiddenCanvasQt : public Canvas { public: /* * Must be created in the main thread. * Must call initializeGL before using it * The default format is usually set globally beforehand, usually directly in the main function. * // Must be set before constructing QApplication * QApplication::setAttribute(Qt::AA_ShareOpenGLContexts); * QApplication::setAttribute(Qt::AA_UseDesktopOpenGL); * QSurfaceFormat defaultFormat; * defaultFormat.setMajorVersion(10); * defaultFormat.setProfile(QSurfaceFormat::CoreProfile); * QSurfaceFormat::setDefaultFormat(defaultFormat); */ HiddenCanvasQt(std::string_view name, QSurfaceFormat format = QSurfaceFormat::defaultFormat()); HiddenCanvasQt(const HiddenCanvasQt&) = delete; HiddenCanvasQt(HiddenCanvasQt&&) = delete; HiddenCanvasQt& operator=(const HiddenCanvasQt&) = delete; HiddenCanvasQt& operator=(HiddenCanvasQt&&) = delete; virtual ~HiddenCanvasQt(); /* * Initialize context and OpenGL functions. Only call this function once. */ void initializeGL(); /* * Does nothing */ virtual void render([[maybe_unused]] std::shared_ptr<const Image>, [[maybe_unused]] LayerType layerType = LayerType::Color, [[maybe_unused]] size_t idx = 0) override{}; virtual void update() override; virtual void activate() override; // used to create hidden canvases used for context in background threads. virtual std::unique_ptr<Canvas> createHiddenCanvas() override; static std::unique_ptr<Canvas> createHiddenQtCanvas(); using ContextID = const void*; virtual ContextID activeContext() const override; virtual ContextID contextId() const override; virtual void releaseContext() override; QOpenGLContext* getContext() { return context_; }; protected: QOpenGLContext* context_; QOffscreenSurface* offScreenSurface_; }; } // namespace inviwo
1,393
1,698
{ "$schema": "http://json-schema.org/draft-04/schema", "title": "JSON Schema for Content Security Policy (Level 2) violation reports", "description": "https://www.w3.org/TR/CSP2/#violation-reports", "type": "object", "required": [ "csp-report" ], "properties": { "csp-report": { "type": "object", "properties": { "blocked-uri": { "type": "string", "description": "The originally requested URL of the resource that was prevented from loading, stripped for reporting, or the empty string if the resource has no URL (inline script and inline style, for example)." }, "document-uri": { "type": "string", "description": "The address of the protected resource, stripped for reporting." }, "effective-directive": { "type": "string", "description": "The name of the policy directive that was violated. This will contain the directive whose enforcement triggered the violation (e.g. \"script-src\") even if that directive does not explicitly appear in the policy, but is implicitly activated via the default-src directive." }, "original-policy": { "type": "string", "description": "The original policy, as received by the user agent." }, "referrer": { "type": "string", "description": "The referrer attribute of the protected resource, or the empty string if the protected resource has no referrer." }, "status-code": { "type": "number", "description": "The status-code of the HTTP response that contained the protected resource, if the protected resource was obtained over HTTP. Otherwise, the number 0." }, "violated-directive": { "type": "string", "description": "The policy directive that was violated, as it appears in the policy. This will contain the default-src directive in the case of violations caused by falling back to the default sources when enforcing a directive." }, "source-file": { "type": "string", "description": "The URL of the resource where the violation occurred, stripped for reporting." }, "line-number": { "type": "number", "description": "The line number in source-file on which the violation occurred." }, "column-number": { "type": "number", "description": "The column number in source-file on which the violation occurred." } } } }, "additionalProperties": false }
936
354
/* * Copyright (C) 2017 <NAME> Software & Consulting (dlsc.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.calendarfx.view.popover; import com.calendarfx.view.CalendarView; import com.calendarfx.view.RecurrenceView; import impl.com.calendarfx.view.popover.RecurrencePopupSkin; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.event.Event; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.scene.control.PopupControl; import javafx.scene.control.Skin; import javafx.scene.layout.StackPane; public class RecurrencePopup extends PopupControl { private static final String DEFAULT_STYLE = "recurrence-popup"; private RecurrenceView recurrenceView; private StackPane root; public RecurrencePopup() { getStyleClass().add(DEFAULT_STYLE); root = new StackPane(); root.getStylesheets().add(CalendarView.class.getResource("calendar.css").toExternalForm()); recurrenceView = new RecurrenceView(); recurrenceView.setShowSummary(false); Bindings.bindContentBidirectional(root.getStyleClass(), getStyleClass()); setAutoFix(true); setAutoHide(true); } @Override protected Skin<?> createDefaultSkin() { return new RecurrencePopupSkin(this); } public final StackPane getRoot() { return root; } public final RecurrenceView getRecurrenceView() { return recurrenceView; } private class RecurrencePopupEventHandlerProperty extends SimpleObjectProperty<EventHandler<RecurrencePopupEvent>> { private EventType<RecurrencePopupEvent> eventType; public RecurrencePopupEventHandlerProperty(final String name, final EventType<RecurrencePopupEvent> eventType) { super(RecurrencePopup.this, name); this.eventType = eventType; } @Override protected void invalidated() { setEventHandler(eventType, get()); } } /* * OK pressed event support. */ private RecurrencePopupEventHandlerProperty onOkPressed; public final ObjectProperty<EventHandler<RecurrencePopupEvent>> onOkPressedProperty() { if (onOkPressed == null) { onOkPressed = new RecurrencePopupEventHandlerProperty("onOkPressed", RecurrencePopupEvent.OK_PRESSED); } return onOkPressed; } public final void setOnOkPressed(EventHandler<RecurrencePopupEvent> value) { onOkPressedProperty().set(value); } public final EventHandler<RecurrencePopupEvent> getOnOkPressed() { return onOkPressed == null ? null : onOkPressedProperty().get(); } /* * Cancel pressed event support. */ private RecurrencePopupEventHandlerProperty onCancelPressed; public final ObjectProperty<EventHandler<RecurrencePopupEvent>> onCancelPressedProperty() { if (onCancelPressed == null) { onCancelPressed = new RecurrencePopupEventHandlerProperty( "onCancelPressed", RecurrencePopupEvent.CANCEL_PRESSED); } return onCancelPressed; } public final void setOnCancelPressed( EventHandler<RecurrencePopupEvent> value) { onCancelPressedProperty().set(value); } public final EventHandler<RecurrencePopupEvent> getOnCancelPressed() { return onCancelPressed == null ? null : onCancelPressedProperty().get(); } public static class RecurrencePopupEvent extends Event { public static final EventType<RecurrencePopupEvent> RECURRENCE_POPUP_CLOSED = new EventType<>( Event.ANY, "RECURRENCE_POPUP_CLOSED"); public static final EventType<RecurrencePopupEvent> OK_PRESSED = new EventType<>( RecurrencePopupEvent.RECURRENCE_POPUP_CLOSED, "OK_PRESSED"); public static final EventType<RecurrencePopupEvent> CANCEL_PRESSED = new EventType<>( RecurrencePopupEvent.RECURRENCE_POPUP_CLOSED, "CANCEL_PRESSED"); public RecurrencePopupEvent(EventType<? extends Event> eventType) { super(eventType); } } }
1,818
4,816
/** * @file include/retdec/bin2llvmir/providers/calling_convention/mips64/mips64_conv.h * @brief Calling convention of Mips64 architecture. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #ifndef RETDEC_BIN2LLVMIR_PROVIDERS_CALL_CONV_MIPS64_MIPS64_H #define RETDEC_BIN2LLVMIR_PROVIDERS_CALL_CONV_MIPS64_MIPS64_H #include "retdec/bin2llvmir/providers/calling_convention/calling_convention.h" namespace retdec { namespace bin2llvmir { class Mips64CallingConvention: public CallingConvention { // Ctors, dtors. // public: Mips64CallingConvention(const Abi* a); // Construcor method. // public: static CallingConvention::Ptr create(const Abi* a); }; } } #endif
274
777
<reponame>google-ar/chromium // Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/process/process_info.h" #include <stdint.h> #include "base/logging.h" #include "base/process/internal_linux.h" #include "base/process/process_handle.h" #include "base/time/time.h" namespace base { // static const Time CurrentProcessInfo::CreationTime() { ProcessHandle pid = GetCurrentProcessHandle(); int64_t start_ticks = internal::ReadProcStatsAndGetFieldAsInt64(pid, internal::VM_STARTTIME); DCHECK(start_ticks); TimeDelta start_offset = internal::ClockTicksToTimeDelta(start_ticks); Time boot_time = internal::GetBootTime(); DCHECK(!boot_time.is_null()); return Time(boot_time + start_offset); } } // namespace base
284
1,655
<reponame>chaosink/tungsten #include "NullBsdf.hpp" #include "io/JsonObject.hpp" namespace Tungsten { NullBsdf::NullBsdf() { _lobes = BsdfLobes::NullLobe; } rapidjson::Value NullBsdf::toJson(Allocator &allocator) const { return JsonObject{Bsdf::toJson(allocator), allocator, "type", "null" }; } bool NullBsdf::sample(SurfaceScatterEvent &/*event*/) const { return false; } Vec3f NullBsdf::eval(const SurfaceScatterEvent &/*event*/) const { return Vec3f(0.0f); } bool NullBsdf::invert(WritablePathSampleGenerator &/*sampler*/, const SurfaceScatterEvent &/*event*/) const { return false; } float NullBsdf::pdf(const SurfaceScatterEvent &/*event*/) const { return 0.0f; } }
301
4,462
import mxnet as mx from mxnet.util import use_np import numpy as np import random @use_np def average_checkpoints(checkpoint_paths, out_path): data_dict_l = [] avg_param_dict = dict() for path in checkpoint_paths: data_dict = mx.npx.load(path) data_dict_l.append(data_dict) for key in data_dict_l[0]: arr = None for i in range(len(data_dict_l)): if arr is None: arr = data_dict_l[i][key] else: arr += data_dict_l[i][key] arr /= len(data_dict_l) avg_param_dict[key] = arr mx.npx.save(out_path, avg_param_dict) @use_np def set_seed(seed): if seed is None: seed = np.random.randint(0, 100000) mx.random.seed(seed) np.random.seed(seed) random.seed(seed)
402
494
<filename>greenmail-core/src/main/java/com/icegreen/greenmail/store/RootFolder.java<gh_stars>100-1000 /* ------------------------------------------------------------------- * This software is released under the Apache license 2.0 * ------------------------------------------------------------------- */ package com.icegreen.greenmail.store; import com.icegreen.greenmail.imap.ImapConstants; /** * @author <NAME> <<EMAIL>> */ class RootFolder extends HierarchicalFolder { public RootFolder() { super(null, ImapConstants.USER_NAMESPACE); } @Override public String getFullName() { return name; } }
190
5,169
{ "name": "Paymentpage-sdk-ios", "version": "1.9.4", "summary": "Payment page SDK", "description": "SDK for iOS is a software development kit for fast integration of the ECommPay payment solutions right in your mobile app for iOS.", "homepage": "https://github.com/ITECOMMPAY/paymentpage-sdk-ios", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "10.0" }, "source": { "http": "https://github.com/ITECOMMPAY/paymentpage-sdk-ios/releases/download/1.9.4/ecommpaySDK.xcframework.zip" }, "source_files": "ecommpaySDK.xcframework/ios-arm64_armv7/ecommpaySDK.framework/Headers/*.{h,m,swift}", "public_header_files": "ecommpaySDK.xcframework/ios-arm64_armv7/ecommpaySDK.framework/Headers/*.{h,m,swift}", "ios": { "vendored_frameworks": "ecommpaySDK.xcframework" }, "frameworks": [ "UIKit", "Security", "QuartzCore", "OpenGLES", "MobileCoreServices", "Foundation", "CoreGraphics", "CoreVideo", "CoreMedia", "Accelerate", "AudioToolbox", "AVFoundation" ] }
460
4,054
<reponame>mforbes/readthedocs.org<filename>readthedocs/settings/proxito/test.py from ..test import CommunityTestSettings from .base import CommunityProxitoSettingsMixin class CommunityProxitoTestSettings( CommunityProxitoSettingsMixin, CommunityTestSettings ): PUBLIC_DOMAIN = 'dev.readthedocs.io' RTD_BUILD_MEDIA_STORAGE = 'readthedocs.proxito.tests.storage.BuildMediaStorageTest' CommunityProxitoTestSettings.load_settings(__name__)
168
631
package com.neu.his.cloud.service.pms.model; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; public class BmsOperatorSettleRecord implements Serializable { private Long id; private Date startDatetime; private Date endDatetime; private Date createDatetime; private Long cashierId; private Long invoiceNum; private Long rushInvoiceNum; private Long reprintInvoiceNum; private String startEndInvoiceIdStr; private String rushInvoiceIdListStr; private String reprintInvoiceIdListStr; private BigDecimal medicineAmount; private BigDecimal herbalAmount; private BigDecimal checkAmount; private BigDecimal dispositionAmount; private BigDecimal registrationAmount; private BigDecimal testAmount; private BigDecimal amount; private BigDecimal cashAmount; private BigDecimal insuranceAmount; private BigDecimal bankCardAmount; private BigDecimal alipayAmount; private BigDecimal wechatAmount; private BigDecimal creditCardAmount; private BigDecimal otherAmount; private Long verifyOperatorId; private Date verifyDatetime; private Integer verifyStatus; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getStartDatetime() { return startDatetime; } public void setStartDatetime(Date startDatetime) { this.startDatetime = startDatetime; } public Date getEndDatetime() { return endDatetime; } public void setEndDatetime(Date endDatetime) { this.endDatetime = endDatetime; } public Date getCreateDatetime() { return createDatetime; } public void setCreateDatetime(Date createDatetime) { this.createDatetime = createDatetime; } public Long getCashierId() { return cashierId; } public void setCashierId(Long cashierId) { this.cashierId = cashierId; } public Long getInvoiceNum() { return invoiceNum; } public void setInvoiceNum(Long invoiceNum) { this.invoiceNum = invoiceNum; } public Long getRushInvoiceNum() { return rushInvoiceNum; } public void setRushInvoiceNum(Long rushInvoiceNum) { this.rushInvoiceNum = rushInvoiceNum; } public Long getReprintInvoiceNum() { return reprintInvoiceNum; } public void setReprintInvoiceNum(Long reprintInvoiceNum) { this.reprintInvoiceNum = reprintInvoiceNum; } public String getStartEndInvoiceIdStr() { return startEndInvoiceIdStr; } public void setStartEndInvoiceIdStr(String startEndInvoiceIdStr) { this.startEndInvoiceIdStr = startEndInvoiceIdStr; } public String getRushInvoiceIdListStr() { return rushInvoiceIdListStr; } public void setRushInvoiceIdListStr(String rushInvoiceIdListStr) { this.rushInvoiceIdListStr = rushInvoiceIdListStr; } public String getReprintInvoiceIdListStr() { return reprintInvoiceIdListStr; } public void setReprintInvoiceIdListStr(String reprintInvoiceIdListStr) { this.reprintInvoiceIdListStr = reprintInvoiceIdListStr; } public BigDecimal getMedicineAmount() { return medicineAmount; } public void setMedicineAmount(BigDecimal medicineAmount) { this.medicineAmount = medicineAmount; } public BigDecimal getHerbalAmount() { return herbalAmount; } public void setHerbalAmount(BigDecimal herbalAmount) { this.herbalAmount = herbalAmount; } public BigDecimal getCheckAmount() { return checkAmount; } public void setCheckAmount(BigDecimal checkAmount) { this.checkAmount = checkAmount; } public BigDecimal getDispositionAmount() { return dispositionAmount; } public void setDispositionAmount(BigDecimal dispositionAmount) { this.dispositionAmount = dispositionAmount; } public BigDecimal getRegistrationAmount() { return registrationAmount; } public void setRegistrationAmount(BigDecimal registrationAmount) { this.registrationAmount = registrationAmount; } public BigDecimal getTestAmount() { return testAmount; } public void setTestAmount(BigDecimal testAmount) { this.testAmount = testAmount; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public BigDecimal getCashAmount() { return cashAmount; } public void setCashAmount(BigDecimal cashAmount) { this.cashAmount = cashAmount; } public BigDecimal getInsuranceAmount() { return insuranceAmount; } public void setInsuranceAmount(BigDecimal insuranceAmount) { this.insuranceAmount = insuranceAmount; } public BigDecimal getBankCardAmount() { return bankCardAmount; } public void setBankCardAmount(BigDecimal bankCardAmount) { this.bankCardAmount = bankCardAmount; } public BigDecimal getAlipayAmount() { return alipayAmount; } public void setAlipayAmount(BigDecimal alipayAmount) { this.alipayAmount = alipayAmount; } public BigDecimal getWechatAmount() { return wechatAmount; } public void setWechatAmount(BigDecimal wechatAmount) { this.wechatAmount = wechatAmount; } public BigDecimal getCreditCardAmount() { return creditCardAmount; } public void setCreditCardAmount(BigDecimal creditCardAmount) { this.creditCardAmount = creditCardAmount; } public BigDecimal getOtherAmount() { return otherAmount; } public void setOtherAmount(BigDecimal otherAmount) { this.otherAmount = otherAmount; } public Long getVerifyOperatorId() { return verifyOperatorId; } public void setVerifyOperatorId(Long verifyOperatorId) { this.verifyOperatorId = verifyOperatorId; } public Date getVerifyDatetime() { return verifyDatetime; } public void setVerifyDatetime(Date verifyDatetime) { this.verifyDatetime = verifyDatetime; } public Integer getVerifyStatus() { return verifyStatus; } public void setVerifyStatus(Integer verifyStatus) { this.verifyStatus = verifyStatus; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", startDatetime=").append(startDatetime); sb.append(", endDatetime=").append(endDatetime); sb.append(", createDatetime=").append(createDatetime); sb.append(", cashierId=").append(cashierId); sb.append(", invoiceNum=").append(invoiceNum); sb.append(", rushInvoiceNum=").append(rushInvoiceNum); sb.append(", reprintInvoiceNum=").append(reprintInvoiceNum); sb.append(", startEndInvoiceIdStr=").append(startEndInvoiceIdStr); sb.append(", rushInvoiceIdListStr=").append(rushInvoiceIdListStr); sb.append(", reprintInvoiceIdListStr=").append(reprintInvoiceIdListStr); sb.append(", medicineAmount=").append(medicineAmount); sb.append(", herbalAmount=").append(herbalAmount); sb.append(", checkAmount=").append(checkAmount); sb.append(", dispositionAmount=").append(dispositionAmount); sb.append(", registrationAmount=").append(registrationAmount); sb.append(", testAmount=").append(testAmount); sb.append(", amount=").append(amount); sb.append(", cashAmount=").append(cashAmount); sb.append(", insuranceAmount=").append(insuranceAmount); sb.append(", bankCardAmount=").append(bankCardAmount); sb.append(", alipayAmount=").append(alipayAmount); sb.append(", wechatAmount=").append(wechatAmount); sb.append(", creditCardAmount=").append(creditCardAmount); sb.append(", otherAmount=").append(otherAmount); sb.append(", verifyOperatorId=").append(verifyOperatorId); sb.append(", verifyDatetime=").append(verifyDatetime); sb.append(", verifyStatus=").append(verifyStatus); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
3,292
2,151
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_VIDEO_MOCK_GPU_VIDEO_ACCELERATOR_FACTORIES_H_ #define MEDIA_VIDEO_MOCK_GPU_VIDEO_ACCELERATOR_FACTORIES_H_ #include <stddef.h> #include <stdint.h> #include <memory> #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/single_thread_task_runner.h" #include "media/video/gpu_video_accelerator_factories.h" #include "media/video/video_decode_accelerator.h" #include "media/video/video_encode_accelerator.h" #include "services/ui/public/cpp/gpu/context_provider_command_buffer.h" #include "testing/gmock/include/gmock/gmock.h" namespace base { class SharedMemory; } namespace media { class MockGpuVideoAcceleratorFactories : public GpuVideoAcceleratorFactories { public: explicit MockGpuVideoAcceleratorFactories(gpu::gles2::GLES2Interface* gles2); ~MockGpuVideoAcceleratorFactories() override; bool IsGpuVideoAcceleratorEnabled() override; MOCK_METHOD0(GetChannelToken, base::UnguessableToken()); MOCK_METHOD0(GetCommandBufferRouteId, int32_t()); // CreateVideo{Decode,Encode}Accelerator returns scoped_ptr, which the mocking // framework does not want. Trampoline them. MOCK_METHOD0(DoCreateVideoDecodeAccelerator, VideoDecodeAccelerator*()); MOCK_METHOD0(DoCreateVideoEncodeAccelerator, VideoEncodeAccelerator*()); MOCK_METHOD5(CreateTextures, bool(int32_t count, const gfx::Size& size, std::vector<uint32_t>* texture_ids, std::vector<gpu::Mailbox>* texture_mailboxes, uint32_t texture_target)); MOCK_METHOD1(DeleteTexture, void(uint32_t texture_id)); MOCK_METHOD0(CreateSyncToken, gpu::SyncToken()); MOCK_METHOD1(WaitSyncToken, void(const gpu::SyncToken& sync_token)); MOCK_METHOD0(ShallowFlushCHROMIUM, void()); MOCK_METHOD0(GetTaskRunner, scoped_refptr<base::SingleThreadTaskRunner>()); MOCK_METHOD0(GetVideoDecodeAcceleratorCapabilities, VideoDecodeAccelerator::Capabilities()); MOCK_METHOD0(GetVideoEncodeAcceleratorSupportedProfiles, VideoEncodeAccelerator::SupportedProfiles()); MOCK_METHOD0(GetMediaContextProvider, scoped_refptr<ui::ContextProviderCommandBuffer>()); MOCK_METHOD1(SetRenderingColorSpace, void(const gfx::ColorSpace&)); std::unique_ptr<gfx::GpuMemoryBuffer> CreateGpuMemoryBuffer( const gfx::Size& size, gfx::BufferFormat format, gfx::BufferUsage usage) override; bool ShouldUseGpuMemoryBuffersForVideoFrames( bool for_media_stream) const override; unsigned ImageTextureTarget(gfx::BufferFormat format) override; OutputFormat VideoFrameOutputFormat(size_t bit_depth) override { return video_frame_output_format_; }; gpu::gles2::GLES2Interface* ContextGL() override { return gles2_; } void SetVideoFrameOutputFormat(const OutputFormat video_frame_output_format) { video_frame_output_format_ = video_frame_output_format; }; void SetFailToAllocateGpuMemoryBufferForTesting(bool fail) { fail_to_allocate_gpu_memory_buffer_ = fail; } void SetGpuMemoryBuffersInUseByMacOSWindowServer(bool in_use); std::unique_ptr<base::SharedMemory> CreateSharedMemory(size_t size) override; std::unique_ptr<VideoDecodeAccelerator> CreateVideoDecodeAccelerator() override; std::unique_ptr<VideoEncodeAccelerator> CreateVideoEncodeAccelerator() override; gpu::gles2::GLES2Interface* GetGLES2Interface() { return gles2_; } const std::vector<gfx::GpuMemoryBuffer*>& created_memory_buffers() { return created_memory_buffers_; } private: DISALLOW_COPY_AND_ASSIGN(MockGpuVideoAcceleratorFactories); base::Lock lock_; OutputFormat video_frame_output_format_ = OutputFormat::I420; bool fail_to_allocate_gpu_memory_buffer_ = false; gpu::gles2::GLES2Interface* gles2_; std::vector<gfx::GpuMemoryBuffer*> created_memory_buffers_; }; } // namespace media #endif // MEDIA_VIDEO_MOCK_GPU_VIDEO_ACCELERATOR_FACTORIES_H_
1,523
374
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #include "_hypre_sstruct_ls.h" /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGCreate( MPI_Comm comm, HYPRE_SStructSolver *solver ) { hypre_PCGFunctions * pcg_functions = hypre_PCGFunctionsCreate( hypre_SStructKrylovCAlloc, hypre_SStructKrylovFree, hypre_SStructKrylovCommInfo, hypre_SStructKrylovCreateVector, hypre_SStructKrylovDestroyVector, hypre_SStructKrylovMatvecCreate, hypre_SStructKrylovMatvec, hypre_SStructKrylovMatvecDestroy, hypre_SStructKrylovInnerProd, hypre_SStructKrylovCopyVector, hypre_SStructKrylovClearVector, hypre_SStructKrylovScaleVector, hypre_SStructKrylovAxpy, hypre_SStructKrylovIdentitySetup, hypre_SStructKrylovIdentity ); *solver = ( (HYPRE_SStructSolver) hypre_PCGCreate( pcg_functions ) ); return hypre_error_flag; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGDestroy( HYPRE_SStructSolver solver ) { return( hypre_PCGDestroy( (void *) solver ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGSetup( HYPRE_SStructSolver solver, HYPRE_SStructMatrix A, HYPRE_SStructVector b, HYPRE_SStructVector x ) { return( HYPRE_PCGSetup( (HYPRE_Solver) solver, (HYPRE_Matrix) A, (HYPRE_Vector) b, (HYPRE_Vector) x ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGSolve( HYPRE_SStructSolver solver, HYPRE_SStructMatrix A, HYPRE_SStructVector b, HYPRE_SStructVector x ) { return( HYPRE_PCGSolve( (HYPRE_Solver) solver, (HYPRE_Matrix) A, (HYPRE_Vector) b, (HYPRE_Vector) x ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGSetTol( HYPRE_SStructSolver solver, HYPRE_Real tol ) { return( HYPRE_PCGSetTol( (HYPRE_Solver) solver, tol ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGSetAbsoluteTol( HYPRE_SStructSolver solver, HYPRE_Real tol ) { return( HYPRE_PCGSetAbsoluteTol( (HYPRE_Solver) solver, tol ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGSetMaxIter( HYPRE_SStructSolver solver, HYPRE_Int max_iter ) { return( HYPRE_PCGSetMaxIter( (HYPRE_Solver) solver, max_iter ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGSetTwoNorm( HYPRE_SStructSolver solver, HYPRE_Int two_norm ) { return( HYPRE_PCGSetTwoNorm( (HYPRE_Solver) solver, two_norm ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGSetRelChange( HYPRE_SStructSolver solver, HYPRE_Int rel_change ) { return( HYPRE_PCGSetRelChange( (HYPRE_Solver) solver, rel_change ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGSetPrecond( HYPRE_SStructSolver solver, HYPRE_PtrToSStructSolverFcn precond, HYPRE_PtrToSStructSolverFcn precond_setup, void *precond_data ) { return( HYPRE_PCGSetPrecond( (HYPRE_Solver) solver, (HYPRE_PtrToSolverFcn) precond, (HYPRE_PtrToSolverFcn) precond_setup, (HYPRE_Solver) precond_data ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGSetLogging( HYPRE_SStructSolver solver, HYPRE_Int logging ) { return( HYPRE_PCGSetLogging( (HYPRE_Solver) solver, logging ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGSetPrintLevel( HYPRE_SStructSolver solver, HYPRE_Int level ) { return( HYPRE_PCGSetPrintLevel( (HYPRE_Solver) solver, level ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGGetNumIterations( HYPRE_SStructSolver solver, HYPRE_Int *num_iterations ) { return( HYPRE_PCGGetNumIterations( (HYPRE_Solver) solver, num_iterations ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGGetFinalRelativeResidualNorm( HYPRE_SStructSolver solver, HYPRE_Real *norm ) { return( HYPRE_PCGGetFinalRelativeResidualNorm( (HYPRE_Solver) solver, norm ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructPCGGetResidual( HYPRE_SStructSolver solver, void **residual ) { return( HYPRE_PCGGetResidual( (HYPRE_Solver) solver, residual ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructDiagScaleSetup( HYPRE_SStructSolver solver, HYPRE_SStructMatrix A, HYPRE_SStructVector y, HYPRE_SStructVector x ) { return( HYPRE_StructDiagScaleSetup( (HYPRE_StructSolver) solver, (HYPRE_StructMatrix) A, (HYPRE_StructVector) y, (HYPRE_StructVector) x ) ); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_SStructDiagScale( HYPRE_SStructSolver solver, HYPRE_SStructMatrix A, HYPRE_SStructVector y, HYPRE_SStructVector x ) { HYPRE_Int nparts= hypre_SStructMatrixNParts(A); hypre_SStructPMatrix *pA; hypre_SStructPVector *px; hypre_SStructPVector *py; hypre_StructMatrix *sA; hypre_StructVector *sx; hypre_StructVector *sy; HYPRE_Int part, vi; HYPRE_Int nvars; for (part = 0; part < nparts; part++) { pA = hypre_SStructMatrixPMatrix(A, part); px = hypre_SStructVectorPVector(x, part); py = hypre_SStructVectorPVector(y, part); nvars= hypre_SStructPMatrixNVars(pA); for (vi = 0; vi < nvars; vi++) { sA = hypre_SStructPMatrixSMatrix(pA, vi, vi); sx = hypre_SStructPVectorSVector(px, vi); sy = hypre_SStructPVectorSVector(py, vi); HYPRE_StructDiagScale( (HYPRE_StructSolver) solver, (HYPRE_StructMatrix) sA, (HYPRE_StructVector) sy, (HYPRE_StructVector) sx ); } } return hypre_error_flag; }
3,660
348
<gh_stars>100-1000 {"nom":"Port-sur-Seille","circ":"6ème circonscription","dpt":"Meurthe-et-Moselle","inscrits":193,"abs":113,"votants":80,"blancs":13,"nuls":3,"exp":64,"res":[{"nuance":"FI","nom":"<NAME>","voix":44},{"nuance":"FN","nom":"<NAME>","voix":20}]}
108
2,209
"""An implementation of Matching Layer.""" import typing import tensorflow as tf from keras.engine import Layer class MatchingLayer(Layer): """ Layer that computes a matching matrix between samples in two tensors. :param normalize: Whether to L2-normalize samples along the dot product axis before taking the dot product. If set to True, then the output of the dot product is the cosine proximity between the two samples. :param matching_type: the similarity function for matching :param kwargs: Standard layer keyword arguments. Examples: >>> import matchzoo as mz >>> layer = mz.layers.MatchingLayer(matching_type='dot', ... normalize=True) >>> num_batch, left_len, right_len, num_dim = 5, 3, 2, 10 >>> layer.build([[num_batch, left_len, num_dim], ... [num_batch, right_len, num_dim]]) """ def __init__(self, normalize: bool = False, matching_type: str = 'dot', **kwargs): """:class:`MatchingLayer` constructor.""" super().__init__(**kwargs) self._normalize = normalize self._validate_matching_type(matching_type) self._matching_type = matching_type self._shape1 = None self._shape2 = None @classmethod def _validate_matching_type(cls, matching_type: str = 'dot'): valid_matching_type = ['dot', 'mul', 'plus', 'minus', 'concat'] if matching_type not in valid_matching_type: raise ValueError(f"{matching_type} is not a valid matching type, " f"{valid_matching_type} expected.") def build(self, input_shape: list): """ Build the layer. :param input_shape: the shapes of the input tensors, for MatchingLayer we need tow input tensors. """ # Used purely for shape validation. if not isinstance(input_shape, list) or len(input_shape) != 2: raise ValueError('A `MatchingLayer` layer should be called ' 'on a list of 2 inputs.') self._shape1 = input_shape[0] self._shape2 = input_shape[1] for idx in 0, 2: if self._shape1[idx] != self._shape2[idx]: raise ValueError( 'Incompatible dimensions: ' f'{self._shape1[idx]} != {self._shape2[idx]}.' f'Layer shapes: {self._shape1}, {self._shape2}.' ) def call(self, inputs: list, **kwargs) -> typing.Any: """ The computation logic of MatchingLayer. :param inputs: two input tensors. """ x1 = inputs[0] x2 = inputs[1] if self._matching_type == 'dot': if self._normalize: x1 = tf.math.l2_normalize(x1, axis=2) x2 = tf.math.l2_normalize(x2, axis=2) return tf.expand_dims(tf.einsum('abd,acd->abc', x1, x2), 3) else: if self._matching_type == 'mul': def func(x, y): return x * y elif self._matching_type == 'plus': def func(x, y): return x + y elif self._matching_type == 'minus': def func(x, y): return x - y elif self._matching_type == 'concat': def func(x, y): return tf.concat([x, y], axis=3) else: raise ValueError(f"Invalid matching type." f"{self._matching_type} received." f"Mut be in `dot`, `mul`, `plus`, " f"`minus` and `concat`.") x1_exp = tf.stack([x1] * self._shape2[1], 2) x2_exp = tf.stack([x2] * self._shape1[1], 1) return func(x1_exp, x2_exp) def compute_output_shape(self, input_shape: list) -> tuple: """ Calculate the layer output shape. :param input_shape: the shapes of the input tensors, for MatchingLayer we need tow input tensors. """ if not isinstance(input_shape, list) or len(input_shape) != 2: raise ValueError('A `MatchingLayer` layer should be called ' 'on a list of 2 inputs.') shape1 = list(input_shape[0]) shape2 = list(input_shape[1]) if len(shape1) != 3 or len(shape2) != 3: raise ValueError('A `MatchingLayer` layer should be called ' 'on 2 inputs with 3 dimensions.') if shape1[0] != shape2[0] or shape1[2] != shape2[2]: raise ValueError('A `MatchingLayer` layer should be called ' 'on 2 inputs with same 0,2 dimensions.') if self._matching_type in ['mul', 'plus', 'minus']: return shape1[0], shape1[1], shape2[1], shape1[2] elif self._matching_type == 'dot': return shape1[0], shape1[1], shape2[1], 1 elif self._matching_type == 'concat': return shape1[0], shape1[1], shape2[1], shape1[2] + shape2[2] else: raise ValueError(f"Invalid `matching_type`." f"{self._matching_type} received." f"Must be in `mul`, `plus`, `minus` " f"`dot` and `concat`.") def get_config(self) -> dict: """Get the config dict of MatchingLayer.""" config = { 'normalize': self._normalize, 'matching_type': self._matching_type, } base_config = super(MatchingLayer, self).get_config() return dict(list(base_config.items()) + list(config.items()))
2,850
852
<gh_stars>100-1000 #ifndef RecoLocalTracker_SiPhase2Clusterizer_Phase2TrackerClusterizerSequentialAlgorithm_h #define RecoLocalTracker_SiPhase2Clusterizer_Phase2TrackerClusterizerSequentialAlgorithm_h #include "DataFormats/Common/interface/DetSetVector.h" #include "DataFormats/Common/interface/DetSetVectorNew.h" #include "DataFormats/Phase2TrackerDigi/interface/Phase2TrackerDigi.h" #include "DataFormats/Phase2TrackerCluster/interface/Phase2TrackerCluster1D.h" class Phase2TrackerClusterizerSequentialAlgorithm { public: inline void clusterizeDetUnit(const edm::DetSet<Phase2TrackerDigi>&, Phase2TrackerCluster1DCollectionNew::FastFiller&) const; }; void Phase2TrackerClusterizerSequentialAlgorithm::clusterizeDetUnit( const edm::DetSet<Phase2TrackerDigi>& digis, Phase2TrackerCluster1DCollectionNew::FastFiller& clusters) const { if (digis.empty()) return; auto di = digis.begin(); unsigned int sizeCluster = 1; Phase2TrackerDigi firstDigi = *di; bool HIPbit = firstDigi.overThreshold(); auto previous = firstDigi; ++di; for (; di != digis.end(); ++di) { auto digi = *di; #ifdef VERIFY_PH2_TK_CLUS if (!(previous < digi)) std::cout << "not ordered " << previous << ' ' << digi << std::endl; #endif if (digi - previous == 1) { HIPbit |= digi.overThreshold(); ++sizeCluster; } else { clusters.push_back(Phase2TrackerCluster1D(firstDigi, sizeCluster, HIPbit)); firstDigi = digi; HIPbit = digi.overThreshold(); sizeCluster = 1; } previous = digi; } clusters.push_back(Phase2TrackerCluster1D(firstDigi, sizeCluster, HIPbit)); } #endif
639
989
{ "properties": [ { "name": "streamx.shiro.anonUrl", "type": "java.lang.String", "description": "Description for streamx.shiro.anonUrl." }, { "name": "streamx.shiro.jwtTimeOut", "type": "java.lang.String", "description": "Description for streamx.shiro.jwtTimeOut." }, { "name": "streamx.hdfs.workspace", "type": "java.lang.String", "description": "Description for streamx.hdfs.workspace." }, { "name": "streamx.docker.register.image-namespace", "type": "java.lang.String", "description": "Description for streamx.docker.register.image-namespace." }, { "name": "streamx.flink-k8s.tracking.silent-state-keep-sec", "type": "java.lang.String", "description": "Description for streamx.flink-k8s.tracking.silent-state-keep-sec." }, { "name": "streamx.flink-k8s.tracking.polling-task-timeout-sec.job-status", "type": "java.lang.String", "description": "Description for streamx.flink-k8s.tracking.polling-task-timeout-sec.job-status." }, { "name": "streamx.flink-k8s.tracking.polling-task-timeout-sec.cluster-metric", "type": "java.lang.String", "description": "Description for streamx.flink-k8s.tracking.polling-task-timeout-sec.cluster-metric." }, { "name": "streamx.flink-k8s.tracking.polling-interval-sec.job-status", "type": "java.lang.String", "description": "Description for streamx.flink-k8s.tracking.polling-interval-sec.job-status." }, { "name": "streamx.flink-k8s.tracking.polling-interval-sec.cluster-metric", "type": "java.lang.String", "description": "Description for streamx.flink-k8s.tracking.polling-interval-sec.cluster-metric." }, { "name": "spring.devtools.restart.enabled", "type": "java.lang.String", "description": "Description for spring.devtools.restart.enabled." }, { "name": "streamx.workspace.local", "type": "java.lang.String", "description": "Description for streamx.workspace.local." }, { "name": "streamx.workspace.remote", "type": "java.lang.String", "description": "Description for streamx.workspace.remote." } ] }
971
10,225
package io.quarkus.grpc.runtime.config; import java.time.Duration; import java.util.Optional; import io.quarkus.runtime.annotations.ConfigGroup; import io.quarkus.runtime.annotations.ConfigItem; @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @ConfigGroup public class GrpcServerNettyConfig { /** * Sets a custom keep-alive duration. This configures the time before sending a `keepalive` ping * when there is no read activity. */ @ConfigItem public Optional<Duration> keepAliveTime; }
173
413
#!/usr/bin/env python3 import argparse import numpy as np import numpy.random as npr import torch import os, sys import shutil import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt plt.style.use('bmh') def main(): parser = argparse.ArgumentParser() parser.add_argument('--minBps', type=int, default=1) parser.add_argument('--maxBps', type=int, default=10) parser.add_argument('--seqLen', type=int, default=100) parser.add_argument('--minHeight', type=int, default=10) parser.add_argument('--maxHeight', type=int, default=100) parser.add_argument('--noise', type=float, default=10) parser.add_argument('--nSamples', type=int, default=10000) parser.add_argument('--save', type=str, default='data/synthetic') args = parser.parse_args() npr.seed(0) save = args.save if os.path.isdir(save): shutil.rmtree(save) os.makedirs(save) X, Y = [], [] for i in range(args.nSamples): Xi, Yi = sample(args) X.append(Xi); Y.append(Yi) if i == 0: fig, ax = plt.subplots(1, 1) plt.plot(Xi, label='Corrupted') plt.plot(Yi, label='Original') plt.legend() f = os.path.join(args.save, "example.png") fig.savefig(f) print("Created {}".format(f)) X = np.array(X) Y = np.array(Y) for loc,arr in (('features.pt', X), ('labels.pt', Y)): fname = os.path.join(args.save, loc) with open(fname, 'wb') as f: torch.save(torch.Tensor(arr), f) print("Created {}".format(fname)) def sample(args): nBps = npr.randint(args.minBps, args.maxBps) bpLocs = [0] + sorted(npr.choice(args.seqLen-2, nBps-1, replace=False)+1) + [args.seqLen] bpDiffs = np.diff(bpLocs) heights = npr.randint(args.minHeight, args.maxHeight, nBps) Y = [] for d, h in zip(bpDiffs, heights): Y += [h]*d Y = np.array(Y, dtype=np.float) X = Y + npr.normal(0, args.noise, (args.seqLen)) return X, Y if __name__=='__main__': main()
964
4,223
<filename>Xcode/Examples/Tests/AutoPingTest/Mobile/AutoPingTest/AutoPingTestViewController.h // // AutoPingTestViewController.h // AutoPingTest // // Created by <NAME> on 9/1/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> @interface AutoPingTestViewController : UIViewController @end
112
679
/************************************************************** * * 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 com.sun.star.wizards.ui.event; import java.util.List; import java.util.Vector; /** * @author rpiterman * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class Task { private int successfull = 0; private int failed = 0; private int max = 0; private String taskName; private List listeners = new Vector(); private String subtaskName; public Task(String taskName_, String subtaskName_, int max_) { taskName = taskName_; subtaskName = subtaskName_; max = max_; } public void start() { fireTaskStarted(); } public void fail() { fireTaskFailed(); } public int getMax() { return max; } public void setMax(int max_) { max = max_; fireTaskStatusChanged(); } public void advance(boolean success_) { if (success_) { successfull++; } else { failed++; } fireTaskStatusChanged(); if (failed + successfull == max) { fireTaskFinished(); } } public void advance(boolean success_, String nextSubtaskName) { advance(success_); setSubtaskName(nextSubtaskName); } public int getStatus() { return successfull + failed; } public void addTaskListener(TaskListener tl) { listeners.add(tl); } public void removeTaskListener(TaskListener tl) { listeners.remove(tl); } protected void fireTaskStatusChanged() { TaskEvent te = new TaskEvent(this, TaskEvent.TASK_STATUS_CHANGED); for (int i = 0; i < listeners.size(); i++) { ((TaskListener) listeners.get(i)).taskStatusChanged(te); } } protected void fireTaskStarted() { TaskEvent te = new TaskEvent(this, TaskEvent.TASK_STARTED); for (int i = 0; i < listeners.size(); i++) { ((TaskListener) listeners.get(i)).taskStarted(te); } } protected void fireTaskFailed() { TaskEvent te = new TaskEvent(this, TaskEvent.TASK_FAILED); for (int i = 0; i < listeners.size(); i++) { ((TaskListener) listeners.get(i)).taskFinished(te); } } protected void fireTaskFinished() { TaskEvent te = new TaskEvent(this, TaskEvent.TASK_FINISHED); for (int i = 0; i < listeners.size(); i++) { ((TaskListener) listeners.get(i)).taskFinished(te); } } protected void fireSubtaskNameChanged() { TaskEvent te = new TaskEvent(this, TaskEvent.SUBTASK_NAME_CHANGED); for (int i = 0; i < listeners.size(); i++) { ((TaskListener) listeners.get(i)).subtaskNameChanged(te); } } /** * @return */ public String getSubtaskName() { return subtaskName; } /** * @return */ public String getTaskName() { return taskName; } /** * @param string */ public void setSubtaskName(String string) { subtaskName = string; fireSubtaskNameChanged(); } /** * @return */ public int getFailed() { return failed; } /** * @return */ public int getSuccessfull() { return successfull; } }
1,800
729
<gh_stars>100-1000 // Generated by the protocol buffer compiler. DO NOT EDIT! // source: enums.proto package org.jigsaw.payment.model; /** * <pre> ** * 状态码 * </pre> * * Protobuf enum {@code StatusCode} */ public enum StatusCode implements com.google.protobuf.ProtocolMessageEnum { /** * <code>SUCCESS = 0;</code> */ SUCCESS(0), /** * <pre> *通用错误 * </pre> * * <code>UNKNOWN = 1;</code> */ UNKNOWN(1), /** * <code>BAD_DATA_FORMAT = 2;</code> */ BAD_DATA_FORMAT(2), /** * <code>PERMISSION_DENIED = 3;</code> */ PERMISSION_DENIED(3), /** * <code>INTERNAL_ERROR = 4;</code> */ INTERNAL_ERROR(4), /** * <code>DATA_REQUIRED = 5;</code> */ DATA_REQUIRED(5), /** * <code>LIMIT_REACHED = 6;</code> */ LIMIT_REACHED(6), /** * <code>QUOTA_REACHED = 7;</code> */ QUOTA_REACHED(7), /** * <code>INVALID_AUTH = 8;</code> */ INVALID_AUTH(8), /** * <code>AUTH_EXPIRED = 9;</code> */ AUTH_EXPIRED(9), /** * <code>DATA_CONFLICT = 10;</code> */ DATA_CONFLICT(10), /** * <code>ENML_VALIDATION = 11;</code> */ ENML_VALIDATION(11), /** * <code>SHARD_UNAVAILABLE = 12;</code> */ SHARD_UNAVAILABLE(12), /** * <code>LEN_TOO_SHORT = 13;</code> */ LEN_TOO_SHORT(13), /** * <code>LEN_TOO_LONG = 14;</code> */ LEN_TOO_LONG(14), /** * <code>TOO_FEW = 15;</code> */ TOO_FEW(15), /** * <code>TOO_MANY = 16;</code> */ TOO_MANY(16), /** * <code>UNSUPPORTED_OPERATION = 17;</code> */ UNSUPPORTED_OPERATION(17), /** * <code>TAKEN_DOWN = 18;</code> */ TAKEN_DOWN(18), /** * <code>RATE_LIMIT_REACHED = 19;</code> */ RATE_LIMIT_REACHED(19), /** * <code>BUSINESS_SECURITY_LOGIN_REQUIRED = 20;</code> */ BUSINESS_SECURITY_LOGIN_REQUIRED(20), /** * <code>DEVICE_LIMIT_REACHED = 21;</code> */ DEVICE_LIMIT_REACHED(21), /** * <pre> *优惠券相关错误代码 * </pre> * * <code>ERROR_COUPONS_FORMAT_INPUT = 101;</code> */ ERROR_COUPONS_FORMAT_INPUT(101), /** * <code>ERROR_COUPON_LOCK = 102;</code> */ ERROR_COUPON_LOCK(102), /** * <code>ERROR_COUPON_USE_EXPIRED = 103;</code> */ ERROR_COUPON_USE_EXPIRED(103), /** * <code>ERROR_COUPON_USE_UNACTIVATED = 104;</code> */ ERROR_COUPON_USE_UNACTIVATED(104), /** * <code>ERROR_COUPON_USE_FROZEN = 105;</code> */ ERROR_COUPON_USE_FROZEN(105), /** * <code>ERROR_COUPON_USE_USED = 106;</code> */ ERROR_COUPON_USE_USED(106), /** * <code>ERROR_COUPON_USE_LOCKED = 107;</code> */ ERROR_COUPON_USE_LOCKED(107), /** * <code>ERROR_COUPON_USE_DESTROYED = 108;</code> */ ERROR_COUPON_USE_DESTROYED(108), /** * <code>ERROR_COUPON_TYPE_CANT_OP = 109;</code> */ ERROR_COUPON_TYPE_CANT_OP(109), /** * <code>ERROR_COUPON_TYPE_CANT_DIRECT_CONSUME = 110;</code> */ ERROR_COUPON_TYPE_CANT_DIRECT_CONSUME(110), /** * <code>ERROR_COUPON_USE_UNSTARTED = 111;</code> */ ERROR_COUPON_USE_UNSTARTED(111), /** * <code>ERROR_ORDER_COUPON_NULL = 112;</code> */ ERROR_ORDER_COUPON_NULL(112), /** * <code>ERROR_ORDER_COUPON_NOT_ALL_LOCK = 113;</code> */ ERROR_ORDER_COUPON_NOT_ALL_LOCK(113), /** * <code>ERROR_COUPON_SEND_UNHAND = 114;</code> */ ERROR_COUPON_SEND_UNHAND(114), /** * <code>ERROR_COUPON_SEND_ACTIVATING = 115;</code> */ ERROR_COUPON_SEND_ACTIVATING(115), /** * <code>ERROR_COUPON_SEND_DESTROYED = 116;</code> */ ERROR_COUPON_SEND_DESTROYED(116), /** * <code>ERROR_COUPON_SEND_LOCKED = 117;</code> */ ERROR_COUPON_SEND_LOCKED(117), /** * <code>ERROR_COUPON_SEND_NO_ENOUGH = 118;</code> */ ERROR_COUPON_SEND_NO_ENOUGH(118), /** * <code>ERROR_COUPON_SEND_TIME_EXPIRED = 119;</code> */ ERROR_COUPON_SEND_TIME_EXPIRED(119), /** * <code>ERROR_COUPON_BATCH_UNAVAILABLE = 120;</code> */ ERROR_COUPON_BATCH_UNAVAILABLE(120), /** * <code>ERROR_ORDER_COUPON_NOT_ALL_VALID = 121;</code> */ ERROR_ORDER_COUPON_NOT_ALL_VALID(121), /** * <code>ERROR_COUPON_BATCH_SEND_UNAVAILABLE = 122;</code> */ ERROR_COUPON_BATCH_SEND_UNAVAILABLE(122), /** * <code>ERROR_COUPON_BIND_LIMIT = 123;</code> */ ERROR_COUPON_BIND_LIMIT(123), /** * <code>ERROR_COUPON_BATCH_NULL = 124;</code> */ ERROR_COUPON_BATCH_NULL(124), /** * <code>ERROR_COUPON_NULL = 125;</code> */ ERROR_COUPON_NULL(125), /** * <code>ERROR_COUPON_BIND_NOT_BELONG_PARTNER = 126;</code> */ ERROR_COUPON_BIND_NOT_BELONG_PARTNER(126), /** * <code>ERROR_COUPON_BIND_IS_SENT = 127;</code> */ ERROR_COUPON_BIND_IS_SENT(127), /** * <code>ERROR_COUPON_BIND_STATUS_NOT_UNUSED = 128;</code> */ ERROR_COUPON_BIND_STATUS_NOT_UNUSED(128), /** * <code>ERROR_COUPON_CONSUME_ERROR = 129;</code> */ ERROR_COUPON_CONSUME_ERROR(129), /** * <code>ERROR_COUPON_BIND_OVER_LIMIT = 130;</code> */ ERROR_COUPON_BIND_OVER_LIMIT(130), /** * <pre> *安全相关的错误 * </pre> * * <code>ERROR_PASSWORD_NOT_SET = 201;</code> */ ERROR_PASSWORD_NOT_SET(201), /** * <code>ERROR_PASSWORD_SAVE_FAIL = 202;</code> */ ERROR_PASSWORD_SAVE_FAIL(202), /** * <code>ERROR_PASSWORD_INVALID = 203;</code> */ ERROR_PASSWORD_INVALID(203), /** * <code>ERROR_PASSWORD_FROZEN = 204;</code> */ ERROR_PASSWORD_FROZEN(204), /** * <code>ERROR_IDCARD_INVALID = 205;</code> */ ERROR_IDCARD_INVALID(205), /** * <code>ERROR_MOBILE_NOT_SET = 206;</code> */ ERROR_MOBILE_NOT_SET(206), /** * <code>ERROR_NAME_IDCARD_NOT_MATCH = 207;</code> */ ERROR_NAME_IDCARD_NOT_MATCH(207), /** * <code>ERROR_ACCOUNT_FROZEN = 208;</code> */ ERROR_ACCOUNT_FROZEN(208), /** * <code>ERROR_ACCOUNT_INACTIVE = 209;</code> */ ERROR_ACCOUNT_INACTIVE(209), /** * <code>ERROR_PASSWORD_WRONG = 210;</code> */ ERROR_PASSWORD_WRONG(210), /** * <pre> *账户相关的错误 * </pre> * * <code>ERROR_ACCOUNT_UNAVAILABLE = 301;</code> */ ERROR_ACCOUNT_UNAVAILABLE(301), /** * <pre> *账户余额不足 * </pre> * * <code>ERROR_ACCOUNT_BALANCE_NOT_ENOUGH = 302;</code> */ ERROR_ACCOUNT_BALANCE_NOT_ENOUGH(302), /** * <pre> *订单相关的错误 * </pre> * * <code>ERROR_ORDER_ALREADY_PAID = 401;</code> */ ERROR_ORDER_ALREADY_PAID(401), ; /** * <code>SUCCESS = 0;</code> */ public static final int SUCCESS_VALUE = 0; /** * <pre> *通用错误 * </pre> * * <code>UNKNOWN = 1;</code> */ public static final int UNKNOWN_VALUE = 1; /** * <code>BAD_DATA_FORMAT = 2;</code> */ public static final int BAD_DATA_FORMAT_VALUE = 2; /** * <code>PERMISSION_DENIED = 3;</code> */ public static final int PERMISSION_DENIED_VALUE = 3; /** * <code>INTERNAL_ERROR = 4;</code> */ public static final int INTERNAL_ERROR_VALUE = 4; /** * <code>DATA_REQUIRED = 5;</code> */ public static final int DATA_REQUIRED_VALUE = 5; /** * <code>LIMIT_REACHED = 6;</code> */ public static final int LIMIT_REACHED_VALUE = 6; /** * <code>QUOTA_REACHED = 7;</code> */ public static final int QUOTA_REACHED_VALUE = 7; /** * <code>INVALID_AUTH = 8;</code> */ public static final int INVALID_AUTH_VALUE = 8; /** * <code>AUTH_EXPIRED = 9;</code> */ public static final int AUTH_EXPIRED_VALUE = 9; /** * <code>DATA_CONFLICT = 10;</code> */ public static final int DATA_CONFLICT_VALUE = 10; /** * <code>ENML_VALIDATION = 11;</code> */ public static final int ENML_VALIDATION_VALUE = 11; /** * <code>SHARD_UNAVAILABLE = 12;</code> */ public static final int SHARD_UNAVAILABLE_VALUE = 12; /** * <code>LEN_TOO_SHORT = 13;</code> */ public static final int LEN_TOO_SHORT_VALUE = 13; /** * <code>LEN_TOO_LONG = 14;</code> */ public static final int LEN_TOO_LONG_VALUE = 14; /** * <code>TOO_FEW = 15;</code> */ public static final int TOO_FEW_VALUE = 15; /** * <code>TOO_MANY = 16;</code> */ public static final int TOO_MANY_VALUE = 16; /** * <code>UNSUPPORTED_OPERATION = 17;</code> */ public static final int UNSUPPORTED_OPERATION_VALUE = 17; /** * <code>TAKEN_DOWN = 18;</code> */ public static final int TAKEN_DOWN_VALUE = 18; /** * <code>RATE_LIMIT_REACHED = 19;</code> */ public static final int RATE_LIMIT_REACHED_VALUE = 19; /** * <code>BUSINESS_SECURITY_LOGIN_REQUIRED = 20;</code> */ public static final int BUSINESS_SECURITY_LOGIN_REQUIRED_VALUE = 20; /** * <code>DEVICE_LIMIT_REACHED = 21;</code> */ public static final int DEVICE_LIMIT_REACHED_VALUE = 21; /** * <pre> *优惠券相关错误代码 * </pre> * * <code>ERROR_COUPONS_FORMAT_INPUT = 101;</code> */ public static final int ERROR_COUPONS_FORMAT_INPUT_VALUE = 101; /** * <code>ERROR_COUPON_LOCK = 102;</code> */ public static final int ERROR_COUPON_LOCK_VALUE = 102; /** * <code>ERROR_COUPON_USE_EXPIRED = 103;</code> */ public static final int ERROR_COUPON_USE_EXPIRED_VALUE = 103; /** * <code>ERROR_COUPON_USE_UNACTIVATED = 104;</code> */ public static final int ERROR_COUPON_USE_UNACTIVATED_VALUE = 104; /** * <code>ERROR_COUPON_USE_FROZEN = 105;</code> */ public static final int ERROR_COUPON_USE_FROZEN_VALUE = 105; /** * <code>ERROR_COUPON_USE_USED = 106;</code> */ public static final int ERROR_COUPON_USE_USED_VALUE = 106; /** * <code>ERROR_COUPON_USE_LOCKED = 107;</code> */ public static final int ERROR_COUPON_USE_LOCKED_VALUE = 107; /** * <code>ERROR_COUPON_USE_DESTROYED = 108;</code> */ public static final int ERROR_COUPON_USE_DESTROYED_VALUE = 108; /** * <code>ERROR_COUPON_TYPE_CANT_OP = 109;</code> */ public static final int ERROR_COUPON_TYPE_CANT_OP_VALUE = 109; /** * <code>ERROR_COUPON_TYPE_CANT_DIRECT_CONSUME = 110;</code> */ public static final int ERROR_COUPON_TYPE_CANT_DIRECT_CONSUME_VALUE = 110; /** * <code>ERROR_COUPON_USE_UNSTARTED = 111;</code> */ public static final int ERROR_COUPON_USE_UNSTARTED_VALUE = 111; /** * <code>ERROR_ORDER_COUPON_NULL = 112;</code> */ public static final int ERROR_ORDER_COUPON_NULL_VALUE = 112; /** * <code>ERROR_ORDER_COUPON_NOT_ALL_LOCK = 113;</code> */ public static final int ERROR_ORDER_COUPON_NOT_ALL_LOCK_VALUE = 113; /** * <code>ERROR_COUPON_SEND_UNHAND = 114;</code> */ public static final int ERROR_COUPON_SEND_UNHAND_VALUE = 114; /** * <code>ERROR_COUPON_SEND_ACTIVATING = 115;</code> */ public static final int ERROR_COUPON_SEND_ACTIVATING_VALUE = 115; /** * <code>ERROR_COUPON_SEND_DESTROYED = 116;</code> */ public static final int ERROR_COUPON_SEND_DESTROYED_VALUE = 116; /** * <code>ERROR_COUPON_SEND_LOCKED = 117;</code> */ public static final int ERROR_COUPON_SEND_LOCKED_VALUE = 117; /** * <code>ERROR_COUPON_SEND_NO_ENOUGH = 118;</code> */ public static final int ERROR_COUPON_SEND_NO_ENOUGH_VALUE = 118; /** * <code>ERROR_COUPON_SEND_TIME_EXPIRED = 119;</code> */ public static final int ERROR_COUPON_SEND_TIME_EXPIRED_VALUE = 119; /** * <code>ERROR_COUPON_BATCH_UNAVAILABLE = 120;</code> */ public static final int ERROR_COUPON_BATCH_UNAVAILABLE_VALUE = 120; /** * <code>ERROR_ORDER_COUPON_NOT_ALL_VALID = 121;</code> */ public static final int ERROR_ORDER_COUPON_NOT_ALL_VALID_VALUE = 121; /** * <code>ERROR_COUPON_BATCH_SEND_UNAVAILABLE = 122;</code> */ public static final int ERROR_COUPON_BATCH_SEND_UNAVAILABLE_VALUE = 122; /** * <code>ERROR_COUPON_BIND_LIMIT = 123;</code> */ public static final int ERROR_COUPON_BIND_LIMIT_VALUE = 123; /** * <code>ERROR_COUPON_BATCH_NULL = 124;</code> */ public static final int ERROR_COUPON_BATCH_NULL_VALUE = 124; /** * <code>ERROR_COUPON_NULL = 125;</code> */ public static final int ERROR_COUPON_NULL_VALUE = 125; /** * <code>ERROR_COUPON_BIND_NOT_BELONG_PARTNER = 126;</code> */ public static final int ERROR_COUPON_BIND_NOT_BELONG_PARTNER_VALUE = 126; /** * <code>ERROR_COUPON_BIND_IS_SENT = 127;</code> */ public static final int ERROR_COUPON_BIND_IS_SENT_VALUE = 127; /** * <code>ERROR_COUPON_BIND_STATUS_NOT_UNUSED = 128;</code> */ public static final int ERROR_COUPON_BIND_STATUS_NOT_UNUSED_VALUE = 128; /** * <code>ERROR_COUPON_CONSUME_ERROR = 129;</code> */ public static final int ERROR_COUPON_CONSUME_ERROR_VALUE = 129; /** * <code>ERROR_COUPON_BIND_OVER_LIMIT = 130;</code> */ public static final int ERROR_COUPON_BIND_OVER_LIMIT_VALUE = 130; /** * <pre> *安全相关的错误 * </pre> * * <code>ERROR_PASSWORD_NOT_SET = 201;</code> */ public static final int ERROR_PASSWORD_NOT_SET_VALUE = 201; /** * <code>ERROR_PASSWORD_SAVE_FAIL = 202;</code> */ public static final int ERROR_PASSWORD_SAVE_FAIL_VALUE = 202; /** * <code>ERROR_PASSWORD_INVALID = 203;</code> */ public static final int ERROR_PASSWORD_INVALID_VALUE = 203; /** * <code>ERROR_PASSWORD_FROZEN = 204;</code> */ public static final int ERROR_PASSWORD_FROZEN_VALUE = 204; /** * <code>ERROR_IDCARD_INVALID = 205;</code> */ public static final int ERROR_IDCARD_INVALID_VALUE = 205; /** * <code>ERROR_MOBILE_NOT_SET = 206;</code> */ public static final int ERROR_MOBILE_NOT_SET_VALUE = 206; /** * <code>ERROR_NAME_IDCARD_NOT_MATCH = 207;</code> */ public static final int ERROR_NAME_IDCARD_NOT_MATCH_VALUE = 207; /** * <code>ERROR_ACCOUNT_FROZEN = 208;</code> */ public static final int ERROR_ACCOUNT_FROZEN_VALUE = 208; /** * <code>ERROR_ACCOUNT_INACTIVE = 209;</code> */ public static final int ERROR_ACCOUNT_INACTIVE_VALUE = 209; /** * <code>ERROR_PASSWORD_WRONG = 210;</code> */ public static final int ERROR_PASSWORD_WRONG_VALUE = 210; /** * <pre> *账户相关的错误 * </pre> * * <code>ERROR_ACCOUNT_UNAVAILABLE = 301;</code> */ public static final int ERROR_ACCOUNT_UNAVAILABLE_VALUE = 301; /** * <pre> *账户余额不足 * </pre> * * <code>ERROR_ACCOUNT_BALANCE_NOT_ENOUGH = 302;</code> */ public static final int ERROR_ACCOUNT_BALANCE_NOT_ENOUGH_VALUE = 302; /** * <pre> *订单相关的错误 * </pre> * * <code>ERROR_ORDER_ALREADY_PAID = 401;</code> */ public static final int ERROR_ORDER_ALREADY_PAID_VALUE = 401; public final int getNumber() { return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static StatusCode valueOf(int value) { return forNumber(value); } public static StatusCode forNumber(int value) { switch (value) { case 0: return SUCCESS; case 1: return UNKNOWN; case 2: return BAD_DATA_FORMAT; case 3: return PERMISSION_DENIED; case 4: return INTERNAL_ERROR; case 5: return DATA_REQUIRED; case 6: return LIMIT_REACHED; case 7: return QUOTA_REACHED; case 8: return INVALID_AUTH; case 9: return AUTH_EXPIRED; case 10: return DATA_CONFLICT; case 11: return ENML_VALIDATION; case 12: return SHARD_UNAVAILABLE; case 13: return LEN_TOO_SHORT; case 14: return LEN_TOO_LONG; case 15: return TOO_FEW; case 16: return TOO_MANY; case 17: return UNSUPPORTED_OPERATION; case 18: return TAKEN_DOWN; case 19: return RATE_LIMIT_REACHED; case 20: return BUSINESS_SECURITY_LOGIN_REQUIRED; case 21: return DEVICE_LIMIT_REACHED; case 101: return ERROR_COUPONS_FORMAT_INPUT; case 102: return ERROR_COUPON_LOCK; case 103: return ERROR_COUPON_USE_EXPIRED; case 104: return ERROR_COUPON_USE_UNACTIVATED; case 105: return ERROR_COUPON_USE_FROZEN; case 106: return ERROR_COUPON_USE_USED; case 107: return ERROR_COUPON_USE_LOCKED; case 108: return ERROR_COUPON_USE_DESTROYED; case 109: return ERROR_COUPON_TYPE_CANT_OP; case 110: return ERROR_COUPON_TYPE_CANT_DIRECT_CONSUME; case 111: return ERROR_COUPON_USE_UNSTARTED; case 112: return ERROR_ORDER_COUPON_NULL; case 113: return ERROR_ORDER_COUPON_NOT_ALL_LOCK; case 114: return ERROR_COUPON_SEND_UNHAND; case 115: return ERROR_COUPON_SEND_ACTIVATING; case 116: return ERROR_COUPON_SEND_DESTROYED; case 117: return ERROR_COUPON_SEND_LOCKED; case 118: return ERROR_COUPON_SEND_NO_ENOUGH; case 119: return ERROR_COUPON_SEND_TIME_EXPIRED; case 120: return ERROR_COUPON_BATCH_UNAVAILABLE; case 121: return ERROR_ORDER_COUPON_NOT_ALL_VALID; case 122: return ERROR_COUPON_BATCH_SEND_UNAVAILABLE; case 123: return ERROR_COUPON_BIND_LIMIT; case 124: return ERROR_COUPON_BATCH_NULL; case 125: return ERROR_COUPON_NULL; case 126: return ERROR_COUPON_BIND_NOT_BELONG_PARTNER; case 127: return ERROR_COUPON_BIND_IS_SENT; case 128: return ERROR_COUPON_BIND_STATUS_NOT_UNUSED; case 129: return ERROR_COUPON_CONSUME_ERROR; case 130: return ERROR_COUPON_BIND_OVER_LIMIT; case 201: return ERROR_PASSWORD_NOT_SET; case 202: return ERROR_PASSWORD_SAVE_FAIL; case 203: return ERROR_PASSWORD_INVALID; case 204: return ERROR_PASSWORD_FROZEN; case 205: return ERROR_IDCARD_INVALID; case 206: return ERROR_MOBILE_NOT_SET; case 207: return ERROR_NAME_IDCARD_NOT_MATCH; case 208: return ERROR_ACCOUNT_FROZEN; case 209: return ERROR_ACCOUNT_INACTIVE; case 210: return ERROR_PASSWORD_WRONG; case 301: return ERROR_ACCOUNT_UNAVAILABLE; case 302: return ERROR_ACCOUNT_BALANCE_NOT_ENOUGH; case 401: return ERROR_ORDER_ALREADY_PAID; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<StatusCode> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< StatusCode> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<StatusCode>() { public StatusCode findValueByNumber(int number) { return StatusCode.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return org.jigsaw.payment.model.Enums.getDescriptor().getEnumTypes().get(0); } private static final StatusCode[] VALUES = values(); public static StatusCode valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int value; private StatusCode(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:StatusCode) }
8,741
381
import geojson import h3 def polyfill_polygon(polygon: geojson.Polygon, resolution): h3_indexes = h3.polyfill(dict(type=polygon.type, coordinates=polygon.coordinates), resolution, geo_json_conformant=True) return h3_indexes
143
2,381
package com.github.dockerjava.cmd; import com.github.dockerjava.api.command.CreateContainerResponse; import com.github.dockerjava.api.exception.NotFoundException; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import static com.github.dockerjava.core.RemoteApiVersion.VERSION_1_24; import static com.github.dockerjava.junit.DockerAssume.assumeNotSwarm; import static com.github.dockerjava.junit.DockerMatchers.isGreaterOrEqual; import static com.github.dockerjava.utils.TestUtils.asString; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; public class CopyFileFromContainerCmdIT extends CmdIT { public static final Logger LOG = LoggerFactory.getLogger(CopyFileFromContainerCmdIT.class); @Test public void copyFromContainer() throws Exception { assumeThat("Doesn't work since 1.24", dockerRule, not(isGreaterOrEqual(VERSION_1_24))); assumeNotSwarm("", dockerRule); String containerName = "copyFileFromContainer" + dockerRule.getKind(); dockerRule.ensureContainerRemoved(containerName); // TODO extract this into a shared method CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox") .withName(containerName) .withCmd("touch", "/copyFileFromContainer") .exec(); LOG.info("Created container: {}", container); assertThat(container.getId(), not(isEmptyOrNullString())); dockerRule.getClient().startContainerCmd(container.getId()).exec(); InputStream response = dockerRule.getClient().copyFileFromContainerCmd(container.getId(), "/copyFileFromContainer").exec(); // read the stream fully. Otherwise, the underlying stream will not be closed. String responseAsString = asString(response); assertNotNull(responseAsString); assertTrue(responseAsString.length() > 0); } @Test(expected = NotFoundException.class) public void copyFromNonExistingContainer() throws Exception { dockerRule.getClient().copyFileFromContainerCmd("non-existing", "/test").exec(); } }
809
892
<reponame>github/advisory-database { "schema_version": "1.2.0", "id": "GHSA-6xc5-p2xh-3cfm", "modified": "2022-05-13T00:00:29Z", "published": "2022-05-13T00:00:28Z", "aliases": [ "CVE-2022-22798" ], "details": "Sysaid – Pro Plus Edition, SysAid Help Desk Broken Access Control v20.4.74 b10, v22.1.20 b62, v22.1.30 b49 - An attacker needs to log in as a guest after that the system redirects him to the service portal or EndUserPortal.JSP, then he needs to change the path in the URL to /ConcurrentLogin%2ejsp after that he will receive an error message with a login button, by clicking on it, he will connect to the system dashboard. The attacker can receive sensitive data like server details, usernames, workstations, etc. He can also perform actions such as uploading files, deleting calls from the system.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-22798" }, { "type": "WEB", "url": "https://www.gov.il/en/departments/faq/cve_advisories" } ], "database_specific": { "cwe_ids": [ ], "severity": null, "github_reviewed": false } }
464
2,959
<gh_stars>1000+ #include <Foundation/Foundation.h> /*! @brief HFRange is the 64 bit analog of NSRange, containing a 64 bit location and length. */ typedef struct { unsigned long long location; unsigned long long length; } HFRange; /*! @brief HFFPRange is a struct used for representing floating point ranges, similar to NSRange. It contains two long doubles. This is useful for (for example) showing the range of visible lines. A double-precision value has 53 significant bits in the mantissa - so we would start to have precision problems at the high end of the range we can represent. Long double has a 64 bit mantissa on Intel, which means that we would start to run into trouble at the very very end of our range - barely acceptable. */ typedef struct { long double location; long double length; } HFFPRange; #if TARGET_OS_IPHONE #define HFColor UIColor #define HFView UIView #define HFFont UIFont #else #define HFColor NSColor #define HFView NSView #define HFFont NSFont #endif typedef NS_ENUM(NSInteger, HFControllerSelectAction) { eSelectResult, eSelectAfterResult, ePreserveSelection, NUM_SELECTION_ACTIONS };
353
768
<gh_stars>100-1000 package net.engio.mbassy.bus; import net.engio.mbassy.bus.common.PubSubSupport; import net.engio.mbassy.bus.config.IBusConfiguration; import net.engio.mbassy.bus.error.MissingPropertyException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * Message bus implementations potentially vary in the features they provide and consequently in the components and properties * they expose. The runtime is a container for all those dynamic properties and components and is meant to be passed around * between collaborating objects such that they may access the different functionality provided by the bus implementation * they all belong to. * * It is the responsibility of the bus implementation to create and configure the runtime according to its capabilities, * */ public class BusRuntime { private PubSubSupport provider; private Map<String, Object> properties = new HashMap<String, Object>(); public BusRuntime(PubSubSupport provider) { this.provider = provider; } public <T> T get(String key){ if(!contains(key)) throw new MissingPropertyException("The property " + key + " is not available in this runtime"); else return (T) properties.get(key); } public PubSubSupport getProvider(){ return provider; } public Collection<String> getKeys(){ return properties.keySet(); } public BusRuntime add(String key, Object property){ properties.put(key, property); return this; } public boolean contains(String key){ return properties.containsKey(key); } }
512
4,339
/* * 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.ignite.internal.client; import java.util.UUID; /** * Ignite Java client API for communicate with node before it start. * If node has already started, then there will be errors. * For get an instance, need to use {@link GridClientFactory#startBeforeNodeStart}. */ public interface GridClientBeforeNodeStart extends AutoCloseable { /** * Gets a unique client identifier. This identifier is generated by factory on client creation * and used in identification and authentication procedure on server node. * * @return Generated client id. */ public UUID id(); /** * Indicates whether client is connected to remote Grid. * In other words it allow to determine if client is able to communicate * with Grid right now. It can be used only fo diagnostic and monitoring purposes. * * @return Whether client is connected to remote Grid. */ public boolean connected(); /** * Closes client instance. This method is identical to * {@link GridClientFactory#stop(UUID) GridClientFactory.stop(clientId)}. */ @Override public void close(); /** * Checking for an error. * * @return {@code Exception} if client was not connected. */ public GridClientException checkLastError(); /** * Getting a client projection of node state before its start. * * @return Projection of node state before its start. * * @see GridClientNodeStateBeforeStart */ public GridClientNodeStateBeforeStart beforeStartState(); }
673
1,170
<reponame>Nightonke/Gitee<gh_stars>1000+ // // VHTrendingLanguageCellView.h // VHGithubNotifier // // Created by Nightonke on 2017/9/24. // Copyright © 2017年 黄伟平. All rights reserved. // #import <Cocoa/Cocoa.h> #import "VHLanguage.h" @protocol VHTrendingLanguageCellViewDelegate <NSObject> @required - (void)onLanguage:(VHLanguage *)language selected:(BOOL)selected; @end @interface VHTrendingLanguageCellView : NSTableCellView @property (nonatomic, strong) VHLanguage *language; @property (nonatomic, weak) id<VHTrendingLanguageCellViewDelegate> delegate; @property (nonatomic, assign) BOOL selected; @end
226
480
<reponame>weicao/galaxysql /* * Copyright [2013-2021], Alibaba Group Holding Limited * * 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.alibaba.polardbx.optimizer.memory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import com.alibaba.polardbx.common.exception.MemoryNotEnoughException; import com.alibaba.polardbx.common.properties.MppConfig; import javax.annotation.concurrent.NotThreadSafe; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import static com.google.common.base.Preconditions.checkState; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; /** * Encapsulating the logic of applying memory which need align to the 1Mb. * This allocator can allocate the reserved & revocable memory, and it need record the blocking flag. * It usually is used by operators. */ @NotThreadSafe public class OperatorMemoryAllocatorCtx implements MemoryAllocatorCtx { private final MemoryPool memoryPool; private final AtomicLong reservedFree = new AtomicLong(0L); private final AtomicLong reservedAllocated = new AtomicLong(0L); private final AtomicLong revocableFree = new AtomicLong(0L); private final AtomicLong revocableAllocated = new AtomicLong(0L); private final AtomicReference<MemoryNotFuture> allocateBytesFuture; private final AtomicReference<MemoryNotFuture> tryAllocateBytesFuture; private final MemoryAllocateFuture allocateFuture = new MemoryAllocateFuture(); private SettableFuture<?> memoryRevokingRequestedFuture; private final boolean revocable; public OperatorMemoryAllocatorCtx(MemoryPool memoryPool, boolean revocable) { this.memoryPool = memoryPool; this.allocateBytesFuture = new AtomicReference<>(); this.allocateBytesFuture.set(MemoryNotFuture.create()); this.allocateBytesFuture.get().set(null); this.tryAllocateBytesFuture = new AtomicReference<>(); this.tryAllocateBytesFuture.set(MemoryNotFuture.create()); this.tryAllocateBytesFuture.get().set(null); this.revocable = revocable; if (this.revocable) { memoryRevokingRequestedFuture = SettableFuture.create(); } } @Override public void allocateReservedMemory(long bytes) { long left = reservedFree.addAndGet(-bytes); if (left < 0) { // Align to block size long amount = -Math.floorDiv(left, BLOCK_SIZE) * BLOCK_SIZE; try { updateMemoryFuture(memoryPool.allocateReserveMemory(amount), allocateBytesFuture, false); } catch (MemoryNotEnoughException t) { reservedFree.addAndGet(bytes); throw t; } reservedFree.addAndGet(amount); reservedAllocated.addAndGet(amount); } } @Override public boolean tryAllocateReservedMemory(long bytes) { Preconditions.checkState(revocable, "Don't allocate memory in the un-spill mode!"); long left = reservedFree.addAndGet(-bytes); allocateFuture.reset(); if (left < 0) { long allocated = -left; if (this.memoryPool.tryAllocateReserveMemory(allocated, allocateFuture)) { reservedAllocated.addAndGet(allocated); reservedFree.addAndGet(allocated); return true; } else { reservedFree.addAndGet(bytes); ListenableFuture<?> driverFuture = allocateFuture.getAllocateFuture(); updateMemoryFuture(driverFuture, tryAllocateBytesFuture, true); return false; } } else { return true; } } @Override public boolean tryAllocateRevocableMemory(long bytes) { Preconditions.checkState(revocable, "Don't allocate memory in the un-spill mode!"); long left = revocableFree.addAndGet(-bytes); allocateFuture.reset(); if (left < 0) { long allocated = -left; if (this.memoryPool.tryAllocateRevocableMemory(allocated, allocateFuture)) { revocableAllocated.addAndGet(allocated); revocableFree.addAndGet(allocated); return true; } else { revocableFree.addAndGet(bytes); ListenableFuture<?> driverFuture = allocateFuture.getAllocateFuture(); updateMemoryFuture(driverFuture, tryAllocateBytesFuture, true); return false; } } else { return true; } } @Override public long getReservedAllocated() { return reservedAllocated.get(); } @Override public void allocateRevocableMemory(long bytes) { Preconditions.checkState(revocable, "Don't allocate memory in the un-spill mode!"); long left = revocableFree.addAndGet(-bytes); if (left < 0) { // Align to block size long amount = -Math.floorDiv(left, BLOCK_SIZE) * BLOCK_SIZE; try { updateMemoryFuture(memoryPool.allocateRevocableMemory(amount), allocateBytesFuture, false); } catch (MemoryNotEnoughException t) { revocableFree.addAndGet(bytes); throw t; } revocableFree.addAndGet(amount); revocableAllocated.addAndGet(amount); } } @Override public void releaseReservedMemory(long bytes, boolean immediately) { if (immediately) { long alreadyAllocated = reservedAllocated.get(); if (alreadyAllocated - bytes < reservedFree.get()) { memoryPool.freeReserveMemory(reservedAllocated.getAndSet(0)); reservedFree.set(0); } else { long actualFreeSize = Math.min(alreadyAllocated, bytes); reservedAllocated.addAndGet(-actualFreeSize); memoryPool.freeReserveMemory(actualFreeSize); } } else if (reservedAllocated.get() > reservedFree.addAndGet(bytes)) { if (reservedFree.get() >= BLOCK_SIZE) { long freeSize = reservedFree.getAndSet(0); long actualFreeSize = Math.min(revocableAllocated.get(), freeSize); reservedAllocated.addAndGet(-actualFreeSize); memoryPool.freeReserveMemory(actualFreeSize); } } else { memoryPool.freeReserveMemory(reservedAllocated.getAndSet(0)); reservedFree.set(0); } } @Override public void releaseRevocableMemory(long bytes, boolean immediately) { Preconditions.checkState(revocable, "Don't allocate memory in the reserved mode!"); if (immediately) { long alreadyAllocated = revocableAllocated.get(); if (alreadyAllocated - bytes <= revocableFree.get()) { memoryPool.freeRevocableMemory(revocableAllocated.getAndSet(0)); revocableFree.set(0); } else { long actualFreeSize = Math.min(alreadyAllocated, bytes); revocableAllocated.addAndGet(-actualFreeSize); memoryPool.freeRevocableMemory(actualFreeSize); } } else if (revocableAllocated.get() > revocableFree.addAndGet(bytes)) { if (revocableFree.get() >= BLOCK_SIZE) { long alreadyAllocated = revocableAllocated.get(); long freeSize = revocableFree.getAndSet(0); long actualFreeSize = Math.min(alreadyAllocated, freeSize); revocableAllocated.addAndGet(-actualFreeSize); memoryPool.freeRevocableMemory(actualFreeSize); } } else { memoryPool.freeRevocableMemory(revocableAllocated.getAndSet(0)); revocableFree.set(0); } } @Override public long getRevocableAllocated() { return revocableAllocated.get(); } public ListenableFuture<?> isWaitingForMemory() { return allocateBytesFuture.get(); } public ListenableFuture<?> isWaitingForTryMemory() { return tryAllocateBytesFuture.get(); } public synchronized SettableFuture<?> getMemoryRevokingRequestedFuture() { return memoryRevokingRequestedFuture; } public synchronized long requestMemoryRevokingOrReturnRevokingBytes() { checkState(revocable, "requestMemoryRevoking for unRevocable operator"); boolean alreadyRequested = isMemoryRevokingRequested(); if (!alreadyRequested && revocableAllocated.get() > 0) { memoryRevokingRequestedFuture.set(null); return revocableAllocated.get(); } if (alreadyRequested) { return revocableAllocated.get(); } return 0; } public synchronized boolean isMemoryRevokingRequested() { if (!revocable) { return false; } return memoryRevokingRequestedFuture.isDone(); } public synchronized void resetMemoryRevokingRequested() { if (!revocable) { return; } SettableFuture<?> currentFuture = memoryRevokingRequestedFuture; if (!currentFuture.isDone()) { return; } memoryRevokingRequestedFuture = SettableFuture.create(); } private void updateMemoryFuture(ListenableFuture<?> memoryPoolFuture, AtomicReference<MemoryNotFuture> targetFutureReference, boolean isTry) { if (memoryPoolFuture != null && !memoryPoolFuture.isDone() && (isTry || getAllAllocated() > MppConfig.getInstance().getLessRevokeBytes() / 8)) { //如果不是尝试性申请内存的话,则不阻塞 4MB 以下的算子 MemoryNotFuture<?> currentMemoryFuture = targetFutureReference.get(); if (currentMemoryFuture.isDone()) { MemoryNotFuture<?> settableFuture = MemoryNotFuture.create(); targetFutureReference.set(settableFuture); } MemoryNotFuture<?> finalMemoryFuture = targetFutureReference.get(); // Create a new future, so that this operator can un-block before the pool does, if it's moved to a new pool Futures.addCallback(memoryPoolFuture, new FutureCallback<Object>() { @Override public void onSuccess(Object result) { finalMemoryFuture.set(null); } @Override public void onFailure(Throwable t) { finalMemoryFuture.set(null); } }, directExecutor()); } } @Override public String getName() { return memoryPool.getName(); } public boolean isRevocable() { return revocable; } @Override public long getAllAllocated() { return reservedAllocated.get() + revocableAllocated.get(); } @VisibleForTesting public AtomicLong getReservedFree() { return reservedFree; } @VisibleForTesting public AtomicLong getRevocableFree() { return revocableFree; } }
4,945
1,812
<reponame>1006079161/qpdf #include <qpdf/SparseOHArray.hh> #include <assert.h> #include <iostream> int main() { SparseOHArray a; assert(a.size() == 0); a.append(QPDFObjectHandle::parse("1")); a.append(QPDFObjectHandle::parse("(potato)")); a.append(QPDFObjectHandle::parse("null")); a.append(QPDFObjectHandle::parse("null")); a.append(QPDFObjectHandle::parse("/Quack")); assert(a.size() == 5); assert(a.at(0).isInteger() && (a.at(0).getIntValue() == 1)); assert(a.at(1).isString() && (a.at(1).getStringValue() == "potato")); assert(a.at(2).isNull()); assert(a.at(3).isNull()); assert(a.at(4).isName() && (a.at(4).getName() == "/Quack")); a.insert(4, QPDFObjectHandle::parse("/BeforeQuack")); assert(a.size() == 6); assert(a.at(0).isInteger() && (a.at(0).getIntValue() == 1)); assert(a.at(4).isName() && (a.at(4).getName() == "/BeforeQuack")); assert(a.at(5).isName() && (a.at(5).getName() == "/Quack")); a.insert(2, QPDFObjectHandle::parse("/Third")); assert(a.size() == 7); assert(a.at(1).isString() && (a.at(1).getStringValue() == "potato")); assert(a.at(2).isName() && (a.at(2).getName() == "/Third")); assert(a.at(3).isNull()); assert(a.at(6).isName() && (a.at(6).getName() == "/Quack")); a.insert(0, QPDFObjectHandle::parse("/First")); assert(a.size() == 8); assert(a.at(0).isName() && (a.at(0).getName() == "/First")); assert(a.at(1).isInteger() && (a.at(1).getIntValue() == 1)); assert(a.at(7).isName() && (a.at(7).getName() == "/Quack")); a.erase(6); assert(a.size() == 7); assert(a.at(0).isName() && (a.at(0).getName() == "/First")); assert(a.at(1).isInteger() && (a.at(1).getIntValue() == 1)); assert(a.at(5).isNull()); assert(a.at(6).isName() && (a.at(6).getName() == "/Quack")); a.erase(6); assert(a.size() == 6); assert(a.at(0).isName() && (a.at(0).getName() == "/First")); assert(a.at(1).isInteger() && (a.at(1).getIntValue() == 1)); assert(a.at(3).isName() && (a.at(3).getName() == "/Third")); assert(a.at(4).isNull()); assert(a.at(5).isNull()); a.setAt(4, QPDFObjectHandle::parse("12")); assert(a.at(4).isInteger() && (a.at(4).getIntValue() == 12)); a.setAt(4, QPDFObjectHandle::newNull()); assert(a.at(4).isNull()); a.remove_last(); assert(a.size() == 5); assert(a.at(0).isName() && (a.at(0).getName() == "/First")); assert(a.at(1).isInteger() && (a.at(1).getIntValue() == 1)); assert(a.at(3).isName() && (a.at(3).getName() == "/Third")); assert(a.at(4).isNull()); a.remove_last(); assert(a.size() == 4); assert(a.at(0).isName() && (a.at(0).getName() == "/First")); assert(a.at(1).isInteger() && (a.at(1).getIntValue() == 1)); assert(a.at(3).isName() && (a.at(3).getName() == "/Third")); a.remove_last(); assert(a.size() == 3); assert(a.at(0).isName() && (a.at(0).getName() == "/First")); assert(a.at(1).isInteger() && (a.at(1).getIntValue() == 1)); assert(a.at(2).isString() && (a.at(2).getStringValue() == "potato")); std::cout << "sparse array tests done" << std::endl; return 0; }
1,465
411
// Copyright 2009, Squish Tech, LLC. #ifndef SRC_XML_ELEMENT_H_ #define SRC_XML_ELEMENT_H_ #include "libxmljs.h" #include "xml_node.h" namespace libxmljs { class XmlElement : public XmlNode { public: explicit XmlElement(xmlNode* node); static void Initialize(v8::Local<v8::Object> target); static Nan::Persistent<v8::FunctionTemplate> constructor_template; // create new xml element to wrap the node static v8::Local<v8::Object> New(xmlNode* node); protected: static NAN_METHOD(New); static NAN_METHOD(Name); static NAN_METHOD(Attr); static NAN_METHOD(Attrs); static NAN_METHOD(Find); static NAN_METHOD(Text); static NAN_METHOD(Path); static NAN_METHOD(Child); static NAN_METHOD(ChildNodes); static NAN_METHOD(AddChild); static NAN_METHOD(AddCData); static NAN_METHOD(NextElement); static NAN_METHOD(PrevElement); static NAN_METHOD(AddPrevSibling); static NAN_METHOD(AddNextSibling); static NAN_METHOD(Replace); void set_name(const char* name); v8::Local<v8::Value> get_name(); v8::Local<v8::Value> get_child(int32_t idx); v8::Local<v8::Value> get_child_nodes(); v8::Local<v8::Value> get_path(); v8::Local<v8::Value> get_attr(const char* name); v8::Local<v8::Value> get_attrs(); void set_attr(const char* name, const char* value); void add_cdata(xmlNode* cdata); void unlink_children(); void set_content(const char* content); v8::Local<v8::Value> get_content(); v8::Local<v8::Value> get_next_element(); v8::Local<v8::Value> get_prev_element(); void replace_element(xmlNode* element); void replace_text(const char* content); bool child_will_merge(xmlNode* child); bool prev_sibling_will_merge(xmlNode* node); bool next_sibling_will_merge(xmlNode* node); }; } // namespace libxmljs #endif // SRC_XML_ELEMENT_H_
758
988
<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.editor.completion; import java.awt.Color; import java.awt.Font; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import javax.swing.JEditorPane; import javax.swing.SwingUtilities; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Document; import javax.swing.text.EditorKit; import javax.swing.text.html.HTMLEditorKit; import org.netbeans.editor.EditorUI; import org.openide.util.Exceptions; /** * HTML documentation view. * Javadoc content is displayed in JEditorPane pane using HTMLEditorKit. * * @author <NAME> * @since 03/2002 */ public class HTMLDocView extends JEditorPane { private HTMLEditorKit htmlKit; private int selectionAnchor = 0; // selection-begin position private Object highlight = null; // selection highlight /** Creates a new instance of HTMLJavaDocView */ public HTMLDocView(Color bgColor) { setEditable(false); setFocusable(true); setBackground(bgColor); setMargin(new Insets(0, 3, 3, 3)); //add listeners for selection support addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { getHighlighter().removeAllHighlights(); selectionAnchor = positionCaret(e); try { highlight = getHighlighter().addHighlight(selectionAnchor, selectionAnchor, DefaultHighlighter.DefaultPainter); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } public void mouseReleased(MouseEvent e) { if(getSelectedText() == null){ getHighlighter().removeAllHighlights(); } } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) { try { if (highlight == null) { getHighlighter().removeAllHighlights(); selectionAnchor = positionCaret(e); highlight = getHighlighter().addHighlight(selectionAnchor, selectionAnchor, DefaultHighlighter.DefaultPainter); } else if (selectionAnchor <= positionCaret(e)) { getHighlighter().changeHighlight(highlight, selectionAnchor, positionCaret(e)); } else { getHighlighter().changeHighlight(highlight, positionCaret(e), selectionAnchor); } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } public void mouseMoved(MouseEvent e) {} }); putClientProperty( JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE ); } private int positionCaret(MouseEvent event) { int positionOffset = this.viewToModel(event.getPoint()); return positionOffset; } @Override public boolean isFocusable() { return false; } /** Sets the javadoc content as HTML document */ public void setContent(final String content, final String reference) { SwingUtilities.invokeLater(new Runnable(){ public void run(){ Reader in = new StringReader("<HTML><BODY>"+content+"</BODY></HTML>");//NOI18N try{ Document doc = getDocument(); doc.remove(0, doc.getLength()); getEditorKit().read(in, getDocument(), 0); //!!! still too expensive to be called from AWT setCaretPosition(0); if (reference != null) { SwingUtilities.invokeLater(new Runnable(){ public void run(){ scrollToReference(reference); } }); } else { scrollRectToVisible(new Rectangle(0,0,0,0)); } }catch(IOException ioe){ ioe.printStackTrace(); }catch(BadLocationException ble){ ble.printStackTrace(); } } }); } protected EditorKit createDefaultEditorKit() { // it is extremelly slow to init it if (htmlKit == null){ htmlKit= new HTMLEditorKit (); setEditorKit(htmlKit); // override the Swing default CSS to make the HTMLEditorKit use the // same font as the rest of the UI. // XXX the style sheet is shared by all HTMLEditorKits. We must // detect if it has been tweaked by ourselves or someone else // (template description for example) and avoid doing the same // thing again if (htmlKit.getStyleSheet().getStyleSheets() != null) { // htmlKit.getStyleSheet().removeStyle("body"); setBodyFontInCSS(); return htmlKit; } setBodyFontInCSS(); } return htmlKit; } private void setBodyFontInCSS() { javax.swing.text.html.StyleSheet css = new javax.swing.text.html.StyleSheet(); Font editorFont = new EditorUI().getDefaultColoring().getFont(); // do not use monospaced font, just adjust fontsize Font useFont = new Font(getFont().getFamily(), Font.PLAIN, editorFont.getSize()); setFont(useFont); try { css.addRule(new StringBuilder("body, div { font-size: ").append(useFont.getSize()) // NOI18N .append("; font-family: ").append(useFont.getFamily()).append(";}").toString()); // NOI18N } catch (Exception e) { } css.addStyleSheet(htmlKit.getStyleSheet()); htmlKit.setStyleSheet(css); } }
3,246