max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
8,633
<gh_stars>1000+ from time import sleep from unittest.mock import MagicMock import pytest from prefect import Task from prefect.engine import signals, state from prefect.engine.runner import ENDRUN, Runner from prefect.utilities.configuration import set_temporary_config from prefect.utilities.executors import run_with_heartbeat def test_state_handlers_must_be_iterable(): with pytest.raises(TypeError): Runner(state_handlers=False) with pytest.raises(TypeError): Runner(state_handlers=1) with pytest.raises(TypeError): Runner(state_handlers=lambda *a: 1) def test_call_runner_target_handlers_gets_called_in_handle_state_change(): """tests that the `call_runner_target_handlers` helper method is called""" class TestRunner(Runner): def call_runner_target_handlers(self, old_state, new_state): raise ValueError() with pytest.raises(ENDRUN): TestRunner().handle_state_change(state.Pending(), state.Running()) @pytest.mark.parametrize("exc", [ENDRUN, signals.PAUSE]) def test_call_runner_target_handlers_reraises_appropriately(exc): class TestRunner(Runner): def call_runner_target_handlers(self, old_state, new_state): raise exc() with pytest.raises(exc): TestRunner().handle_state_change(state.Pending(), state.Running()) def test_call_runner_target_handlers_calls_handlers_appropriately(): class TestRunner(Runner): def call_runner_target_handlers(self, old_state, new_state): return new_state my_handler = MagicMock(return_value=state.Running()) TestRunner(state_handlers=[my_handler]).handle_state_change( state.Pending(), state.Running() ) assert my_handler.call_args[0][1:] == (state.Pending(), state.Running()) def test_call_runner_target_handlers_allows_for_none_return_values(): class TestRunner(Runner): def call_runner_target_handlers(self, old_state, new_state): return new_state my_handler = MagicMock(return_value=None) res = TestRunner(state_handlers=[my_handler]).handle_state_change( state.Pending(), state.Running() ) assert res == state.Running() def test_runner_has_logger(): r = Runner() assert r.logger.name == "prefect.Runner" class TestInitializeRun: def test_initialize_run_returns_state_and_context(self): state_, context = state.Pending(), {} s, c = Runner().initialize_run(state=state_, context=context) assert s is state_ assert c is context @pytest.mark.parametrize( "state", [ state.Success(), state.Failed(), state.Pending(), state.Scheduled(), state.Skipped(), state.Cached(), state.Retrying(), state.Running(), ], ) def test_initialize_run_returns_state(self, state): new_state, _ = Runner().initialize_run(state, context={}) assert new_state is state @pytest.mark.parametrize( "state", [ state.Submitted(state=state.Pending()), state.Submitted(state=state.Retrying()), state.Submitted(state=state.Scheduled()), state.Submitted(state=state.Resume()), state.Queued(state=state.Pending()), state.Queued(state=state.Retrying()), state.Queued(state=state.Scheduled()), state.Queued(state=state.Resume()), ], ) def test_initialize_run_gets_wrapped_state_from_submitted_states(self, state): new_state, _ = Runner().initialize_run(state, context={}) assert new_state is state.state def test_initialize_run_creates_pending_if_no_state_provided(self): new_state, _ = Runner().initialize_run(state=None, context={}) assert isinstance(new_state, state.Pending) def test_bad_heartbeat_doesnt_prevent_completion_of_run(): class BadHeartBeatRunner(Runner): def _heartbeat(self): raise SyntaxError("message") @run_with_heartbeat def run(self): sleep(2) return state.Success() with set_temporary_config({"cloud.heartbeat_interval": 1.0}): res = BadHeartBeatRunner().run() assert res.is_successful()
1,786
812
package edu.stanford.nlp.sempre; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.google.common.base.Strings; import fig.basic.Option; /** * A Session contains the information specific to a user. * It maintains the context for discourse as well as the last example, so that * we can inspect the different predicted derivations and generate new training * examples / update parameters interactively. * * @author <NAME> */ public class Session { public final String id; // Session id public static class Options { // path for default parameters, if using a different set for each session @Option public String inParamsPath; } public String remoteHost; // Where we connected from public String format; // html or json public ContextValue context; // Current context used to create new examples Example lastEx; // Last example that we processed // if every user have their own model Params params; Learner learner; public Map<String,String> reqParams; public static Options opts = new Options(); // per session parameters public Session(String id) { this.id = id; context = new ContextValue(id, DateValue.now(), new ArrayList<ContextValue.Exchange>()); } public Example getLastExample() { return lastEx; } public String getLastQuery() { return lastEx == null ? null : lastEx.utterance; } public void updateContext() { context = context.withDate(DateValue.now()); } public void updateContext(Example ex, int maxExchanges) { lastEx = ex; List<Derivation> derivations = lastEx.getPredDerivations(); if (derivations.size() > 0) { Derivation deriv = derivations.get(0); List<ContextValue.Exchange> newExchanges = new ArrayList<ContextValue.Exchange>(); newExchanges.addAll(context.exchanges); newExchanges.add(new ContextValue.Exchange(ex.utterance, deriv.formula, deriv.value)); while (newExchanges.size() > maxExchanges) newExchanges.remove(0); context = context.withNewExchange(newExchanges); } } public void updateContextWithNewAnswer(Example ex, Derivation deriv) { List<ContextValue.Exchange> newExchanges = new ArrayList<ContextValue.Exchange>(); for (int i = 0; i < context.exchanges.size() - 1; i++) newExchanges.add(context.exchanges.get(i)); newExchanges.add(new ContextValue.Exchange(ex.utterance, deriv.formula, deriv.value)); context = context.withNewExchange(newExchanges); } public ContextValue getContextExcludingLast() { List<ContextValue.Exchange> newExchanges = new ArrayList<ContextValue.Exchange>(); for (int i = 0; i < context.exchanges.size() - 1; i++) newExchanges.add(context.exchanges.get(i)); return context.withNewExchange(newExchanges); } public void useIndependentLearner(Builder builder) { this.params = new Params(); if (!Strings.isNullOrEmpty(opts.inParamsPath)) this.params.read(opts.inParamsPath); this.learner = new Learner(builder.parser, this.params, new Dataset()); } @Override public String toString() { return String.format("%s: %s; last: %s", id, context, lastEx); } // Decides if we write out any logs public boolean isLogging() { return defaultTrue("logging");} public boolean isWritingCitation() { return defaultTrue("cite");} public boolean isWritingGrammar() { return defaultTrue("grammar");} public boolean isLearning() { return defaultTrue("learn");} public boolean isStatsing() { return defaultTrue("stats");} private boolean defaultTrue(String key) { if (this.reqParams == null) return true; if (!this.reqParams.containsKey(key)) return true; return !this.reqParams.get(key).equals("0"); } }
1,204
3,200
<filename>mindspore/lite/micro/coder/opcoders/nnacl/int8/detection_post_process_int8_coder.h<gh_stars>1000+ /** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_LITE_MICRO_CODER_OPCODERS_NNACL_INT8_DETECTION_POST_PROCESS_INT8_CODER_H_ #define MINDSPORE_LITE_MICRO_CODER_OPCODERS_NNACL_INT8_DETECTION_POST_PROCESS_INT8_CODER_H_ #include <string> #include <memory> #include <vector> #include "coder/opcoders/base/detection_post_process_base_coder.h" namespace mindspore::lite::micro::nnacl { class DetectionPostProcessInt8Coder final : public DetectionPostProcessBaseCoder { public: DetectionPostProcessInt8Coder(const std::vector<Tensor *> &in_tensors, const std::vector<Tensor *> &out_tensors, const Model::Node *node, size_t node_index, Target target) : DetectionPostProcessBaseCoder(in_tensors, out_tensors, node, node_index, target) {} ~DetectionPostProcessInt8Coder() override = default; private: int GetInputData(CoderContext *const context, Serializer *const code) override; int MallocInputsBuffer() override; }; } // namespace mindspore::lite::micro::nnacl #endif // MINDSPORE_LITE_MICRO_CODER_OPCODERS_NNACL_INT8_DETECTION_POST_PROCESS_INT8_CODER_H_
627
4,320
/* * Copyright (c) 2019 Abex * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.api.geometry; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.Arrays; import java.util.Iterator; import java.util.List; import lombok.Getter; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class Shapes<T extends Shape> implements Shape { public Shapes(T ...shape) { this(Arrays.asList(shape)); } @Getter private final List<T> shapes; @Override public Rectangle getBounds() { int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE; for (Shape shape : shapes) { Rectangle bounds = shape.getBounds(); minX = Math.min(bounds.x, minX); minY = Math.min(bounds.y, minY); maxX = Math.max(bounds.x + bounds.width, maxX); maxY = Math.max(bounds.y + bounds.height, maxY); } return new Rectangle(minX, minY, maxX - minX, maxY - minY); } @Override public Rectangle2D getBounds2D() { double minX = Double.MAX_VALUE, minY = Double.MAX_VALUE, maxX = Double.MIN_VALUE, maxY = Double.MIN_VALUE; for (Shape shape : shapes) { Rectangle2D bounds = shape.getBounds2D(); minX = Math.min(bounds.getX(), minX); minY = Math.min(bounds.getY(), minY); maxX = Math.max(bounds.getMaxX(), maxX); maxY = Math.max(bounds.getMaxY(), maxY); } return new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY); } @Override public boolean contains(double x, double y) { return shapes.stream().anyMatch(s -> s.contains(x, y)); } @Override public boolean contains(Point2D p) { return shapes.stream().anyMatch(s -> s.contains(p)); } @Override public boolean intersects(double x, double y, double w, double h) { return shapes.stream().anyMatch(s -> s.intersects(x, y, w, h)); } @Override public boolean intersects(Rectangle2D r) { return shapes.stream().anyMatch(s -> s.intersects(r)); } @Override public boolean contains(double x, double y, double w, double h) { return shapes.stream().anyMatch(s -> s.contains(x, y, w, h)); } @Override public boolean contains(Rectangle2D r) { return shapes.stream().anyMatch(s -> s.contains(r)); } @Override public PathIterator getPathIterator(AffineTransform at) { return new ShapeIterator(shapes.stream() .map(s -> s.getPathIterator(at)) .iterator()); } @Override public PathIterator getPathIterator(AffineTransform at, double flatness) { return new ShapeIterator(shapes.stream() .map(s -> s.getPathIterator(at, flatness)) .iterator()); } private static class ShapeIterator implements PathIterator { private final Iterator<PathIterator> iter; private PathIterator current = null; private final int windingRule; ShapeIterator(Iterator<PathIterator> iter) { this.iter = iter; if (iter.hasNext()) { current = iter.next(); windingRule = current.getWindingRule(); checkDone(); } else { windingRule = 0; } } @Override public int getWindingRule() { return windingRule; } @Override public boolean isDone() { return current == null; } @Override public void next() { current.next(); checkDone(); } private void checkDone() { for (; current != null && current.isDone(); ) { if (iter.hasNext()) { current = iter.next(); assert windingRule == current.getWindingRule(); } else { current = null; } } } @Override public int currentSegment(float[] coords) { return current.currentSegment(coords); } @Override public int currentSegment(double[] coords) { return current.currentSegment(coords); } } }
1,903
637
<gh_stars>100-1000 /* * Copyright (C) 2017 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** This header is private to the Twitter Core SDK and not exposed for public SDK consumption */ #import <Foundation/Foundation.h> typedef void (^TWTRAuthenticationProviderCompletion)(NSDictionary *responseObject, NSError *error); @interface TWTRAuthenticationProvider : NSObject /** * Authenticate with the Twitter API * * @param completion (required) The completion block to be called upon succes or failure. * Will be called on an arbitrary queue. */ - (void)authenticateWithCompletion:(TWTRAuthenticationProviderCompletion)completion; @end
355
2,453
<filename>XVim2/XcodeHeader/IDEKit/IDEWelcomeWindowAuthorizationHelper.h // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @interface IDEWelcomeWindowAuthorizationHelper : NSObject { } + (BOOL)isAuthorized; + (struct AuthorizationOpaqueRef *)acquireAuthorizationForRightString:(const char *)arg1 withPrompt:(const char *)arg2; + (void)releaseAuthorization; + (struct AuthorizationOpaqueRef *)_createAuthorizationForRightString:(const char *)arg1 withPrompt:(const char *)arg2; + (void)initialize; @end
205
826
// SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenColorIO Project. #include <algorithm> #include <cstring> #include <sstream> #include <vector> #include <OpenColorIO/OpenColorIO.h> #include "transforms/Lut3DTransform.h" namespace OCIO_NAMESPACE { Lut3DTransformRcPtr Lut3DTransform::Create() { return Lut3DTransformRcPtr(new Lut3DTransformImpl(), &Lut3DTransformImpl::deleter); } Lut3DTransformRcPtr Lut3DTransform::Create(unsigned long gridSize) { return Lut3DTransformRcPtr(new Lut3DTransformImpl(gridSize), &Lut3DTransformImpl::deleter); } void Lut3DTransformImpl::deleter(Lut3DTransform* t) { delete static_cast<Lut3DTransformImpl *>(t); } Lut3DTransformImpl::Lut3DTransformImpl() : m_data(2) { } Lut3DTransformImpl::Lut3DTransformImpl(unsigned long gridSize) : m_data(gridSize) { } TransformRcPtr Lut3DTransformImpl::createEditableCopy() const { Lut3DTransformRcPtr transform = Lut3DTransform::Create(); dynamic_cast<Lut3DTransformImpl*>(transform.get())->data() = data(); return transform; } TransformDirection Lut3DTransformImpl::getDirection() const noexcept { return data().getDirection(); } void Lut3DTransformImpl::setDirection(TransformDirection dir) noexcept { data().setDirection(dir); } void Lut3DTransformImpl::validate() const { try { Transform::validate(); data().validate(); } catch (Exception & ex) { std::string errMsg("Lut3DTransform validation failed: "); errMsg += ex.what(); throw Exception(errMsg.c_str()); } } BitDepth Lut3DTransformImpl::getFileOutputBitDepth() const noexcept { return data().getFileOutputBitDepth(); } void Lut3DTransformImpl::setFileOutputBitDepth(BitDepth bitDepth) noexcept { data().setFileOutputBitDepth(bitDepth); } FormatMetadata & Lut3DTransformImpl::getFormatMetadata() noexcept { return data().getFormatMetadata(); } const FormatMetadata & Lut3DTransformImpl::getFormatMetadata() const noexcept { return data().getFormatMetadata(); } bool Lut3DTransformImpl::equals(const Lut3DTransform & other) const noexcept { if (this == &other) return true; return data() == dynamic_cast<const Lut3DTransformImpl*>(&other)->data(); } unsigned long Lut3DTransformImpl::getGridSize() const { return m_data.getArray().getLength(); } void Lut3DTransformImpl::setGridSize(unsigned long gridSize) { auto & lutArray = m_data.getArray(); lutArray = Lut3DOpData::Lut3DArray(gridSize); } namespace { static constexpr char COMPONENT_R[] = "Red"; static constexpr char COMPONENT_G[] = "Green"; static constexpr char COMPONENT_B[] = "Blue"; void CheckLUT3DIndex(const char * function, const char * component, unsigned long index, unsigned long size) { if (index >= size) { std::ostringstream oss; oss << "Lut3DTransform " << function << ": " << component << " index ("; oss << index << ") should be less than the grid size ("; oss << size << ")."; throw Exception(oss.str().c_str()); } } } void Lut3DTransformImpl::setValue(unsigned long indexR, unsigned long indexG, unsigned long indexB, float r, float g, float b) { const unsigned long gs = getGridSize(); CheckLUT3DIndex("setValue", COMPONENT_R, indexR, gs); CheckLUT3DIndex("setValue", COMPONENT_G, indexG, gs); CheckLUT3DIndex("setValue", COMPONENT_B, indexB, gs); // Array is stored in blue-fastest order. const unsigned long arrayIdx = 3 * ((indexR*gs + indexG)*gs + indexB); m_data.getArray()[arrayIdx] = r; m_data.getArray()[arrayIdx + 1] = g; m_data.getArray()[arrayIdx + 2] = b; } void Lut3DTransformImpl::getValue(unsigned long indexR, unsigned long indexG, unsigned long indexB, float & r, float & g, float & b) const { const unsigned long gs = getGridSize(); CheckLUT3DIndex("getValue", COMPONENT_R, indexR, gs); CheckLUT3DIndex("getValue", COMPONENT_G, indexG, gs); CheckLUT3DIndex("getValue", COMPONENT_B, indexB, gs); // Array is stored in blue-fastest order. const unsigned long arrayIdx = 3 * ((indexR*gs + indexG)*gs + indexB); r = m_data.getArray()[arrayIdx]; g = m_data.getArray()[arrayIdx + 1]; b = m_data.getArray()[arrayIdx + 2]; } void Lut3DTransformImpl::setInterpolation(Interpolation algo) { m_data.setInterpolation(algo); } Interpolation Lut3DTransformImpl::getInterpolation() const { return m_data.getInterpolation(); } std::ostream & operator<< (std::ostream & os, const Lut3DTransform & t) { os << "<Lut3DTransform "; os << "direction=" << TransformDirectionToString(t.getDirection()) << ", "; os << "fileoutdepth=" << BitDepthToString(t.getFileOutputBitDepth()) << ", "; os << "interpolation=" << InterpolationToString(t.getInterpolation()) << ", "; const unsigned long l = t.getGridSize(); os << "gridSize=" << l << ", "; if (l > 0) { float rMin = std::numeric_limits<float>::max(); float gMin = std::numeric_limits<float>::max(); float bMin = std::numeric_limits<float>::max(); float rMax = -rMin; float gMax = -gMin; float bMax = -bMin; for (unsigned long r = 0; r < l; ++r) { for (unsigned long g = 0; g < l; ++g) { for (unsigned long b = 0; b < l; ++b) { float rv = 0.f; float gv = 0.f; float bv = 0.f; t.getValue(r, g , b, rv, gv, bv); rMin = std::min(rMin, rv); gMin = std::min(gMin, gv); bMin = std::min(bMin, bv); rMax = std::max(rMin, rv); gMax = std::max(gMin, gv); bMax = std::max(bMin, bv); } } } os << "minrgb=["; os << rMin << " " << gMin << " " << bMin << "], "; os << "maxrgb=["; os << rMax << " " << gMax << " " << bMax << "]"; } os << ">"; return os; } } // namespace OCIO_NAMESPACE
2,844
335
{ "word": "Dissident", "definitions": [ "In opposition to official policy." ], "parts-of-speech": "Adjective" }
60
852
#ifndef BLOBPEDESTALS_H #define BLOBPEDESTALS_H #include "CondFormats/Serialization/interface/Serializable.h" #include <vector> class BlobPedestals { public: BlobPedestals(); virtual ~BlobPedestals(); std::vector<unsigned int> m_pedestals; COND_SERIALIZABLE; }; #endif
108
395
package timely.test; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; import org.apache.accumulo.core.client.lexicoder.Lexicoder; import org.apache.accumulo.core.client.lexicoder.PairLexicoder; import org.apache.accumulo.core.client.lexicoder.StringLexicoder; import org.apache.accumulo.core.conf.AccumuloConfiguration; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.TabletId; import org.apache.accumulo.core.data.impl.KeyExtent; import org.apache.accumulo.core.data.impl.TabletIdImpl; import org.apache.accumulo.core.metadata.schema.DataFileValue; import org.apache.accumulo.core.util.ComparablePair; import org.apache.accumulo.server.fs.FileRef; import org.apache.accumulo.server.fs.VolumeManager; import org.apache.accumulo.tserver.compaction.MajorCompactionReason; import org.apache.accumulo.tserver.compaction.MajorCompactionRequest; import org.easymock.EasyMock; import timely.adapter.accumulo.MetricAdapter; public class CompactionRequestBuilder { private static final long DEFAULT_TIME_MILLIS = new GregorianCalendar(2019, Calendar.JANUARY, 1).getTimeInMillis(); private static final Lexicoder<String> stringEncoder = new StringLexicoder(); private static final PairLexicoder<String, String> badPairEncoder = new PairLexicoder<>(stringEncoder, stringEncoder); private final Map<FileRef, DataFileValue> refs = new LinkedHashMap<>(); private final Map<String, String> tableProperties; private final long timeMillis; private Key endKeyMetric; private Key prevKeyMetric; public CompactionRequestBuilder() { this(DEFAULT_TIME_MILLIS); } public CompactionRequestBuilder(long timeMillis) { this.timeMillis = timeMillis; this.tableProperties = new TreeMap<>(); } public CompactionRequestBuilder endKeyMetricNonOffset(String name, String offset) { byte[] rowKey = offset != null ? badPairEncoder.encode(new ComparablePair<>(name, offset)) : stringEncoder.encode(name); endKeyMetric = new Key(rowKey); return this; } public CompactionRequestBuilder endKeyMetric(String name, long offset) { long ts = timeMillis - offset; byte[] rowKey = MetricAdapter.encodeRowKey(name, ts); endKeyMetric = new Key(rowKey); return this; } public CompactionRequestBuilder prevEndKeyMetric(String name, long offset) { long ts = timeMillis - offset; byte[] rowKey = MetricAdapter.encodeRowKey(name, ts); prevKeyMetric = new Key(rowKey); return this; } public CompactionRequestBuilder prevEndKeyMetricNonOffset(String name, String offset) { byte[] rowKey = offset != null ? badPairEncoder.encode(new ComparablePair<>(name, offset)) : stringEncoder.encode(name); prevKeyMetric = new Key(rowKey); return this; } public CompactionRequestBuilder file(String path, long size, long entries) { refs.put(new FileRef(path), new DataFileValue(size, entries)); return this; } public CompactionRequestBuilder tableProperties(String key, String value) { tableProperties.put(key, value); return this; } public MajorCompactionRequest build() { String tableName = "1"; KeyExtent ke = new KeyExtent(); ke.setTableId(tableName); if (null != endKeyMetric) { ke.setEndRow(endKeyMetric.getRow()); } if (null != prevKeyMetric) { ke.setPrevEndRow(prevKeyMetric.getRow()); } TabletId tid = new TabletIdImpl(ke); // @formatter:off MajorCompactionRequest req = EasyMock.partialMockBuilder(MajorCompactionRequest.class) .withConstructor(KeyExtent.class, MajorCompactionReason.class, VolumeManager.class, AccumuloConfiguration.class) .withArgs(ke, MajorCompactionReason.NORMAL, null, AccumuloConfiguration.getDefaultConfiguration()) .addMockedMethod("getTabletId") .addMockedMethod("getTableProperties") .createMock(); // @formatter:on req.setFiles(refs); EasyMock.expect(req.getTabletId()).andStubReturn(tid); EasyMock.expect(req.getTableProperties()).andStubReturn(tableProperties); EasyMock.replay(req); return req; } }
1,759
1,587
package io.reflectoring.springcloudredis.controller; import io.reflectoring.springcloudredis.entity.User; import io.reflectoring.springcloudredis.service.UserService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Slf4j(topic = "PRODUCT_CONTROLLER") @RestController @RequestMapping("/user") @AllArgsConstructor public class UserController { private final UserService userService; @GetMapping("/{id}") public User getUser(@PathVariable String id) { return userService.getUser(id); } }
258
2,461
def test_simple(): assert True # A syntax error: :
22
374
/* * Copyright (c) 1999-2004 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "includes.h" #include <sys/types.h> #ifdef HAVE_SYS_SELECT_H # include <sys/select.h> #endif #ifdef HAVE_SYS_TIME_H # include <sys/time.h> #endif #include <err.h> #include <string.h> #include <signal.h> #include <stdlib.h> #include <time.h> #include <unistd.h> int nanosleep(const struct timespec *req, struct timespec *rem) { int rc, saverrno; extern int errno; struct timeval tstart, tstop, tremain, time2wait; TIMESPEC_TO_TIMEVAL(&time2wait, req); (void) gettimeofday(&tstart, NULL); rc = select(0, NULL, NULL, NULL, &time2wait); if (rc == -1) { saverrno = errno; (void) gettimeofday (&tstop, NULL); errno = saverrno; tremain.tv_sec = time2wait.tv_sec - (tstop.tv_sec - tstart.tv_sec); tremain.tv_usec = time2wait.tv_usec - (tstop.tv_usec - tstart.tv_usec); tremain.tv_sec += tremain.tv_usec / 1000000L; tremain.tv_usec %= 1000000L; } else { tremain.tv_sec = 0; tremain.tv_usec = 0; } if (rem != NULL) TIMEVAL_TO_TIMESPEC(&tremain, rem); return(rc); }
697
1,114
<reponame>abod1944/cognitive-services-speech-sdk<filename>samples/java/jre/console/src/com/microsoft/cognitiveservices/speech/samples/console/SpeechSynthesisScenarioSamples.java // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // package com.microsoft.cognitiveservices.speech.samples.console; import com.microsoft.cognitiveservices.speech.*; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.commons.text.StringEscapeUtils; import java.util.*; import java.util.stream.IntStream; // Scenario: // In scenario like voice assistant or call center, normally TTS can be integrated from service side // The client app will talk to the middle layer service which will talk to ASR, dialog, and TTS. // In this scenario, latency is one important metrics for better user experience. // // Best Practice: // For server scenario synthesizing with high concurrency, we recommend two methods to reduce the latency. // Firstly, reuse the synthesizers (e.g. use a synthesizer pool ) to reduce the connection establish latency. // This is because new synthesizer instance need to take time to connect to the service. Reusing the instance can save time of connection. // Secondly, use AudioOutputStream or synthesizing event to streaming receive the synthesized audio to lower the first byte latency. // This middle layer service should send audio back to client app/device as soon as possible. // On the client side, it can start playback when enough audio bytes has been received. public class SpeechSynthesisScenarioSamples { public static class SynthesizerPoolFactory extends BasePooledObjectFactory<SpeechSynthesizer> { private final SpeechConfig config; public SynthesizerPoolFactory(){ // Creates an instance of a speech config with specified // subscription key and service region. Replace with your own subscription key // and service region (e.g., "westus"). config = SpeechConfig.fromSubscription("YourSubscriptionKey", "YourServiceRegion"); // Use a compression format e.g. mp3 to save the bandwidth. config.setSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3); } @Override public SpeechSynthesizer create() { System.out.println("create a brand new synthesizer"); return new SpeechSynthesizer(config, null); } @Override public PooledObject<SpeechSynthesizer> wrap(SpeechSynthesizer synthesizer) { return new DefaultPooledObject<>(synthesizer); } @Override public void destroyObject(PooledObject<SpeechSynthesizer> p) { SpeechSynthesizer synthesizer = p.getObject(); synthesizer.close(); } } /** * A synthesizer class to handle concurrent request */ public static class SpeechSynthesisService { // Update the SSML pattern to control the synthesis voice, style and rate. private static final String SSML_PATTERN = "<speak xmlns='http://www.w3.org/2001/10/synthesis' xmlns:mstts='http://www.w3.org/2001/mstts' xmlns:emo='http://www.w3.org/2009/10/emotionml' version='1.0' xml:lang='zh-CN'><voice name='%s' style='chat' rate='5%%'>%s</voice></speak>"; private final GenericObjectPool<SpeechSynthesizer> pool; public SpeechSynthesisService() { // For server scenario synthesizing with high concurrency, we recommend two methods to reduce the latency. // Firstly, reuse the synthesizers (e.g. use a synthesizer pool )to reduce the connection establish latency; // This is because new synthesizer instance need to take time to connect to the service. Reusing the instance can save time of conenction. // secondly, use AudioOutputStream or synthesizing event to streaming receive the synthesized audio to lower the first byte latency. GenericObjectPoolConfig<SpeechSynthesizer> poolConfig = new GenericObjectPoolConfig<>(); poolConfig.setMinIdle(2); poolConfig.setMaxTotal(64); // Make sure pool is a single object instance used to handle all request. // You can put it as a static field of a class pool = new GenericObjectPool<>(new SynthesizerPoolFactory(), poolConfig); } /** * A thread-safe method to synthesize content * @param content The text to synthesize * @param voice The voice name, e.g. en-US-JennyNeural * @return The first byte latency and processing time, in millisecond. */ public long[] synthesis(String content, String voice) { long[] latency = new long[2]; try { long start = System.currentTimeMillis(); boolean first = true; String ssml = String.format(SSML_PATTERN, voice, StringEscapeUtils.escapeXml11(content)); SpeechSynthesizer synthesizer = pool.borrowObject(); SpeechSynthesisResult result = synthesizer.StartSpeakingSsml(ssml); AudioDataStream audioDataStream = AudioDataStream.fromResult(result); // Adjust the buffer size based on your format. You use the buffer size of 50ms audio. byte[] buffer = new byte[1600]; while (true) { long len = audioDataStream.readData(buffer); if (len == 0) { break; } if (first) { latency[0] = System.currentTimeMillis() - start; System.out.printf("Speaking [%s], first byte latency: %s ms.%n", content, latency[0]); first = false; } // Here you can save the audio or send the data to another pipeline in your service. } latency[1] = System.currentTimeMillis() - start; if (audioDataStream.getStatus() != StreamStatus.AllData) { SpeechSynthesisCancellationDetails speechSynthesisCancellationDetails = SpeechSynthesisCancellationDetails.fromStream(audioDataStream); System.out.println(speechSynthesisCancellationDetails); synthesizer.close(); } else { pool.returnObject(synthesizer); } audioDataStream.close(); } catch (Exception e) { e.printStackTrace(); } return latency; } } // Speech synthesis sample for server scenario public static void synthesisServerScenarioAsync() throws InterruptedException { List<Long> latencies = new ArrayList<>(); List<Long> processingTimes = new ArrayList<>(); SpeechSynthesisService service = new SpeechSynthesisService(); for (int turn = 0; turn < 3; turn++) { int finalTurn = turn; System.out.printf("Turn: %d%n", finalTurn); IntStream.range(0, 64).parallel().forEach(i -> { long[] latency = service.synthesis(String.format("today is a nice day. %d%d", finalTurn, i), "en-US-JennyNeural"); if (finalTurn > 0) { latencies.add(latency[0]); processingTimes.add(latency[1]); } }); Thread.sleep(2000); } Collections.sort(latencies); int avgLatency = (int) latencies.stream().mapToLong(val -> val).average().orElse(-1.0); Long minLatency = latencies.stream().mapToLong(val -> val).min().orElse(-1); Long maxLatency = latencies.stream().mapToLong(val -> val).max().orElse(-1); Long latency90 = latencies.get((int) Math.ceil(latencies.size() * 0.9)); Long latency95 = latencies.get((int) Math.ceil(latencies.size() * 0.95)); Collections.sort(processingTimes); int avgProcessingTime = (int) processingTimes.stream().mapToLong(val -> val).average().orElse(-1.0); Long minProcessingTime = processingTimes.stream().mapToLong(val -> val).min().orElse(-1); Long maxProcessingTime = processingTimes.stream().mapToLong(val -> val).max().orElse(-1); Long processingTime90 = processingTimes.get((int) Math.ceil(processingTimes.size() * 0.9)); Long processingTime95 = processingTimes.get((int) Math.ceil(processingTimes.size() * 0.95)); System.out.printf( "Min Latency :%d ms\n" + "Max Latency :%d ms\n" + "Average Latency :%d ms\n" + "90 Percentile Latency :%d ms\n" + "95 Percentile Latency :%d ms\n" + "\n" + "Min Process Time :%d ms\n" + "Max Process Time :%d ms\n" + "Average Process Time :%d ms\n" + "90 Percentile Process Time :%d ms\n" + "95 Percentile Process Time :%d ms\n%n", minLatency, maxLatency, avgLatency, latency90, latency95, minProcessingTime, maxProcessingTime, avgProcessingTime, processingTime90, processingTime95 ); } }
3,942
1,603
package com.linkedin.metadata.recommendation; import com.linkedin.common.urn.Urn; import com.linkedin.metadata.recommendation.candidatesource.RecommendationSource; import com.linkedin.metadata.recommendation.ranker.RecommendationModuleRanker; import com.linkedin.metadata.utils.ConcurrencyUtils; import io.opentelemetry.extension.annotations.WithSpan; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.Nonnull; import lombok.extern.slf4j.Slf4j; @Slf4j public class RecommendationsService { private final List<RecommendationSource> _candidateSources; private final RecommendationModuleRanker _moduleRanker; public RecommendationsService( final List<RecommendationSource> candidateSources, final RecommendationModuleRanker moduleRanker) { validateRecommendationSources(candidateSources); _candidateSources = candidateSources; _moduleRanker = moduleRanker; } private void validateRecommendationSources(final List<RecommendationSource> candidateSources) { final Map<String, Long> moduleIdCount = candidateSources.stream() .collect(Collectors.groupingBy(RecommendationSource::getModuleId, Collectors.counting())); List<String> moduleIdsWithDuplicates = moduleIdCount.entrySet() .stream() .filter(entry -> entry.getValue() > 1) .map(Map.Entry::getKey) .collect(Collectors.toList()); if (!moduleIdsWithDuplicates.isEmpty()) { throw new IllegalArgumentException( String.format("Found recommendations candidate sources with duplicate module IDs: %s", moduleIdsWithDuplicates.toString())); } } /** * Return the list of recommendation modules given input context * * @param userUrn User requesting recommendations * @param requestContext Context of where the recommendations are being requested * @param limit Max number of modules to return * @return List of recommendation modules */ @Nonnull @WithSpan public List<RecommendationModule> listRecommendations( @Nonnull Urn userUrn, @Nonnull RecommendationRequestContext requestContext, int limit) { // Get recommendation candidates from sources which are eligible, in parallel final List<RecommendationModule> candidateModules = ConcurrencyUtils.transformAndCollectAsync(_candidateSources.stream() .filter(source -> source.isEligible(userUrn, requestContext)) .collect(Collectors.toList()), source -> source.getRecommendationModule(userUrn, requestContext), (source, exception) -> { log.error("Error while fetching candidate modules from source {}", source, exception); return Optional.<RecommendationModule>empty(); }).stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()); // Rank recommendation modules, which determines their ordering during rendering return _moduleRanker.rank(candidateModules, userUrn, requestContext, limit); } }
905
383
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zuoxiaolong.niubi.job.persistent; import com.zuoxiaolong.niubi.job.persistent.entity.User; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; /** * @author <NAME> * @since 0.9.4.2 */ public class BaseDaoTest extends AbstractSpringTestCase { @Autowired private BaseDao baseDao; @Test public void baseAutowired() { Assert.assertNotNull(baseDao); } @Test public void save() { User user = new User(); user.setUserName("123"); user.setUserPassword("<PASSWORD>"); user.setPasswordSalt("<PASSWORD>"); String id = baseDao.save(user); User userInDb = baseDao.get(User.class, id); Assert.assertNotNull(userInDb); Assert.assertEquals(userInDb.getUserName(), "123"); Assert.assertEquals(userInDb.getUserPassword(), "<PASSWORD>"); Assert.assertEquals(userInDb.getPasswordSalt(), "<PASSWORD>"); baseDao.delete(userInDb); } @Test public void update() { User user = new User(); user.setUserName("123"); user.setUserPassword("<PASSWORD>"); user.setPasswordSalt("<PASSWORD>"); String id = baseDao.save(user); User userInDb = baseDao.get(User.class, id); userInDb.setUserName("aaa"); userInDb.setUserPassword("<PASSWORD>"); userInDb.setPasswordSalt("<PASSWORD>"); baseDao.update(userInDb); userInDb = baseDao.get(User.class, id); Assert.assertNotNull(userInDb); Assert.assertEquals(userInDb.getUserName(), "aaa"); Assert.assertEquals(userInDb.getUserPassword(), "bbb"); Assert.assertEquals(userInDb.getPasswordSalt(), "ccc"); baseDao.delete(userInDb); } @Test public void delete() { User user = new User(); user.setUserName("123"); user.setUserPassword("<PASSWORD>"); user.setPasswordSalt("<PASSWORD>"); String id = baseDao.save(user); User userInDb = baseDao.get(User.class, id); Assert.assertNotNull(userInDb); baseDao.delete(userInDb); userInDb = baseDao.get(User.class, id); Assert.assertNull(userInDb); } @Test public void getAll() { User user1 = new User(); user1.setUserName("1"); user1.setUserPassword("1"); user1.setPasswordSalt("1"); User user2 = new User(); user2.setUserName("2"); user2.setUserPassword("2"); user2.setPasswordSalt("2"); User user3 = new User(); user3.setUserName("3"); user3.setUserPassword("3"); user3.setPasswordSalt("3"); String id1 = baseDao.save(user1); String id2 = baseDao.save(user2); String id3 = baseDao.save(user3); List<User> users = baseDao.getAll(User.class); Assert.assertNotNull(users); Assert.assertTrue(users.size() == 3); Assert.assertNotNull(users.get(0)); Assert.assertEquals(users.get(0).getUserName(), "1"); Assert.assertEquals(users.get(0).getUserPassword(), "1"); Assert.assertEquals(users.get(0).getPasswordSalt(), "1"); Assert.assertEquals(users.get(0).getId(), id1); Assert.assertNotNull(users.get(0)); Assert.assertEquals(users.get(1).getUserName(), "2"); Assert.assertEquals(users.get(1).getUserPassword(), "2"); Assert.assertEquals(users.get(1).getPasswordSalt(), "2"); Assert.assertEquals(users.get(1).getId(), id2); Assert.assertNotNull(users.get(2)); Assert.assertEquals(users.get(2).getUserName(), "3"); Assert.assertEquals(users.get(2).getUserPassword(), "3"); Assert.assertEquals(users.get(2).getPasswordSalt(), "3"); Assert.assertEquals(users.get(2).getId(), id3); baseDao.delete(user1); baseDao.delete(user2); baseDao.delete(user3); } @Test public void get() { User user = new User(); user.setUserName("123"); user.setUserPassword("<PASSWORD>"); user.setPasswordSalt("<PASSWORD>"); String id = baseDao.save(user); User userInDb = baseDao.get(User.class, id); Assert.assertNotNull(userInDb); Assert.assertEquals(userInDb.getUserName(), "123"); Assert.assertEquals(userInDb.getUserPassword(), "<PASSWORD>"); Assert.assertEquals(userInDb.getPasswordSalt(), "<PASSWORD>"); baseDao.delete(userInDb); } @Test public void getList() { User user = new User(); user.setUserName("123"); user.setUserPassword("<PASSWORD>"); user.setPasswordSalt("<PASSWORD>"); String id = baseDao.save(user); List<User> users = baseDao.getList(User.class, user); Assert.assertNotNull(users); Assert.assertTrue(users.size() == 1); Assert.assertNotNull(users.get(0)); Assert.assertEquals(users.get(0).getUserName(), "123"); Assert.assertEquals(users.get(0).getUserPassword(), "<PASSWORD>"); Assert.assertEquals(users.get(0).getPasswordSalt(), "<PASSWORD>"); Assert.assertEquals(users.get(0).getId(), id); baseDao.delete(users.get(0)); } @Test public void getUnique() { User user = new User(); user.setUserName("123"); user.setUserPassword("<PASSWORD>"); user.setPasswordSalt("<PASSWORD>"); String id = baseDao.save(user); User userInDb = baseDao.getUnique(User.class, user); Assert.assertNotNull(userInDb); Assert.assertEquals(userInDb.getUserName(), "123"); Assert.assertEquals(userInDb.getUserPassword(), "<PASSWORD>"); Assert.assertEquals(userInDb.getPasswordSalt(), "<PASSWORD>"); Assert.assertEquals(userInDb.getId(), id); baseDao.delete(userInDb); } @Test public void getByPager() { User user = new User(); user.setUserName("123"); user.setUserPassword("<PASSWORD>"); user.setPasswordSalt("<PASSWORD>"); String id = baseDao.save(user); Pager<User> pager = new Pager<>(); Pager<User> pagerInDb = baseDao.getByPager(User.class, pager, user, false); Assert.assertNotNull(pagerInDb); Assert.assertTrue(pagerInDb.getTotalCount() == 1); Assert.assertTrue(pagerInDb.getViewJsonData().getRows().size() == 1); Assert.assertEquals(pagerInDb.getViewJsonData().getRows().get(0).getUserName(), "123"); Assert.assertEquals(pagerInDb.getViewJsonData().getRows().get(0).getUserPassword(), "<PASSWORD>"); Assert.assertEquals(pagerInDb.getViewJsonData().getRows().get(0).getPasswordSalt(), "<PASSWORD>"); Assert.assertEquals(pagerInDb.getViewJsonData().getRows().get(0).getId(), id); baseDao.delete(pagerInDb.getViewJsonData().getRows().get(0)); } }
3,285
342
<reponame>ramesh-kr/sentinel<filename>mobile-client-android/sentinel_android/app/src/main/java/sentinelgroup/io/sentinel/db/dao/VpnListEntryDao.java package sentinelgroup.io.sentinel.db.dao; import android.arch.lifecycle.LiveData; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Insert; import android.arch.persistence.room.OnConflictStrategy; import android.arch.persistence.room.Query; import java.util.List; import sentinelgroup.io.sentinel.network.model.VpnListEntity; /** * DAO to do CRUD operation related to VPN List. */ @Dao public interface VpnListEntryDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insertVpnListEntity(List<VpnListEntity> iEntity); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery") LiveData<List<VpnListEntity>> getVpnLisEntity(String iSearchQuery); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery AND isBookmarked = :toFilterByBookmark") LiveData<List<VpnListEntity>> getVpnLisEntity(String iSearchQuery, boolean toFilterByBookmark); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery ORDER BY location_country COLLATE NOCASE ASC") LiveData<List<VpnListEntity>> getVpnLisEntitySortCountryA(String iSearchQuery); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery AND isBookmarked = :toFilterByBookmark ORDER BY location_country COLLATE NOCASE ASC") LiveData<List<VpnListEntity>> getVpnLisEntitySortCountryA(String iSearchQuery, boolean toFilterByBookmark); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery ORDER BY location_country COLLATE NOCASE DESC") LiveData<List<VpnListEntity>> getVpnLisEntitySortCountryD(String iSearchQuery); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery AND isBookmarked = :toFilterByBookmark ORDER BY location_country COLLATE NOCASE DESC") LiveData<List<VpnListEntity>> getVpnLisEntitySortCountryD(String iSearchQuery, boolean toFilterByBookmark); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery ORDER BY latency COLLATE NOCASE ASC") LiveData<List<VpnListEntity>> getVpnLisEntitySortLatencyI(String iSearchQuery); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery AND isBookmarked = :toFilterByBookmark ORDER BY latency COLLATE NOCASE ASC") LiveData<List<VpnListEntity>> getVpnLisEntitySortLatencyI(String iSearchQuery, boolean toFilterByBookmark); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery ORDER BY latency COLLATE NOCASE DESC") LiveData<List<VpnListEntity>> getVpnLisEntitySortLatencyD(String iSearchQuery); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery AND isBookmarked = :toFilterByBookmark ORDER BY latency COLLATE NOCASE DESC") LiveData<List<VpnListEntity>> getVpnLisEntitySortLatencyD(String iSearchQuery, boolean toFilterByBookmark); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery ORDER BY net_download COLLATE NOCASE ASC") LiveData<List<VpnListEntity>> getVpnLisEntitySortBandwidthI(String iSearchQuery); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery AND isBookmarked = :toFilterByBookmark ORDER BY net_download COLLATE NOCASE ASC") LiveData<List<VpnListEntity>> getVpnLisEntitySortBandwidthI(String iSearchQuery, boolean toFilterByBookmark); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery ORDER BY net_download COLLATE NOCASE DESC") LiveData<List<VpnListEntity>> getVpnLisEntitySortBandwidthD(String iSearchQuery); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery AND isBookmarked = :toFilterByBookmark ORDER BY net_download COLLATE NOCASE DESC") LiveData<List<VpnListEntity>> getVpnLisEntitySortBandwidthD(String iSearchQuery, boolean toFilterByBookmark); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery ORDER BY pricePerGb COLLATE NOCASE ASC") LiveData<List<VpnListEntity>> getVpnLisEntitySortPriceI(String iSearchQuery); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery AND isBookmarked = :toFilterByBookmark ORDER BY pricePerGb COLLATE NOCASE ASC") LiveData<List<VpnListEntity>> getVpnLisEntitySortPriceI(String iSearchQuery, boolean toFilterByBookmark); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery ORDER BY pricePerGb COLLATE NOCASE DESC") LiveData<List<VpnListEntity>> getVpnLisEntitySortPriceD(String iSearchQuery); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery AND isBookmarked = :toFilterByBookmark ORDER BY pricePerGb COLLATE NOCASE DESC") LiveData<List<VpnListEntity>> getVpnLisEntitySortPriceD(String iSearchQuery, boolean toFilterByBookmark); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery ORDER BY rating COLLATE NOCASE ASC") LiveData<List<VpnListEntity>> getVpnLisEntitySortRatingI(String iSearchQuery); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery AND isBookmarked = :toFilterByBookmark ORDER BY rating COLLATE NOCASE ASC") LiveData<List<VpnListEntity>> getVpnLisEntitySortRatingI(String iSearchQuery, boolean toFilterByBookmark); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery ORDER BY rating COLLATE NOCASE DESC") LiveData<List<VpnListEntity>> getVpnLisEntitySortRatingD(String iSearchQuery); @Query("SELECT * FROM vpn_list_entity WHERE location_country LIKE :iSearchQuery AND isBookmarked = :toFilterByBookmark ORDER BY rating COLLATE NOCASE DESC") LiveData<List<VpnListEntity>> getVpnLisEntitySortRatingD(String iSearchQuery, boolean toFilterByBookmark); @Query("SELECT * FROM vpn_list_entity WHERE accountAddress = :iVpnAddress") LiveData<VpnListEntity> getVpnEntity(String iVpnAddress); @Query("UPDATE vpn_list_entity SET isBookmarked = :isBookmarked WHERE accountAddress = :iVpnAddress AND ip = :iIP") void updateBookmark(boolean isBookmarked, String iVpnAddress, String iIP); @Query("DELETE FROM vpn_list_entity") void deleteVpnListEntity(); }
2,035
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.analytics.synapse.artifacts.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** A copy activity Azure Table source. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonTypeName("AzureTableSource") @Fluent public final class AzureTableSource extends TabularSource { /* * Azure Table source query. Type: string (or Expression with resultType * string). */ @JsonProperty(value = "azureTableSourceQuery") private Object azureTableSourceQuery; /* * Azure Table source ignore table not found. Type: boolean (or Expression * with resultType boolean). */ @JsonProperty(value = "azureTableSourceIgnoreTableNotFound") private Object azureTableSourceIgnoreTableNotFound; /** * Get the azureTableSourceQuery property: Azure Table source query. Type: string (or Expression with resultType * string). * * @return the azureTableSourceQuery value. */ public Object getAzureTableSourceQuery() { return this.azureTableSourceQuery; } /** * Set the azureTableSourceQuery property: Azure Table source query. Type: string (or Expression with resultType * string). * * @param azureTableSourceQuery the azureTableSourceQuery value to set. * @return the AzureTableSource object itself. */ public AzureTableSource setAzureTableSourceQuery(Object azureTableSourceQuery) { this.azureTableSourceQuery = azureTableSourceQuery; return this; } /** * Get the azureTableSourceIgnoreTableNotFound property: Azure Table source ignore table not found. Type: boolean * (or Expression with resultType boolean). * * @return the azureTableSourceIgnoreTableNotFound value. */ public Object getAzureTableSourceIgnoreTableNotFound() { return this.azureTableSourceIgnoreTableNotFound; } /** * Set the azureTableSourceIgnoreTableNotFound property: Azure Table source ignore table not found. Type: boolean * (or Expression with resultType boolean). * * @param azureTableSourceIgnoreTableNotFound the azureTableSourceIgnoreTableNotFound value to set. * @return the AzureTableSource object itself. */ public AzureTableSource setAzureTableSourceIgnoreTableNotFound(Object azureTableSourceIgnoreTableNotFound) { this.azureTableSourceIgnoreTableNotFound = azureTableSourceIgnoreTableNotFound; return this; } }
927
2,338
// Test that verifies TSan runtime doesn't contain compiler-emitted // memcpy/memmove calls. It builds the binary with TSan and check's // its objdump. // RUN: %clang_tsan -O1 %s -o %t // RUN: llvm-objdump -d -l %t | FileCheck %s int main() { return 0; } // CHECK-NOT: callq {{.*<(__interceptor_)?mem(cpy|set)>}} // tail calls: // CHECK-NOT: jmpq {{.*<(__interceptor_)?mem(cpy|set)>}}
156
380
<gh_stars>100-1000 #ifndef SERVER_TRACKER_VIEW_H #define SERVER_TRACKER_VIEW_H //-- includes ----- #include "ServerDeviceView.h" #include "PSMoveProtocolInterface.h" #include <vector> // -- pre-declarations ----- namespace PSMoveProtocol { class Response_ResultTrackerSettings; class TrackingColorPreset; }; // -- declarations ----- class ServerTrackerView : public ServerDeviceView { public: ServerTrackerView(const int device_id); ~ServerTrackerView(); bool open(const class DeviceEnumerator *enumerator) override; void close() override; // Starts or stops streaming of the video feed to the shared memory buffer. // Keep a ref count of how many clients are following the stream. void startSharedMemoryVideoStream(); void stopSharedMemoryVideoStream(); // Fetch the next video frame and copy to shared memory bool poll() override; IDeviceInterface* getDevice() const override {return m_device;} // Returns what type of tracker this tracker view represents CommonDeviceState::eDeviceType getTrackerDeviceType() const; // Returns what type of driver this tracker uses ITrackerInterface::eDriverType getTrackerDriverType() const; // Returns the full usb device path for the controller std::string getUSBDevicePath() const; // Returns the name of the shared memory block video frames are written to std::string getSharedMemoryStreamName() const; void loadSettings(); void saveSettings(); double getFrameWidth() const; void setFrameWidth(double value, bool bUpdateConfig); double getFrameHeight() const; void setFrameHeight(double value, bool bUpdateConfig); double getFrameRate() const; void setFrameRate(double value, bool bUpdateConfig); double getExposure() const; void setExposure(double value, bool bUpdateConfig); double getGain() const; void setGain(double value, bool bUpdateConfig); bool computeProjectionForController( const class ServerControllerView* tracked_controller, const struct CommonDeviceTrackingShape *tracking_shape, struct ControllerOpticalPoseEstimation *out_pose_estimate); bool computeProjectionForHMD( const class ServerHMDView* tracked_hmd, const struct CommonDeviceTrackingShape *tracking_shape, struct HMDOpticalPoseEstimation *out_pose_estimate); bool computePoseForProjection( const struct CommonDeviceTrackingProjection *projection, const struct CommonDeviceTrackingShape *tracking_shape, const struct CommonDevicePose *pose_guess, struct ControllerOpticalPoseEstimation *out_pose_estimate); std::vector<CommonDeviceScreenLocation> projectTrackerRelativePositions( const std::vector<CommonDevicePosition> &objectPositions) const; CommonDeviceScreenLocation projectTrackerRelativePosition(const CommonDevicePosition *trackerRelativePosition) const; CommonDevicePosition computeWorldPosition(const CommonDevicePosition *tracker_relative_position) const; CommonDeviceQuaternion computeWorldOrientation(const CommonDeviceQuaternion *tracker_relative_orientation) const; CommonDevicePosition computeTrackerPosition(const CommonDevicePosition *world_relative_position) const; CommonDeviceQuaternion computeTrackerOrientation(const CommonDeviceQuaternion *world_relative_orientation) const; /// Given a single screen location on two different trackers, compute the triangulated world space location static CommonDevicePosition triangulateWorldPosition( const ServerTrackerView *tracker, const CommonDeviceScreenLocation *screen_location, const ServerTrackerView *other_tracker, const CommonDeviceScreenLocation *other_screen_location); /// Given a set of screen locations on two different trackers, compute the triangulated world space locations static void triangulateWorldPositions( const ServerTrackerView *tracker, const CommonDeviceScreenLocation *screen_locations, const ServerTrackerView *other_tracker, const CommonDeviceScreenLocation *other_screen_locations, const int screen_location_count, CommonDevicePosition *out_result); /// Given screen projections on two different trackers, compute the triangulated world space location static CommonDevicePose triangulateWorldPose( const ServerTrackerView *tracker, const CommonDeviceTrackingProjection *tracker_relative_projection, const ServerTrackerView *other_tracker, const CommonDeviceTrackingProjection *other_tracker_relative_projection); void getCameraIntrinsics( float &outFocalLengthX, float &outFocalLengthY, float &outPrincipalX, float &outPrincipalY, float &outDistortionK1, float &outDistortionK2, float &outDistortionK3, float &outDistortionP1, float &outDistortionP2) const; void setCameraIntrinsics( float focalLengthX, float focalLengthY, float principalX, float principalY, float distortionK1, float distortionK2, float distortionK3, float distortionP1, float distortionP2); CommonDevicePose getTrackerPose() const; void setTrackerPose(const struct CommonDevicePose *pose); void getPixelDimensions(float &outWidth, float &outHeight) const; void getFOV(float &outHFOV, float &outVFOV) const; void getZRange(float &outZNear, float &outZFar) const; void gatherTrackerOptions(PSMoveProtocol::Response_ResultTrackerSettings* settings) const; bool setOptionIndex(const std::string &option_name, int option_index); bool getOptionIndex(const std::string &option_name, int &out_option_index) const; void gatherTrackingColorPresets(const class ServerControllerView *controller, PSMoveProtocol::Response_ResultTrackerSettings* settings) const; void gatherTrackingColorPresets(const class ServerHMDView *hmd, PSMoveProtocol::Response_ResultTrackerSettings* settings) const; void setControllerTrackingColorPreset(const class ServerControllerView *controller, eCommonTrackingColorID color, const CommonHSVColorRange *preset); void getControllerTrackingColorPreset(const class ServerControllerView *controller, eCommonTrackingColorID color, CommonHSVColorRange *out_preset) const; void setHMDTrackingColorPreset(const class ServerHMDView *controller, eCommonTrackingColorID color, const CommonHSVColorRange *preset); void getHMDTrackingColorPreset(const class ServerHMDView *controller, eCommonTrackingColorID color, CommonHSVColorRange *out_preset) const; protected: bool allocate_device_interface(const class DeviceEnumerator *enumerator) override; void free_device_interface() override; void publish_device_data_frame() override; static void generate_tracker_data_frame_for_stream( const ServerTrackerView *tracker_view, const struct TrackerStreamInfo *stream_info, DeviceOutputDataFramePtr &data_frame); private: char m_shared_memory_name[256]; class SharedVideoFrameReadWriteAccessor *m_shared_memory_accesor; int m_shared_memory_video_stream_count; class OpenCVBufferState *m_opencv_buffer_state; ITrackerInterface *m_device; }; #endif // SERVER_TRACKER_VIEW_H
2,152
2,177
package org.nutz.mvc.testapp.classes.bean; public class Issue1109 { private String id; private String goodsPicMain; private String marketingNum; private String goodsName; // private String goodsId; // private String goodsUrl; // private String couponUrl; // @Column // @Comment("渠道") // @ColDefine(type = ColType.VARCHAR, width = 100) // private String channel; // @Column // @Comment("业务员") // @ColDefine(type = ColType.VARCHAR, width = 100) // private String salesman; // @Column // @Comment("ffffff") // @ColDefine(type = ColType.VARCHAR, width = 100) // private String ffffff; // // @Column // @Comment("eeeee") // @ColDefine(type = ColType.VARCHAR, width = 100) // private String eeeee; // // @Column // @Comment("ddddd") // @ColDefine(type = ColType.VARCHAR, width = 100) // private String ddddd; // // @Column // @Comment("ccccc") // @ColDefine(type = ColType.VARCHAR, width = 100) // private String ccccc; // // @Column // @Comment("bbbbb") // @ColDefine(type = ColType.VARCHAR, width = 100) // private String bbbbb; // // @Column // @Comment("aaaaaa") // @ColDefine(type = ColType.VARCHAR, width = 100) // private String aaaaaa; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getGoodsPicMain() { return goodsPicMain; } public void setGoodsPicMain(String goodsPicMain) { this.goodsPicMain = goodsPicMain; } public String getMarketingNum() { return marketingNum; } public void setMarketingNum(String marketingNum) { this.marketingNum = marketingNum; } public String getGoodsName() { return goodsName; } public void setGoodsName(String goodsName) { this.goodsName = goodsName; } // public String getGoodsId() { // return goodsId; // } // // public void setGoodsId(String goodsId) { // this.goodsId = goodsId; // } // // public String getGoodsUrl() { // return goodsUrl; // } // // public void setGoodsUrl(String goodsUrl) { // this.goodsUrl = goodsUrl; // } // // public String getCouponUrl() { // return couponUrl; // } // // public void setCouponUrl(String couponUrl) { // this.couponUrl = couponUrl; // } // public String getChannel() { // return channel; // } // // public void setChannel(String channel) { // this.channel = channel; // } // // public String getSalesman() { // return salesman; // } // // public void setSalesman(String salesman) { // this.salesman = salesman; // } // // public String getFfffff() { // return ffffff; // } // // public void setFfffff(String ffffff) { // this.ffffff = ffffff; // } // // public String getEeeee() { // return eeeee; // } // // public void setEeeee(String eeeee) { // this.eeeee = eeeee; // } // // public String getDdddd() { // return ddddd; // } // // public void setDdddd(String ddddd) { // this.ddddd = ddddd; // } // // public String getCcccc() { // return ccccc; // } // // public void setCcccc(String ccccc) { // this.ccccc = ccccc; // } // // public String getBbbbb() { // return bbbbb; // } // // public void setBbbbb(String bbbbb) { // this.bbbbb = bbbbb; // } // // public String getAaaaaa() { // return aaaaaa; // } // // public void setAaaaaa(String aaaaaa) { // this.aaaaaa = aaaaaa; // } }
1,618
3,348
<gh_stars>1000+ #!/usr/bin/env python3 # -*- encoding: utf-8 -*- # 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. ''' rest.py ''' import requests ROUTE_SIGNATURES = { 'activate': (requests.post, '/api/v1/topologies/%s/%s/%s/%s/activate', []), 'deactivate': (requests.post, '/api/v1/topologies/%s/%s/%s/%s/deactivate', []), 'kill': (requests.delete, '/api/v1/topologies/%s/%s/%s/%s', []), 'restart': (requests.post, '/api/v1/topologies/%s/%s/%s/%s/restart', []), 'submit': (requests.post, '/api/v1/topologies', ['name', 'cluster', 'role', 'env', 'user']), 'update': (requests.post, '/api/v1/topologies/%s/%s/%s/%s/update', []), 'version': (requests.get, '/api/v1/version', []), }
517
5,169
{ "name": "IBProperty", "version": "1.2.0", "platforms": { "ios": "8.0" }, "summary": "A iOS Kit which would adapt screen by XIB and Storyboard better, and use better for XIB and Storyboard。", "homepage": "https://github.com/SunriseOYR/IBProperty", "license": { "type": "MIT", "file": "LICENSE" }, "authors": "Oranges and lemons", "social_media_url": "https://www.jianshu.com/u/80c622a1fe98", "source": { "git": "https://github.com/SunriseOYR/IBProperty.git", "tag": "v1.2.0" }, "source_files": [ "IBProperty", "IBProperty/**/*" ], "requires_arc": true, "dependencies": { "Aspects": [ "~> 1.4.1" ] } }
305
401
import unittest import logging import os from anchore.util.resources import ResourceCache logging.basicConfig(level='DEBUG') class TestResourceCache (unittest.TestCase): def test_basic(self): cache = ResourceCache(directory='/tmp') cache.clear() assert cache.is_empty() entry = cache.get('http://downloads.anchore.s3-website-us-west-2.amazonaws.com/') print entry assert entry['content'] is not None print cache.metadata cache.clear() def test_etagmatch(self): cache = ResourceCache(directory='/tmp') cache.clear() entry = cache.get('http://downloads.anchore.s3-website-us-west-2.amazonaws.com/') print entry assert entry['content'] is not None cache.clear()
316
862
import os import glob import pandas as pd import xml.etree.ElementTree as ET import json import io import csv from PIL import Image from utils.labelingtool_utils.json_to_csv import json_to_csv from utils.labelingtool_utils.xml_to_csv import xml_to_csv """ calls xml_to_csv and json_to_csv to generate a labels pandas dataframe then dumps the dataframe to a csv file Parameters ---------- images_path: str path of the images folder labels_path: str path of the labels folder output_path: str path of the folder to store the resulting csv file labels_type: str type of labels """ def labels_to_csv(images_path, labels_path, output_path, labels_type): labels_df = None if labels_type == "json": labels_df = json_to_csv(labels_path, images_path) labels_df.to_csv(output_path, index=None) print('Successfully converted json to csv.') elif labels_type == "pascal": column_name, xml_list = xml_to_csv(labels_path) with open(output_path, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=column_name) writer.writeheader() for row in xml_list: writer.writerow(row) print('Successfully converted pascal to csv.')
535
435
<filename>pycon-ph-2019/videos/pycon-apac-2019-gyenn-neil-ibo-multi-lingual-text-data-for-sentiment-classification.json { "copyright_text": null, "description": "Labeled Training Datasets or off-the-shelf tools for labeling training datasets for Sentiment Classification are readily available for English and other major languages. For Tagalog and other Filipino languages, however, this is rarely the case. I developed a novel technique that essentially transfers the knowledge of the labeled training dataset on one language (English) into Tagalog and other Filipino languages. This thus enables one to develop Neural Network Sentiment Classification models on several Filipino languages, leveraging on the availability of large amounts of training data on the English language. This is a better approach than manually labeling data on Filipino languages, as it would take too many resources, and Neural Networks need huge amounts of training data in order to be effective.", "duration": 2595, "language": "eng", "recorded": "2019-02-23", "related_urls": [ { "label": "Conference schedule", "url": "https://pycon.python.ph" } ], "speakers": [ "<NAME>" ], "tags": [ "sentiment analysis", "multilingual" ], "thumbnail_url": "https://i.ytimg.com/vi/9JA4sZ8BmJU/maxresdefault.jpg", "title": "Multi-lingual Text Data for Sentiment Classification", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=9JA4sZ8BmJU" } ] }
456
1,083
//===--- PILLayout.cpp - Defines PIL-level aggregate layouts --------------===// // // 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines classes that describe the physical layout of nominal // types in PIL, including structs, classes, and boxes. This is distinct from // the AST-level layout for several reasons: // - It avoids redundant work lowering the layout of aggregates from the AST. // - It allows optimizations to manipulate the layout of aggregates without // requiring changes to the AST. For instance, optimizations can eliminate // dead fields from instances or turn invariant fields into global variables. // - It allows for PIL-only aggregates to exist, such as boxes. // - It improves the robustness of code in the face of resilience. A resilient // type can be modeled in PIL as not having a layout at all, preventing the // inappropriate use of fragile projection and injection operations on the // type. // //===----------------------------------------------------------------------===// #include "polarphp/ast/AstContext.h" #include "polarphp/ast/PILLayout.h" #include "polarphp/ast/GenericSignature.h" #include "polarphp/ast/Types.h" #include "polarphp/basic/Range.h" namespace polar { static bool anyMutable(ArrayRef <PILField> Fields) { for (auto &field : Fields) { if (field.isMutable()) return true; } return false; } #ifndef NDEBUG /// Verify that the types of fields are valid within a given generic signature. static void verifyFields(CanGenericSignature Sig, ArrayRef <PILField> Fields) { for (auto &field : Fields) { auto ty = field.getLoweredType(); // Layouts should never refer to archetypes, since they represent an // abstract generic type layout. assert(!ty->hasArchetype() && "PILLayout field cannot have an archetype type"); assert(!ty->hasTypeVariable() && "PILLayout cannot contain constraint system type variables"); if (!ty->hasTypeParameter()) continue; field.getLoweredType().findIf([Sig](Type t) -> bool { if (auto gpt = t->getAs<GenericTypeParamType>()) { // Check that the generic param exists in the generic signature. assert(Sig && "generic param in nongeneric layout?"); assert(std::find(Sig.getGenericParams().begin(), Sig.getGenericParams().end(), gpt->getCanonicalType()) != Sig.getGenericParams().end() && "generic param not declared in generic signature?!"); } return false; }); } } #endif PILLayout::PILLayout(CanGenericSignature Sig, ArrayRef <PILField> Fields) : GenericSigAndFlags(Sig, getFlagsValue(anyMutable(Fields))), NumFields(Fields.size()) { #ifndef NDEBUG verifyFields(Sig, Fields); #endif auto FieldsMem = getTrailingObjects<PILField>(); for (unsigned i : indices(Fields)) { new(FieldsMem + i) PILField(Fields[i]); } } void PILLayout::Profile(llvm::FoldingSetNodeID &id, CanGenericSignature Generics, ArrayRef <PILField> Fields) { id.AddPointer(Generics.getPointer()); for (auto &field : Fields) { id.AddPointer(field.getLoweredType().getPointer()); id.AddBoolean(field.isMutable()); } } } // polar
1,314
1,056
<filename>enterprise/web.jsf/src/org/netbeans/modules/web/jsf/api/JsfComponentUtils.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.web.jsf.api; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.text.BadLocationException; import javax.swing.text.StyledDocument; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.java.project.classpath.ProjectClassPathModifier; import org.netbeans.api.project.FileOwnerQuery; import org.netbeans.api.project.Project; import org.netbeans.api.project.libraries.Library; import org.netbeans.api.project.libraries.LibraryManager; import org.netbeans.modules.editor.indent.api.Reformat; import org.netbeans.modules.java.api.common.util.CommonProjectUtils; import org.netbeans.modules.web.api.webmodule.WebModule; import org.netbeans.spi.project.ant.AntArtifactProvider; import org.netbeans.spi.project.libraries.LibraryFactory; import org.netbeans.spi.project.libraries.LibraryImplementation3; import org.openide.cookies.EditorCookie; import org.openide.filesystems.FileObject; import org.openide.loaders.DataObject; import org.openide.text.NbDocument; import org.openide.util.Exceptions; import org.openide.util.Mutex; import org.openide.util.Parameters; /** * Contains utilities methods for JSF components plugins. * * @author <NAME> <<EMAIL>> */ public class JsfComponentUtils { private JsfComponentUtils() { } /** * Recreates library with maven-pom content. If the library already contains * maven-pom content, nothing happen then. * <p> * Should be replaced once will be possible to enhance library content over API. * * @param library original library to be cloned * @param poms {@code List} of maven-pom {@code URI}s * @return library with pom content (the original library if the content wasn't added) * @throws IOException when original library cannot be deleted or recreated * @deprecated Instead of enhancing Ant libraries for Maven contents, another memory library should be created and * added to project using {@link ProjectClassPathModifier#addLibraries(org.netbeans.api.project.libraries.Library[], * org.openide.filesystems.FileObject, java.lang.String)}. Library enhances by "maven-pom" needn't to work since * {@code LibraryImplementation3}. Use {@link #createMavenDependencyLibrary(java.lang.String, java.lang.String[], * java.lang.String[])} instead. * @see #createMavenDependencyLibrary(java.lang.String, java.lang.String[], java.lang.String[]) */ @Deprecated public static Library enhanceLibraryWithPomContent(final Library library, final List<URI> poms) throws IOException { Parameters.notNull("library", library); //NOI18N Parameters.notNull("poms", poms); //NOI18N List<URL> mavenContent = library.getContent("maven-pom"); //NOI18N final String name = library.getName(); if (mavenContent == null || mavenContent.isEmpty()) { final Runnable call = new Runnable() { @Override public void run() { // copy existing contents final String type = library.getType(); final String name = library.getName(); final String displayName = library.getDisplayName(); final String desc = library.getDescription(); Map<String, List<URI>> content = new HashMap<String, List<URI>>(); content.put("classpath", library.getURIContent("classpath")); //NOI18N content.put("src", library.getURIContent("src")); //NOI18N content.put("javadoc", library.getURIContent("javadoc")); //NOI18N // include references to maven-pom artifacts content.put("maven-pom", poms); //NOI18N try { LibraryManager.getDefault().removeLibrary(library); LibraryManager.getDefault().createURILibrary(type, name, displayName, desc, content); } catch (IOException ioe) { Exceptions.printStackTrace(ioe); } catch (IllegalArgumentException iae) { Exceptions.printStackTrace(iae); } } }; Mutex.EVENT.writeAccess(call); } return LibraryManager.getDefault().getLibrary(name); } /** * Reformats given {@code DataObject}. * @param dob {@code DataObject} to reformat. * @since 1.35 */ public static void reformat(@NonNull DataObject dob) { Parameters.notNull("dob", dob); //NOI18N try { EditorCookie ec = dob.getLookup().lookup(EditorCookie.class); if (ec == null) { return; } final StyledDocument doc = ec.openDocument(); final Reformat reformat = Reformat.get(doc); reformat.lock(); try { NbDocument.runAtomicAsUser(doc, new Runnable() { @Override public void run() { try { reformat.reformat(0, doc.getLength()); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } }); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } finally { reformat.unlock(); ec.saveDocument(); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } } /** * Enhances existing data object for content. * @param dob data object to be enhanced * @param find text element where text should be included * @param enhanceBy enhancing content * @since 1.35 */ public static void enhanceFileBody(@NonNull DataObject dob, @NonNull final String find, @NonNull final String enhanceBy) { Parameters.notNull("dob", dob); //NOI18N Parameters.notNull("find", find); //NOI18N Parameters.notNull("enhanceBy", enhanceBy); //NOI18N try { EditorCookie ec = dob.getLookup().lookup(EditorCookie.class); if (ec == null) { return; } final StyledDocument doc = ec.openDocument(); try { NbDocument.runAtomicAsUser(doc, new Runnable() { @Override public void run() { try { int position = doc.getText(0, doc.getLength()).indexOf(find); // if element wasn't found - it isn't likely new project with sample index.html page and // there is probably not wished to have it changed, so don't do it if (position >= 0) { doc.insertString(position, enhanceBy + "\n", null); //NOI18N } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } }); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } finally { ec.saveDocument(); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } } /** * Says whether the given webModule is Maven based or not. It should prevent dependency of JSF component suite * libraries on Maven or Ant based modules. * @param webModule to be examined * @return {@code true} when the webModule is Maven based, {@code false} otherwise * @since 1.43 */ public static boolean isMavenBased(@NonNull WebModule webModule) { Parameters.notNull("webModule", webModule); //NOI18N FileObject fo = webModule.getDocumentBase(); if (fo == null) { // FIXME this is just best effort, perhaps there should be WebModule.getProject() FileObject[] sources = webModule.getJavaSources(); if (sources.length > 0) { fo = sources[0]; } } Project project = FileOwnerQuery.getOwner(fo); AntArtifactProvider antArtifactProvider = project.getLookup().lookup(AntArtifactProvider.class); return antArtifactProvider == null; } /** * Creates library used for Maven project extending by given pom resources. * @param name name of the library * @param mavenDeps maven dependencies to store in project pom.xml * @param mavenRepos maven repositories to store in project pom.xml * @return created library * @since 1.43 */ public static Library createMavenDependencyLibrary(@NonNull String name, @NonNull String[] mavenDeps, @NonNull String[] mavenRepos) { Parameters.notNull("name", name); //NOI18N Parameters.notNull("mavenDeps", mavenDeps); //NOI18N Parameters.notNull("mavenRepos", mavenRepos); //NOI18N LibraryImplementation3 libImpl = CommonProjectUtils.createJavaLibraryImplementation( name, new URL[0], new URL[0], new URL[0], mavenDeps, mavenRepos); return LibraryFactory.createLibrary(libImpl); } }
4,448
384
<gh_stars>100-1000 import torch import torch.nn as nn import torch.nn.functional as F import numpy as np #import matplotlib.pyplot as plt import pdb from torch.nn.modules.loss import _Loss from torch.autograd import Function, Variable #import scipy.io as sio class alpha_loss(_Loss): def __init__(self): super(alpha_loss,self).__init__() def forward(self,alpha,alpha_pred,mask): return normalized_l1_loss(alpha,alpha_pred,mask) class compose_loss(_Loss): def __init__(self): super(compose_loss,self).__init__() def forward(self,image,alpha_pred,fg,bg,mask): alpha_pred=(alpha_pred+1)/2 comp=fg*alpha_pred + (1-alpha_pred)*bg return normalized_l1_loss(image,comp,mask) class alpha_gradient_loss(_Loss): def __init__(self): super(alpha_gradient_loss,self).__init__() def forward(self,alpha,alpha_pred,mask): if alpha.is_cuda: fx = torch.Tensor([[1, 0, -1],[2, 0, -2],[1, 0, -1]]); fx=fx.view((1,1,3,3)); fx=Variable(fx.cuda()) fy = torch.Tensor([[1, 2, 1],[0, 0, 0],[-1, -2, -1]]); fy=fy.view((1,1,3,3)); fy=Variable(fy.cuda()) else: fx = torch.Tensor([[1, 0, -1],[2, 0, -2],[1, 0, -1]]); fx=fx.view((1,1,3,3)); fx=Variable(fx) fy = torch.Tensor([[1, 2, 1],[0, 0, 0],[-1, -2, -1]]); fy=fy.view((1,1,3,3)); fy=Variable(fy) G_x = F.conv2d(alpha,fx,padding=1); G_y = F.conv2d(alpha,fy,padding=1) G_x_pred = F.conv2d(alpha_pred,fx,padding=1); G_y_pred = F.conv2d(alpha_pred,fy,padding=1) loss=normalized_l1_loss(G_x,G_x_pred,mask) + normalized_l1_loss(G_y,G_y_pred,mask) return loss class alpha_gradient_reg_loss(_Loss): def __init__(self): super(alpha_gradient_reg_loss,self).__init__() def forward(self,alpha,mask): if alpha.is_cuda: fx = torch.Tensor([[1, 0, -1],[2, 0, -2],[1, 0, -1]]); fx=fx.view((1,1,3,3)); fx=Variable(fx.cuda()) fy = torch.Tensor([[1, 2, 1],[0, 0, 0],[-1, -2, -1]]); fy=fy.view((1,1,3,3)); fy=Variable(fy.cuda()) else: fx = torch.Tensor([[1, 0, -1],[2, 0, -2],[1, 0, -1]]); fx=fx.view((1,1,3,3)); fx=Variable(fx) fy = torch.Tensor([[1, 2, 1],[0, 0, 0],[-1, -2, -1]]); fy=fy.view((1,1,3,3)); fy=Variable(fy) G_x = F.conv2d(alpha,fx,padding=1); G_y = F.conv2d(alpha,fy,padding=1) loss=(torch.sum(torch.abs(G_x))+torch.sum(torch.abs(G_y)))/torch.sum(mask) return loss class GANloss(_Loss): def __init__(self): super(GANloss,self).__init__() def forward(self,pred,label_type): MSE=nn.MSELoss() loss=0 for i in range(0,len(pred)): if label_type: labels=torch.ones(pred[i][0].shape) else: labels=torch.zeros(pred[i][0].shape) if pred[i][0].is_cuda: labels=Variable(labels.cuda()) else: labels=Variable(labels) loss += MSE(pred[i][0],labels) return loss/len(pred) def normalized_l1_loss(alpha,alpha_pred,mask): loss=0; eps=1e-6; for i in range(alpha.shape[0]): if mask[i,...].sum()>0: loss = loss + torch.sum(torch.abs(alpha[i,...]*mask[i,...]-alpha_pred[i,...]*mask[i,...]))/(torch.sum(mask[i,...])+eps) loss=loss/alpha.shape[0] return loss
1,432
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/user_board_view_mojo.h" #include <utility> #include "chrome/browser/chromeos/login/lock_screen_utils.h" #include "chrome/browser/ui/ash/login_screen_client.h" namespace chromeos { namespace { ash::mojom::EasyUnlockIconId GetEasyUnlockIconIdFromUserPodCustomIconId( proximity_auth::ScreenlockBridge::UserPodCustomIcon icon) { switch (icon) { case proximity_auth::ScreenlockBridge::USER_POD_CUSTOM_ICON_NONE: return ash::mojom::EasyUnlockIconId::NONE; case proximity_auth::ScreenlockBridge::USER_POD_CUSTOM_ICON_HARDLOCKED: return ash::mojom::EasyUnlockIconId::HARDLOCKED; case proximity_auth::ScreenlockBridge::USER_POD_CUSTOM_ICON_LOCKED: return ash::mojom::EasyUnlockIconId::LOCKED; case proximity_auth::ScreenlockBridge:: USER_POD_CUSTOM_ICON_LOCKED_TO_BE_ACTIVATED: return ash::mojom::EasyUnlockIconId::LOCKED_TO_BE_ACTIVATED; case proximity_auth::ScreenlockBridge:: USER_POD_CUSTOM_ICON_LOCKED_WITH_PROXIMITY_HINT: return ash::mojom::EasyUnlockIconId::LOCKED_WITH_PROXIMITY_HINT; case proximity_auth::ScreenlockBridge::USER_POD_CUSTOM_ICON_UNLOCKED: return ash::mojom::EasyUnlockIconId::UNLOCKED; case proximity_auth::ScreenlockBridge::USER_POD_CUSTOM_ICON_SPINNER: return ash::mojom::EasyUnlockIconId::SPINNER; } } // Converts parameters to a mojo struct that can be sent to the // screenlock view-based UI. ash::mojom::EasyUnlockIconOptionsPtr ToEasyUnlockIconOptionsPtr( const proximity_auth::ScreenlockBridge::UserPodCustomIconOptions& icon_options) { ash::mojom::EasyUnlockIconOptionsPtr options = ash::mojom::EasyUnlockIconOptions::New(); options->icon = GetEasyUnlockIconIdFromUserPodCustomIconId(icon_options.icon()); if (!icon_options.tooltip().empty()) { options->tooltip = icon_options.tooltip(); options->autoshow_tooltip = icon_options.autoshow_tooltip(); } if (!icon_options.aria_label().empty()) options->aria_label = icon_options.aria_label(); if (icon_options.hardlock_on_click()) options->hardlock_on_click = true; if (icon_options.is_trial_run()) options->is_trial_run = true; return options; } } // namespace UserBoardViewMojo::UserBoardViewMojo() : weak_factory_(this) {} UserBoardViewMojo::~UserBoardViewMojo() = default; void UserBoardViewMojo::SetPublicSessionDisplayName( const AccountId& account_id, const std::string& display_name) { LoginScreenClient::Get()->login_screen()->SetPublicSessionDisplayName( account_id, display_name); } void UserBoardViewMojo::SetPublicSessionLocales( const AccountId& account_id, std::unique_ptr<base::ListValue> locales, const std::string& default_locale, bool multiple_recommended_locales) { DCHECK(locales); LoginScreenClient::Get()->login_screen()->SetPublicSessionLocales( account_id, lock_screen_utils::FromListValueToLocaleItem(std::move(locales)), default_locale, multiple_recommended_locales); // Send a request to get keyboard layouts for |default_locale|. LoginScreenClient::Get()->RequestPublicSessionKeyboardLayouts(account_id, default_locale); } void UserBoardViewMojo::ShowUserPodCustomIcon( const AccountId& account_id, const proximity_auth::ScreenlockBridge::UserPodCustomIconOptions& icon_options) { ash::mojom::EasyUnlockIconOptionsPtr icon = ToEasyUnlockIconOptionsPtr(icon_options); if (!icon) return; LoginScreenClient::Get()->login_screen()->ShowUserPodCustomIcon( account_id, std::move(icon)); } void UserBoardViewMojo::HideUserPodCustomIcon(const AccountId& account_id) { LoginScreenClient::Get()->login_screen()->HideUserPodCustomIcon(account_id); } void UserBoardViewMojo::SetAuthType(const AccountId& account_id, proximity_auth::mojom::AuthType auth_type, const base::string16& initial_value) { LoginScreenClient::Get()->login_screen()->SetAuthType(account_id, auth_type, initial_value); } base::WeakPtr<UserBoardView> UserBoardViewMojo::GetWeakPtr() { return weak_factory_.GetWeakPtr(); } } // namespace chromeos
1,733
852
import FWCore.ParameterSet.Config as cms # Energy scale correction for Fixed Matrix Endcap SuperClusters correctedFixedMatrixSuperClustersWithPreshower = cms.EDProducer("EgammaSCCorrectionMaker", corectedSuperClusterCollection = cms.string(''), sigmaElectronicNoise = cms.double(0.15), superClusterAlgo = cms.string('FixedMatrix'), etThresh = cms.double(0.0), rawSuperClusterProducer = cms.InputTag("fixedMatrixSuperClustersWithPreshower"), applyEnergyCorrection = cms.bool(True), # energy correction fix_fCorrPset = cms.PSet( brLinearLowThr = cms.double(0.9), fBremVec = cms.vdouble(-0.1234, 0.2347, 0.8831, 0.002377, 1.037), brLinearHighThr = cms.double(5.0), fEtEtaVec = cms.vdouble(1.002, -0.09255, 0.0, 0.0, -4.072, 67.93, -7.333, 0.0, 0.0, 0.0, 2.6), corrF = cms.vint32(0, 0, 1) ), VerbosityLevel = cms.string('ERROR'), recHitProducer = cms.InputTag("ecalRecHit","EcalRecHitsEE") )
462
407
<gh_stars>100-1000 package com.alibaba.tesla.gateway.common.exception; /** * @author <EMAIL> */ public class OperatorRouteException extends Exception{ public OperatorRouteException(String message) { super(message); } public OperatorRouteException(String message, Throwable cause) { super(message, cause); } public OperatorRouteException(Throwable cause) { super(cause); } }
148
1,442
#include "list_controller.h" #include "../app.h" #include <assert.h> #include <algorithm> #include <apps/i18n.h> using namespace Shared; using namespace Poincare; using namespace Escher; namespace Sequence { ListController::ListController(Responder * parentResponder, Escher::InputEventHandlerDelegate * inputEventHandlerDelegate, ButtonRowController * header, ButtonRowController * footer) : Shared::FunctionListController(parentResponder, header, footer, I18n::Message::AddSequence), m_sequenceTitleCells{}, m_expressionCells{}, m_parameterController(inputEventHandlerDelegate, this), m_typeParameterController(this, this), m_typeStackController(nullptr, &m_typeParameterController), m_sequenceToolbox() { for (int i = 0; i < k_maxNumberOfRows; i++) { m_expressionCells[i].setLeftMargin(k_expressionMargin); } } const char * ListController::title() { return I18n::translate(I18n::Message::SequenceTab); } int ListController::numberOfExpressionRows() const { int numberOfRows = 0; SequenceStore * store = const_cast<ListController *>(this)->modelStore(); const int modelsCount = store->numberOfModels(); for (int i = 0; i < modelsCount; i++) { Shared::Sequence * sequence = store->modelForRecord(store->recordAtIndex(i)); numberOfRows += sequence->numberOfElements(); } return numberOfRows + (modelsCount == store->maxNumberOfModels()? 0 : 1); }; KDCoordinate ListController::expressionRowHeight(int j) { KDCoordinate defaultHeight = Metric::StoreRowHeight; if (isAddEmptyRow(j)) { return defaultHeight; } Shared::Sequence * sequence = modelStore()->modelForRecord(modelStore()->recordAtIndex(modelIndexForRow(j))); Layout layout = sequence->layout(); if (sequenceDefinitionForRow(j) == 1) { layout = sequence->firstInitialConditionLayout(); } if (sequenceDefinitionForRow(j) == 2) { layout = sequence->secondInitialConditionLayout(); } if (layout.isUninitialized()) { return defaultHeight; } KDCoordinate sequenceHeight = layout.layoutSize().height(); return std::max<KDCoordinate>(defaultHeight, sequenceHeight + 2*k_expressionCellVerticalMargin); } void ListController::willDisplayCellAtLocation(HighlightCell * cell, int i, int j) { Shared::FunctionListController::willDisplayCellAtLocation(cell, i, j); EvenOddCell * myCell = static_cast<EvenOddCell *>(cell); myCell->setEven(modelIndexForRow(j)%2 == 0); } Toolbox * ListController::toolboxForInputEventHandler(InputEventHandler * textInput) { // Set extra cells int recurrenceDepth = -1; int sequenceDefinition = sequenceDefinitionForRow(selectedRow()); Shared::Sequence * sequence = modelStore()->modelForRecord(modelStore()->recordAtIndex(modelIndexForRow(selectedRow()))); if (sequenceDefinition == 0) { recurrenceDepth = sequence->numberOfElements()-1; } m_sequenceToolbox.buildExtraCellsLayouts(sequence->fullName(), recurrenceDepth); // Set sender m_sequenceToolbox.setSender(textInput); return &m_sequenceToolbox; } void ListController::selectPreviousNewSequenceCell() { if (sequenceDefinitionForRow(selectedRow()) >= 0) { selectCellAtLocation(selectedColumn(), selectedRow()-sequenceDefinitionForRow(selectedRow())); } } void ListController::editExpression(int sequenceDefinition, Ion::Events::Event event) { Ion::Storage::Record record = modelStore()->recordAtIndex(modelIndexForRow(selectedRow())); Shared::Sequence * sequence = modelStore()->modelForRecord(record); InputViewController * inputController = Shared::FunctionApp::app()->inputViewController(); if (event == Ion::Events::OK || event == Ion::Events::EXE) { char initialTextContent[Constant::MaxSerializedExpressionSize]; switch (sequenceDefinition) { case 0: sequence->text(initialTextContent, sizeof(initialTextContent)); break; case 1: sequence->firstInitialConditionText(initialTextContent, sizeof(initialTextContent)); break; default: sequence->secondInitialConditionText(initialTextContent, sizeof(initialTextContent)); break; } inputController->setTextBody(initialTextContent); } // Invalidate the sequences context cache App::app()->localContext()->resetCache(); switch (sequenceDefinition) { case 0: inputController->edit(this, event, this, [](void * context, void * sender){ ListController * myController = static_cast<ListController *>(context); InputViewController * myInputViewController = (InputViewController *)sender; const char * textBody = myInputViewController->textBody(); return myController->editSelectedRecordWithText(textBody); }, [](void * context, void * sender){ return true; }); break; case 1: inputController->edit(this, event, this, [](void * context, void * sender){ ListController * myController = static_cast<ListController *>(context); InputViewController * myInputViewController = (InputViewController *)sender; const char * textBody = myInputViewController->textBody(); return myController->editInitialConditionOfSelectedRecordWithText(textBody, true); }, [](void * context, void * sender){ return true; }); break; default: inputController->edit(this, event, this, [](void * context, void * sender){ ListController * myController = static_cast<ListController *>(context); InputViewController * myInputViewController = (InputViewController *)sender; const char * textBody = myInputViewController->textBody(); return myController->editInitialConditionOfSelectedRecordWithText(textBody, false); }, [](void * context, void * sender){ return true; }); } } bool ListController::editInitialConditionOfSelectedRecordWithText(const char * text, bool firstInitialCondition) { // Reset memoization of the selected cell which always corresponds to the k_memoizedCellsCount/2 memoized cell resetMemoizationForIndex(k_memoizedCellsCount/2); Ion::Storage::Record record = modelStore()->recordAtIndex(modelIndexForRow(selectedRow())); Shared::Sequence * sequence = modelStore()->modelForRecord(record); Context * context = App::app()->localContext(); Ion::Storage::Record::ErrorStatus error = firstInitialCondition? sequence->setFirstInitialConditionContent(text, context) : sequence->setSecondInitialConditionContent(text, context); return (error == Ion::Storage::Record::ErrorStatus::None); } ListParameterController * ListController::parameterController() { return &m_parameterController; } int ListController::maxNumberOfDisplayableRows() { return k_maxNumberOfRows; } FunctionTitleCell * ListController::titleCells(int index) { assert(index >= 0 && index < k_maxNumberOfRows); return &m_sequenceTitleCells[index]; } HighlightCell * ListController::expressionCells(int index) { assert(index >= 0 && index < k_maxNumberOfRows); return &m_expressionCells[index]; } void ListController::willDisplayTitleCellAtIndex(HighlightCell * cell, int j) { assert(j>=0 && j < k_maxNumberOfRows); SequenceTitleCell * myCell = static_cast<SequenceTitleCell *>(cell); // Update the corresponding expression cell to get its baseline willDisplayExpressionCellAtIndex(m_selectableTableView.cellAtLocation(1, j), j); myCell->setBaseline(baseline(j)); // Set the layout Ion::Storage::Record record = modelStore()->recordAtIndex(modelIndexForRow(j)); Shared::Sequence * sequence = modelStore()->modelForRecord(record); if (sequenceDefinitionForRow(j) == 0) { myCell->setLayout(sequence->definitionName()); } if (sequenceDefinitionForRow(j) == 1) { myCell->setLayout(sequence->firstInitialConditionName()); } if (sequenceDefinitionForRow(j) == 2) { myCell->setLayout(sequence->secondInitialConditionName()); } // Set the color KDColor nameColor = sequence->isActive() ? sequence->color() : Palette::GrayDark; myCell->setColor(nameColor); } void ListController::willDisplayExpressionCellAtIndex(HighlightCell * cell, int j) { FunctionExpressionCell * myCell = static_cast<FunctionExpressionCell *>(cell); Ion::Storage::Record record = modelStore()->recordAtIndex(modelIndexForRow(j)); Shared::Sequence * sequence = modelStore()->modelForRecord(record); if (sequenceDefinitionForRow(j) == 0) { myCell->setLayout(sequence->layout()); } if (sequenceDefinitionForRow(j) == 1) { myCell->setLayout(sequence->firstInitialConditionLayout()); } if (sequenceDefinitionForRow(j) == 2) { myCell->setLayout(sequence->secondInitialConditionLayout()); } bool active = sequence->isActive(); KDColor textColor = active ? KDColorBlack : Palette::GrayDark; myCell->setTextColor(textColor); } int ListController::modelIndexForRow(int j) { if (j < 0) { return j; } if (isAddEmptyRow(j)) { return modelIndexForRow(j-1)+1; } int rowIndex = 0; int sequenceIndex = -1; do { sequenceIndex++; Shared::Sequence * sequence = modelStore()->modelForRecord(modelStore()->recordAtIndex(sequenceIndex)); rowIndex += sequence->numberOfElements(); } while (rowIndex <= j); return sequenceIndex; } int ListController::sequenceDefinitionForRow(int j) { if (j < 0) { return j; } if (isAddEmptyRow(j)) { return 0; } int rowIndex = 0; int sequenceIndex = -1; Shared::Sequence * sequence; do { sequenceIndex++; sequence = modelStore()->modelForRecord(modelStore()->recordAtIndex(sequenceIndex)); rowIndex += sequence->numberOfElements(); } while (rowIndex <= j); assert(sequence); return sequence->numberOfElements()-rowIndex+j; } void ListController::addModel() { Container::activeApp()->displayModalViewController(&m_typeStackController, 0.f, 0.f, Metric::PopUpTopMargin, Metric::PopUpRightMargin, 0, Metric::PopUpLeftMargin); } void ListController::editExpression(Ion::Events::Event event) { editExpression(sequenceDefinitionForRow(selectedRow()), event); } void ListController::reinitSelectedExpression(ExpiringPointer<ExpressionModelHandle> model) { // Invalidate the sequences context cache App::app()->localContext()->resetCache(); Shared::Sequence * sequence = static_cast<Shared::Sequence *>(model.pointer()); switch (sequenceDefinitionForRow(selectedRow())) { case 1: if (sequence->firstInitialConditionExpressionClone().isUninitialized()) { return; } sequence->setFirstInitialConditionContent("", nullptr); // No context needed here break; case 2: if (sequence->secondInitialConditionExpressionClone().isUninitialized()) { return; } sequence->setSecondInitialConditionContent("", nullptr); // No context needed here break; default: if (sequence->expressionClone().isUninitialized()) { return; } sequence->setContent("", nullptr); // No context needed break; } selectableTableView()->reloadData(); } bool ListController::removeModelRow(Ion::Storage::Record record) { Shared::FunctionListController::removeModelRow(record); // Invalidate the sequences context cache App::app()->localContext()->resetCache(); return true; } SequenceStore * ListController::modelStore() { return App::app()->functionStore(); } }
3,584
1,350
<reponame>ppartarr/azure-sdk-for-java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.containerregistry.models; import com.azure.core.annotation.Fluent; import com.azure.resourcemanager.resources.fluentcore.model.Attachable; import com.azure.resourcemanager.resources.fluentcore.model.Settable; import java.util.List; import java.util.Map; /** An immutable client-side representation of an Azure RegistryFileTaskStep registry task. */ @Fluent() public interface RegistryFileTaskStep extends RegistryTaskStep { /** @return the task file path of this file task step */ String taskFilePath(); /** @return the values file path of this file task step */ String valuesFilePath(); /** @return the values of this file task step */ List<SetValue> values(); /** Container interface for all the definitions related to a RegistryFileTaskStep. */ interface Definition extends RegistryFileTaskStep.DefinitionStages.Blank, RegistryFileTaskStep.DefinitionStages.FileTaskPath, RegistryFileTaskStep.DefinitionStages.FileTaskStepAttachable { } /** Container interface for all the updates related to a RegistryFileTaskStep. */ interface Update extends RegistryFileTaskStep.UpdateStages.FileTaskPath, RegistryFileTaskStep.UpdateStages.ValuePath, RegistryFileTaskStep.UpdateStages.OverridingValues, Settable<RegistryTask.Update> { } /** Grouping of registry file task definition stages. */ interface DefinitionStages { /** The first stage of a RegistryFileTaskStep definition. */ interface Blank extends FileTaskPath { } /** The stage of the container registry FileTaskStep definition allowing to specify the task path. */ interface FileTaskPath { /** * The function that specifies the path to the task file. * * @param path the path to the task file. * @return the next stage of the container registry FileTaskStep definition. */ FileTaskStepAttachable withTaskPath(String path); } /** * The stage of the definition which contains all the minimum required inputs for the resource to be attached, * but also allows for any other optional settings to be specified. */ interface FileTaskStepAttachable extends Attachable<RegistryTask.DefinitionStages.SourceTriggerDefinition> { /** * The function that specifies the path to the values. * * @param path the path to the values. * @return the next stage of the container registry FileTaskStep definition. */ FileTaskStepAttachable withValuesPath(String path); /** * The function that specifies the values that override the corresponding values specified under the * function withValuesPath(). * * @param overridingValues a map which contains the values that will override the corresponding values * specified under the function withValuesPath(). * @return the next stage of the container registry FileTaskStep definition. */ FileTaskStepAttachable withOverridingValues(Map<String, OverridingValue> overridingValues); /** * The function that specifies a single value that will override the corresponding value specified under the * function withValuesPath(). * * @param name the name of the value to be overridden. * @param overridingValue the value of the value to be overridden. * @return the next stage of the container registry FileTaskStep definition. */ FileTaskStepAttachable withOverridingValue(String name, OverridingValue overridingValue); } } /** Grouping of registry file task update stages. */ interface UpdateStages { /** The stage of the container registry FileTaskStep update allowing to specify the task path. */ interface FileTaskPath { /** * The function that specifies the path to the task file. * * @param path the path to the task file. * @return the next stage of the container registry FileTaskStep update. */ Update withTaskPath(String path); } /** The stage of the container registry FileTaskStep update allowing to specify the path to the values. */ interface ValuePath { /** * The function that specifies the path to the values. * * @param path the path to the values. * @return the next stage of the container registry FileTaskStep update. */ Update withValuesPath(String path); } /** The stage of the container registry FileTaskStep update allowing to specify the overriding values. */ interface OverridingValues { /** * The function that specifies the values that override the corresponding values specified under the * function withValuesPath(). * * @param overridingValues a map which contains the values that will override the corresponding values * specified under the function withValuesPath(). * @return the next stage of the container registry FileTaskStep update. */ Update withOverridingValues(Map<String, OverridingValue> overridingValues); /** * The function that specifies a single value that will override the corresponding value specified under the * function withValuesPath(). * * @param name the name of the value to be overridden. * @param overridingValue the value of the value to be overridden. * @return the next stage of the container registry FileTaskStep update. */ Update withOverridingValue(String name, OverridingValue overridingValue); } } }
2,263
2,338
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py // REQUIRES: aarch64-registered-target // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefix=CPP-CHECK // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -o /dev/null %s #include <arm_sve.h> // CHECK-LABEL: @test_svpnext_b8( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.pnext.nxv16i1(<vscale x 16 x i1> [[PG:%.*]], <vscale x 16 x i1> [[OP:%.*]]) // CHECK-NEXT: ret <vscale x 16 x i1> [[TMP0]] // // CPP-CHECK-LABEL: @_Z15test_svpnext_b8u10__SVBool_tu10__SVBool_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.pnext.nxv16i1(<vscale x 16 x i1> [[PG:%.*]], <vscale x 16 x i1> [[OP:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 16 x i1> [[TMP0]] // svbool_t test_svpnext_b8(svbool_t pg, svbool_t op) { return svpnext_b8(pg, op); } // CHECK-LABEL: @test_svpnext_b16( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> [[PG:%.*]]) // CHECK-NEXT: [[TMP1:%.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> [[OP:%.*]]) // CHECK-NEXT: [[TMP2:%.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.pnext.nxv8i1(<vscale x 8 x i1> [[TMP0]], <vscale x 8 x i1> [[TMP1]]) // CHECK-NEXT: [[TMP3:%.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> [[TMP2]]) // CHECK-NEXT: ret <vscale x 16 x i1> [[TMP3]] // // CPP-CHECK-LABEL: @_Z16test_svpnext_b16u10__SVBool_tu10__SVBool_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> [[PG:%.*]]) // CPP-CHECK-NEXT: [[TMP1:%.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> [[OP:%.*]]) // CPP-CHECK-NEXT: [[TMP2:%.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.pnext.nxv8i1(<vscale x 8 x i1> [[TMP0]], <vscale x 8 x i1> [[TMP1]]) // CPP-CHECK-NEXT: [[TMP3:%.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv8i1(<vscale x 8 x i1> [[TMP2]]) // CPP-CHECK-NEXT: ret <vscale x 16 x i1> [[TMP3]] // svbool_t test_svpnext_b16(svbool_t pg, svbool_t op) { return svpnext_b16(pg, op); } // CHECK-LABEL: @test_svpnext_b32( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> [[PG:%.*]]) // CHECK-NEXT: [[TMP1:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> [[OP:%.*]]) // CHECK-NEXT: [[TMP2:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.pnext.nxv4i1(<vscale x 4 x i1> [[TMP0]], <vscale x 4 x i1> [[TMP1]]) // CHECK-NEXT: [[TMP3:%.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> [[TMP2]]) // CHECK-NEXT: ret <vscale x 16 x i1> [[TMP3]] // // CPP-CHECK-LABEL: @_Z16test_svpnext_b32u10__SVBool_tu10__SVBool_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> [[PG:%.*]]) // CPP-CHECK-NEXT: [[TMP1:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> [[OP:%.*]]) // CPP-CHECK-NEXT: [[TMP2:%.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.pnext.nxv4i1(<vscale x 4 x i1> [[TMP0]], <vscale x 4 x i1> [[TMP1]]) // CPP-CHECK-NEXT: [[TMP3:%.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv4i1(<vscale x 4 x i1> [[TMP2]]) // CPP-CHECK-NEXT: ret <vscale x 16 x i1> [[TMP3]] // svbool_t test_svpnext_b32(svbool_t pg, svbool_t op) { return svpnext_b32(pg, op); } // CHECK-LABEL: @test_svpnext_b64( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> [[PG:%.*]]) // CHECK-NEXT: [[TMP1:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> [[OP:%.*]]) // CHECK-NEXT: [[TMP2:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.pnext.nxv2i1(<vscale x 2 x i1> [[TMP0]], <vscale x 2 x i1> [[TMP1]]) // CHECK-NEXT: [[TMP3:%.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv2i1(<vscale x 2 x i1> [[TMP2]]) // CHECK-NEXT: ret <vscale x 16 x i1> [[TMP3]] // // CPP-CHECK-LABEL: @_Z16test_svpnext_b64u10__SVBool_tu10__SVBool_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> [[PG:%.*]]) // CPP-CHECK-NEXT: [[TMP1:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> [[OP:%.*]]) // CPP-CHECK-NEXT: [[TMP2:%.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.pnext.nxv2i1(<vscale x 2 x i1> [[TMP0]], <vscale x 2 x i1> [[TMP1]]) // CPP-CHECK-NEXT: [[TMP3:%.*]] = call <vscale x 16 x i1> @llvm.aarch64.sve.convert.to.svbool.nxv2i1(<vscale x 2 x i1> [[TMP2]]) // CPP-CHECK-NEXT: ret <vscale x 16 x i1> [[TMP3]] // svbool_t test_svpnext_b64(svbool_t pg, svbool_t op) { return svpnext_b64(pg, op); }
2,958
4,569
<reponame>adouhuges/java-learning package com.brianway.learning.java.multithread.timer.example4; /** * Created by brian on 2016/4/15. */ import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /** * P257 * scheduleAtFixedRate(TimerTask task, Date firstTime,long period)方法 * Date类型 * 不延时的情况下,若执行任务未被延时,下次执行任务的开始时间是上一次任务的开始时间加上period */ public class Run4_scheduleAtFixedRate1 { static public class MyTask extends TimerTask { @Override public void run() { try { System.out.println("begin timer=" + System.currentTimeMillis()); Thread.sleep(1000); System.out.println("end timer=" + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { MyTask task = new MyTask(); Calendar calendar = Calendar.getInstance(); Date runDate = calendar.getTime(); Timer timer = new Timer(); timer.scheduleAtFixedRate(task, runDate, 3000); } } /* 输出: begin timer=1460738424663 end timer=1460738425663 begin timer=1460738427636 end timer=1460738428636 begin timer=1460738430635 end timer=1460738431635 */
625
362
<gh_stars>100-1000 // Copyright (c) 2018-2020, <NAME>. For more information see 'LICENSE' #include "tests/pipeline_compiler/Utils.h" #include "VPipelineReflection.h" extern void Test1 (VPipelineCompiler* compiler) { GraphicsPipelineDesc ppln; ppln.AddShader( EShader::Vertex, EShaderLangFormat::GLSL_450, "main", R"#( #version 450 core #extension GL_ARB_separate_shader_objects : enable layout(location=0) in vec2 at_Position; layout(location=1) in vec2 at_Texcoord; layout(location=0) out vec2 v_Texcoord; void main() { gl_Position = vec4( at_Position, 0.0, 1.0 ); v_Texcoord = at_Texcoord; } )#" ); ppln.AddShader( EShader::Fragment, EShaderLangFormat::GLSL_450, "main", R"#( #version 450 core #extension GL_ARB_separate_shader_objects : enable layout (binding=0, std140) uniform UB { vec4 color; } ub; layout(binding=1) uniform sampler2D un_ColorTexture; layout(location=0) in vec2 v_Texcoord; layout(location=0) out vec4 out_Color; void main() { out_Color = texture(un_ColorTexture, v_Texcoord) * ub.color; } )#" ); TEST( compiler->Compile( INOUT ppln, EShaderLangFormat::SPIRV_100 )); TEST( FindVertexInput( ppln, VertexID("at_Position") )); TEST( FindVertexInput( ppln, VertexID("at_Texcoord") )); TEST( TestFragmentOutput( ppln, EFragOutput::Float4, 0 )); auto ds = FindDescriptorSet( ppln, DescriptorSetID("0") ); TEST( ds ); TEST( FindUniform< PipelineDescription::Texture >( *ds, UniformID("un_ColorTexture") ).second ); TEST( FindUniform< PipelineDescription::UniformBuffer >( *ds, UniformID("UB") ).second ); TEST( ppln._earlyFragmentTests ); TEST( ppln._supportedTopology.test( uint(EPrimitive::Point) )); TEST( ppln._supportedTopology.test( uint(EPrimitive::LineList) )); TEST( ppln._supportedTopology.test( uint(EPrimitive::LineStrip) )); TEST( ppln._supportedTopology.test( uint(EPrimitive::TriangleList) )); TEST( ppln._supportedTopology.test( uint(EPrimitive::TriangleStrip) )); TEST( ppln._supportedTopology.test( uint(EPrimitive::TriangleFan) )); TEST( not ppln._supportedTopology.test( uint(EPrimitive::LineListAdjacency) )); TEST( not ppln._supportedTopology.test( uint(EPrimitive::LineStripAdjacency) )); TEST( not ppln._supportedTopology.test( uint(EPrimitive::TriangleListAdjacency) )); TEST( not ppln._supportedTopology.test( uint(EPrimitive::TriangleStripAdjacency) )); TEST( not ppln._supportedTopology.test( uint(EPrimitive::Patch) )); GraphicsPipelineDesc ppln2 = ppln; ppln2._fragmentOutput.clear(); ppln2._vertexAttribs.clear(); ppln2._pipelineLayout = Default; VPipelineReflection pr; TEST( pr.Reflect( INOUT ppln2 )); std::sort( ppln2._fragmentOutput.begin(), ppln2._fragmentOutput.end(), [](auto& lhs, auto& rhs) { return lhs.index < rhs.index; }); std::sort( ppln._fragmentOutput.begin(), ppln._fragmentOutput.end(), [](auto& lhs, auto& rhs) { return lhs.index < rhs.index; }); TEST( ppln2._fragmentOutput == ppln._fragmentOutput ); std::sort( ppln2._vertexAttribs.begin(), ppln2._vertexAttribs.end(), [](auto& lhs, auto& rhs) { return lhs.id < rhs.id; }); std::sort( ppln._vertexAttribs.begin(), ppln._vertexAttribs.end(), [](auto& lhs, auto& rhs) { return lhs.id < rhs.id; }); TEST( ppln2._vertexAttribs == ppln._vertexAttribs ); std::sort( ppln2._pipelineLayout.descriptorSets.begin(), ppln2._pipelineLayout.descriptorSets.end(), [](auto& lhs, auto& rhs) { return lhs.id < rhs.id; }); std::sort( ppln._pipelineLayout.descriptorSets.begin(), ppln._pipelineLayout.descriptorSets.end(), [](auto& lhs, auto& rhs) { return lhs.id < rhs.id; }); TEST( ppln2._pipelineLayout.descriptorSets.size() == ppln._pipelineLayout.descriptorSets.size() ); for (size_t i = 0, cnt = ppln._pipelineLayout.descriptorSets.size(); i < cnt; ++i) { auto& lhs = ppln._pipelineLayout.descriptorSets[i]; auto& rhs = ppln2._pipelineLayout.descriptorSets[i]; TEST( lhs.bindingIndex == rhs.bindingIndex ); //TEST( lhs.id == rhs.id ); TEST( lhs.uniforms ); TEST( rhs.uniforms ); TEST( lhs.uniforms->size() == rhs.uniforms->size() ); for (auto& [lkey, lun] : *lhs.uniforms) { auto riter = rhs.uniforms->find( lkey ); TEST( riter != rhs.uniforms->end() ); //TEST( riter->second == lun ); // TODO: texture type doesn't match } } TEST( ppln2._pipelineLayout.pushConstants.size() == ppln._pipelineLayout.pushConstants.size() ); for (size_t i = 0, cnt = ppln._pipelineLayout.pushConstants.size(); i < cnt; ++i) { auto& lhs = ppln._pipelineLayout.pushConstants[i]; auto& rhs = ppln2._pipelineLayout.pushConstants[i]; TEST( lhs.first == rhs.first ); TEST( lhs.second.offset == rhs.second.offset ); TEST( lhs.second.size == rhs.second.size ); TEST( lhs.second.stageFlags == rhs.second.stageFlags ); } TEST_PASSED(); }
1,968
7,090
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from paddle_serving_server.web_service import WebService, Op class TIPCExampleOp(Op): """TIPCExampleOp ExampleOp for serving server. You can rename by yourself. """ def init_op(self): """init_op Initialize the class. Args: None Returns: None """ pass def preprocess(self, input_dicts, data_id, log_id): """preprocess In preprocess stage, assembling data for process stage. users can override this function for model feed features. Args: input_dicts: input data to be preprocessed data_id: inner unique id, increase auto log_id: global unique id for RTT, 0 default Return: output_data: data for process stage is_skip_process: skip process stage or not, False default prod_errcode: None default, otherwise, product errores occured. It is handled in the same way as exception. prod_errinfo: "" default """ pass def postprocess(self, input_dicts, fetch_dict, data_id, log_id): """postprocess In postprocess stage, assemble data for next op or output. Args: input_data: data returned in preprocess stage, dict(for single predict) or list(for batch predict) fetch_data: data returned in process stage, dict(for single predict) or list(for batch predict) data_id: inner unique id, increase auto log_id: logid, 0 default Returns: fetch_dict: fetch result must be dict type. prod_errcode: None default, otherwise, product errores occured. It is handled in the same way as exception. prod_errinfo: "" default """ # postprocess for the service output pass class TIPCExampleService(WebService): """TIPCExampleService Service class to define the Serving OP. """ def get_pipeline_response(self, read_op): tipc_example_op = TIPCExampleOp( name="tipc_example", input_ops=[read_op]) return tipc_example_op # define the service class uci_service = TIPCExampleService(name="tipc_example") # load config and prepare the service uci_service.prepare_pipeline_config("config.yml") # start the service uci_service.run_service()
1,152
1,857
<reponame>efedo/renderer #ifndef TEST_PBR_H #define TEST_PBR_H void test_pbr(int argc, char *argv[]); #endif
53
892
{ "schema_version": "1.2.0", "id": "GHSA-g8jg-j3w6-vgf8", "modified": "2022-05-13T00:00:49Z", "published": "2022-05-13T00:00:49Z", "aliases": [ "CVE-2022-24910" ], "details": "A buffer overflow vulnerability exists in the httpd parse_ping_result API functionality of InHand Networks InRouter302 V3.5.4. A specially-crafted file can lead to remote code execution. An attacker can send a sequence of requests to trigger this vulnerability.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24910" }, { "type": "WEB", "url": "https://talosintelligence.com/vulnerability_reports/TALOS-2022-1471" }, { "type": "WEB", "url": "https://www.inhandnetworks.com/upload/attachment/202205/10/InHand-PSA-2022-01.pdf" } ], "database_specific": { "cwe_ids": [ ], "severity": null, "github_reviewed": false } }
424
1,350
<reponame>Shashi-rk/azure-sdk-for-java<filename>sdk/synapse/azure-resourcemanager-synapse/src/main/java/com/azure/resourcemanager/synapse/implementation/CheckNameAvailabilityResponseImpl.java<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.synapse.implementation; import com.azure.resourcemanager.synapse.fluent.models.CheckNameAvailabilityResponseInner; import com.azure.resourcemanager.synapse.models.CheckNameAvailabilityResponse; public final class CheckNameAvailabilityResponseImpl implements CheckNameAvailabilityResponse { private CheckNameAvailabilityResponseInner innerObject; private final com.azure.resourcemanager.synapse.SynapseManager serviceManager; CheckNameAvailabilityResponseImpl( CheckNameAvailabilityResponseInner innerObject, com.azure.resourcemanager.synapse.SynapseManager serviceManager) { this.innerObject = innerObject; this.serviceManager = serviceManager; } public String message() { return this.innerModel().message(); } public Boolean available() { return this.innerModel().available(); } public String reason() { return this.innerModel().reason(); } public String name() { return this.innerModel().name(); } public CheckNameAvailabilityResponseInner innerModel() { return this.innerObject; } private com.azure.resourcemanager.synapse.SynapseManager manager() { return this.serviceManager; } }
511
679
<filename>main/ucb/source/ucp/webdav/SerfMoveReqProcImpl.cxx<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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_webdav.hxx" #include "SerfMoveReqProcImpl.hxx" #include <serf.h> namespace http_dav_ucp { SerfMoveReqProcImpl::SerfMoveReqProcImpl( const char* inSourcePath, const DAVRequestHeaders& inRequestHeaders, const char* inDestinationPath, const bool inOverwrite, const char* inLockToken) : SerfRequestProcessorImpl( inSourcePath, inRequestHeaders ) , mDestPathStr( inDestinationPath ) , mbOverwrite( inOverwrite ) , mpLockToken( inLockToken ) { } SerfMoveReqProcImpl::~SerfMoveReqProcImpl() { } serf_bucket_t * SerfMoveReqProcImpl::createSerfRequestBucket( serf_request_t * inSerfRequest ) { // create serf request serf_bucket_t *req_bkt = serf_request_bucket_request_create( inSerfRequest, "MOVE", getPathStr(), 0, serf_request_get_alloc( inSerfRequest ) ); // set request header fields serf_bucket_t* hdrs_bkt = serf_bucket_request_get_headers( req_bkt ); // general header fields provided by caller setRequestHeaders( hdrs_bkt ); // MOVE specific header fields serf_bucket_headers_set( hdrs_bkt, "Destination", mDestPathStr ); if ( mbOverwrite ) { serf_bucket_headers_set( hdrs_bkt, "Overwrite", "T" ); } else { serf_bucket_headers_set( hdrs_bkt, "Overwrite", "F" ); } if(mpLockToken) { serf_bucket_headers_set( hdrs_bkt, "if", mpLockToken ); } return req_bkt; } void SerfMoveReqProcImpl::processChunkOfResponseData( const char* /*data*/, apr_size_t /*len*/ ) { // nothing to do; } void SerfMoveReqProcImpl::handleEndOfResponseData( serf_bucket_t * /*inSerfResponseBucket*/ ) { // nothing to do; } } // namespace http_dav_ucp
1,458
403
from .metrics import ( uplift_curve, perfect_uplift_curve, uplift_auc_score, qini_curve, perfect_qini_curve, qini_auc_score, uplift_at_k, response_rate_by_percentile, weighted_average_uplift, uplift_by_percentile, treatment_balance_curve, average_squared_deviation, make_uplift_scorer ) __all__ = [ 'uplift_curve', 'perfect_uplift_curve', 'uplift_auc_score', 'qini_curve', 'perfect_qini_curve', 'qini_auc_score', 'uplift_at_k', 'response_rate_by_percentile', 'weighted_average_uplift', 'uplift_by_percentile', 'treatment_balance_curve', 'average_squared_deviation', 'make_uplift_scorer' ]
273
575
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/tools/quic/quic_simple_server.h" #include <string.h> #include <memory> #include "base/bind.h" #include "base/location.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/log/net_log_source.h" #include "net/quic/address_utils.h" #include "net/socket/udp_server_socket.h" #include "net/third_party/quiche/src/quic/core/crypto/crypto_handshake.h" #include "net/third_party/quiche/src/quic/core/crypto/quic_random.h" #include "net/third_party/quiche/src/quic/core/quic_crypto_stream.h" #include "net/third_party/quiche/src/quic/core/quic_data_reader.h" #include "net/third_party/quiche/src/quic/core/quic_packets.h" #include "net/third_party/quiche/src/quic/tools/quic_simple_dispatcher.h" #include "net/tools/quic/quic_simple_server_packet_writer.h" #include "net/tools/quic/quic_simple_server_session_helper.h" #include "net/tools/quic/quic_simple_server_socket.h" namespace net { namespace { const char kSourceAddressTokenSecret[] = "secret"; const size_t kNumSessionsToCreatePerSocketEvent = 16; // Allocate some extra space so we can send an error if the client goes over // the limit. const int kReadBufferSize = 2 * quic::kMaxIncomingPacketSize; } // namespace QuicSimpleServer::QuicSimpleServer( std::unique_ptr<quic::ProofSource> proof_source, const quic::QuicConfig& config, const quic::QuicCryptoServerConfig::ConfigOptions& crypto_config_options, const quic::ParsedQuicVersionVector& supported_versions, quic::QuicSimpleServerBackend* quic_simple_server_backend) : version_manager_(supported_versions), helper_( new QuicChromiumConnectionHelper(&clock_, quic::QuicRandom::GetInstance())), alarm_factory_(new QuicChromiumAlarmFactory( base::ThreadTaskRunnerHandle::Get().get(), &clock_)), config_(config), crypto_config_options_(crypto_config_options), crypto_config_(kSourceAddressTokenSecret, quic::QuicRandom::GetInstance(), std::move(proof_source), quic::KeyExchangeSource::Default()), read_pending_(false), synchronous_read_count_(0), read_buffer_(base::MakeRefCounted<IOBufferWithSize>(kReadBufferSize)), quic_simple_server_backend_(quic_simple_server_backend) { DCHECK(quic_simple_server_backend); Initialize(); } void QuicSimpleServer::Initialize() { #if MMSG_MORE use_recvmmsg_ = true; #endif // If an initial flow control window has not explicitly been set, then use a // sensible value for a server: 1 MB for session, 64 KB for each stream. const uint32_t kInitialSessionFlowControlWindow = 1 * 1024 * 1024; // 1 MB const uint32_t kInitialStreamFlowControlWindow = 64 * 1024; // 64 KB if (config_.GetInitialStreamFlowControlWindowToSend() == quic::kMinimumFlowControlSendWindow) { config_.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindow); } if (config_.GetInitialSessionFlowControlWindowToSend() == quic::kMinimumFlowControlSendWindow) { config_.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindow); } std::unique_ptr<quic::CryptoHandshakeMessage> scfg( crypto_config_.AddDefaultConfig(helper_->GetRandomGenerator(), helper_->GetClock(), crypto_config_options_)); } QuicSimpleServer::~QuicSimpleServer() = default; bool QuicSimpleServer::CreateUDPSocketAndListen( const quic::QuicSocketAddress& address) { return Listen(ToIPEndPoint(address)); } void QuicSimpleServer::HandleEventsForever() { base::RunLoop().Run(); } bool QuicSimpleServer::Listen(const IPEndPoint& address) { socket_ = CreateQuicSimpleServerSocket(address, &server_address_); if (socket_ == nullptr) return false; dispatcher_ = std::make_unique<quic::QuicSimpleDispatcher>( &config_, &crypto_config_, &version_manager_, std::unique_ptr<quic::QuicConnectionHelperInterface>(helper_), std::unique_ptr<quic::QuicCryptoServerStreamBase::Helper>( new QuicSimpleServerSessionHelper(quic::QuicRandom::GetInstance())), std::unique_ptr<quic::QuicAlarmFactory>(alarm_factory_), quic_simple_server_backend_, quic::kQuicDefaultConnectionIdLength); QuicSimpleServerPacketWriter* writer = new QuicSimpleServerPacketWriter(socket_.get(), dispatcher_.get()); dispatcher_->InitializeWithWriter(writer); StartReading(); return true; } void QuicSimpleServer::Shutdown() { DVLOG(1) << "QuicSimpleServer is shutting down"; // Before we shut down the epoll server, give all active sessions a chance to // notify clients that they're closing. dispatcher_->Shutdown(); if (!socket_) { return; } socket_->Close(); socket_.reset(); } void QuicSimpleServer::StartReading() { if (synchronous_read_count_ == 0) { // Only process buffered packets once per message loop. dispatcher_->ProcessBufferedChlos(kNumSessionsToCreatePerSocketEvent); } if (read_pending_) { return; } read_pending_ = true; int result = socket_->RecvFrom( read_buffer_.get(), read_buffer_->size(), &client_address_, base::BindOnce(&QuicSimpleServer::OnReadComplete, base::Unretained(this))); if (result == ERR_IO_PENDING) { synchronous_read_count_ = 0; if (dispatcher_->HasChlosBuffered()) { // No more packets to read, so yield before processing buffered packets. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&QuicSimpleServer::StartReading, weak_factory_.GetWeakPtr())); } return; } if (++synchronous_read_count_ > 32) { synchronous_read_count_ = 0; // Schedule the processing through the message loop to 1) prevent infinite // recursion and 2) avoid blocking the thread for too long. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&QuicSimpleServer::OnReadComplete, weak_factory_.GetWeakPtr(), result)); } else { OnReadComplete(result); } } void QuicSimpleServer::OnReadComplete(int result) { read_pending_ = false; if (result > 0) { quic::QuicReceivedPacket packet(read_buffer_->data(), result, helper_->GetClock()->Now(), false); dispatcher_->ProcessPacket(ToQuicSocketAddress(server_address_), ToQuicSocketAddress(client_address_), packet); } else { LOG(ERROR) << "QuicSimpleServer read failed: " << ErrorToString(result); // Do not act on ERR_MSG_TOO_BIG as that indicates that we received a UDP // packet whose payload is larger than our receive buffer. Do not act on 0 // as that indicates that we received a UDP packet with an empty payload. // In both cases, the socket should still be usable. if (result != ERR_MSG_TOO_BIG && result != 0) { Shutdown(); return; } } StartReading(); } } // namespace net
2,828
10,031
/* * Copyright (c) 2018. paascloud.net All Rights Reserved. * 项目名称:paascloud快速搭建企业级分布式微服务平台 * 类名称:PtcPayInfoService.java * 创建人:刘兆明 * 联系方式:<EMAIL> * 开源地址: https://github.com/paascloud * 博客地址: http://blog.paascloud.net * 项目官网: http://paascloud.net */ package com.paascloud.provider.service; import com.paascloud.core.support.IService; import com.paascloud.provider.model.domain.PtcPayInfo; /** * The interface Ptc pay info service. * * @author <EMAIL> */ public interface PtcPayInfoService extends IService<PtcPayInfo> { }
289
348
{"nom":"Martigny-les-Gerbonvaux","circ":"4ème circonscription","dpt":"Vosges","inscrits":83,"abs":45,"votants":38,"blancs":5,"nuls":2,"exp":31,"res":[{"nuance":"SOC","nom":"<NAME>","voix":16},{"nuance":"LR","nom":"<NAME>","voix":15}]}
97
1,442
#ifndef POINCARE_PARSING_PARSER_H #define POINCARE_PARSING_PARSER_H /* A precedence-climbing parser is implemented hereafter. * It is a trade-off between * a readable but less efficient recursive-descent parser * and * an efficient but less readable shunting-yard parser. */ #include <poincare_expressions.h> #include "tokenizer.h" namespace Poincare { class Parser { public: enum class Status { Success, Progress, Error }; Parser(const char * text, Context * context) : m_context(context), m_status(Status::Progress), m_tokenizer(text), m_currentToken(Token(Token::Undefined)), m_nextToken(m_tokenizer.popToken()), m_pendingImplicitMultiplication(false), m_symbolPlusParenthesesAreFunctions(false) {} Expression parse(); Status getStatus() const { return m_status; } static bool IsReservedName(const char * name, size_t nameLength); private: static const Expression::FunctionHelper * const * GetReservedFunction(const char * name, size_t nameLength); static bool IsSpecialIdentifierName(const char * name, size_t nameLength); Expression parseUntil(Token::Type stoppingType); // Methods on Tokens void popToken(); bool popTokenIfType(Token::Type type); bool nextTokenHasPrecedenceOver(Token::Type stoppingType); void isThereImplicitMultiplication(); // Specific Token parsers void parseUnexpected(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseNumber(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseConstant(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseUnit(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseIdentifier(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseEmpty(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseMatrix(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseLeftParenthesis(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseLeftSystemParenthesis(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseBang(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parsePlus(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseMinus(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseTimes(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseSlash(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseImplicitTimes(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseCaret(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseCaretWithParenthesis(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseEqual(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseRightwardsArrow(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); void parseLeftSuperscript(Expression & leftHandSide, Token::Type stoppingType = (Token::Type)0); // Parsing helpers bool parseBinaryOperator(const Expression & leftHandSide, Expression & rightHandSide, Token::Type stoppingType); Expression parseVector(); Expression parseFunctionParameters(); Expression parseCommaSeparatedList(); void parseReservedFunction(Expression & leftHandSide, const Expression::FunctionHelper * const * functionHelper); void parseSpecialIdentifier(Expression & leftHandSide); void parseSequence(Expression & leftHandSide, const char * name, Token::Type leftDelimiter1, Token::Type rightDelimiter1, Token::Type leftDelimiter2, Token::Type rightDelimiter2); void parseCustomIdentifier(Expression & leftHandSide, const char * name, size_t length); void defaultParseLeftParenthesis(bool isSystemParenthesis, Expression & leftHandSide, Token::Type stoppingType); // Data members Context * m_context; Status m_status; /* m_status is initialized to Status::Progress, * is changed to Status::Error if the Parser encounters an error, * and is otherwise changed Status::Success. */ Tokenizer m_tokenizer; Token m_currentToken; Token m_nextToken; bool m_pendingImplicitMultiplication; bool m_symbolPlusParenthesesAreFunctions; // The array of reserved functions' helpers static constexpr const Expression::FunctionHelper * s_reservedFunctions[] = { // Ordered according to name and numberOfChildren &AbsoluteValue::s_functionHelper, &ArcCosine::s_functionHelper, &HyperbolicArcCosine::s_functionHelper, &ArcCotangent::s_functionHelper, &ArcCosecant::s_functionHelper, &ComplexArgument::s_functionHelper, &ArcSecant::s_functionHelper, &ArcSine::s_functionHelper, &HyperbolicArcSine::s_functionHelper, &ArcTangent::s_functionHelper, &HyperbolicArcTangent::s_functionHelper, &BinomCDF::s_functionHelper, &BinomialCoefficient::s_functionHelper, &BinomPDF::s_functionHelper, &Ceiling::s_functionHelper, &ConfidenceInterval::s_functionHelper, &Conjugate::s_functionHelper, &Cosine::s_functionHelper, &HyperbolicCosine::s_functionHelper, &Cotangent::s_functionHelper, &VectorCross::s_functionHelper, &Cosecant::s_functionHelper, &Determinant::s_functionHelper, &Derivative::s_functionHelper, &MatrixDimension::s_functionHelper, &VectorDot::s_functionHelper, &Factor::s_functionHelper, &Floor::s_functionHelper, &FracPart::s_functionHelper, &GreatCommonDivisor::s_functionHelper, &MatrixIdentity::s_functionHelper, &ImaginaryPart::s_functionHelper, &Integral::s_functionHelper, &InvBinom::s_functionHelper, &MatrixInverse::s_functionHelper, &InvNorm::s_functionHelper, &LeastCommonMultiple::s_functionHelper, &NaperianLogarithm::s_functionHelper, &CommonLogarithm::s_functionHelper, &Logarithm::s_functionHelper, &VectorNorm::s_functionHelper, &NormCDF::s_functionHelper, &NormCDF2::s_functionHelper, &NormPDF::s_functionHelper, &PermuteCoefficient::s_functionHelper, &SimplePredictionInterval::s_functionHelper, &PredictionInterval::s_functionHelper, &Product::s_functionHelper, &DivisionQuotient::s_functionHelper, &Randint::s_functionHelper, &Random::s_functionHelper, &RealPart::s_functionHelper, &MatrixRowEchelonForm::s_functionHelper, &DivisionRemainder::s_functionHelper, &NthRoot::s_functionHelper, &Round::s_functionHelper, &MatrixReducedRowEchelonForm::s_functionHelper, &Secant::s_functionHelper, &SignFunction::s_functionHelper, &Sine::s_functionHelper, &HyperbolicSine::s_functionHelper, &Sum::s_functionHelper, &Tangent::s_functionHelper, &HyperbolicTangent::s_functionHelper, &MatrixTrace::s_functionHelper, &MatrixTranspose::s_functionHelper, &SquareRoot::s_functionHelper }; static constexpr const Expression::FunctionHelper * const * s_reservedFunctionsUpperBound = s_reservedFunctions + (sizeof(s_reservedFunctions)/sizeof(Expression::FunctionHelper *)); /* The method GetReservedFunction passes through the successive * entries of the above array in order to determine whether m_currentToken * corresponds to an entry. As a helper, the static constexpr * s_reservedFunctionsUpperBound marks the end of the array. */ }; } #endif
2,455
965
// Retrieve the current time CFileTime myFT; myFT = CFileTime::GetCurrentTime();
58
394
<filename>samples/interceptor/spring-fatjar-interceptor-service/src/main/java/org/wso2/msf4j/samples/springfatjarinterceptorservice/Application.java /* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.msf4j.samples.springfatjarinterceptorservice; import org.springframework.context.ConfigurableApplicationContext; import org.wso2.msf4j.samples.interceptor.common.LogTextRequestInterceptor; import org.wso2.msf4j.samples.interceptor.common.LogTextResponseInterceptor; import org.wso2.msf4j.samples.interceptor.common.PropertyAddRequestInterceptor; import org.wso2.msf4j.samples.interceptor.common.PropertyGetResponseInterceptor; import org.wso2.msf4j.spring.MSF4JSpringApplication; /** * Main class of starting the spring interceptor demo. * * @since 2.4.2 */ public class Application { public static void main(String[] args) { MSF4JSpringApplication msf4JSpringApplication = new MSF4JSpringApplication(ReceptionService.class); ConfigurableApplicationContext configurableApplicationContext = MSF4JSpringApplication.run(ReceptionService.class, "--http.port=8090"); msf4JSpringApplication.addService(configurableApplicationContext, ReceptionService.class, "/reception-service") .addGlobalRequestInterceptor(new LogTextRequestInterceptor(), new PropertyAddRequestInterceptor()) .addGlobalResponseInterceptor(new LogTextResponseInterceptor(), new PropertyGetResponseInterceptor()); } }
685
894
<filename>spec/support/fixtures/user_representation.json { "github_access_token_present": true, "repos":["ctlc/docker-mysql","ctlc/docker-apache"], "email":"<EMAIL>", "github_username":"githubuser" }
75
743
package pl.allegro.tech.hermes.client; import pl.allegro.tech.hermes.client.metrics.MetricsMessageDeliveryListener; import pl.allegro.tech.hermes.client.metrics.MetricsProvider; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.Executors; import java.util.function.Predicate; import java.util.function.Supplier; public class ReactiveHermesClientBuilder { private ReactiveHermesSender sender; private URI uri = URI.create("http://localhost:8080"); private final Map<String, String> defaultHeaders = new HashMap<>(); private int retries = 3; private Predicate<HermesResponse> retryCondition = new HermesClientBasicRetryCondition(); private long retrySleepInMillis = 100; private long maxRetrySleepInMillis = 300; private double jitterFactor = 0.5d; private Supplier<Scheduler> schedulerFactory = () -> Schedulers.fromExecutor(Executors.newSingleThreadScheduledExecutor()); private Optional<MetricsProvider> metrics = Optional.empty(); public ReactiveHermesClientBuilder(ReactiveHermesSender sender) { this.sender = sender; this.defaultHeaders.put(HermesMessage.CONTENT_TYPE_HEADER, HermesMessage.APPLICATION_JSON); } public static ReactiveHermesClientBuilder hermesClient(ReactiveHermesSender sender) { return new ReactiveHermesClientBuilder(sender); } public ReactiveHermesClient build() { ReactiveHermesClient hermesClient = new ReactiveHermesClient(sender, uri, defaultHeaders, retries, retryCondition, retrySleepInMillis, maxRetrySleepInMillis, jitterFactor, schedulerFactory.get()); metrics.ifPresent((metricsProvider) -> { hermesClient.addMessageDeliveryListener(new MetricsMessageDeliveryListener(metricsProvider)); }); return hermesClient; } public ReactiveHermesClientBuilder withURI(URI uri) { this.uri = uri; return this; } public ReactiveHermesClientBuilder withMetrics(MetricsProvider metrics) { this.metrics = Optional.of(metrics); return this; } public ReactiveHermesClientBuilder withDefaultContentType(String defaultContentType) { defaultHeaders.put(HermesMessage.CONTENT_TYPE_HEADER, defaultContentType); return this; } public ReactiveHermesClientBuilder withDefaultHeaderValue(String header, String value) { defaultHeaders.put(header, value); return this; } public ReactiveHermesClientBuilder withRetries(int retries) { this.retries = retries; return this; } public ReactiveHermesClientBuilder withRetries(int retries, Predicate<HermesResponse> retryCondition) { this.retryCondition = retryCondition; return withRetries(retries); } public ReactiveHermesClientBuilder withRetrySleep(long retrySleepInMillis) { this.retrySleepInMillis = retrySleepInMillis; return this; } public ReactiveHermesClientBuilder withRetrySleep(long retrySleepInMillis, long maxRetrySleepInMillis) { this.retrySleepInMillis = retrySleepInMillis; this.maxRetrySleepInMillis = maxRetrySleepInMillis; return this; } public ReactiveHermesClientBuilder withScheduler(Scheduler scheduler) { this.schedulerFactory = () -> scheduler; return this; } public ReactiveHermesClientBuilder withJitter(Double jitterFactor) { this.jitterFactor = jitterFactor; return this; } }
1,299
777
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/system/system_clock.h" #include <memory> #include "base/logging.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/system/system_clock_observer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/pref_names.h" #include "chromeos/login/login_state.h" #include "chromeos/settings/cros_settings_names.h" #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/notification_service.h" namespace chromeos { namespace system { namespace { void SetShouldUse24HourClock(bool use_24_hour_clock) { user_manager::User* const user = user_manager::UserManager::Get()->GetActiveUser(); if (!user) return; // May occur if not running on a device. Profile* const profile = ProfileHelper::Get()->GetProfileByUser(user); if (!profile) return; // May occur in tests or if not running on a device. OwnerSettingsServiceChromeOS* const service = OwnerSettingsServiceChromeOSFactory::GetForBrowserContext(profile); CHECK(service); service->SetBoolean(kSystemUse24HourClock, use_24_hour_clock); } } // anonymous namespace SystemClock::SystemClock() : user_pod_was_focused_(false), last_focused_pod_hour_clock_type_(base::k12HourClock), user_profile_(NULL), device_settings_observer_(CrosSettings::Get()->AddSettingsObserver( kSystemUse24HourClock, base::Bind(&SystemClock::OnSystemPrefChanged, base::Unretained(this)))) { if (LoginState::IsInitialized()) LoginState::Get()->AddObserver(this); // Register notifications on construction so that events such as // PROFILE_CREATED do not get missed if they happen before Initialize(). registrar_.reset(new content::NotificationRegistrar); if (!LoginState::IsInitialized() || LoginState::Get()->GetLoggedInUserType() == LoginState::LOGGED_IN_USER_NONE) { registrar_->Add(this, chrome::NOTIFICATION_SESSION_STARTED, content::NotificationService::AllSources()); } registrar_->Add(this, chrome::NOTIFICATION_PROFILE_CREATED, content::NotificationService::AllSources()); registrar_->Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED, content::NotificationService::AllSources()); registrar_->Add(this, chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, content::NotificationService::AllSources()); user_manager::UserManager::Get()->AddSessionStateObserver(this); } SystemClock::~SystemClock() { registrar_.reset(); device_settings_observer_.reset(); if (LoginState::IsInitialized()) LoginState::Get()->RemoveObserver(this); if (user_manager::UserManager::IsInitialized()) user_manager::UserManager::Get()->RemoveSessionStateObserver(this); } // LoginState::Observer overrides. void SystemClock::LoggedInStateChanged() { // It apparently sometimes takes a while after login before the current user // is recognized as the owner. Make sure that the system-wide clock setting // is updated when the recognition eventually happens (crbug.com/278601). if (user_manager::UserManager::Get()->IsCurrentUserOwner()) SetShouldUse24HourClock(ShouldUse24HourClock()); } // content::NotificationObserver implementation. void SystemClock::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED: { UpdateClockType(); break; } case chrome::NOTIFICATION_PROFILE_CREATED: { OnActiveProfileChanged(content::Source<Profile>(source).ptr()); registrar_->Remove(this, chrome::NOTIFICATION_PROFILE_CREATED, content::NotificationService::AllSources()); break; } case chrome::NOTIFICATION_PROFILE_DESTROYED: { if (OnProfileDestroyed(content::Source<Profile>(source).ptr())) { registrar_->Remove(this, chrome::NOTIFICATION_PROFILE_DESTROYED, content::NotificationService::AllSources()); } break; } case chrome::NOTIFICATION_SESSION_STARTED: { OnActiveProfileChanged(ProfileManager::GetActiveUserProfile()); break; } default: NOTREACHED(); } } void SystemClock::ActiveUserChanged(const user_manager::User* /*user*/) { UpdateClockType(); } void SystemClock::AddObserver(SystemClockObserver* observer) { observer_list_.AddObserver(observer); } void SystemClock::RemoveObserver(SystemClockObserver* observer) { observer_list_.RemoveObserver(observer); } void SystemClock::OnActiveProfileChanged(Profile* profile) { user_profile_ = profile; PrefService* prefs = profile->GetPrefs(); user_pref_registrar_.reset(new PrefChangeRegistrar); user_pref_registrar_->Init(prefs); user_pref_registrar_->Add( prefs::kUse24HourClock, base::Bind(&SystemClock::UpdateClockType, base::Unretained(this))); } bool SystemClock::OnProfileDestroyed(Profile* profile) { if (profile != user_profile_) return false; user_pref_registrar_.reset(); user_profile_ = NULL; return true; } void SystemClock::SetLastFocusedPodHourClockType( base::HourClockType hour_clock_type) { user_pod_was_focused_ = true; last_focused_pod_hour_clock_type_ = hour_clock_type; UpdateClockType(); } bool SystemClock::ShouldUse24HourClock() const { // On login screen and in guest mode owner default is used for // kUse24HourClock preference. const chromeos::LoginState::LoggedInUserType status = LoginState::IsInitialized() ? LoginState::Get()->GetLoggedInUserType() : LoginState::LOGGED_IN_USER_NONE; if (status == LoginState::LOGGED_IN_USER_NONE && user_pod_was_focused_) return last_focused_pod_hour_clock_type_ == base::k24HourClock; const CrosSettings* const cros_settings = CrosSettings::Get(); bool system_use_24_hour_clock = true; const bool system_value_found = cros_settings->GetBoolean( kSystemUse24HourClock, &system_use_24_hour_clock); if ((status == LoginState::LOGGED_IN_USER_NONE) || !user_pref_registrar_) { return (system_value_found ? system_use_24_hour_clock : (base::GetHourClockType() == base::k24HourClock)); } const PrefService::Preference* user_pref = user_pref_registrar_->prefs()->FindPreference(prefs::kUse24HourClock); if (status == LoginState::LOGGED_IN_USER_GUEST && user_pref->IsDefaultValue()) { return (system_value_found ? system_use_24_hour_clock : (base::GetHourClockType() == base::k24HourClock)); } user_manager::User* active_user = user_manager::UserManager::Get()->GetActiveUser(); if (active_user) { Profile* user_profile = ProfileHelper::Get()->GetProfileByUser(active_user); if (user_profile) { user_pref = user_profile->GetPrefs()->FindPreference(prefs::kUse24HourClock); } } bool use_24_hour_clock = true; user_pref->GetValue()->GetAsBoolean(&use_24_hour_clock); return use_24_hour_clock; } void SystemClock::OnSystemPrefChanged() { UpdateClockType(); } void SystemClock::UpdateClockType() { // This also works for enterprise-managed devices because they never have // a local owner. if (user_manager::UserManager::Get()->IsCurrentUserOwner()) SetShouldUse24HourClock(ShouldUse24HourClock()); for (auto& observer : observer_list_) observer.OnSystemClockChanged(this); } } // namespace system } // namespace chromeos
2,970
521
// Copyright 2016 <NAME>. // Copyright (C) 2011 - 2012 <NAME>. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) /** * \file * \brief Contains an implementation of C++17 optional (n3793). * * \sa https://github.com/akrzemi1/Optional * \sa http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3848.html */ #ifndef NETWORK_OPTIONAL_INC #define NETWORK_OPTIONAL_INC #include <stdexcept> #include <type_traits> #include <utility> #include <memory> #include <algorithm> #if !defined(DOXYGEN_SHOULD_SKIP_THIS) #ifdef NDEBUG #define NETWORK_ASSERTED_EXPRESSION(CHECK, EXPR) (EXPR) #else #define NETWORK_ASSERTED_EXPRESSION(CHECK, EXPR) \ ((CHECK) ? (EXPR) : (fail(#CHECK, __FILE__, __LINE__), (EXPR))) inline void fail(const char*, const char*, unsigned) {} #endif // NDEBUG #endif // !defined(DOXYGEN_SHOULD_SKIP_THIS) namespace network { /** * \ingroup optional * \class nullopt_t optional.hpp network/uri.hpp * \brief Disengaged state indicator. * \sa optional */ struct nullopt_t { #if !defined(DOXYGEN_SHOULD_SKIP_THIS) struct init {}; constexpr nullopt_t(init) {} #endif // !defined(DOXYGEN_SHOULD_SKIP_THIS) }; /** * \ingroup optional * \brief Used to indicate a *disengaged* state for optional objects. */ constexpr nullopt_t nullopt{nullopt_t::init{}}; /** * \ingroup optional * \class bad_optional_access optional.hpp network/uri.hpp * \brief Exception thrown when the value member function is called when the * optional object is disengaged. */ class bad_optional_access : public std::logic_error { public: /** * \brief Constructor. * \param what_arg The error message. */ explicit bad_optional_access(const std::string& what_arg) : std::logic_error(what_arg) {} /** * \brief Constructor. * \param what_arg The error message. */ explicit bad_optional_access(const char* what_arg) : std::logic_error(what_arg) {} }; #if !defined(DOXYGEN_SHOULD_SKIP_THIS) namespace details { struct dummy_t {}; template <class T> union trivially_destructible_optional_storage { static_assert(std::is_trivially_destructible<T>::value, ""); dummy_t dummy_; T value_; constexpr trivially_destructible_optional_storage() : dummy_{} {} constexpr trivially_destructible_optional_storage(const T& v) : value_{v} {} ~trivially_destructible_optional_storage() = default; }; template <class T> union optional_storage { dummy_t dummy_; T value_; constexpr optional_storage() : dummy_{} {} constexpr optional_storage(const T& v) : value_{v} {} ~optional_storage() {} }; template <class T> class trivially_destructible_optional_base { public: typedef T value_type; constexpr trivially_destructible_optional_base() noexcept : init_(false), storage_{} {} constexpr trivially_destructible_optional_base(const T& v) : init_(true), storage_{v} {} constexpr trivially_destructible_optional_base(T&& v) : init_(true), storage_{std::move(v)} {} ~trivially_destructible_optional_base() = default; protected: bool init_; optional_storage<T> storage_; }; template <class T> class optional_base { public: typedef T value_type; constexpr optional_base() noexcept : init_(false), storage_{} {} constexpr optional_base(const T& v) : init_(true), storage_{v} {} constexpr optional_base(T&& v) : init_(true), storage_{std::move(v)} {} ~optional_base() { if (init_) { storage_.value_.T::~T(); } } protected: bool init_; optional_storage<T> storage_; }; } // namespace details #endif // !defined(DOXYGEN_SHOULD_SKIP_THIS) /** * \ingroup optional * \class optional optional.hpp network/uri.hpp * \brief An implementation of C++17 optional (n3793) */ #if !defined(DOXYGEN_SHOULD_SKIP_THIS) template <class T> using optional_base = typename std::conditional< std::is_trivially_destructible<T>::value, details::trivially_destructible_optional_base<T>, details::optional_base<T>>::type; #endif // !defined(DOXYGEN_SHOULD_SKIP_THIS) template <class T> #if !defined(DOXYGEN_SHOULD_SKIP_THIS) class optional : optional_base<T> { #else class optional { #endif // !defined(DOXYGEN_SHOULD_SKIP_THIS) typedef optional_base<T> base_type; public: /** * \brief Optional value type. */ typedef T value_type; /** * \brief Constructor. * \post *disengaged*. */ constexpr optional() : optional_base<T>() {} /** * \brief Constructor. * \post *disengaged*. */ constexpr optional(nullopt_t) noexcept : optional_base<T>() {} /** * \brief Copy constructor. * \param other The other optional object. */ optional(const optional& other) { if (other) { ::new(static_cast<void*>(ptr())) T(*other); base_type::init_ = true; } } /** * \brief Move constructor. * \param other The other optional object. */ optional(optional&& other) noexcept { if (other) { ::new(static_cast<void*>(ptr())) T(std::move(other.storage_.value_)); base_type::init_ = true; } } /** * \brief Constructor. * \param value The value with which to initialize the optional object. * \post *engaged* */ constexpr optional(const T& value) : optional_base<T>(value) {} /** * \brief Constructor. * \param value The value with which to initialize the optional object. * \post *engaged* */ constexpr optional(T&& value) : optional_base<T>(std::move(value)) {} /** * \brief Assignment operator. * \post *disengaged*. * \returns \c *this. */ optional& operator=(nullopt_t) noexcept { if (base_type::init_) { ptr()->T::~T(); } base_type::init_ = false; return *this; } /** * \brief Copy assignment operator. * \param other The other optional object. * \returns \c *this. */ optional& operator=(const optional& other) { if (bool(*this) && !other) { ptr()->T::~T(); base_type::init_ = false; } else if (!(*this) && bool(other)) { ::new(static_cast<void*>(ptr())) T(*other); base_type::init_ = true; } else if (bool(*this) && bool(other)) { base_type::storage_.value_ = *other; } return *this; } /** * \brief Move assignment operator. * \param other The other optional object. * \returns \c *this. */ optional& operator=(optional&& other) noexcept { if (bool(*this) && !other) { ptr()->T::~T(); base_type::init_ = false; } else if (!(*this) && bool(other)) { ::new(static_cast<void*>(ptr())) T(std::move(*other)); base_type::init_ = true; } else if (bool(*this) && bool(other)) { base_type::storage_.value_ = std::move(*other); } return *this; } /** * \brief Destructor. */ ~optional() = default; /** * \brief Swap function. * \param other The other optional object. */ void swap(optional& other) noexcept { if (bool(*this) && !other) { ::new(static_cast<void*>(other.ptr())) T(std::move(**this)); ptr()->T::~T(); std::swap(base_type::init_, other.base_type::init_); } else if (!(*this) && bool(other)) { ::new(static_cast<void*>(ptr())) T(std::move(*other)); other.ptr()->T::~T(); std::swap(base_type::init_, other.init_); } else if (bool(*this) && bool(other)) { std::swap(**this, *other); } } /** * \brief Observer. * \pre *engaged* * \returns The underlying optional value. */ constexpr T const* operator->() const { return NETWORK_ASSERTED_EXPRESSION(bool(*this), ptr()); } /** * \brief Observer. * \pre *engaged* * \returns The underlying optional value. */ T* operator->() { return NETWORK_ASSERTED_EXPRESSION(bool(*this), ptr()); } /** * \brief Observer. * \pre *engaged* * \returns The underlying optional value. */ constexpr T const& operator*() const { return NETWORK_ASSERTED_EXPRESSION(bool(*this), base_type::storage_.value_); } /** * \brief Observer. * \pre *engaged* * \returns The underlying optional value. */ T& operator*() { return NETWORK_ASSERTED_EXPRESSION(bool(*this), base_type::storage_.value_); } /** * \brief Operator bool overloads. * \returns \c true if the optional is *engaged*, \c false if it is *disengaged*. */ constexpr explicit operator bool() const noexcept { return base_type::init_; } /** * \returns The underlying optional value, if \c bool(*this). * \throws A bad_optional_access if \c !*this. */ constexpr T const& value() const { return *this ? base_type::storage_.value_ : (throw bad_optional_access("Uninitialized optional value"), base_type::storage_.value_); } /** * \returns The underlying optional value, if \c bool(*this). * \throws A bad_optional_access if \c !*this. */ T& value() { return *this ? base_type::storage_.value_ : (throw bad_optional_access("Uninitialized optional value"), base_type::storage_.value_); } /** * \returns <tt>bool(*this) ? **this : static_cast<T>(std::forward<U>(v))</tt>. * \pre \c <tt>std::is_copy_constructible<T>::value</tt> is \c true and <tt>std::is_convertible<U&&, T>::value</tt> is \c true. */ template <class U> T value_or(U&& other) const & { static_assert(std::is_copy_constructible<value_type>::value, "Must be copy constructible."); static_assert(std::is_convertible<U, value_type>::value, "U must be convertible to T."); return bool(*this) ? **this : static_cast<T>(std::forward<U>(other)); } /** * \returns <tt>bool(*this) ? std::move(**this) : static_cast<T>(std::forward<U>(v))</tt>. * \pre <tt>std::is_move_constructible<T>::value</tt> is \c true and <tt>std::is_convertible<U&&, T>::value</tt> is \c true. */ template <class U> T value_or(U&& other) && { static_assert(std::is_copy_constructible<value_type>::value, "Must be copy constructible."); static_assert(std::is_convertible<U, value_type>::value, "U must be convertible to T."); return bool(*this) ? std::move(**this) : static_cast<T>(std::forward<U>(other)); } private: T* ptr() { return std::addressof(base_type::storage_.value_); } }; /** * \brief Equality operator. */ template <class T> bool operator==(const optional<T>& lhs, const optional<T>& rhs) { if (bool(lhs) != bool(rhs)) { return false; } else if (!bool(lhs)) { return true; } else { return *lhs == *rhs; } } /** * \brief Inequality operator. */ template <class T> bool operator!=(const optional<T>& lhs, const optional<T>& rhs) { return !(lhs == rhs); } /** * \brief Comparison operator. */ template <class T> bool operator<(const optional<T>& lhs, const optional<T>& rhs) { if (!rhs) { return false; } else if (!lhs) { return true; } else { return *lhs < *rhs; } } /** * \brief Comparison operator. * \returns <tt>rhs < lhs</tt>. */ template <class T> bool operator>(const optional<T>& lhs, const optional<T>& rhs) { return rhs < lhs; } /** * \brief Comparison operator. * \returns <tt>!(rhs < lhs)</tt>. */ template <class T> bool operator<=(const optional<T>& lhs, const optional<T>& rhs) { return !(rhs < lhs); } /** * \brief Comparison operator. * \returns <tt>!(rhs > lhs)</tt>. */ template <class T> bool operator>=(const optional<T>& lhs, const optional<T>& rhs) { return !(lhs < rhs); } /** * \brief Equality operator. * \returns \c !x. */ template <class T> bool operator==(const optional<T>& x, nullopt_t) noexcept { return !x; } /** * \brief Equality operator. * \returns \c !x. */ template <class T> bool operator==(nullopt_t, const optional<T>& x) noexcept { return !x; } /** * \brief Inequality operator. * \returns \c bool(x). */ template <class T> bool operator!=(const optional<T>& x, nullopt_t) noexcept { return bool(x); } /** * \brief Inequality operator. * \returns \c bool(x). */ template <class T> bool operator!=(nullopt_t, const optional<T>& x) noexcept { return bool(x); } /** * \brief Comparison operator. * \returns \c false. */ template <class T> bool operator<(const optional<T>& x, nullopt_t) noexcept { return false; } /** * \brief Comparison operator. * \returns \c bool(x). */ template <class T> bool operator<(nullopt_t, const optional<T>& x) noexcept { return bool(x); } /** * \brief Comparison operator. * \returns \c !x. */ template <class T> bool operator<=(const optional<T>& x, nullopt_t) noexcept { return !x; } /** * \brief Comparison operator. * \returns \c true. */ template <class T> bool operator<=(nullopt_t, const optional<T>& x) noexcept { return true; } /** * \brief Comparison operator. * \returns \c bool(x). */ template <class T> bool operator>(const optional<T>& x, nullopt_t) noexcept { return bool(x); } /** * \brief Comparison operator. * \returns \c false. */ template <class T> bool operator>(nullopt_t, const optional<T>& x) noexcept { return false; } /** * \brief Comparison operator. * \returns \c true. */ template <class T> bool operator>=(const optional<T>& x, nullopt_t) noexcept { return true; } /** * \brief Comparison operator. * \returns \c !x. */ template <class T> bool operator>=(nullopt_t, const optional<T>& x) noexcept { return !x; } /** * \brief Equality operator. * \returns <tt>bool(x) ? *x == v : false</tt>. */ template <class T> bool operator==(const optional<T>& x, const T& v) { return bool(x) ? *x == v : false; } /** * \brief Equality operator. * \returns <tt>bool(x) ? v == *x : false</tt>. */ template <class T> bool operator==(const T& v, const optional<T>& x) { return bool(x) ? v == *x : false; } /** * \brief Inequality operator. * \returns <tt>bool(x) ? !(*x == v) : true</tt>. */ template <class T> bool operator!=(const optional<T>& x, const T& v) { return bool(x) ? !(*x == v) : true; } /** * \brief Inequality operator. * \returns <tt>bool(x) ? !(v == *x) : true</tt>. */ template <class T> bool operator!=(const T& v, const optional<T>& x) { return bool(x) ? !(v == *x) : true; } /** * \brief Comparison operator. * \returns <tt>bool(x) ? *x < v : true</tt>. */ template <class T> bool operator<(const optional<T>& x, const T& v) { return bool(x) ? *x < v : true; } /** * \brief Comparison operator. * \returns <tt>bool(x) ? v < *x : false</tt>. */ template <class T> bool operator<(const T& v, const optional<T>& x) { return bool(x) ? v < *x : false; } /** * \brief Comparison operator. * \returns <tt>bool(x) ? *x < v : true</tt>. */ template <class T> bool operator>(const optional<T>& x, const T& v) { return bool(x) ? *x < v : true; } /** * \brief Comparison operator. * \returns <tt>bool(x) ? v < *x : false</tt>. */ template <class T> bool operator>(const T& v, const optional<T>& x) { return bool(x) ? v < *x : false; } /** * \brief Comparison operator. * \returns <tt>!(x < v)</tt>. */ template <class T> bool operator>=(const optional<T>& x, const T& v) { return !(x < v); } /** * \brief Comparison operator. * \returns <tt>!(v < x)</tt>. */ template <class T> bool operator>=(const T& v, const optional<T>& x) { return !(v < x); } /** * \brief Comparison operator. * \returns <tt>!(x > v)</tt>. */ template <class T> bool operator<=(const optional<T>& x, const T& v) { return !(x > v); } /** * \brief Comparison operator. * \returns <tt>!(v > x)</tt>. */ template <class T> bool operator<=(const T& v, const optional<T>& x) { return !(v > x); } /** * \ingroup optional * \brief Swap function. * \param lhs The first optional object. * \param rhs The second optional object. * * Calls: * \code{.cpp} * lhs.swap(rhs); * \endcode */ template <class T> inline void swap(optional<T>& lhs, optional<T>& rhs) noexcept(noexcept(lhs.swap(rhs))) { return lhs.swap(rhs); } /** * \ingroup optional * \brief A helper function to contruct an optional object. * \returns <tt>optional<typename std::decay<T>::type>(std::forward(value))</tt>. */ template <class T> inline constexpr optional<typename std::decay<T>::type> make_optional(T&& value) { return optional<typename std::decay<T>::type>(std::forward(value)); } } // namespace network #endif // NETWORK_OPTIONAL_INC
6,310
575
<gh_stars>100-1000 /* * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple 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. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_SERIALIZERS_MARKUP_ACCUMULATOR_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_SERIALIZERS_MARKUP_ACCUMULATOR_H_ #include <utility> #include "base/macros.h" #include "third_party/blink/renderer/core/editing/editing_strategy.h" #include "third_party/blink/renderer/core/editing/serializers/markup_formatter.h" #include "third_party/blink/renderer/core/editing/serializers/serialization.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" namespace blink { class Attribute; class Element; class Node; class MarkupAccumulator { STACK_ALLOCATED(); public: MarkupAccumulator(AbsoluteURLs, SerializationType, IncludeShadowRoots, ClosedRootsSet = ClosedRootsSet()); virtual ~MarkupAccumulator(); template <typename Strategy> String SerializeNodes(const Node&, ChildrenOnly); protected: // Returns serialized prefix. It should be passed to AppendEndTag(). virtual AtomicString AppendElement(const Element&); virtual void AppendAttribute(const Element&, const Attribute&); MarkupFormatter formatter_; StringBuilder markup_; IncludeShadowRoots include_shadow_roots_; ClosedRootsSet include_closed_roots_; private: bool SerializeAsHTML() const; String ToString() { return markup_.ToString(); } void AppendString(const String&); // Serialize a Node, without its children and its end tag. void AppendStartMarkup(const Node&); class ElementSerializationData; // Returns 'ignore namespace definition attribute' flag and the serialized // prefix. // If the flag is true, we should not serialize xmlns="..." on the element. // The prefix should be used in end tag serialization. ElementSerializationData AppendStartTagOpen(const Element&); void AppendStartTagClose(const Element&); void AppendNamespace(const AtomicString& prefix, const AtomicString& namespace_uri); void AppendAttributeAsXMLWithNamespace(const Element& element, const Attribute& attribute, const String& value); bool ShouldAddNamespaceAttribute(const Attribute& attribute, const AtomicString& candidate_prefix); void AppendEndTag(const Element&, const AtomicString& prefix); EntityMask EntityMaskForText(const Text&) const; void PushNamespaces(const Element& element); void PopNamespaces(const Element& element); void RecordNamespaceInformation(const Element& element); AtomicString RetrievePreferredPrefixString(const AtomicString& ns, const AtomicString& prefix); void AddPrefix(const AtomicString& prefix, const AtomicString& namespace_uri); AtomicString LookupNamespaceURI(const AtomicString& prefix); AtomicString GeneratePrefix(const AtomicString& new_namespace); virtual void AppendCustomAttributes(const Element&); virtual bool ShouldIgnoreAttribute(const Element&, const Attribute&) const; virtual bool ShouldIgnoreElement(const Element&) const; // Returns an auxiliary DOM tree, i.e. shadow tree, that needs also to be // serialized. The root of auxiliary DOM tree is returned as an 1st element // in the pair. It can be null if no auxiliary DOM tree exists. An additional // element used to enclose the serialized content of auxiliary DOM tree // can be returned as 2nd element in the pair. It can be null if this is not // needed. For shadow tree, a <template> element is needed to wrap the shadow // tree content. virtual std::pair<Node*, Element*> GetAuxiliaryDOMTree(const Element&) const; template <typename Strategy> void SerializeNodesWithNamespaces(const Node& target_node, ChildrenOnly children_only); class NamespaceContext; Vector<NamespaceContext> namespace_stack_; // https://w3c.github.io/DOM-Parsing/#dfn-generated-namespace-prefix-index uint32_t prefix_index_; DISALLOW_COPY_AND_ASSIGN(MarkupAccumulator); }; extern template String MarkupAccumulator::SerializeNodes<EditingStrategy>( const Node&, ChildrenOnly); } // namespace blink #endif
1,870
2,342
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='<KEY>' language='*'\"") #include "UI\_Source\GacStudioUI.h" #include "Studio\StudioModel.h" #include <Windows.h> using namespace vl::collections; using namespace vl::stream; using namespace ui; using namespace vm; int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int CmdShow) { int result = SetupWindowsDirect2DRenderer(); #ifdef VCZH_CHECK_MEMORY_LEAKS _CrtDumpMemoryLeaks(); #endif return result; } #define GACSTUDIO_LOADBINARYRESOURCE void GuiMain() { List<WString> errors; #ifdef GACSTUDIO_LOADBINARYRESOURCE Ptr<GuiResource> resource; { FileStream fileStream(L"..\\GacStudio\\UI\\_UIRes\\Resources.bin", FileStream::ReadOnly); LzwDecoder decoder; DecoderStream decoderStream(fileStream, decoder); resource = GuiResource::LoadPrecompiledBinary(decoderStream, errors); } #else auto resource = GuiResource::LoadFromXml(L"..\\GacStudio\\UI\\_UIRes\\Resources.xml", errors); #endif GetInstanceLoaderManager()->SetResource(L"GacStudioUI", resource); MainWindow window(new StudioModel); window.ForceCalculateSizeImmediately(); window.MoveToScreenCenter(); GetApplication()->Run(&window); }
467
711
<gh_stars>100-1000 package com.java110.community.smo.impl; import com.java110.community.dao.IDictDao; import com.java110.intf.community.DictInnerServiceSMO; import com.java110.dto.Dict.DictDto; import com.java110.dto.Dict.DictQueryDto; import com.java110.utils.util.BeanConvertUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * <br> * Created by <NAME> on 10/22/2019 * <p> */ @RestController public class DictInnerServiceSMOImpl implements DictInnerServiceSMO { @Autowired private IDictDao iDictDao; @Override public List<DictDto> queryDict(@RequestBody DictQueryDto queryDto) { return this.iDictDao.queryDict(BeanConvertUtil.beanCovertMap(queryDto)); } }
332
1,231
<reponame>RalfGuder/LaTeX-examples class Fruit { } class Apple extends Fruit { } class Orange extends Fruit { }
40
30,785
package jadx.plugins.input.javaconvert; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConvertResult implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(ConvertResult.class); private final List<Path> converted = new ArrayList<>(); private final List<Path> tmpPaths = new ArrayList<>(); public List<Path> getConverted() { return converted; } public void addConvertedFiles(List<Path> paths) { converted.addAll(paths); } public void addTempPath(Path path) { tmpPaths.add(path); } public boolean isEmpty() { return converted.isEmpty(); } @Override public void close() { for (Path tmpPath : tmpPaths) { try { delete(tmpPath); } catch (Exception e) { LOG.warn("Failed to delete temp path: {}", tmpPath, e); } } } @SuppressWarnings("ResultOfMethodCallIgnored") private static void delete(Path path) throws IOException { if (Files.isRegularFile(path)) { Files.delete(path); return; } if (Files.isDirectory(path)) { try (Stream<Path> pathStream = Files.walk(path)) { pathStream .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } } } @Override public String toString() { return "ConvertResult{converted=" + converted + ", tmpPaths=" + tmpPaths + '}'; } }
586
4,526
#include <test.hpp> #include <vtzero/builder.hpp> #ifdef VTZERO_TEST_WITH_VARIANT # include <boost/variant.hpp> using variant_type = boost::variant<std::string, float, double, int64_t, uint64_t, bool>; #endif #include <map> #include <string> #include <unordered_map> TEST_CASE("property map") { vtzero::tile_builder tile; vtzero::layer_builder layer_points{tile, "points"}; { vtzero::point_feature_builder fbuilder{layer_points}; fbuilder.set_id(1); fbuilder.add_points(1); fbuilder.set_point(10, 10); fbuilder.add_property("foo", "bar"); fbuilder.add_property("x", "y"); fbuilder.add_property("abc", "def"); fbuilder.commit(); } std::string data = tile.serialize(); vtzero::vector_tile vt{data}; REQUIRE(vt.count_layers() == 1); auto layer = vt.next_layer(); REQUIRE(layer.valid()); REQUIRE(layer.num_features() == 1); const auto feature = layer.next_feature(); REQUIRE(feature.valid()); REQUIRE(feature.num_properties() == 3); #ifdef VTZERO_TEST_WITH_VARIANT SECTION("std::map") { using prop_map_type = std::map<std::string, variant_type>; auto map = vtzero::create_properties_map<prop_map_type>(feature); REQUIRE(map.size() == 3); REQUIRE(boost::get<std::string>(map["foo"]) == "bar"); REQUIRE(boost::get<std::string>(map["x"]) == "y"); REQUIRE(boost::get<std::string>(map["abc"]) == "def"); } SECTION("std::unordered_map") { using prop_map_type = std::unordered_map<std::string, variant_type>; auto map = vtzero::create_properties_map<prop_map_type>(feature); REQUIRE(map.size() == 3); REQUIRE(boost::get<std::string>(map["foo"]) == "bar"); REQUIRE(boost::get<std::string>(map["x"]) == "y"); REQUIRE(boost::get<std::string>(map["abc"]) == "def"); } #endif }
824
879
package org.zstack.sdk; import org.zstack.sdk.PolicyRouteRuleInventory; public class CreatePolicyRouteRuleResult { public PolicyRouteRuleInventory inventory; public void setInventory(PolicyRouteRuleInventory inventory) { this.inventory = inventory; } public PolicyRouteRuleInventory getInventory() { return this.inventory; } }
122
322
<reponame>axivion/rules_python<filename>examples/pip_parse/main.py import requests def version(): return requests.__version__
45
607
<gh_stars>100-1000 /* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013,2014 <NAME> <www.andybrown.me.uk> * Please see website for licensing terms. */ #pragma once namespace stm32plus { namespace net { /** * Class for the Texas Instruments DP83848C PHY. Contains additional * register definitions that describe the additional features of this PHY. */ class DP83848C : public PhyBase { public: /** * Custom registers for this PHY */ enum { PHY_STATUS = 0x10, //!< PHY_STATUS INTERRUPT_CONTROL = 0x11, //!< INTERRUPT_CONTROL INTERRUPT_STATUS = 0x12, //!< INTERRUPT_STATUS FALSE_CARRIER_SENSE_COUNTER = 0x14, //!< FALSE_CARRIER_SENSE_COUNTER RXER_COUNTER = 0x15, //!< RXER_COUNTER PCS_CONFIG_STATUS_100 = 0x16, //!< PCS_CONFIG_STATUS_100 RMII_AND_BYPASS = 0x17, //!< RMII_AND_BYPASS LED_DIRECT_CONTROL = 0x18, //!< LED_DIRECT_CONTROL PHY_CONTROL = 0x19, //!< PHY_CONTROL STATUS_CONTROL_10BASET = 0x1a, //!< STATUS_CONTROL_10BASET CD_TEST_BIST = 0x1b, //!< CD_TEST_BIST ENERGY_DETECT_CONTROL = 0x1d //!< ENERGY_DETECT_CONTROL }; /** * Interrupt bits */ enum { INTERRUPT_ENERGY_DETECT = 0x40, //!< INTERRUPT_ENERGY_DETECT INTERRUPT_LINK_STATUS_CHANGE = 0x20, //!< INTERRUPT_LINK_STATUS_CHANGE INTERRUPT_SPEED_STATUS_CHANGE = 0x10, //!< INTERRUPT_SPEED_STATUS_CHANGE INTERRUPT_DUPLEX_STATUS_CHANGE = 0x8, //!< INTERRUPT_DUPLEX_STATUS_CHANGE INTERRUPT_AUTO_NEGOTIATION_COMPLETE = 0x4, //!< INTERRUPT_AUTO_NEGOTIATION_COMPLETE INTERRUPT_FCC_HALF_FULL = 0x2, //!< INTERRUPT_FCC_HALF_FULL INTERRUPT_RXER_HALF_FULL = 0x1, //!< INTERRUPT_RXER_HALF_FULL INTERRUPT_ALL = 0x7f //!< INTERRUPT_ALL }; /** * Configuration parameters for the DP83848C */ struct Parameters : virtual PhyBase::Parameters { /** * Constructor: set defaults */ Parameters() { phy_resetDelay = 2; // wait 2ms after reset is asserted phy_speedStatusBit = 0x0002; // link speed bit in status word phy_duplexStatusBit = 0x0004; // full duplex bit in status word } }; bool phyEnableInterrupts(uint8_t interruptMask) const; bool phyDisableInterrupts(uint8_t interruptMask) const; bool phyIs100M(bool& is100) const; bool phyIsFullDuplex(bool& isFull) const; bool phyClearPendingInterrupts() const; bool phyGetPendingInterrupts(uint16_t& interrupts) const; // hard reset is supported through the PhyHardReset feature class void phyHardReset(GpioPinRef& pin) const; bool initialise(Parameters& params,NetworkUtilityObjects& netutils); bool startup(); }; /** * Initialise the PHY class * @param params The parameters class * @param netutils The network utilities * @return true if it worked */ inline bool DP83848C::initialise(Parameters& params,NetworkUtilityObjects& netutils) { return PhyBase::initialise(params,netutils); } /** * Startup * @return true if it worked */ inline bool DP83848C::startup() { return PhyBase::startup(); } /** * Check if we are linked at 100Mb/s * @param is100 true if we are at 100Mb/s * @return true if it worked */ inline bool DP83848C::phyIs100M(bool& is100) const { uint16_t value; if(!phyReadRegister(PHY_STATUS,value)) return false; is100=(value & 0x0002)==0; return true; } /** * Check if we are linked at full duplex * @param is100 true if we are at 100Mb/s * @return true if it worked */ inline bool DP83848C::phyIsFullDuplex(bool& isFull) const { uint16_t value; if(!phyReadRegister(PHY_STATUS,value)) return false; isFull=(value & 0x0004)!=0; return true; } /** * Clear pending interrupt flags. On the DP83848C reading the MISR register * clears the pending interrupt flags * @return true if it worked */ inline bool DP83848C::phyClearPendingInterrupts() const { uint16_t value; return phyReadRegister(INTERRUPT_STATUS,value); } /** * Read the pending interrupts register to determine which ones have fired * @param[out] interrupts The interrupt bitmask. Can be AND'ed with INTERRUPT_ values * @return true if it worked */ inline bool DP83848C::phyGetPendingInterrupts(uint16_t& interrupts) const { if(!phyReadRegister(INTERRUPT_STATUS,interrupts)) return false; // pending bits are in the upper byte, shift them down so that the INTERRUPT_* masks apply interrupts>>=8; return true; } /** * Enable interrupts to be received on the Observable interface. This function merges * the bits in interrupt mask into the register * @param interruptMask The interrupts to enable (INTERRUPT_*) * @return true if it worked */ inline bool DP83848C::phyEnableInterrupts(uint8_t interruptMask) const { return phySetRegisterBits(INTERRUPT_CONTROL,0x3) && // INT(pin-7) + INTEN phySetRegisterBits(INTERRUPT_STATUS,interruptMask); } /** * Disable interrupts to be received on the Observable interface. This function masks out * the bits in interrupt mask into the register * @param interruptMask The interrupts to enable (INTERRUPT_*) * @return true if it worked */ inline bool DP83848C::phyDisableInterrupts(uint8_t interruptMask) const { return phyClearRegisterBits(INTERRUPT_STATUS,interruptMask); } /** * Hard-reset the PHY by pulling the RESET pin low for 5ms. The datasheet * indicates that 1us is the minimum between stable power and rising reset so * we're playing safe. * @param pin */ inline void DP83848C::phyHardReset(GpioPinRef& pin) const { pin.reset(); MillisecondTimer::delay(5); pin.set(); } } }
3,071
2,757
/*++ Copyright (c) 2004, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. Module Name: DeviceIo.h Abstract: Device IO protocol as defined in the EFI 1.0 specification. Device IO is used to abstract hardware access to devices. It includes memory mapped IO, IO, PCI Config space, and DMA. --*/ #ifndef _DEVICE_IO_H_ #define _DEVICE_IO_H_ #define EFI_DEVICE_IO_PROTOCOL_GUID \ { \ 0xaf6ac311, 0x84c3, 0x11d2, {0x8e, 0x3c, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b} \ } EFI_FORWARD_DECLARATION (EFI_DEVICE_IO_PROTOCOL); typedef enum { IO_UINT8, IO_UINT16, IO_UINT32, IO_UINT64, MMIO_COPY_UINT8, MMIO_COPY_UINT16, MMIO_COPY_UINT32, MMIO_COPY_UINT64 } EFI_IO_WIDTH; typedef EFI_STATUS (EFIAPI *EFI_DEVICE_IO) ( IN EFI_DEVICE_IO_PROTOCOL * This, IN EFI_IO_WIDTH Width, IN UINT64 Address, IN UINTN Count, IN OUT VOID *Buffer ); typedef struct { EFI_DEVICE_IO Read; EFI_DEVICE_IO Write; } EFI_IO_ACCESS; typedef EFI_STATUS (EFIAPI *EFI_PCI_DEVICE_PATH) ( IN EFI_DEVICE_IO_PROTOCOL * This, IN UINT64 Address, IN OUT EFI_DEVICE_PATH_PROTOCOL **PciDevicePath ); typedef enum { EfiBusMasterRead, EfiBusMasterWrite, EfiBusMasterCommonBuffer } EFI_IO_OPERATION_TYPE; typedef EFI_STATUS (EFIAPI *EFI_IO_MAP) ( IN EFI_DEVICE_IO_PROTOCOL * This, IN EFI_IO_OPERATION_TYPE Operation, IN EFI_PHYSICAL_ADDRESS * HostAddress, IN OUT UINTN *NumberOfBytes, OUT EFI_PHYSICAL_ADDRESS * DeviceAddress, OUT VOID **Mapping ); typedef EFI_STATUS (EFIAPI *EFI_IO_UNMAP) ( IN EFI_DEVICE_IO_PROTOCOL * This, IN VOID *Mapping ); typedef EFI_STATUS (EFIAPI *EFI_IO_ALLOCATE_BUFFER) ( IN EFI_DEVICE_IO_PROTOCOL * This, IN EFI_ALLOCATE_TYPE Type, IN EFI_MEMORY_TYPE MemoryType, IN UINTN Pages, IN OUT EFI_PHYSICAL_ADDRESS * HostAddress ); typedef EFI_STATUS (EFIAPI *EFI_IO_FLUSH) ( IN EFI_DEVICE_IO_PROTOCOL * This ); typedef EFI_STATUS (EFIAPI *EFI_IO_FREE_BUFFER) ( IN EFI_DEVICE_IO_PROTOCOL * This, IN UINTN Pages, IN EFI_PHYSICAL_ADDRESS HostAddress ); struct _EFI_DEVICE_IO_PROTOCOL { EFI_IO_ACCESS Mem; EFI_IO_ACCESS Io; EFI_IO_ACCESS Pci; EFI_IO_MAP Map; EFI_PCI_DEVICE_PATH PciDevicePath; EFI_IO_UNMAP Unmap; EFI_IO_ALLOCATE_BUFFER AllocateBuffer; EFI_IO_FLUSH Flush; EFI_IO_FREE_BUFFER FreeBuffer; }; extern EFI_GUID gEfiDeviceIoProtocolGuid; #endif
2,049
530
from typing import Any, Iterable, List, Optional, Union from tartiflette.types.exceptions.tartiflette import CoercionError __all__ = ("Path", "CoercionResult", "coercion_error") class Path: """ Representations of the path traveled during the coercion. """ __slots__ = ("prev", "key") def __init__(self, prev: Optional["Path"], key: Union[str, int]) -> None: """ :param prev: the previous value of the path :param key: the current value of the path :type prev: Optional[Path] :type key: Union[str, int] """ self.prev = prev self.key = key def __repr__(self) -> str: """ Returns the representation of an Path instance. :return: the representation of an Path instance :rtype: str """ return "Path(prev=%r, key=%r)" % (self.prev, self.key) def __str__(self) -> str: """ Returns a human-readable representation of the full path. :return: a human-readable representation of the full path :rtype: str """ path_str = "" current_path = self while current_path: path_str = ( f".{current_path.key}" if isinstance(current_path.key, str) else f"[{current_path.key}]" ) + path_str current_path = current_path.prev return f"value{path_str}" if path_str else "" def as_list(self) -> List[str]: """ Computes and returns the path as a list. :return: the full path as a list :rtype: List[str] """ path = [] current_path = self while current_path: path.append(current_path.key) current_path = current_path.prev return path[::-1] class CoercionResult: """ Represents the result of a coercion. """ __slots__ = ("value", "errors") def __init__( self, value: Optional[Any] = None, errors: Optional[List["TartifletteError"]] = None, ) -> None: """ :param value: the computed value :param errors: the errors encountered :type value: Optional[Any] :type errors: Optional[List[TartifletteError]] """ self.value = value if not errors else None self.errors = errors def __repr__(self) -> str: """ Returns the representation of a CoercionResult instance. :return: the representation of a CoercionResult instance :rtype: str """ return "CoercionResult(value=%r, errors=%r)" % ( self.value, self.errors, ) def __iter__(self) -> Iterable: """ Returns an iterator over the computed value and errors encountered to allow unpacking the value like a tuple. :return: an iterator over the computed value and errors encountered :rtype: Iterable """ yield from [self.value, self.errors] def coercion_error( message: str, node: Optional["Node"] = None, path: Optional["Path"] = None, sub_message: Optional[str] = None, original_error: Optional[Exception] = None, ) -> "CoercionError": """ Returns a CoercionError whose message is formatted according to the message, path, and sub-message filled in. :param message: the message of the error :param node: the AST node linked to the error :param path: the path where the error occurred :param sub_message: the sub-message to append :param original_error: the original raw exception :type message: str :type node: Optional[Node] :type path: Optional[Path] :type sub_message: Optional[str] :type original_error: Optional[Exception] :return: a CoercionError :rtype: CoercionError """ return CoercionError( message + (" at " + str(path) if path else "") + ("; " + sub_message if sub_message else "."), locations=[node.location] if node else None, original_error=original_error, )
1,704
373
/** @file Copyright 2020 NXP SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef SOC_H__ #define SOC_H__ #include <Chassis.h> /** Soc Memory Map **/ #define LS1046A_DRAM0_PHYS_ADDRESS (BASE_2GB) #define LS1046A_DRAM0_SIZE (SIZE_2GB) #define LS1046A_DRAM1_PHYS_ADDRESS (BASE_32GB + BASE_2GB) #define LS1046A_DRAM1_SIZE (SIZE_32GB - SIZE_2GB) // 30 GB #define LS1046A_CCSR_PHYS_ADDRESS (BASE_16MB) #define LS1046A_CCSR_SIZE (SIZE_256MB - SIZE_16MB) // 240MB #define LS1046A_QSPI0_PHYS_ADDRESS (BASE_1GB) #define LS1046A_QSPI0_SIZE (SIZE_512MB) #define LS1046A_DCFG_ADDRESS NXP_LAYERSCAPE_CHASSIS2_DCFG_ADDRESS #define LS1046A_SCFG_ADDRESS NXP_LAYERSCAPE_CHASSIS2_SCFG_ADDRESS /** Reset Control Word (RCW) Bits RCWSR contains the Reset Configuration Word (RCW) information written with values read from flash memory by the device at power-on reset and read-only upon exiting reset. RCW bits in RCWSR registers are mirror of bit position in Little Endian (LE) RCW Bits | in RCWSR | (MSBit 0)| 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------------------------------------------------------------------------------------------ LE | 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 (LSBit 0)| Moreover the RCW bits are to be interpreted in below fasion Bit(s) | Field Name | Description | Notes/comments ---------------------------------------------------------------------- 2-6 | SYS_PLL_RAT | System PLL Multiplier/Ratio | This field selects the platform | | | clock:SYSCLK ratio. | | | 0_0011 3:1 | | | 0_0100 4:1 | | | 0_1101 13:1 | | | 0_1111 15:1 | | | 1_0000 16:1 which is why the RCW bits in RCWSR registers are parsed this way **/ #define SYS_PLL_RAT(x) (((x) >> 25) & 0x1f) // Bits 2-6 typedef NXP_LAYERSCAPE_CHASSIS2_DEVICE_CONFIG LS1046A_DEVICE_CONFIG; typedef NXP_LAYERSCAPE_CHASSIS2_SUPPLEMENTAL_CONFIG LS1046A_SUPPLEMENTAL_CONFIG; #endif // SOC_H__
1,221
860
<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.codehaus.groovy.transform.sc.transformers; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.classgen.asm.sc.StaticTypesTypeChooser; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import org.codehaus.groovy.syntax.Types; import org.codehaus.groovy.transform.sc.StaticCompilationVisitor; import org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor; import java.util.*; /** * Some expressions use symbols as aliases to method calls (<<, +=, ...). In static compilation, * if such a method call is found, we transform the original binary expression into a method * call expression so that the call gets statically compiled. * * @author <NAME> */ public class StaticCompilationTransformer extends ClassCodeExpressionTransformer { protected static final ClassNode BYTECODE_ADAPTER_CLASS = ClassHelper.make(ScriptBytecodeAdapter.class); protected static final Map<Integer, MethodNode> BYTECODE_BINARY_ADAPTERS = Collections.unmodifiableMap(new HashMap<Integer, MethodNode>() {{ put(Types.COMPARE_EQUAL, BYTECODE_ADAPTER_CLASS.getMethods("compareEqual").get(0)); put(Types.COMPARE_GREATER_THAN, BYTECODE_ADAPTER_CLASS.getMethods("compareGreaterThan").get(0)); put(Types.COMPARE_GREATER_THAN_EQUAL, BYTECODE_ADAPTER_CLASS.getMethods("compareGreaterThanEqual").get(0)); put(Types.COMPARE_LESS_THAN, BYTECODE_ADAPTER_CLASS.getMethods("compareLessThan").get(0)); put(Types.COMPARE_LESS_THAN_EQUAL, BYTECODE_ADAPTER_CLASS.getMethods("compareLessThanEqual").get(0)); put(Types.COMPARE_NOT_EQUAL, BYTECODE_ADAPTER_CLASS.getMethods("compareNotEqual").get(0)); put(Types.COMPARE_TO, BYTECODE_ADAPTER_CLASS.getMethods("compareTo").get(0)); }}); private ClassNode classNode; private final SourceUnit unit; private final StaticTypesTypeChooser typeChooser = new StaticTypesTypeChooser(); private final StaticTypeCheckingVisitor staticCompilationVisitor; // various helpers in order to avoid a potential very big class private final StaticMethodCallExpressionTransformer staticMethodCallExpressionTransformer = new StaticMethodCallExpressionTransformer(this); private final ConstructorCallTransformer constructorCallTransformer = new ConstructorCallTransformer(this); private final MethodCallExpressionTransformer methodCallExpressionTransformer = new MethodCallExpressionTransformer(this); private final BinaryExpressionTransformer binaryExpressionTransformer = new BinaryExpressionTransformer(this); private final ClosureExpressionTransformer closureExpressionTransformer = new ClosureExpressionTransformer(this); private final BooleanExpressionTransformer booleanExpressionTransformer = new BooleanExpressionTransformer(this); private final VariableExpressionTransformer variableExpressionTransformer = new VariableExpressionTransformer(); private final RangeExpressionTransformer rangeExpressionTransformer = new RangeExpressionTransformer(this); private final ListExpressionTransformer listExpressionTransformer = new ListExpressionTransformer(this); private final CastExpressionOptimizer castExpressionTransformer = new CastExpressionOptimizer(this); public StaticCompilationTransformer(final SourceUnit unit, final StaticTypeCheckingVisitor visitor) { this.unit = unit; this.staticCompilationVisitor = visitor; } @Override protected SourceUnit getSourceUnit() { return unit; } public StaticTypesTypeChooser getTypeChooser() { return typeChooser; } public ClassNode getClassNode() { return classNode; } @Override public void visitClassCodeContainer(final Statement code) { super.visitClassCodeContainer(code); } @Override public Expression transform(Expression expr) { if (expr instanceof StaticMethodCallExpression) { return staticMethodCallExpressionTransformer.transformStaticMethodCallExpression((StaticMethodCallExpression) expr); } if (expr instanceof BinaryExpression) { return binaryExpressionTransformer.transformBinaryExpression((BinaryExpression)expr); } if (expr instanceof MethodCallExpression) { return methodCallExpressionTransformer.transformMethodCallExpression((MethodCallExpression) expr); } if (expr instanceof ClosureExpression) { return closureExpressionTransformer.transformClosureExpression((ClosureExpression) expr); } if (expr instanceof ConstructorCallExpression) { return constructorCallTransformer.transformConstructorCall((ConstructorCallExpression) expr); } if (expr instanceof BooleanExpression) { return booleanExpressionTransformer.transformBooleanExpression((BooleanExpression)expr); } if (expr instanceof VariableExpression) { return variableExpressionTransformer.transformVariableExpression((VariableExpression)expr); } if (expr instanceof RangeExpression) { return rangeExpressionTransformer.transformRangeExpression(((RangeExpression)expr)); } if (expr instanceof ListExpression) { return listExpressionTransformer.transformListExpression((ListExpression) expr); } if (expr instanceof CastExpression) { return castExpressionTransformer.transformCastExpression(((CastExpression)expr)); } return super.transform(expr); } /** * Called by helpers when super.transform() is needed. */ final Expression superTransform(Expression expr) { return super.transform(expr); } @Override public void visitClass(final ClassNode node) { ClassNode prec = classNode; classNode = node; super.visitClass(node); Iterator<InnerClassNode> innerClasses = classNode.getInnerClasses(); while (innerClasses.hasNext()) { InnerClassNode innerClassNode = innerClasses.next(); visitClass(innerClassNode); } classNode = prec; } @Override protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) { if (staticCompilationVisitor.isSkipMode(node)) { // method has already been visited by a static type checking visitor return; } super.visitConstructorOrMethod(node, isConstructor); } }
2,449
2,180
package com.xiaojukeji.kafka.manager.service.service.gateway.impl; import com.xiaojukeji.kafka.manager.dao.gateway.KafkaAclDao; import com.xiaojukeji.kafka.manager.dao.gateway.KafkaUserDao; import com.xiaojukeji.kafka.manager.common.entity.pojo.gateway.KafkaAclDO; import com.xiaojukeji.kafka.manager.common.entity.pojo.gateway.KafkaUserDO; import com.xiaojukeji.kafka.manager.service.service.gateway.SecurityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; /** * @author zengqiao * @date 20/7/27 */ @Service("securityService") public class SecurityServiceImpl implements SecurityService { @Autowired private KafkaUserDao kafkaUserDao; @Autowired private KafkaAclDao kafkaAclDao; @Override public List<KafkaUserDO> getKafkaUsers(Long startTime, Long endTime) { return kafkaUserDao.getKafkaUsers(new Date(startTime), new Date(endTime)); } @Override public List<KafkaAclDO> getKafkaAcls(Long clusterId, Long startTime, Long endTime) { return kafkaAclDao.getKafkaAcls(clusterId, new Date(startTime), new Date(endTime)); } }
469
521
<reponame>zai1208/fbc /* rmdir function */ #include "fb.h" #ifdef HOST_MINGW #include <direct.h> #else #include <unistd.h> #endif /*:::::*/ FBCALL int fb_RmDir( FBSTRING *path ) { int res; #ifdef HOST_MINGW res = _rmdir( path->data ); #else res = rmdir( path->data ); #endif /* del if temp */ fb_hStrDelTemp( path ); return res; }
160
412
<reponame>Mechachleopteryx/graphbrain<gh_stars>100-1000 from html import escape from IPython.core.display import display from IPython.core.display import HTML from graphbrain import hedge TYPE_COLORS = {'C': '#268bd2', 'M': '#dc322f', 'B': '#859900', 'P': '#cb4b16', 'T': '#d33682', 'J': '#b58900', 'R': '#eee8d5', 'S': '#6c71c4'} def _edge2html_show(edge, style='indented', indent=False, close=True, close_html=''): ret_close_html = '' if indent: main_tag = 'div' margin = 'margin-left:20px;' else: main_tag = 'span' margin = '' et = edge.type()[0] if et == 'R': color = '#303030' else: color = TYPE_COLORS[edge.type()[0]] color_html = 'color:{}'.format(color) if edge.is_atom(): html = '<span style="{}">{}</span>'.format( color_html, escape(str(edge.root()))) if len(edge.parts()) > 1: escaped_codes = '/'.join(edge.parts()[1:]) escaped_codes = escape(escaped_codes).strip() html = '{}<span style="color:#000000;font-weight:lighter">/{}'\ '</span>'.format(html, escaped_codes) else: et = edge.type()[0] arity = len(edge) contains_edges = any(not child.is_atom() for child in edge) color_html = 'color:{}'.format(color) # render opening symbol html = '<span style="font-weight:bold">(</span>' close_html = '</{}>'.format(main_tag) # render edge children for i in range(arity): child = edge[i] # first edge (connector)? if i == 0: child_indent = False sep = '' # not connector else: # indent depending on style if style == 'indented': # edges with only two items are rendered in one line child_indent = arity > 2 if child_indent and child.is_atom() and not contains_edges: child_indent = False elif style == 'oneline': child_indent = False sep = ' ' if child.is_atom(): child_html, _ = _edge2html_show(child, style=style, indent=child_indent) else: # Do not render closing html of children that are the last # edge in a hyperedge. Instead, let some higher-level edge # render it to avoid ugly multi-line staircases when closing # a sequence of edges. child_close = i < arity - 1 child_html, child_cl_html = _edge2html_show( child, style=style, indent=child_indent, close=child_close) # accumulate close_html of child close_html = '{}{}'.format(child_cl_html, close_html) html = '{}{}{}'.format(html, sep, child_html) # if closing html should not be rendered at the end of this edge # representation, then return it to the parent if not close: ret_close_html = close_html close_html = '' # render close symbol html = '{}<span style="{}">'.format(html, color_html) html = '{}<span style="font-weight:bold">)</span></span>'.format(html) # render edge html = '<{} style="{}{}">{}{}'.format( main_tag, margin, color_html, html, close_html) return html, ret_close_html def show(edge, style='indented'): """Displays a representation of the edge in the notebook. Keyword arguments: style -- render style ('indented', 'line') (default: 'indented') """ edge = hedge(edge) html = _edge2html_show(edge, style=style)[0] display(HTML(html)) def _edge2html_vblocks(edge): tcolor = TYPE_COLORS[edge.type()[0]] if edge.is_atom(): html_root = '<span style="color:#fdf6e3;font-weight:bold">{}'\ '</span>'.format(edge.root()) parts = '/'.join(edge.parts()[1:]) html_parts = '<span style="color:#eee8d5;font-weight:lighter">/{}'\ '</span>'.format(parts) html = '<div style="padding:5px;background-color:{};'\ 'border:2px solid #fdf6e3;border-radius:10px">{}{}'\ '</div>'.format(tcolor, html_root, html_parts) return html elif len(edge) == 2 or all(subedge.is_atom() for subedge in edge): conn_html = _edge2html_vblocks(edge[0]) arg_htmls = ['<div style="display: table-cell;vertical-align: middle"' '>{}</div>'.format(_edge2html_vblocks(arg)) for arg in edge[1:]] html = '<div style="display:table;border:2px solid #fdf6e3;'\ 'background-color:{};border-radius:10px;padding:3px">'\ '<div style="display:table-row">'\ '<div style="display: table-cell; vertical-align: middle;'\ 'background-color:{};padding-left:5px">{}</div>'\ '<div style="display: table-cell; vertical-align: middle;'\ 'background-color:{};padding:5px">'\ '<div style="display:table-row">{}</div></div>'\ '</div></div>'.format( tcolor, tcolor, conn_html, tcolor, '<div style="width:5px"></div>'.join(arg_htmls)) return html else: conn_html = _edge2html_vblocks(edge[0]) arg_htmls = ['<div>{}</div>'.format(_edge2html_vblocks(arg)) for arg in edge[1:]] html = '<div style="display:table;border:2px solid #fdf6e3;'\ 'background-color:{};border-radius:10px;padding:3px">'\ '<div style="display:table-row">'\ '<div style="display: table-cell; vertical-align: top;'\ 'background-color:{};padding:5px">{}</div>'\ '<div style="display: table-cell; vertical-align: top;'\ 'background-color:{};padding:5px">'\ '<div style="display:table-row">{}</div></div>'\ '</div></div>'.format( tcolor, tcolor, conn_html, tcolor, '<div style="height:5px"></div>'.join(arg_htmls)) return html def vblocks(edge, subtypes=False, argroles=True, namespaces=False): edge = hedge(edge) sedge = edge.simplify(subtypes=subtypes, argroles=argroles, namespaces=namespaces) html = _edge2html_vblocks(sedge) html = '<div style="background-color:#fcfcfc; padding:50px">{}'\ '</div>'.format(html) display(HTML(html)) def _edge2html_blocks(edge): tcolor = TYPE_COLORS[edge.type()[0]] if edge.is_atom(): html_root = '<span style="color:#fdf6e3;font-weight:bold">{}'\ '</span>'.format(edge.root()) parts = '/'.join(edge.parts()[1:]) html_parts = '<span style="color:#eee8d5;font-weight:lighter">/{}'\ '</span>'.format(parts) html = '<div style="padding:5px;background-color:{};'\ 'border:2px solid #fdf6e3; border-radius:10px;'\ 'text-align:center">{}{}</div>'.format( tcolor, html_root, html_parts) return html elif len(edge) > 2: conn_html = _edge2html_blocks(edge[0]) arg_htmls = ['<div style="display: table-cell;vertical-align: middle">' '{}</div>'.format(_edge2html_blocks(arg)) for arg in edge[1:]] html = '<div style="display:table;border:2px solid #fdf6e3;'\ 'background-color:{};border-radius:10px;padding:3px">'\ '<div style="display:table-row">'\ '<div style="display: table-cell; vertical-align: middle;'\ 'background-color:{};padding-left:5px">{}</div>'\ '<div style="display: table-cell; vertical-align: middle;'\ 'background-color:{};padding:5px">'\ '<div style="display:table-row">{}</div></div>'\ '</div></div>'.format( tcolor, tcolor, conn_html, tcolor, '<div style="width:5px"></div>'.join(arg_htmls)) return html else: conn_html = _edge2html_blocks(edge[0]) arg_htmls = ['<div style="display: table-row">{}</div>'.format( _edge2html_blocks(arg)) for arg in edge[1:]] html = '<div style="display:table;border:2px solid #fdf6e3;'\ 'background-color:{};border-radius:10px;padding:8px">'\ '<div style="display:table-row">'\ '<div style="display: table-row; vertical-align: top;'\ 'background-color:{};padding:5px">{}</div>'\ '<div style="display: table-row; height:8px"></div>'\ '<div style="display: table-row; vertical-align: top;'\ 'background-color:{};padding:5px">'\ '<div style="display:table">{}</div></div>'\ '</div></div>'.format( tcolor, tcolor, conn_html, tcolor, '<div style="height:5px"></div>'.join(arg_htmls)) return html def blocks(edge, subtypes=False, argroles=True, namespaces=False): edge = hedge(edge) sedge = edge.simplify(subtypes=subtypes, argroles=argroles, namespaces=namespaces) html = _edge2html_blocks(sedge) html = '<div style="background-color:#fcfcfc; padding:50px">{}'\ '</div>'.format(html) display(HTML(html))
5,270
611
<gh_stars>100-1000 // ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // ---------------------------------------------------------------------------- package com.embedsample.appownsdata.services; import java.net.MalformedURLException; import java.util.Collections; import java.util.concurrent.ExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.embedsample.appownsdata.config.Config; import com.microsoft.aad.msal4j.ClientCredentialFactory; import com.microsoft.aad.msal4j.ClientCredentialParameters; import com.microsoft.aad.msal4j.ConfidentialClientApplication; import com.microsoft.aad.msal4j.IAuthenticationResult; import com.microsoft.aad.msal4j.PublicClientApplication; import com.microsoft.aad.msal4j.UserNamePasswordParameters; /** * Service to authenticate using MSAL */ public class AzureADService { static final Logger logger = LoggerFactory.getLogger(AzureADService.class); // Prevent instantiation private AzureADService () { throw new IllegalStateException("Authentication service class"); } /** * Acquires access token for the based on config values * @return AccessToken */ public static String getAccessToken() throws MalformedURLException, InterruptedException, ExecutionException { if (Config.authenticationType.equalsIgnoreCase("MasterUser")) { return getAccessTokenUsingMasterUser(Config.clientId, Config.pbiUsername, Config.pbiPassword); } else if (Config.authenticationType.equalsIgnoreCase("ServicePrincipal")) { // Check if Tenant Id is empty if (Config.tenantId.isEmpty()) { throw new RuntimeException("Tenant Id is empty"); } return getAccessTokenUsingServicePrincipal(Config.clientId, Config.tenantId, Config.appSecret); } else { // Authentication Type is none of the above throw new RuntimeException("Invalid authentication type: " + Config.authenticationType); } } /** * Acquires access token for the given clientId and app secret * @param clientId * @param tenantId * @param appSecret * @return AccessToken */ private static String getAccessTokenUsingServicePrincipal(String clientId, String tenantId, String appSecret) throws MalformedURLException, InterruptedException, ExecutionException { // Build Confidential Client App ConfidentialClientApplication app = ConfidentialClientApplication.builder( clientId, ClientCredentialFactory.createFromSecret(appSecret)) .authority(Config.authorityUrl + tenantId) .build(); ClientCredentialParameters clientCreds = ClientCredentialParameters.builder( Collections.singleton(Config.scopeUrl)) .build(); // Acquire new AAD token IAuthenticationResult result = app.acquireToken(clientCreds).get(); // Return access token if token is acquired successfully if (result != null && result.accessToken() != null && !result.accessToken().isEmpty()) { if (Config.DEBUG) { logger.info("Authenticated with Service Principal mode"); } return result.accessToken(); } else { logger.error("Failed to authenticate with Service Principal mode"); return null; } } /** * Acquires access token for the given clientId and user credentials * @param clientId * @param username * @param password * @return AccessToken */ private static String getAccessTokenUsingMasterUser(String clientId, String username, String password) throws MalformedURLException, InterruptedException, ExecutionException { // Build Public Client App PublicClientApplication app = PublicClientApplication.builder(clientId) .authority(Config.authorityUrl + "organizations") // Use authorityUrl+tenantId if this doesn't work .build(); UserNamePasswordParameters userCreds = UserNamePasswordParameters.builder( Collections.singleton(Config.scopeUrl), username, password.toCharArray()).build(); // Acquire new AAD token IAuthenticationResult result = app.acquireToken(userCreds).get(); // Return access token if token is acquired successfully if (result != null && result.accessToken() != null && !result.accessToken().isEmpty()) { if (Config.DEBUG) { logger.info("Authenticated with MasterUser mode"); } return result.accessToken(); } else { logger.error("Failed to authenticate with MasterUser mode"); return null; } } }
1,340
1,144
/* * #%L * de.metas.cucumber * %% * Copyright (C) 2021 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.cucumber.stepdefs.pricing; import de.metas.cucumber.stepdefs.DataTableUtil; import de.metas.cucumber.stepdefs.StepDefConstants; import de.metas.cucumber.stepdefs.StepDefData; import de.metas.currency.CurrencyCode; import de.metas.currency.CurrencyRepository; import de.metas.location.ICountryDAO; import de.metas.money.CurrencyId; import de.metas.organization.OrgId; import de.metas.tax.api.ITaxBL; import de.metas.tax.api.TaxCategoryId; import de.metas.util.Services; import io.cucumber.datatable.DataTable; import io.cucumber.java.en.And; import lombok.NonNull; import org.adempiere.model.InterfaceWrapperHelper; import org.compiere.model.I_C_Country; import org.compiere.model.I_C_TaxCategory; import org.compiere.model.I_M_PriceList; import org.compiere.model.I_M_PriceList_Version; import org.compiere.model.I_M_PricingSystem; import org.compiere.model.I_M_Product; import org.compiere.model.I_M_ProductPrice; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.List; import java.util.Map; import java.util.Optional; import static org.adempiere.model.InterfaceWrapperHelper.saveRecord; import static org.assertj.core.api.Assertions.assertThat; import static org.compiere.model.I_C_Order.COLUMNNAME_M_PriceList_ID; import static org.compiere.model.I_C_Order.COLUMNNAME_M_PricingSystem_ID; public class M_PriceList_StepDef { private final OrgId defaultOrgId = StepDefConstants.ORG_ID; private final CurrencyRepository currencyRepository; private final StepDefData<I_M_Product> productTable; private final StepDefData<I_M_PricingSystem> pricingSystemTable; private final StepDefData<I_M_PriceList> priceListTable; private final StepDefData<I_M_PriceList_Version> priceListVersionTable; private final StepDefData<I_M_ProductPrice> productPriceTable; private final ITaxBL taxBL = Services.get(ITaxBL.class); public M_PriceList_StepDef( @NonNull final CurrencyRepository currencyRepository, @NonNull final StepDefData<I_M_Product> productTable, @NonNull final StepDefData<I_M_PricingSystem> pricingSystemTable, @NonNull final StepDefData<I_M_PriceList> priceListTable, @NonNull final StepDefData<I_M_PriceList_Version> priceListVersionTable, @NonNull final StepDefData<I_M_ProductPrice> productPriceTable) { this.currencyRepository = currencyRepository; this.productTable = productTable; this.pricingSystemTable = pricingSystemTable; this.priceListTable = priceListTable; this.priceListVersionTable = priceListVersionTable; this.productPriceTable = productPriceTable; } @And("metasfresh contains M_PricingSystems") public void add_M_PricingSystem(@NonNull final DataTable dataTable) { final Map<String, String> dataTableRow = dataTable.asMaps().get(0); createM_PricingSystem(dataTableRow); } @And("metasfresh contains M_PriceLists") public void add_M_PriceList(@NonNull final DataTable dataTable) { final List<Map<String, String>> row = dataTable.asMaps(); for (final Map<String, String> dataTableRow : row) { createM_PriceList(dataTableRow); } } private void createM_PricingSystem(@NonNull final Map<String, String> row) { final String name = DataTableUtil.extractStringForColumnName(row, "Name"); final String value = DataTableUtil.extractStringForColumnName(row, "Value"); final String description = DataTableUtil.extractStringOrNullForColumnName(row, "OPT.Description"); final boolean isActive = DataTableUtil.extractBooleanForColumnNameOr(row, "OPT.IsActive", true); final I_M_PricingSystem m_pricingSystem = InterfaceWrapperHelper.newInstance(I_M_PricingSystem.class); m_pricingSystem.setAD_Org_ID(defaultOrgId.getRepoId()); m_pricingSystem.setName(name); m_pricingSystem.setValue(value); m_pricingSystem.setIsActive(isActive); m_pricingSystem.setDescription(description); saveRecord(m_pricingSystem); final String recordIdentifier = DataTableUtil.extractRecordIdentifier(row, I_M_PricingSystem.Table_Name); pricingSystemTable.put(recordIdentifier, m_pricingSystem); } private void createM_PriceList(@NonNull final Map<String, String> row) { final String pricingSystemIdentifier = DataTableUtil.extractStringForColumnName(row, COLUMNNAME_M_PricingSystem_ID + "." + StepDefConstants.TABLECOLUMN_IDENTIFIER); final String countryCode = DataTableUtil.extractStringOrNullForColumnName(row, "OPT.C_Country.CountryCode"); final String isoCode = DataTableUtil.extractStringForColumnName(row, "C_Currency.ISO_Code"); final String name = DataTableUtil.extractStringForColumnName(row, "Name"); final String description = DataTableUtil.extractStringOrNullForColumnName(row, "OPT.Description"); final boolean soTrx = DataTableUtil.extractBooleanForColumnName(row, "SOTrx"); final boolean isTaxIncluded = DataTableUtil.extractBooleanForColumnName(row, "IsTaxIncluded"); final String pricePrecision = DataTableUtil.extractStringForColumnName(row, "PricePrecision"); final boolean isActive = DataTableUtil.extractBooleanForColumnNameOr(row, "OPT.IsActive", true); final CurrencyId currencyId = getCurrencyIdByCurrencyISO(isoCode); final I_M_PriceList m_priceList = InterfaceWrapperHelper.newInstance(I_M_PriceList.class); m_priceList.setAD_Org_ID(defaultOrgId.getRepoId()); m_priceList.setM_PricingSystem_ID(pricingSystemTable.get(pricingSystemIdentifier).getM_PricingSystem_ID()); m_priceList.setC_Currency_ID(currencyId.getRepoId()); m_priceList.setName(name); m_priceList.setIsTaxIncluded(isTaxIncluded); m_priceList.setPricePrecision(Integer.parseInt(pricePrecision)); m_priceList.setIsActive(isActive); m_priceList.setIsSOPriceList(soTrx); if (countryCode != null) { final I_C_Country countryPO = Services.get(ICountryDAO.class).retrieveCountryByCountryCode(countryCode); m_priceList.setC_Country_ID(countryPO.getC_Country_ID()); } if (description != null) { m_priceList.setDescription(description); } saveRecord(m_priceList); final String recordIdentifier = DataTableUtil.extractRecordIdentifier(row, I_M_PriceList.Table_Name); priceListTable.put(recordIdentifier, m_priceList); } @NonNull private CurrencyId getCurrencyIdByCurrencyISO(@NonNull final String currencyISO) { final CurrencyCode convertedToCurrencyCode = CurrencyCode.ofThreeLetterCode(currencyISO); return currencyRepository.getCurrencyIdByCurrencyCode(convertedToCurrencyCode); } @And("metasfresh contains M_PriceList_Versions") public void add_M_PriceListVersion(@NonNull final DataTable dataTable) { final List<Map<String, String>> row = dataTable.asMaps(); for (final Map<String, String> dataTableRow : row) { createM_PriceList_Version(dataTableRow); } } private void createM_PriceList_Version(@NonNull final Map<String, String> row) { final String priceListIdentifier = DataTableUtil.extractStringForColumnName(row, COLUMNNAME_M_PriceList_ID + "." + StepDefConstants.TABLECOLUMN_IDENTIFIER); final Timestamp validFrom = DataTableUtil.extractDateTimestampForColumnName(row, I_M_PriceList_Version.COLUMNNAME_ValidFrom); final String name = DataTableUtil.extractStringForColumnName(row, I_M_PriceList_Version.COLUMNNAME_Name); final String description = DataTableUtil.extractStringOrNullForColumnName(row, "OPT." + I_M_PriceList_Version.COLUMNNAME_Description); final I_M_PriceList_Version m_priceList_Version = InterfaceWrapperHelper.newInstance(I_M_PriceList_Version.class); m_priceList_Version.setAD_Org_ID(StepDefConstants.ORG_ID.getRepoId()); m_priceList_Version.setM_PriceList_ID(priceListTable.get(priceListIdentifier).getM_PriceList_ID()); m_priceList_Version.setName(name); m_priceList_Version.setDescription(description); m_priceList_Version.setValidFrom(validFrom); saveRecord(m_priceList_Version); final String recordIdentifier = DataTableUtil.extractRecordIdentifier(row, I_M_PriceList_Version.Table_Name); priceListVersionTable.put(recordIdentifier, m_priceList_Version); } @And("metasfresh contains M_ProductPrices") public void add_M_ProductPrice(@NonNull final DataTable dataTable) { final List<Map<String, String>> tableRows = dataTable.asMaps(); for (final Map<String, String> tableRow : tableRows) { createM_ProductPrice(tableRow); } } private void createM_ProductPrice(@NonNull final Map<String, String> tableRow) { final String productIdentifier = DataTableUtil.extractStringForColumnName(tableRow, I_M_ProductPrice.COLUMNNAME_M_Product_ID + "." + StepDefConstants.TABLECOLUMN_IDENTIFIER); final I_M_Product product = productTable.get(productIdentifier); final BigDecimal priceStd = DataTableUtil.extractBigDecimalForColumnName(tableRow, I_M_ProductPrice.COLUMNNAME_PriceStd); final String taxCategoryInternalName = DataTableUtil.extractStringForColumnName(tableRow, I_M_ProductPrice.COLUMNNAME_C_TaxCategory_ID + "." + I_C_TaxCategory.COLUMNNAME_InternalName); final Optional<TaxCategoryId> taxCategoryId = taxBL.getTaxCategoryIdByInternalName(taxCategoryInternalName); assertThat(taxCategoryId).as("Missing taxCategory for internalName=%s", taxCategoryInternalName).isPresent(); final String plvIdentifier = DataTableUtil.extractStringForColumnName(tableRow, I_M_ProductPrice.COLUMNNAME_M_PriceList_Version_ID + "." + StepDefConstants.TABLECOLUMN_IDENTIFIER); final I_M_ProductPrice productPrice = InterfaceWrapperHelper.newInstance(I_M_ProductPrice.class); productPrice.setM_PriceList_Version_ID(priceListVersionTable.get(plvIdentifier).getM_PriceList_Version_ID()); productPrice.setM_Product_ID(product.getM_Product_ID()); productPrice.setC_UOM_ID(product.getC_UOM_ID()); productPrice.setPriceStd(priceStd); productPrice.setC_TaxCategory_ID(taxCategoryId.get().getRepoId()); saveRecord(productPrice); final String recordIdentifier = DataTableUtil.extractRecordIdentifier(tableRow, I_M_ProductPrice.Table_Name); productPriceTable.put(recordIdentifier, productPrice); } }
3,625
16,870
/* * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Run this file with the `java_sample.sh` script. import MyGame.Sample.Color; import MyGame.Sample.Equipment; import MyGame.Sample.Monster; import MyGame.Sample.Vec3; import MyGame.Sample.Weapon; import com.google.flatbuffers.FlatBufferBuilder; import java.nio.ByteBuffer; class SampleBinary { // Example how to use FlatBuffers to create and read binary buffers. public static void main(String[] args) { FlatBufferBuilder builder = new FlatBufferBuilder(0); // Create some weapons for our Monster ('Sword' and 'Axe'). int weaponOneName = builder.createString("Sword"); short weaponOneDamage = 3; int weaponTwoName = builder.createString("Axe"); short weaponTwoDamage = 5; // Use the `createWeapon()` helper function to create the weapons, since we set every field. int[] weaps = new int[2]; weaps[0] = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage); weaps[1] = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage); // Serialize the FlatBuffer data. int name = builder.createString("Orc"); byte[] treasure = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int inv = Monster.createInventoryVector(builder, treasure); int weapons = Monster.createWeaponsVector(builder, weaps); int pos = Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f); Monster.startMonster(builder); Monster.addPos(builder, pos); Monster.addName(builder, name); Monster.addColor(builder, Color.Red); Monster.addHp(builder, (short)300); Monster.addInventory(builder, inv); Monster.addWeapons(builder, weapons); Monster.addEquippedType(builder, Equipment.Weapon); Monster.addEquipped(builder, weaps[1]); int orc = Monster.endMonster(builder); builder.finish(orc); // You could also call `Monster.finishMonsterBuffer(builder, orc);`. // We now have a FlatBuffer that can be stored on disk or sent over a network. // ...Code to store to disk or send over a network goes here... // Instead, we are going to access it right away, as if we just received it. ByteBuffer buf = builder.dataBuffer(); // Get access to the root: Monster monster = Monster.getRootAsMonster(buf); // Note: We did not set the `mana` field explicitly, so we get back the default value. assert monster.mana() == (short)150; assert monster.hp() == (short)300; assert monster.name().equals("Orc"); assert monster.color() == Color.Red; assert monster.pos().x() == 1.0f; assert monster.pos().y() == 2.0f; assert monster.pos().z() == 3.0f; // Get and test the `inventory` FlatBuffer `vector`. for (int i = 0; i < monster.inventoryLength(); i++) { assert monster.inventory(i) == (byte)i; } // Get and test the `weapons` FlatBuffer `vector` of `table`s. String[] expectedWeaponNames = {"Sword", "Axe"}; int[] expectedWeaponDamages = {3, 5}; for (int i = 0; i < monster.weaponsLength(); i++) { assert monster.weapons(i).name().equals(expectedWeaponNames[i]); assert monster.weapons(i).damage() == expectedWeaponDamages[i]; } Weapon.Vector weaponsVector = monster.weaponsVector(); for (int i = 0; i < weaponsVector.length(); i++) { assert weaponsVector.get(i).name().equals(expectedWeaponNames[i]); assert weaponsVector.get(i).damage() == expectedWeaponDamages[i]; } // Get and test the `equipped` FlatBuffer `union`. assert monster.equippedType() == Equipment.Weapon; Weapon equipped = (Weapon)monster.equipped(new Weapon()); assert equipped.name().equals("Axe"); assert equipped.damage() == 5; System.out.println("The FlatBuffer was successfully created and verified!"); } }
1,388
890
<filename>vireo/common/math.h /* * MIT License * * Copyright (c) 2017 Twitter * * 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. */ #pragma once #include <limits> #include <math.h> #include <vector> #include "vireo/base_h.h" #include "vireo/error/error.h" namespace vireo { namespace common { using namespace std; template <class T> T mean(vector<T> values) { T acc = 0; for (auto v: values) { acc += v; } return acc / values.size(); } template <class T> double variance(vector<T> values) { T avg = mean(values); double acc = 0; for (auto v: values) { acc += v * v; } return (acc / values.size()) - avg * avg; } template <class T> double std_dev(vector<T> values) { return sqrt(variance(values)); } template <class T> static inline typename std::enable_if<std::is_unsigned<T>::value & std::is_integral<T>::value, T>::type safe_umul(T x, T y) { THROW_IF(y && x > numeric_limits<T>::max() / y, Overflow); return x * y; } template <class T> static inline T round_divide(T x, T num, T denom) { return (safe_umul(x, num) + (denom / 2)) / denom; }; template <class T> static inline T ceil_divide(T x, T num, T denom) { return (safe_umul(x, num) + (denom - 1)) / denom; }; template <class T> static inline T align_shift(T x, int shift) { return ((x + (1 << shift) - 1) >> shift) << shift; }; template <class T> static inline T align_divide(T x, T denom) { return ((x + (denom - 1)) / denom) * denom; }; template <class T> static T median(vector<T> values) { auto size = values.size(); sort(values.begin(), values.end()); auto mid = size / 2; return size ? ((size % 2 == 0) ? (values[mid - 1] + values[mid]) / 2 : values[mid]) : 0; }; template <class T> static inline T even(T x) { return x + (x & 0x01); } template <class T> static inline T even_floor(T x) { return x - (x & 0x01); } }}
985
619
<gh_stars>100-1000 /* * Author: <NAME> <<EMAIL>> * Copyright (c) 2016 Intel Corporation. * * This program and the accompanying materials are made available under the * terms of the The MIT License which is available at * https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: MIT */ #include <unistd.h> #include <stdio.h> #include <signal.h> #include <upm_utilities.h> #include <buzzer.h> int main(int argc, char **argv) { //! [Interesting] int chord[] = { BUZZER_DO, BUZZER_RE, BUZZER_MI, BUZZER_FA, BUZZER_SOL, BUZZER_LA, BUZZER_SI }; // create Buzzer context, using PWM pin 5 buzzer_context sound = buzzer_init(5); if (!sound) { printf("buzzer_init() failed\n"); return 1; } printf("Playing...\n"); // play each sound (DO, RE, MI, etc...) for .5 seconds, pausing // for 0.1 seconds between notes for (int chord_ind = 0; chord_ind < 7; chord_ind++) { buzzer_play_sound(sound, chord[chord_ind], 500000); printf("%d\n", chord[chord_ind]); upm_delay_ms(100); } printf("Exiting...\n"); buzzer_close(sound); //! [Interesting] return 0; }
523
930
<filename>vm/safepoints.cpp<gh_stars>100-1000 #include "master.hpp" namespace factor { void factor_vm::enqueue_fep() { if (fep_p) fatal_error("Low-level debugger interrupted", 0); atomic::store(&safepoint_fep_p, true); code->set_safepoint_guard(true); } void factor_vm::enqueue_samples(cell samples, cell pc, bool foreign_thread_p) { if (!atomic::load(&sampling_profiler_p)) return; atomic::fetch_add(&current_sample.sample_count, samples); if (foreign_thread_p) atomic::fetch_add(&current_sample.foreign_thread_sample_count, samples); else { if (atomic::load(&current_gc_p)) atomic::fetch_add(&current_sample.gc_sample_count, samples); if (atomic::load(&current_jit_count) > 0) atomic::fetch_add(&current_sample.jit_sample_count, samples); if (!code->seg->in_segment_p(pc)) atomic::fetch_add(&current_sample.foreign_sample_count, samples); } code->set_safepoint_guard(true); } // Allocates memory (record_sample) void factor_vm::handle_safepoint(cell pc) { code->set_safepoint_guard(false); faulting_p = false; if (atomic::load(&safepoint_fep_p)) { if (atomic::load(&sampling_profiler_p)) end_sampling_profiler(); std::cout << "Interrupted\n"; if (stop_on_ctrl_break) { /* Ctrl-Break throws an exception, interrupting the main thread, same as the "t" command in the factorbug debugger. But for Ctrl-Break to work we don't require the debugger to be activated, or even enabled. */ atomic::store(&safepoint_fep_p, false); general_error(ERROR_INTERRUPT, false_object, false_object); FACTOR_ASSERT(false); } factorbug(); atomic::store(&safepoint_fep_p, false); } else if (atomic::load(&sampling_profiler_p)) { FACTOR_ASSERT(code->seg->in_segment_p(pc)); code_block* block = code->code_block_for_address(pc); bool prolog_p = block->entry_point() == pc; record_sample(prolog_p); } } }
829
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once #include "stdafx.h" #include "JsonSerializableTestBase.h" namespace NativeAndManagedSerializationInteropTest { /// Json properties of this class should match json properties of managed class defined in file: /// %SDXROOT%\services\winfab\prod\test\System.Fabric\unit\Common\Serialization\DescriptionSerializationInterop.Test.cs class DescriptionSerializationInteropTest : public JsonSerializableTestBase { public: DescriptionSerializationInteropTest() { // TODO: remove when 4586918 is fixed Common::CommonConfig::GetConfig().EnableApplicationTypeHealthEvaluation = true; } BEGIN_JSON_SERIALIZABLE_PROPERTIES() SERIALIZABLE_PROPERTY(L"FABRIC_SERVICE_TYPE_DESCRIPTION_", FABRIC_SERVICE_TYPE_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_SERVICE_PLACEMENT_POLICY_DESCRIPTION_", FABRIC_SERVICE_PLACEMENT_POLICY_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_SERVICE_TYPE_DESCRIPTION_EXTENSION_", FABRIC_SERVICE_TYPE_DESCRIPTION_EXTENSION_) SERIALIZABLE_PROPERTY(L"FABRIC_PARTITION_SCHEME_", FABRIC_PARTITION_SCHEME_) SERIALIZABLE_PROPERTY(L"FABRIC_SERVICE_DESCRIPTION_", FABRIC_SERVICE_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_APPLICATION_DESCRIPTION_", FABRIC_APPLICATION_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_SERVICE_GROUP_TYPE_DESCRIPTION_", FABRIC_SERVICE_GROUP_TYPE_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_SERVICE_GROUP_TYPE_MEMBER_DESCRIPTION_", FABRIC_SERVICE_GROUP_TYPE_MEMBER_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_SERVICE_GROUP_MEMBER_DESCRIPTION_", FABRIC_SERVICE_GROUP_MEMBER_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION_", FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_APPLICATION_UPGRADE_DESCRIPTION_", FABRIC_APPLICATION_UPGRADE_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_APPLICATION_UPGRADE_UPDATE_DESCRIPTION_", FABRIC_APPLICATION_UPGRADE_UPDATE_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_UPGRADE_DESCRIPTION_", FABRIC_UPGRADE_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_UPGRADE_UPDATE_DESCRIPTION_", FABRIC_UPGRADE_UPDATE_DESCRIPTION_) SERIALIZABLE_PROPERTY(L"FABRIC_ROLLING_UPGRADE_MONITORING_POLICY_", FABRIC_ROLLING_UPGRADE_MONITORING_POLICY_) SERIALIZABLE_PROPERTY(L"FABRIC_APPLICATION_HEALTH_POLICY_MAP_", FABRIC_APPLICATION_HEALTH_POLICY_MAP_) END_JSON_SERIALIZABLE_PROPERTIES() ServiceModel::ApplicationDescriptionWrapper FABRIC_APPLICATION_DESCRIPTION_; ServiceModel::ApplicationUpgradeDescriptionWrapper FABRIC_APPLICATION_UPGRADE_DESCRIPTION_; Management::ClusterManager::ApplicationUpgradeUpdateDescription FABRIC_APPLICATION_UPGRADE_UPDATE_DESCRIPTION_; ServiceModel::FabricUpgradeDescriptionWrapper FABRIC_UPGRADE_DESCRIPTION_; Management::ClusterManager::FabricUpgradeUpdateDescription FABRIC_UPGRADE_UPDATE_DESCRIPTION_; ServiceModel::PartitionDescription FABRIC_PARTITION_SCHEME_; ServiceModel::PartitionedServiceDescWrapper FABRIC_SERVICE_DESCRIPTION_; ServiceModel::RollingUpgradeMonitoringPolicy FABRIC_ROLLING_UPGRADE_MONITORING_POLICY_; ServiceModel::ServiceLoadMetricDescription FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION_; ServiceModel::ServiceGroupMemberDescriptionAdaptor FABRIC_SERVICE_GROUP_MEMBER_DESCRIPTION_; ServiceModel::ServiceGroupTypeDescription FABRIC_SERVICE_GROUP_TYPE_DESCRIPTION_; ServiceModel::ServiceGroupTypeMemberDescription FABRIC_SERVICE_GROUP_TYPE_MEMBER_DESCRIPTION_; ServiceModel::ServicePlacementPolicyDescription FABRIC_SERVICE_PLACEMENT_POLICY_DESCRIPTION_; ServiceModel::ServiceTypeDescription FABRIC_SERVICE_TYPE_DESCRIPTION_; ServiceModel::DescriptionExtension FABRIC_SERVICE_TYPE_DESCRIPTION_EXTENSION_; ServiceModel::ClusterHealthQueryDescription FABRIC_CLUSTER_HEALTH_QUERY_DESCRIPTION_; ServiceModel::ApplicationHealthPolicyMap FABRIC_APPLICATION_HEALTH_POLICY_MAP_; }; }
1,761
432
<filename>launchers/fs/src/main/java/io/activej/launchers/fs/ClusterTcpServerLauncher.java /* * Copyright (C) 2020 ActiveJ LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.activej.launchers.fs; import io.activej.async.service.EventloopTaskScheduler; import io.activej.common.exception.MalformedDataException; import io.activej.config.Config; import io.activej.eventloop.Eventloop; import io.activej.fs.ActiveFs; import io.activej.fs.cluster.ClusterRepartitionController; import io.activej.fs.cluster.DiscoveryService; import io.activej.fs.cluster.FsPartitions; import io.activej.fs.cluster.ServerSelector; import io.activej.fs.tcp.ActiveFsServer; import io.activej.http.AsyncServlet; import io.activej.inject.annotation.Eager; import io.activej.inject.annotation.Named; import io.activej.inject.annotation.Provides; import io.activej.inject.binding.OptionalDependency; import io.activej.inject.module.AbstractModule; import io.activej.inject.module.Module; import io.activej.launchers.fs.gui.ActiveFsGuiServlet; import static io.activej.common.Utils.first; import static io.activej.fs.cluster.ServerSelector.RENDEZVOUS_HASH_SHARDER; import static io.activej.launchers.fs.Initializers.ofClusterRepartitionController; import static io.activej.launchers.initializers.Initializers.ofEventloopTaskScheduler; public class ClusterTcpServerLauncher extends SimpleTcpServerLauncher { public static final String DEFAULT_DEAD_CHECK_INTERVAL = "1 seconds"; public static final String DEFAULT_REPARTITION_INTERVAL = "1 seconds"; //[START EXAMPLE] @Provides @Eager @Named("repartition") EventloopTaskScheduler repartitionScheduler(Config config, ClusterRepartitionController controller) { return EventloopTaskScheduler.create(controller.getEventloop(), controller::repartition) .withInitializer(ofEventloopTaskScheduler(config.getChild("activefs.repartition"))); } @Provides @Eager @Named("clusterDeadCheck") EventloopTaskScheduler deadCheckScheduler(Config config, FsPartitions partitions) { return EventloopTaskScheduler.create(partitions.getEventloop(), partitions::checkDeadPartitions) .withInitializer(ofEventloopTaskScheduler(config.getChild("activefs.repartition.deadCheck"))); } @Provides ClusterRepartitionController repartitionController(Config config, ActiveFsServer localServer, FsPartitions partitions) { String localPartitionId = first(partitions.getAllPartitions()); assert localPartitionId != null; return ClusterRepartitionController.create(localPartitionId, partitions) .withInitializer(ofClusterRepartitionController(config.getChild("activefs.repartition"))); } @Provides DiscoveryService discoveryService(Eventloop eventloop, ActiveFs activeFs, Config config) throws MalformedDataException { return Initializers.constantDiscoveryService(eventloop, activeFs, config); } @Provides FsPartitions fsPartitions(Eventloop eventloop, DiscoveryService discoveryService, OptionalDependency<ServerSelector> serverSelector) { return FsPartitions.create(eventloop, discoveryService) .withServerSelector(serverSelector.orElse(RENDEZVOUS_HASH_SHARDER)); } //[END EXAMPLE] @Override protected Module getOverrideModule() { return new AbstractModule() { @Provides AsyncServlet guiServlet(ActiveFs fs, ClusterRepartitionController controller) { return ActiveFsGuiServlet.create(fs, "Cluster server [" + controller.getLocalPartitionId() + ']'); } }; } @Override protected Config createConfig() { return super.createConfig() .with("activefs.repartition.schedule.type", "interval") .with("activefs.repartition.schedule.value", DEFAULT_REPARTITION_INTERVAL) .with("activefs.repartition.deadCheck.schedule.type", "interval") .with("activefs.repartition.deadCheck.schedule.value", DEFAULT_DEAD_CHECK_INTERVAL); } public static void main(String[] args) throws Exception { new ClusterTcpServerLauncher().launch(args); } }
1,407
2,158
import argparse import json import time from pathlib import Path from sklearn import metrics from scipy import interpolate import torch.nn.functional as F from models import * from utils.utils import * from torchvision.transforms import transforms as T from utils.datasets import LoadImages, JointDataset, collate_fn def extract_ped_per_frame( cfg, input_root, output_root, weights, batch_size=16, img_size=416, iou_thres=0.5, conf_thres=0.3, nms_thres=0.45, print_interval=40, nID=14455, ): mkdir_if_missing(output_root) # Initialize model model = Darknet(cfg, img_size, nID) # Load weights if weights.endswith('.pt'): # pytorch format model.load_state_dict(torch.load(weights, map_location='cpu')['model'], strict=False) else: # darknet format load_darknet_weights(model, weights) model = torch.nn.DataParallel(model) model.cuda().eval() vlist = os.listdir(input_root) vlist = [osp.join(input_root, v, 'img1') for v in vlist] for vpath in vlist: vroot = osp.join('/',*vpath.split('/')[:-1]) out_vroot = vroot.replace(input_root, output_root) mkdir_if_missing(out_vroot) dataloader = LoadImages(vpath, img_size) for frame_id, (frame_path, frame, frame_ori) in enumerate(dataloader): frame_ground_id = frame_path.split('/')[-1].split('.')[0] if frame_id % 20 == 0: print('Processing frame {} of video {}'.format(frame_id, frame_path)) blob = torch.from_numpy(frame).cuda().unsqueeze(0) pred = model(blob) pred = pred[pred[:,:,4] > conf_thres] if len(pred) > 0: dets = non_max_suppression(pred.unsqueeze(0), conf_thres, nms_thres)[0].cpu() scale_coords(img_size, dets[:, :4], frame_ori.shape).round() frame_dir = osp.join(out_vroot, frame_ground_id) mkdir_if_missing(frame_dir) dets = dets[:, :5] for ped_id, det in enumerate(dets): box = det[:4].int() conf = det[4] ped = frame_ori[box[1]:box[3], box[0]:box[2]] ped_path = osp.join(frame_dir, ('{:04d}_'+ '{:d}_'*4 + '{:.2f}.jpg').format(ped_id, *box, conf)) cv2.imwrite(ped_path, ped) if __name__ == '__main__': parser = argparse.ArgumentParser(prog='test.py') parser.add_argument('--batch-size', type=int, default=40, help='size of each image batch') parser.add_argument('--cfg', type=str, default='cfg/yolov3.cfg', help='cfg file path') parser.add_argument('--weights', type=str, default='weights/mot_64/latest.pt', help='path to weights file') parser.add_argument('--iou-thres', type=float, default=0.3, help='iou threshold required to qualify as detected') parser.add_argument('--conf-thres', type=float, default=0.3, help='object confidence threshold') parser.add_argument('--nms-thres', type=float, default=0.3, help='iou threshold for non-maximum suppression') parser.add_argument('--img-size', type=int, default=(1088, 608), help='size of each image dimension') parser.add_argument('--print-interval', type=int, default=10, help='size of each image dimension') parser.add_argument('--input-root', type=str, default='/home/wangzd/datasets/youtube/data/0004/frame', help='path to input frames') parser.add_argument('--output-root', type=str, default='/home/wangzd/datasets/youtube/data/0004/ped_per_frame', help='path to output frames') opt = parser.parse_args() print(opt, end='\n\n') with torch.no_grad(): extract_ped_per_frame( opt.cfg, opt.input_root, opt.output_root, opt.weights, opt.batch_size, opt.img_size, opt.iou_thres, opt.conf_thres, opt.nms_thres, opt.print_interval, )
1,980
2,705
from argparse import RawTextHelpFormatter from textwrap import dedent from fontTools.ttLib import TTFont from fontTools.otlLib.optimize.gpos import compact, GPOS_COMPACT_MODE_DEFAULT def main(args=None): """Optimize the layout tables of an existing font.""" from argparse import ArgumentParser from fontTools import configLogger parser = ArgumentParser(prog="otlLib.optimize", description=main.__doc__, formatter_class=RawTextHelpFormatter) parser.add_argument("font") parser.add_argument( "-o", metavar="OUTPUTFILE", dest="outfile", default=None, help="output file" ) parser.add_argument( "--gpos-compact-mode", help=dedent( f"""\ GPOS Lookup type 2 (PairPos) compaction mode: 0 = do not attempt to compact PairPos lookups; 1 to 8 = create at most 1 to 8 new subtables for each existing subtable, provided that it would yield a 50%% file size saving; 9 = create as many new subtables as needed to yield a file size saving. Default: {GPOS_COMPACT_MODE_DEFAULT}. This compaction aims to save file size, by splitting large class kerning subtables (Format 2) that contain many zero values into smaller and denser subtables. It's a trade-off between the overhead of several subtables versus the sparseness of one big subtable. See the pull request: https://github.com/fonttools/fonttools/pull/2326 """ ), default=int(GPOS_COMPACT_MODE_DEFAULT), choices=list(range(10)), type=int, ) logging_group = parser.add_mutually_exclusive_group(required=False) logging_group.add_argument( "-v", "--verbose", action="store_true", help="Run more verbosely." ) logging_group.add_argument( "-q", "--quiet", action="store_true", help="Turn verbosity off." ) options = parser.parse_args(args) configLogger( level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") ) font = TTFont(options.font) # TODO: switch everything to have type(mode) = int when using the Config class compact(font, str(options.gpos_compact_mode)) font.save(options.outfile or options.font) if __name__ == "__main__": import sys if len(sys.argv) > 1: sys.exit(main()) import doctest sys.exit(doctest.testmod().failed)
976
1,099
package com.example.chat.mvp.skin; import com.example.chat.base.AppBasePresenter; import com.example.chat.bean.SkinBean; import com.example.chat.manager.MsgManager; import com.example.chat.manager.UserDBManager; import com.example.commonlibrary.baseadapter.empty.EmptyLayout; import com.example.commonlibrary.bean.chat.SkinEntity; import com.example.commonlibrary.mvp.model.DefaultModel; import com.example.commonlibrary.mvp.view.IView; import com.example.commonlibrary.utils.CommonLogger; import com.example.commonlibrary.utils.ToastUtils; import java.util.ArrayList; import java.util.List; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.FindListener; /** * 项目名称: NewFastFrame * 创建人: 李晨 * 创建时间: 2018/5/22 23:48 */ public class SkinListPresenter extends AppBasePresenter<IView<List<SkinEntity>>,DefaultModel>{ private int page; public SkinListPresenter(IView<List<SkinEntity>> iView, DefaultModel baseModel) { super(iView, baseModel); } public void getSkinData(boolean isRefresh) { if (isRefresh) { iView.showLoading(null); page=0; } page++; BmobQuery<SkinBean> skinBeanBmobQuery=new BmobQuery<>(); skinBeanBmobQuery.setLimit(10); skinBeanBmobQuery.setSkip((page-1)*10); skinBeanBmobQuery.order("-createdAt"); addSubscription(skinBeanBmobQuery.findObjects(new FindListener<SkinBean>() { @Override public void done(List<SkinBean> list, BmobException e) { List<SkinEntity> skinEntityList=null; if (e == null) { if (list != null && list.size() > 0) { skinEntityList=new ArrayList<>(); for (SkinBean bean : list) { skinEntityList.add(MsgManager.getInstance().cover(bean)); } } }else { page--; ToastUtils.showShortToast("缓存数据获取"); CommonLogger.e("查询服务器上皮肤数据出错"+e.toString()); if (isRefresh) { skinEntityList= UserDBManager .getInstance().getSkinList(); } } iView.updateData(skinEntityList); iView.hideLoading(); } })); } }
1,288
533
<gh_stars>100-1000 #include "saber/funcs/impl/x86/saber_argmax.h" namespace anakin { namespace saber { template <typename dtype> void Argmax_kernel_axis(const dtype* din, dtype* dout, int num, int in_stride, \ int out_stride, int size, int in_ss, int out_ss, int top, bool out_max) { for (int n = 0; n < num * out_stride; n++) { for (int k = 0; k < in_stride; k ++) { const dtype* din_ch = din + n * in_ss + k; std::vector< std::pair<dtype, int> > vec; vec.resize(size); for (int i = 0; i < size; i++) { vec[i] = std::make_pair(din_ch[i * in_stride], i); } //sort std::partial_sort(vec.begin(), vec.begin() + top, vec.end(), std::greater< std::pair<float, int> >()); //out dtype* dout_ch = dout + n * out_ss + k; for (int i = 0; i < top ; i ++) { if (out_max) { dout_ch[i * in_stride] = vec[i].first; } else { dout_ch[i * in_stride] = vec[i].second; } } } } } template <typename dtype> void Argmax_kernel(const dtype* din, dtype* dout, int num, int in_channel, \ int out_channel, int top, bool out_max) { for (int n = 0; n < num; n++) { const dtype* din_ch = din + n * in_channel; std::vector< std::pair<dtype, int> > vec; vec.resize(in_channel); for (int i = 0; i < in_channel; i++) { vec[i] = std::make_pair(din_ch[i], i); } //sort std::partial_sort(vec.begin(), vec.begin() + top, vec.end(), std::greater< std::pair<float, int> >()); //out if (out_max) { dtype* dout_ch = dout + n * out_channel; dtype* dout_index = dout_ch; dtype* dout_data = dout_ch + top; for (int i = 0; i < top; i++) { dout_data[i] = vec[i].first; dout_index[i] = vec[i].second; //LOG(INFO) << "max_data: " <<dout_data[i] << ", max_index: "<<dout_index[i]; } } else { dtype* dout_data = dout + n * out_channel; for (int i = 0; i < top; i++) { dout_data[i] = vec[i].second; // LOG(INFO) << "max_data: " <<vec[i].first << ", max_index: "<< dout_data[i]; } } //vec.clear(); } } template <DataType OpDtype> SaberStatus SaberArgmax<X86, OpDtype>::dispatch(const std::vector<Tensor<X86>*>& inputs, std::vector<Tensor<X86>*>& outputs, ArgmaxParam<X86>& param) { int num = inputs[0]->num(); int channel = inputs[0]->channel(); int height = inputs[0]->height(); int width = inputs[0]->width(); int ch_out = outputs[0]->channel(); int w_out = outputs[0]->width(); int h_out = outputs[0]->height(); int top = param.top_k; bool has_ax = param.has_axis; int ax = param.axis; bool out_max = param.out_max_val; const OpDataType* din = (const OpDataType*)inputs[0]->data(); OpDataType* dout = (OpDataType*)outputs[0]->mutable_data(); int in_channel = channel * height * width; int out_channel = ch_out * w_out * h_out; if (has_ax) { //nchw auto shape = inputs[0]->valid_shape(); int stride = shape.count(ax + 1, shape.dims()); int out_stride = shape.count(1, ax); int out_ss = outputs[0]->valid_shape().count(ax, shape.dims()); int in_ss = shape.count(ax, shape.dims()); // LOG(INFO) << "stride: "<<stride << ", out_stride: " << out_stride; int size = shape[ax]; if (size < top) { LOG(INFO) << "input data size less than topk"; return SaberUnImplError; } /* for (int n = 0; n < num * out_stride; n++){ for(int k = 0; k < stride; k ++){ const OpDataType* din_ch = din + n * in_ss + k; std::vector< std::pair<OpDataType, int> > vec; vec.resize(size); for (int i = 0; i < size; i++){ vec[i] = std::make_pair(din_ch[i*stride], i); } //sort std::partial_sort(vec.begin(), vec.begin() + top, vec.end(), std::greater< std::pair<float, int> >()); //out OpDataType* dout_ch = dout + n * out_ss + k; for(int i = 0; i < top ;i ++){ if(out_max) dout_ch[i*stride] = vec[i].first; else dout_ch[i*stride] = vec[i].second; } } } */ Argmax_kernel_axis<float>(din, dout, num, stride, out_stride, size, in_ss, out_ss, top, out_max); } else { //all if (in_channel < top) { LOG(INFO) << "input data size less than topk"; return SaberUnImplError; } /* for (int n = 0; n < num; n++){ const OpDataType* din_ch = din + n * in_channel; std::vector< std::pair<OpDataType, int> > vec; vec.resize(in_channel); for (int i = 0; i < in_channel; i++){ vec[i] = std::make_pair(din_ch[i], i); } //sort std::partial_sort(vec.begin(), vec.begin() + top, vec.end(), std::greater< std::pair<float, int> >()); //out if(out_max){ OpDataType* dout_ch = dout + n * out_channel; OpDataType* dout_data = dout_ch; OpDataType* dout_index = dout_ch + top; for (int i = 0; i < top; i++){ dout_data[i] = vec[i].first; dout_index[i] = vec[i].second; //LOG(INFO) << "max_data: " <<dout_data[i] << ", max_index: "<<dout_index[i]; } }else{ OpDataType* dout_data = dout + n * out_channel; for (int i = 0; i < top; i++){ dout_data[i] = vec[i].second; // LOG(INFO) << "max_data: " <<vec[i].first << ", max_index: "<< dout_data[i]; } } vec.clear(); } */ Argmax_kernel<float>(din, dout, num, in_channel, out_channel, top, out_max); } return SaberSuccess; } template class SaberArgmax<X86, AK_FLOAT>; DEFINE_OP_TEMPLATE(SaberArgmax, ArgmaxParam, X86, AK_HALF); DEFINE_OP_TEMPLATE(SaberArgmax, ArgmaxParam, X86, AK_INT8); } //namespace anakin } //namespace anakin
3,613
3,308
<reponame>hw07216/imaginaire // Copyright (C) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // // This work is made available under the Nvidia Source Code License-NC. // To view a copy of this license, check out LICENSE.md #include <torch/extension.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <vector> // Fast voxel traversal along rays std::vector<torch::Tensor> ray_voxel_intersection_perspective_cuda(const torch::Tensor& in_voxel, const torch::Tensor& cam_ori, const torch::Tensor& cam_dir, const torch::Tensor& cam_up, float cam_f, const std::vector<float>& cam_c, const std::vector<int>& img_dims, int max_samples); // World Coordinate Sparse Trilinear Interpolation torch::Tensor sp_trilinear_worldcoord_cuda(const torch::Tensor& in_feature, const torch::Tensor& in_corner_lut, const torch::Tensor& in_worldcoord, bool ign_zero, int channel_pos); std::vector<torch::Tensor> sp_trilinear_worldcoord_backward_cuda(const torch::Tensor& out_feature_grad , const torch::Tensor& in_feature, const torch::Tensor& in_corner_lut, const torch::Tensor& in_worldcoord, bool ign_zero, bool need_coord_grad); // Fast & Memory Efficient Positional Encoding torch::Tensor positional_encoding_cuda(const torch::Tensor& in_feature, int ndegrees, int dim, bool incl_orig); torch::Tensor positional_encoding_backward_cuda(const torch::Tensor& out_feature_grad, const torch::Tensor& out_feature, int ndegrees, int dim, bool incl_orig); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("ray_voxel_intersection_perspective", &ray_voxel_intersection_perspective_cuda, "Ray-voxel intersections given perspective camera parameters (CUDA)"); m.def("sp_trilinear_worldcoord", &sp_trilinear_worldcoord_cuda, "Sparse Trilinear interpolation, world coordinate [forward] (CUDA)"); m.def("sp_trilinear_worldcoord_backward", &sp_trilinear_worldcoord_backward_cuda, "Sparse Trilinear interpolation, world coordinate [backward] (CUDA)"); m.def("positional_encoding", &positional_encoding_cuda, "Fused Positional Encoding [forward] (CUDA)"); m.def("positional_encoding_backward", &positional_encoding_backward_cuda, "Fused Positional Encoding [backward] (CUDA)"); }
773
1,056
<gh_stars>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.swing.outline; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.CellRendererPane; import javax.swing.Icon; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.tree.AbstractLayoutCache; import javax.swing.tree.TreePath; /** An outline-aware TableCellRenderer which knows how to paint expansion * handles and indent child nodes an appropriate amount. * * @author <NAME> */ public class DefaultOutlineCellRenderer extends DefaultTableCellRenderer { private static int expansionHandleWidth = 0; private static int expansionHandleHeight = 0; private boolean expanded = false; private boolean leaf = true; private boolean showHandle = true; private int nestingDepth = 0; private int labelTextGap = 0; private final JCheckBox theCheckBox; private final CellRendererPane fakeCellRendererPane; private JCheckBox checkBox; private Reference<RenderDataProvider> lastRendererRef = new WeakReference<RenderDataProvider>(null); // Used by lazy tooltip private Reference<Object> lastRenderedValueRef = new WeakReference<Object>(null); // Used by lazy tooltip private static final Border expansionBorder = new ExpansionHandleBorder(); private static final Class htmlRendererClass = useSwingHtmlRendering() ? null : HtmlRenderer.getDelegate(); private final HtmlRenderer.Renderer htmlRenderer = (htmlRendererClass != null) ? HtmlRenderer.createRenderer(htmlRendererClass) : null; private final boolean swingRendering = htmlRenderer == null; private static boolean useSwingHtmlRendering() { try { return Boolean.getBoolean("nb.useSwingHtmlRendering"); // NOI18N } catch (SecurityException se) { return false; } } /** Creates a new instance of DefaultOutlineTreeCellRenderer */ public DefaultOutlineCellRenderer() { theCheckBox = createCheckBox(); // In order to paint the check-box correctly, following condition must be true: // SwingUtilities.getAncestorOfClass(CellRendererPane.class, theCheckBox) != null // (See e.g.: paintSkin() method in com/sun/java/swing/plaf/windows/XPStyle.java) fakeCellRendererPane = new CellRendererPane(); fakeCellRendererPane.add(theCheckBox); } final JCheckBox createCheckBox() { JCheckBox cb = new JCheckBox(); cb.setSize(cb.getPreferredSize()); cb.setBorderPainted(false); cb.setOpaque(false); return cb; } /** Overridden to combine the expansion border (whose insets determine how * much a child tree node is shifted to the right relative to the ancestor * root node) with whatever border is set, as a CompoundBorder. The expansion * border is also responsible for drawing the expansion icon. * @param b the border to be rendered for this component */ @Override public final void setBorder (Border b) { b = new RestrictedInsetsBorder(b); if (!swingRendering) { super.setBorder(b); return ; } if (b == expansionBorder) { super.setBorder(b); } else { super.setBorder(BorderFactory.createCompoundBorder (b, expansionBorder)); } } @Override protected void setValue(Object value) { if (swingRendering) { super.setValue(value); } } private static Icon getDefaultOpenIcon() { return UIManager.getIcon("Tree.openIcon"); //NOI18N } private static Icon getDefaultClosedIcon() { return UIManager.getIcon("Tree.closedIcon"); //NOI18N } private static Icon getDefaultLeafIcon() { return UIManager.getIcon("Tree.leafIcon"); //NOI18N } static Icon getExpandedIcon() { return UIManager.getIcon ("Tree.expandedIcon"); //NOI18N } static Icon getCollapsedIcon() { return UIManager.getIcon ("Tree.collapsedIcon"); //NOI18N } static int getNestingWidth() { return getExpansionHandleWidth(); } static int getExpansionHandleWidth() { if (expansionHandleWidth == 0) { expansionHandleWidth = getExpandedIcon ().getIconWidth (); } return expansionHandleWidth; } static int getExpansionHandleHeight() { if (expansionHandleHeight == 0) { expansionHandleHeight = getExpandedIcon ().getIconHeight (); } return expansionHandleHeight; } private void setNestingDepth (int i) { nestingDepth = i; } private void setExpanded (boolean val) { expanded = val; } private void setLeaf (boolean val) { leaf = val; } private void setShowHandle (boolean val) { showHandle = val; } private void setCheckBox(JCheckBox checkBox) { this.checkBox = checkBox; } private boolean isLeaf () { return leaf; } private boolean isExpanded () { return expanded; } private boolean isShowHandle() { return showHandle; } private void setLabelTextGap(int labelTextGap) { this.labelTextGap = labelTextGap; } private int getLabelTextGap() { return labelTextGap; } /** Set the nesting depth - the number of path elements below the root. * This is set in getTableCellEditorComponent(), and retrieved by the * expansion border to determine how far to the right to indent the current * node. */ private int getNestingDepth() { return nestingDepth; } private JCheckBox getCheckBox() { return checkBox; } final JCheckBox setUpCheckBox(CheckRenderDataProvider crendata, Object value, JCheckBox cb) { Boolean chSelected = crendata.isSelected(value); cb.setEnabled(true); cb.setSelected(!Boolean.FALSE.equals(chSelected)); // Third state is "selected armed" to be consistent with org.openide.explorer.propertysheet.ButtonModel3Way cb.getModel().setArmed(chSelected == null); cb.getModel().setPressed(chSelected == null); cb.setEnabled(crendata.isCheckEnabled(value)); cb.setBackground(getBackground()); return cb; } int getTheCheckBoxWidth() { return theCheckBox.getSize().width; } /** Get a component that can render cells in an Outline. If * <code>((Outline) table).isTreeColumnIndex(column)</code> is true, * it will paint as indented and with an expansion handle if the * Outline's model returns false from <code>isLeaf</code> for the * passed value. * <p> * If the column is not the tree column, its behavior is the same as * DefaultTableCellRenderer. */ @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setForeground(null); setBackground(null); setLabelTextGap(0); super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); JLabel label = null; if (!swingRendering) { htmlRenderer.setColors(getForeground(), getBackground()); label = (JLabel) htmlRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } Outline tbl = (Outline) table; if (tbl.isTreeColumnIndex(column)) { AbstractLayoutCache layout = tbl.getLayoutCache(); row = tbl.convertRowIndexToModel(row); boolean isleaf = tbl.getOutlineModel().isLeaf(value); setLeaf(isleaf); setShowHandle(true); TreePath path = layout.getPathForRow(row); boolean isExpanded = layout.isExpanded(path); setExpanded (isExpanded); int nd = path == null ? 0 : path.getPathCount() - (tbl.isRootVisible() ? 1 : 2); if (nd < 0) { nd = 0; } setNestingDepth (nd ); RenderDataProvider rendata = tbl.getRenderDataProvider(); Icon icon = null; if (rendata != null && value != null) { String displayName = rendata.getDisplayName(value); if (displayName != null) { if (rendata.isHtmlDisplayName(value) && !(displayName.startsWith("<html") || displayName.startsWith("<HTML"))) { if (swingRendering) { setText("<html>" + displayName.replaceAll(" ", "&nbsp;") + "</html>"); // NOI18N } else { label.setText("<html>" + displayName.replaceAll(" ", "&nbsp;") + "</html>"); // NOI18N } } else { if (swingRendering) { setText (displayName); } else { label.setText (displayName); } } } lastRendererRef = new WeakReference<RenderDataProvider>(rendata); lastRenderedValueRef = new WeakReference<Object>(value); Color bg = rendata.getBackground(value); Color fg = rendata.getForeground(value); if (bg != null && !isSelected) { if (swingRendering) { setBackground (bg); } else { label.setBackground (bg); } } else { if (!swingRendering) { label.setBackground(getBackground()); } } if (fg != null && !isSelected) { if (swingRendering) { setForeground (fg); } else { label.setForeground (fg); } } else { if (!swingRendering) { label.setForeground(getForeground()); } } icon = rendata.getIcon(value); JCheckBox cb = null; if (rendata instanceof CheckRenderDataProvider) { CheckRenderDataProvider crendata = (CheckRenderDataProvider) rendata; if (crendata.isCheckable(value)) { cb = setUpCheckBox(crendata, value, theCheckBox); } } setCheckBox(cb); } else { setCheckBox(null); } if (icon == null) { if (!isleaf) { if (isExpanded) { icon = getDefaultOpenIcon(); } else { // ! expanded icon = getDefaultClosedIcon(); } } else { // leaf icon = getDefaultLeafIcon(); } } if (swingRendering) { setIcon(icon); } else { label.setIcon(icon); } if (icon == null || icon.getIconWidth() == 0) { setLabelTextGap(getIconTextGap()); } } else { // ! tbl.isTreeColumnIndex(column) setCheckBox(null); if (swingRendering) { setIcon(null); } else { label.setIcon(null); } setShowHandle(false); lastRendererRef = new WeakReference<RenderDataProvider>(null); lastRenderedValueRef = new WeakReference<Object>(null); } if (swingRendering) { return this; } else { Border b = getBorder(); if (b == null) { label.setBorder(expansionBorder); } else { label.setBorder(BorderFactory.createCompoundBorder (b, expansionBorder)); } label.setOpaque(true); label.putClientProperty(DefaultOutlineCellRenderer.class, this); return label; } } @Override public String getToolTipText() { // Retrieve the tooltip only when someone asks for it... RenderDataProvider rendata = lastRendererRef.get(); Object value = lastRenderedValueRef.get(); if (rendata != null && value != null) { String toolT = rendata.getTooltipText(value); if (toolT != null && (toolT = toolT.trim ()).length () > 0) { return toolT; } } return super.getToolTipText(); } private static class ExpansionHandleBorder implements Border { private static final boolean isGtk = "GTK".equals (UIManager.getLookAndFeel ().getID ()); //NOI18N private static final boolean isNimbus = "Nimbus".equals (UIManager.getLookAndFeel ().getID ()); //NOI18N private Insets insets = new Insets(0,0,0,0); private static JLabel lExpandedIcon = null; private static JLabel lCollapsedIcon = null; { if (isGtk) { lExpandedIcon = new JLabel (getExpandedIcon (), SwingUtilities.TRAILING); lCollapsedIcon = new JLabel (getCollapsedIcon (), SwingUtilities.TRAILING); } } @Override public Insets getBorderInsets(Component c) { DefaultOutlineCellRenderer ren = (DefaultOutlineCellRenderer) ((JComponent) c).getClientProperty(DefaultOutlineCellRenderer.class); if (ren == null) { ren = (DefaultOutlineCellRenderer) c; } if (ren.isShowHandle()) { insets.left = getExpansionHandleWidth() + (ren.getNestingDepth() * getNestingWidth()) + ren.getLabelTextGap(); //Defensively adjust all the insets fields insets.top = 1; insets.right = 1; insets.bottom = 1; } else { //Defensively adjust all the insets fields insets.left = 1; insets.top = 1; insets.right = 1; insets.bottom = 1; } if (ren.getCheckBox() != null) { insets.left += ren.getCheckBox().getSize().width; } return insets; } @Override public boolean isBorderOpaque() { return false; } @Override public void paintBorder(Component c, java.awt.Graphics g, int x, int y, int width, int height) { DefaultOutlineCellRenderer ren = (DefaultOutlineCellRenderer) ((JComponent) c).getClientProperty(DefaultOutlineCellRenderer.class); if (ren == null) { ren = (DefaultOutlineCellRenderer) c; } if (ren.isShowHandle() && !ren.isLeaf()) { Icon icon = ren.isExpanded() ? getExpandedIcon() : getCollapsedIcon(); int iconY; int iconX = ren.getNestingDepth() * getNestingWidth(); if (icon.getIconHeight() < height) { iconY = (height / 2) - (icon.getIconHeight() / 2); } else { iconY = 0; } if (isNimbus) { iconX += icon.getIconWidth()/3; // To look good } if (isGtk) { JLabel lbl = ren.isExpanded () ? lExpandedIcon : lCollapsedIcon; lbl.setSize (Math.max (getExpansionHandleWidth (), iconX + getExpansionHandleWidth ()), height); lbl.paint (g); } else { icon.paintIcon(c, g, iconX, iconY); } } JCheckBox chBox = ren.getCheckBox(); if (chBox != null) { int chBoxX = getExpansionHandleWidth() + ren.getNestingDepth() * getNestingWidth(); Rectangle bounds = chBox.getBounds(); int chBoxY; if (bounds.getHeight() < height) { chBoxY = (height / 2) - (((int) bounds.getHeight()) / 2); } else { if (isNimbus) { chBoxY = 1; } else { chBoxY = 0; } } Dimension chDim = chBox.getSize(); java.awt.Graphics gch = g.create(chBoxX, chBoxY, chDim.width, chDim.height); chBox.paint(gch); } } } /** * Use reflection to access org.openide.awt.HtmlRenderer class * so that we do not have to have a dependency on org.openide.awt module. */ private static final class HtmlRenderer { private static final String HTML_RENDERER_CLASS = "org.openide.awt.HtmlRenderer"; // NOI18N static Class getDelegate() { Class delegate; try { delegate = ClassLoader.getSystemClassLoader().loadClass(HTML_RENDERER_CLASS); } catch (ClassNotFoundException ex) { try { delegate = Thread.currentThread().getContextClassLoader().loadClass(HTML_RENDERER_CLASS); } catch (ClassNotFoundException ex2) { // We are searching for org.openide.awt.HtmlRenderer class. // However, we can not find it directly from the system class loader. // We need to find it via Lookup try { Class lookupClass = ClassLoader.getSystemClassLoader().loadClass("org.openide.util.Lookup"); // NOI18N try { Object defaultLookup = lookupClass.getMethod("getDefault").invoke(null); // NOI18N ClassLoader systemClassLoader = (ClassLoader) lookupClass.getMethod("lookup", Class.class).invoke(defaultLookup, ClassLoader.class); // NOI18N if (systemClassLoader == null) { return null; } delegate = systemClassLoader.loadClass(HTML_RENDERER_CLASS); } catch (NoSuchMethodException mex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (SecurityException mex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (IllegalAccessException mex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (IllegalArgumentException mex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (InvocationTargetException mex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); return null; } } catch (ClassNotFoundException ex3) { return null; } catch (SecurityException se) { return null; } } catch (SecurityException se) { return null; } } catch (SecurityException se) { return null; } return delegate; } private static Renderer createRenderer(Class htmlRendererClass) { try { Method createRenderer = htmlRendererClass.getMethod("createRenderer"); // NOI18N return new Renderer(createRenderer.invoke(null)); } catch (NoSuchMethodException ex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (SecurityException ex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (IllegalAccessException ex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (IllegalArgumentException ex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (InvocationTargetException ex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); return null; } } private static class Renderer { private Object renderer; private Method getTableCellRendererComponent; private Renderer(Object renderer) throws NoSuchMethodException { this.renderer = renderer; this.getTableCellRendererComponent = TableCellRenderer.class.getMethod( "getTableCellRendererComponent", // NOI18N JTable.class, Object.class, Boolean.TYPE, Boolean.TYPE, Integer.TYPE, Integer.TYPE); } public Component getTableCellRendererComponent( JTable table, Object value, boolean selected, boolean leadSelection, int row, int column ) { try { return (Component) getTableCellRendererComponent.invoke( renderer, table, value, selected, leadSelection, row, column); } catch (IllegalAccessException ex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); throw new IllegalStateException(ex); } catch (IllegalArgumentException ex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); throw new IllegalStateException(ex); } catch (InvocationTargetException ex) { Logger.getLogger(DefaultOutlineCellRenderer.class.getName()).log(Level.SEVERE, null, ex); throw new IllegalStateException(ex); } } private void setColors(Color foreground, Color background) { Component c = (Component) renderer; c.setForeground(foreground); c.setBackground(background); } } } private static class RestrictedInsetsBorder implements Border { private final Border delegate; public RestrictedInsetsBorder(Border delegate) { this.delegate = delegate; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { delegate.paintBorder(c, g, x, y, width, height); } @Override public Insets getBorderInsets(Component c) { Insets insets = delegate.getBorderInsets(c); if (insets.top > 1 || insets.left > 1 || insets.bottom > 1 || insets.right > 1) { insets = new Insets(Math.min(insets.top, 1), Math.min(insets.left, 1), Math.min(insets.bottom, 1), Math.min(insets.right, 1)); } return insets; } @Override public boolean isBorderOpaque() { return delegate.isBorderOpaque(); } } }
12,461
1,603
package com.linkedin.datahub.graphql.resolvers.operation; import com.google.common.collect.ImmutableList; import com.linkedin.common.Operation; import com.linkedin.common.OperationSourceType; import com.linkedin.common.OperationType; import com.linkedin.common.urn.Urn; import com.linkedin.common.urn.UrnUtils; import com.linkedin.data.template.SetMode; import com.linkedin.data.template.StringMap; import com.linkedin.datahub.graphql.QueryContext; import com.linkedin.datahub.graphql.authorization.AuthorizationUtils; import com.linkedin.datahub.graphql.authorization.ConjunctivePrivilegeGroup; import com.linkedin.datahub.graphql.authorization.DisjunctivePrivilegeGroup; import com.linkedin.datahub.graphql.exception.AuthorizationException; import com.linkedin.datahub.graphql.exception.DataHubGraphQLErrorCode; import com.linkedin.datahub.graphql.exception.DataHubGraphQLException; import com.linkedin.datahub.graphql.generated.ReportOperationInput; import com.linkedin.datahub.graphql.generated.StringMapEntryInput; import com.linkedin.entity.client.EntityClient; import com.linkedin.events.metadata.ChangeType; import com.linkedin.metadata.Constants; import com.linkedin.metadata.authorization.PoliciesConfig; import com.linkedin.metadata.utils.GenericRecordUtils; import com.linkedin.mxe.MetadataChangeProposal; import com.linkedin.timeseries.PartitionSpec; import com.linkedin.timeseries.PartitionType; import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; import java.net.URISyntaxException; import java.util.List; import java.util.concurrent.CompletableFuture; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import static com.linkedin.datahub.graphql.resolvers.AuthUtils.*; import static com.linkedin.datahub.graphql.resolvers.ResolverUtils.*; /** * Resolver used for reporting Asset Operations */ @Slf4j @RequiredArgsConstructor public class ReportOperationResolver implements DataFetcher<CompletableFuture<Boolean>> { private static final List<String> SUPPORTED_ENTITY_TYPES = ImmutableList.of( Constants.DATASET_ENTITY_NAME ); private final EntityClient _entityClient; @Override public CompletableFuture<Boolean> get(DataFetchingEnvironment environment) throws Exception { final QueryContext context = environment.getContext(); final ReportOperationInput input = bindArgument(environment.getArgument("input"), ReportOperationInput.class); return CompletableFuture.supplyAsync(() -> { Urn entityUrn = UrnUtils.getUrn(input.getUrn()); if (!isAuthorizedToReportOperationForResource(entityUrn, context)) { throw new AuthorizationException("Unauthorized to perform this action. Please contact your DataHub administrator."); } validateInput(entityUrn, input); try { // Create an MCP to emit the operation final MetadataChangeProposal proposal = new MetadataChangeProposal(); proposal.setEntityUrn(entityUrn); proposal.setEntityType(entityUrn.getEntityType()); proposal.setAspectName(Constants.OPERATION_ASPECT_NAME); proposal.setAspect(GenericRecordUtils.serializeAspect(mapOperation(input, context))); proposal.setChangeType(ChangeType.UPSERT); _entityClient.ingestProposal(proposal, context.getAuthentication()); return true; } catch (Exception e) { log.error("Failed to report operation. {}", e.getMessage()); throw new RuntimeException("Failed to report operation", e); } }); } private Operation mapOperation(final ReportOperationInput input, final QueryContext context) throws URISyntaxException { final Operation result = new Operation(); result.setActor(UrnUtils.getUrn(context.getActorUrn())); result.setOperationType(OperationType.valueOf(input.getOperationType().toString())); result.setCustomOperationType(input.getCustomOperationType(), SetMode.IGNORE_NULL); result.setNumAffectedRows(input.getNumAffectedRows(), SetMode.IGNORE_NULL); long timestampMillis = input.getTimestampMillis() != null ? input.getTimestampMillis() : System.currentTimeMillis(); result.setLastUpdatedTimestamp(timestampMillis); result.setTimestampMillis(timestampMillis); result.setSourceType(OperationSourceType.valueOf(input.getSourceType().toString())); if (input.getPartition() != null) { result.setPartitionSpec(new PartitionSpec().setType(PartitionType.PARTITION).setPartition(input.getPartition())); } if (input.getCustomProperties() != null) { result.setCustomProperties(mapCustomProperties(input.getCustomProperties())); } return result; } private StringMap mapCustomProperties(final List<StringMapEntryInput> properties) throws URISyntaxException { final StringMap result = new StringMap(); for (StringMapEntryInput entry : properties) { result.put(entry.getKey(), entry.getValue()); } return result; } private void validateInput(final Urn entityUrn, final ReportOperationInput input) { if (!SUPPORTED_ENTITY_TYPES.contains(entityUrn.getEntityType())) { throw new DataHubGraphQLException( String.format("Unable to report operation. Invalid entity type %s provided.", entityUrn.getEntityType()), DataHubGraphQLErrorCode.BAD_REQUEST); } } private boolean isAuthorizedToReportOperationForResource(final Urn resourceUrn, final QueryContext context) { final DisjunctivePrivilegeGroup orPrivilegeGroups = new DisjunctivePrivilegeGroup(ImmutableList.of( ALL_PRIVILEGES_GROUP, new ConjunctivePrivilegeGroup(ImmutableList.of(PoliciesConfig.EDIT_ENTITY_OPERATIONS_PRIVILEGE.getType())) )); return AuthorizationUtils.isAuthorized( context.getAuthorizer(), context.getActorUrn(), resourceUrn.getEntityType(), resourceUrn.toString(), orPrivilegeGroups); } }
1,961
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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" // INCLUDE --------------------------------------------------------------- #ifdef SOLARIS // HACK: prevent conflict between STLPORT and Workshop headers on Solaris 8 #include <ctime> #endif #include <string> // HACK: prevent conflict between STLPORT and Workshop headers #include <sot/exchange.hxx> #include <comphelper/processfactory.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <sfx2/docfac.hxx> #include <sfx2/docfilt.hxx> #include "fltfnc.hxx" #include <sfx2/sfxuno.hxx> #include <sfx2/objsh.hxx> using namespace ::com::sun::star; // STATIC DATA ----------------------------------------------------------- DBG_NAME(SfxFilter) SfxFilter::SfxFilter( const String &rName, const String &rWildCard, SfxFilterFlags nType, sal_uInt32 lFmt, const String &rTypNm, sal_uInt16 nIcon, const String &rMimeType, const String &rUsrDat, const String &rServiceName ): aWildCard(rWildCard, ';'), lFormat(lFmt), aTypeName(rTypNm), aUserData(rUsrDat), nFormatType(nType), nDocIcon(nIcon), aServiceName( rServiceName ), aMimeType( rMimeType ), aFilterName( rName ) { String aExts = GetWildcard()(); String aShort, aLong; String aRet; sal_uInt16 nMaxLength = USHRT_MAX; String aTest; sal_uInt16 nPos = 0; while( ( aRet = aExts.GetToken( nPos++, ';' ) ).Len() ) { aTest = aRet; aTest.SearchAndReplace( DEFINE_CONST_UNICODE( "*." ), String() ); if( aTest.Len() <= nMaxLength ) { if( aShort.Len() ) aShort += ';'; aShort += aRet; } else { if( aLong.Len() ) aLong += ';'; aLong += aRet; } } if( aShort.Len() && aLong.Len() ) { aShort += ';'; aShort += aLong; } aWildCard = aShort; nVersion = SOFFICE_FILEFORMAT_50; aUIName = aFilterName; } SfxFilter::~SfxFilter() { } String SfxFilter::GetDefaultExtension() const { return GetWildcard()().GetToken( 0, ';' ); } String SfxFilter::GetSuffixes() const { String aRet = GetWildcard()(); while( aRet.SearchAndReplaceAscii( "*.", String() ) != STRING_NOTFOUND ) ; while( aRet.SearchAndReplace( ';', ',' ) != STRING_NOTFOUND ) ; return aRet; } const SfxFilter* SfxFilter::GetDefaultFilter( const String& rName ) { return SfxFilterContainer::GetDefaultFilter_Impl( rName ); } const SfxFilter* SfxFilter::GetDefaultFilterFromFactory( const String& rFact ) { return GetDefaultFilter( SfxObjectShell::GetServiceNameFromFactory( rFact ) ); } const SfxFilter* SfxFilter::GetFilterByName( const String& rName ) { SfxFilterMatcher aMatch; return aMatch.GetFilter4FilterName( rName, 0, 0 ); } String SfxFilter::GetTypeFromStorage( const SotStorage& rStg ) { const char* pType=0; if ( rStg.IsStream( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "WordDocument" ) ) ) ) { if ( rStg.IsStream( String::CreateFromAscii("0Table" ) ) || rStg.IsStream( String::CreateFromAscii("1Table" ) ) ) pType = "writer_MS_Word_97"; else pType = "writer_MS_Word_95"; } else if ( rStg.IsStream( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "Book" ) ) ) ) { pType = "calc_MS_Excel_95"; } else if ( rStg.IsStream( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "Workbook" ) ) ) ) { pType = "calc_MS_Excel_97"; } else if ( rStg.IsStream( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "PowerPoint Document" ) ) ) ) { pType = "impress_MS_PowerPoint_97"; } else if ( rStg.IsStream( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "Equation Native" ) ) ) ) { pType = "math_MathType_3x"; } else { sal_Int32 nClipId = ((SotStorage&)rStg).GetFormat(); if ( nClipId ) { const SfxFilter* pFilter = SfxFilterMatcher().GetFilter4ClipBoardId( nClipId ); if ( pFilter ) return pFilter->GetTypeName(); } } return pType ? String::CreateFromAscii(pType) : String(); } String SfxFilter::GetTypeFromStorage( const com::sun::star::uno::Reference< com::sun::star::embed::XStorage >& xStorage, sal_Bool bTemplate, String* pFilterName ) throw ( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException ) { SfxFilterMatcher aMatcher; const char* pType=0; String aName; if ( pFilterName ) { aName = *pFilterName; pFilterName->Erase(); } com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet > xProps( xStorage, com::sun::star::uno::UNO_QUERY ); if ( xProps.is() ) { ::rtl::OUString aMediaType; xProps->getPropertyValue( ::rtl::OUString::createFromAscii( "MediaType" ) ) >>= aMediaType; if ( aMediaType.getLength() ) { ::com::sun::star::datatransfer::DataFlavor aDataFlavor; aDataFlavor.MimeType = aMediaType; sal_uInt32 nClipId = SotExchange::GetFormat( aDataFlavor ); if ( nClipId ) { SfxFilterFlags nMust = SFX_FILTER_IMPORT, nDont = SFX_FILTER_NOTINSTALLED; if ( bTemplate ) // template filter was preselected, try to verify nMust |= SFX_FILTER_TEMPLATEPATH; else // template filters shouldn't be detected if not explicitly asked for nDont |= SFX_FILTER_TEMPLATEPATH; const SfxFilter* pFilter = 0; if ( aName.Len() ) // get preselected Filter if it matches the desired filter flags pFilter = aMatcher.GetFilter4FilterName( aName, nMust, nDont ); if ( !pFilter || pFilter->GetFormat() != nClipId ) { // get filter from storage MediaType pFilter = aMatcher.GetFilter4ClipBoardId( nClipId, nMust, nDont ); if ( !pFilter ) // template filter is asked for , but there isn't one; so at least the "normal" format should be detected // or storage *is* a template, but bTemplate is not set pFilter = aMatcher.GetFilter4ClipBoardId( nClipId ); } if ( pFilter ) { if ( pFilterName ) *pFilterName = pFilter->GetName(); return pFilter->GetTypeName(); } } } } //TODO: do it without SfxFilter //TODO/LATER: don't yield FilterName, should be done in FWK! String aRet; if ( pType ) { aRet = String::CreateFromAscii(pType); if ( pFilterName ) *pFilterName = aMatcher.GetFilter4EA( aRet )->GetName(); } return aRet; }
3,276
852
# PYTHON configuration file for class: JetCorExample # Description: Example of simple EDAnalyzer for correcting jets on the fly. # Author: <NAME> # Date: 02 - September - 2009 import FWCore.ParameterSet.Config as cms process = cms.Process("Ana") process.load("FWCore.MessageService.MessageLogger_cfi") ############# Set the number of events ############# process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) ) ############# Define the source file ############### process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring('/store/relval/CMSSW_3_1_2/RelValQCD_FlatPt_15_3000/GEN-SIM-RECO/MC_31X_V3-v1/0007/9E83A122-E978-DE11-9D04-001D09F23C73.root') ) ############# Include the jet corrections ########## process.load("JetMETCorrections.Configuration.L2L3Corrections_Summer09_cff") # set the record's IOV. Must be defined once. Choose ANY correction service. # process.prefer("L2L3JetCorrectorSC5Calo") ############# Correct Calo Jets on the fly ######### process.calo = cms.EDAnalyzer("CaloJetCorExample", JetAlgorithm = cms.string('sisCone5CaloJets'), HistoFileName = cms.string('CaloJetCorOnTheFlyExample_SC5Calo.root'), JetCorrectionService = cms.string('L2L3JetCorrectorSC5Calo') ) ############# Correct PF Jets on the fly ######### process.calo = cms.EDAnalyzer("PFJetCorExample", JetAlgorithm = cms.string('sisCone5PFJets'), HistoFileName = cms.string('PFJetCorOnTheFlyExample_SC5PF.root'), JetCorrectionService = cms.string('L2L3JetCorrectorSC5PF') ) ############# Path ########################### process.p = cms.Path(process.calo) ############# Format MessageLogger ################# process.MessageLogger.cerr.FwkReport.reportEvery = 10
654
2,168
{ "name": "playground", "version": "0.1.0", "description": "tera playground", "main": "index.js", "scripts": { "build": "rm -rf static/playground && webpack", "build:prod": "rm -rf static/playground && webpack --production", "start": "webpack-dev-server" }, "author": "<NAME> <<EMAIL>>", "license": "(MIT OR Apache-2.0)", "homepage": "https://tera.netlify.app/", "dependencies": { "tera-web": "file:playground/pkg/" }, "devDependencies": { "webpack": "^4.29.3", "webpack-cli": "^3.1.0", "webpack-dev-server": "^3.1.5" } }
249
306
# Copyright 2013 Google Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This service module provides various resident Workers within the application. """ import logging from support.modeling import * from lask import core import lask.services.services_model class CacheWorker(object): WORKER_GUID = 'cache.weblab' @classmethod def get(cls, task): """ Called by Task.create_Task() whenever a new task is created. This method will return the task with any appropriate modifications. """ m_name = 'get_%s_task' % (task.topic_name) if hasattr(cls, m_name): m_attr = getattr(cls, m_name) if callable(m_attr): return m_attr(task) return None @classmethod def put(cls, task): """ Called by Task.stop() when a task is completed so that it may be cached. """ logging.info('CacheWorker.put') m_name = 'put_%s_task' % (task.topic_name) if hasattr(cls, m_name): m_attr = getattr(cls, m_name) if callable(m_attr): return m_attr(task) return None ############################################################## # # caching for traceroute topic # @classmethod def traceroute_cache_key_name(cls, task, destination): key_name = '%s_%s' % (task.kind(), destination) return key_name @classmethod def get_traceroute_task(cls, task): """ Try to retrieve a cached traceroute result. """ logging.info('get_traceroute_task') if task.payload is not None and 'destination' in task.payload: key_name = CacheWorker.traceroute_cache_key_name(task, task.payload['destination']) logging.info(key_name) o = lask.services.services_model.CloudworkerTaskResultCache.get_by_key_name(key_name) if o is not None: payload = task.payload payload['route'] = o.payload_patch task._impl_stop( CacheWorker.WORKER_GUID, 'Finished from cache', payload, o.is_success) task.is_cached = True return task return None @classmethod def put_traceroute_task(cls, task): """ Try to store a traceroute result. """ logging.info('put_traceroute_task: %s' % (task)) # logging.info('a:'+str(task.payload is not None)) # logging.info('a:'+str('destination' in task.payload)) # logging.info('a:'+str('route' in task.payload)) if task.payload is not None and 'destination' in task.payload and 'route' in task.payload: key_name = CacheWorker.traceroute_cache_key_name(task, task.payload['destination']) o = lask.services.services_model.CloudworkerTaskResultCache( key_name = key_name, payload_patch = task.payload['route'], is_success = task.state == core.model.TaskStateProperty.STOPPED_SUCCESS ) o.put() logging.info('Successfully cached %s' % (key_name)) logging.info(o.payload_patch)
1,723
4,879
#include "pugixml.hpp" #include <iostream> int main() { // tag::code[] pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file("tree.xml"); std::cout << "Load result: " << result.description() << ", mesh name: " << doc.child("mesh").attribute("name").value() << std::endl; // end::code[] } // vim:et
129
1,483
<gh_stars>1000+ /* * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.lealone.storage.fs; import java.io.EOFException; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.NonWritableChannelException; import org.lealone.db.SysProperties; /** * This file system stores files on disk and uses java.nio to access the files. * This class used memory mapped files. */ public class FilePathNioMapped extends FilePathNio { @Override public FileChannel open(String mode) throws IOException { return new FileNioMapped(name.substring(getScheme().length() + 1), mode); } @Override public String getScheme() { return "nioMapped"; } } /** * Uses memory mapped files. * The file size is limited to 2 GB. */ class FileNioMapped extends FileBase { private static final long GC_TIMEOUT_MS = 10000; private final String name; private final MapMode mode; private RandomAccessFile file; private MappedByteBuffer mapped; private long fileLength; /** * The position within the file. Can't use the position of the mapped buffer * because it doesn't support seeking past the end of the file. */ private int pos; FileNioMapped(String fileName, String mode) throws IOException { if ("r".equals(mode)) { this.mode = MapMode.READ_ONLY; } else { this.mode = MapMode.READ_WRITE; } this.name = fileName; file = new RandomAccessFile(fileName, mode); reMap(); } private void unMap() throws IOException { if (mapped == null) { return; } // first write all data mapped.force(); // need to dispose old direct buffer, see bug // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038 boolean useSystemGc = true; if (SysProperties.NIO_CLEANER_HACK) { try { Method cleanerMethod = mapped.getClass().getMethod("cleaner"); cleanerMethod.setAccessible(true); Object cleaner = cleanerMethod.invoke(mapped); if (cleaner != null) { Method clearMethod = cleaner.getClass().getMethod("clean"); clearMethod.invoke(cleaner); } useSystemGc = false; } catch (Throwable e) { // useSystemGc is already true } finally { mapped = null; } } if (useSystemGc) { WeakReference<MappedByteBuffer> bufferWeakRef = new WeakReference<MappedByteBuffer>(mapped); mapped = null; long start = System.currentTimeMillis(); while (bufferWeakRef.get() != null) { if (System.currentTimeMillis() - start > GC_TIMEOUT_MS) { throw new IOException( "Timeout (" + GC_TIMEOUT_MS + " ms) reached while trying to GC mapped buffer"); } System.gc(); Thread.yield(); } } } /** * Re-map byte buffer into memory, called when file size has changed or file * was created. */ private void reMap() throws IOException { int oldPos = 0; if (mapped != null) { oldPos = pos; unMap(); } fileLength = file.length(); checkFileSizeLimit(fileLength); // maps new MappedByteBuffer; the old one is disposed during GC mapped = file.getChannel().map(mode, 0, fileLength); int limit = mapped.limit(); int capacity = mapped.capacity(); if (limit < fileLength || capacity < fileLength) { throw new IOException("Unable to map: length=" + limit + " capacity=" + capacity + " length=" + fileLength); } if (SysProperties.NIO_LOAD_MAPPED) { mapped.load(); } this.pos = Math.min(oldPos, (int) fileLength); } private static void checkFileSizeLimit(long length) throws IOException { if (length > Integer.MAX_VALUE) { throw new IOException("File over 2GB is not supported yet when using this file system"); } } @Override public void implCloseChannel() throws IOException { if (file != null) { unMap(); file.close(); file = null; } } @Override public long position() { return pos; } @Override public String toString() { return "nioMapped:" + name; } @Override public synchronized long size() throws IOException { return fileLength; } @Override public synchronized int read(ByteBuffer dst) throws IOException { try { int len = dst.remaining(); if (len == 0) { return 0; } len = (int) Math.min(len, fileLength - pos); if (len <= 0) { return -1; } mapped.position(pos); mapped.get(dst.array(), dst.arrayOffset() + dst.position(), len); dst.position(dst.position() + len); pos += len; return len; } catch (IllegalArgumentException e) { EOFException e2 = new EOFException("EOF"); e2.initCause(e); throw e2; } catch (BufferUnderflowException e) { EOFException e2 = new EOFException("EOF"); e2.initCause(e); throw e2; } } @Override public FileChannel position(long pos) throws IOException { checkFileSizeLimit(pos); this.pos = (int) pos; return this; } @Override public synchronized FileChannel truncate(long newLength) throws IOException { // compatibility with JDK FileChannel#truncate if (mode == MapMode.READ_ONLY) { throw new NonWritableChannelException(); } if (newLength < size()) { setFileLength(newLength); } return this; } public synchronized void setFileLength(long newLength) throws IOException { checkFileSizeLimit(newLength); int oldPos = pos; unMap(); for (int i = 0;; i++) { try { file.setLength(newLength); break; } catch (IOException e) { if (i > 16 || e.toString().indexOf("user-mapped section open") < 0) { throw e; } } System.gc(); } reMap(); pos = (int) Math.min(newLength, oldPos); } @Override public void force(boolean metaData) throws IOException { mapped.force(); file.getFD().sync(); } @Override public synchronized int write(ByteBuffer src) throws IOException { int len = src.remaining(); // check if need to expand file if (mapped.capacity() < pos + len) { setFileLength(pos + len); } mapped.position(pos); mapped.put(src); pos += len; return len; } @Override public synchronized FileLock tryLock(long position, long size, boolean shared) throws IOException { return file.getChannel().tryLock(position, size, shared); } }
3,431
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.php.dbgp; import java.util.List; import org.netbeans.api.debugger.DebuggerManagerAdapter; import org.netbeans.api.debugger.Session; import org.netbeans.modules.php.dbgp.actions.KillActionProvider; import org.netbeans.spi.debugger.ActionsProvider; /** * @author ads * */ public class SessionListener extends DebuggerManagerAdapter { @Override public void sessionAdded(Session session) { if (session.lookupFirst(null, SessionId.class) == null) { return; } SessionProgress progress = SessionProgress.forSession(session); progress.start(); List list = session.lookup(null, ActionsProvider.class); boolean found = false; for (Object object : list) { if (object instanceof KillActionProvider) { ((KillActionProvider) object).setEnabled(true); found = true; } } assert found; } @Override public void sessionRemoved(Session session) { super.sessionRemoved(session); SessionProgress progress = SessionProgress.forSession(session); progress.finish(); } }
647
372
<reponame>ucsf-ckm/geddify<gh_stars>100-1000 (int)(long)&((struct stringpool_t *)0)->stringpool_str275, (int)(long)&((struct stringpool_t *)0)->stringpool_str465,
71
354
<reponame>muehleisen/OpenStudio /*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. 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 any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #include "../ForwardTranslator.hpp" #include "../../model/CoilSystemIntegratedHeatPumpAirSource.hpp" #include "../../model/CoilSystemIntegratedHeatPumpAirSource_Impl.hpp" #include "../../model/Model.hpp" #include <utilities/idd/CoilSystem_IntegratedHeatPump_AirSource_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> #include <utilities/idd/IddFactory.hxx> using namespace openstudio::model; using namespace std; namespace openstudio { namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translateCoilSystemIntegratedHeatPumpAirSource(CoilSystemIntegratedHeatPumpAirSource& modelObject) { IdfObject idfObject(IddObjectType::CoilSystem_IntegratedHeatPump_AirSource); m_idfObjects.push_back(idfObject); // Name if (auto s = modelObject.name()) { idfObject.setName(*s); } boost::optional<std::string> s; boost::optional<double> value; boost::optional<int> i; // Space Cooling Coil Name boost::optional<IdfObject> _spaceCoolingCoil; auto spaceCoolingCoil = modelObject.spaceCoolingCoil(); if ((_spaceCoolingCoil = translateAndMapModelObject(spaceCoolingCoil))) { idfObject.setString(CoilSystem_IntegratedHeatPump_AirSourceFields::SpaceCoolingCoilName, _spaceCoolingCoil->name().get()); } // Space Heating Coil Name boost::optional<IdfObject> _spaceHeatingCoil; auto spaceHeatingCoil = modelObject.spaceHeatingCoil(); if ((_spaceHeatingCoil = translateAndMapModelObject(spaceHeatingCoil))) { idfObject.setString(CoilSystem_IntegratedHeatPump_AirSourceFields::SpaceHeatingCoilName, _spaceHeatingCoil->name().get()); } // Dedicated Water Heating Coil Name boost::optional<IdfObject> _dedicatedWaterHeatingCoil; auto dedicatedWaterHeatingCoil = modelObject.dedicatedWaterHeatingCoil(); if ((_dedicatedWaterHeatingCoil = translateAndMapModelObject(dedicatedWaterHeatingCoil))) { idfObject.setString(CoilSystem_IntegratedHeatPump_AirSourceFields::DedicatedWaterHeatingCoilName, _dedicatedWaterHeatingCoil->name().get()); } // SCWH Coil Name boost::optional<IdfObject> _scwhCoil; auto scwhCoil = modelObject.scwhCoil(); if ((_scwhCoil = translateAndMapModelObject(scwhCoil))) { idfObject.setString(CoilSystem_IntegratedHeatPump_AirSourceFields::SCWHCoilName, _scwhCoil->name().get()); } // SCDWH Cooling Coil Name boost::optional<IdfObject> _scdwhCoolingCoil; auto scdwhCoolingCoil = modelObject.scdwhCoolingCoil(); if ((_scdwhCoolingCoil = translateAndMapModelObject(scdwhCoolingCoil))) { idfObject.setString(CoilSystem_IntegratedHeatPump_AirSourceFields::SCDWHCoolingCoilName, _scdwhCoolingCoil->name().get()); } // SCDWH Water Heating Coil Name boost::optional<IdfObject> _scdwhWaterHeatingCoil; auto scdwhWaterHeatingCoil = modelObject.scdwhWaterHeatingCoil(); if ((_scdwhWaterHeatingCoil = translateAndMapModelObject(scdwhWaterHeatingCoil))) { idfObject.setString(CoilSystem_IntegratedHeatPump_AirSourceFields::SCDWHWaterHeatingCoilName, _scdwhWaterHeatingCoil->name().get()); } // SHDWH Heating Coil Name boost::optional<IdfObject> _shdwhHeatingCoil; auto shdwhHeatingCoil = modelObject.shdwhHeatingCoil(); if ((_shdwhHeatingCoil = translateAndMapModelObject(shdwhHeatingCoil))) { idfObject.setString(CoilSystem_IntegratedHeatPump_AirSourceFields::SHDWHHeatingCoilName, _shdwhHeatingCoil->name().get()); } // SHDWH Water Heating Coil Name boost::optional<IdfObject> _shdwhWaterHeatingCoil; auto shdwhWaterHeatingCoil = modelObject.shdwhWaterHeatingCoil(); if ((_shdwhWaterHeatingCoil = translateAndMapModelObject(shdwhWaterHeatingCoil))) { idfObject.setString(CoilSystem_IntegratedHeatPump_AirSourceFields::SHDWHWaterHeatingCoilName, _shdwhWaterHeatingCoil->name().get()); } // Indoor Temperature Limit for SCWH Mode if ((value = modelObject.indoorTemperatureLimitForSCWHMode())) { idfObject.setDouble(CoilSystem_IntegratedHeatPump_AirSourceFields::IndoorTemperatureLimitforSCWHMode, value.get()); } // Ambient Temperature Limit for SCWH Mode if ((value = modelObject.ambientTemperatureLimitForSCWHMode())) { idfObject.setDouble(CoilSystem_IntegratedHeatPump_AirSourceFields::AmbientTemperatureLimitforSCWHMode, value.get()); } // Indoor Temperature above Which WH has Higher Priority if ((value = modelObject.indoorTemperatureAboveWhichWHHasHigherPriority())) { idfObject.setDouble(CoilSystem_IntegratedHeatPump_AirSourceFields::IndoorTemperatureaboveWhichWHhasHigherPriority, value.get()); } // Ambient Temperature above Which WH has Higher Priority if ((value = modelObject.ambientTemperatureAboveWhichWHHasHigherPriority())) { idfObject.setDouble(CoilSystem_IntegratedHeatPump_AirSourceFields::AmbientTemperatureaboveWhichWHhasHigherPriority, value.get()); } // Flag to Indicate Load Control in SCWH Mode if ((i = modelObject.flagtoIndicateLoadControlInSCWHMode())) { idfObject.setInt(CoilSystem_IntegratedHeatPump_AirSourceFields::FlagtoIndicateLoadControlinSCWHMode, i.get()); } // Minimum Speed Level for SCWH Mode if ((i = modelObject.minimumSpeedLevelForSCWHMode())) { idfObject.setInt(CoilSystem_IntegratedHeatPump_AirSourceFields::MinimumSpeedLevelforSCWHMode, i.get()); } // Maximum Water Flow Volume before Switching from SCDWH to SCWH Mode if ((value = modelObject.maximumWaterFlowVolumeBeforeSwitchingfromSCDWHtoSCWHMode())) { idfObject.setDouble(CoilSystem_IntegratedHeatPump_AirSourceFields::MaximumWaterFlowVolumebeforeSwitchingfromSCDWHtoSCWHMode, value.get()); } // Minimum Speed Level for SCDWH Mode if ((i = modelObject.minimumSpeedLevelForSCDWHMode())) { idfObject.setInt(CoilSystem_IntegratedHeatPump_AirSourceFields::MinimumSpeedLevelforSCDWHMode, i.get()); } // Maximum Running Time before Allowing Electric Resistance Heat Use during SHDWH Mode if ((value = modelObject.maximumRunningTimeBeforeAllowingElectricResistanceHeatUseDuringSHDWHMode())) { idfObject.setDouble(CoilSystem_IntegratedHeatPump_AirSourceFields::MaximumRunningTimebeforeAllowingElectricResistanceHeatUseduringSHDWHMode, value.get()); } // Minimum Speed Level for SHDWH Mode if ((i = modelObject.minimumSpeedLevelForSHDWHMode())) { idfObject.setInt(CoilSystem_IntegratedHeatPump_AirSourceFields::MinimumSpeedLevelforSHDWHMode, i.get()); } return idfObject; } } // namespace energyplus } // namespace openstudio
2,938
817
<gh_stars>100-1000 """tests.""" import os import csv from ntc_templates.parse import _get_template_dir def load_index_data(): """Load data from index file.""" with open("{0}{1}index".format(_get_template_dir(), os.sep)) as indexfs: data = csv.reader(indexfs) return [row for row in data if len(row) > 2 and row[0] != "Template"]
140
2,406
<gh_stars>1000+ // Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include "openvino/opsets/opset8.hpp" #include "openvino/pass/serialize.hpp" #include "read_ir.hpp" #include "util/graph_comparator.hpp" #include "util/test_common.hpp" class TensorNameSerializationTest : public ov::test::TestsCommon { protected: std::string test_name = GetTestName() + "_" + GetTimestamp(); std::string m_out_xml_path = test_name + ".xml"; std::string m_out_bin_path = test_name + ".bin"; void TearDown() override { std::remove(m_out_xml_path.c_str()); std::remove(m_out_bin_path.c_str()); } }; TEST_F(TensorNameSerializationTest, SerializeFunctionWithTensorNames) { std::shared_ptr<ngraph::Function> function; { auto parameter = std::make_shared<ov::opset8::Parameter>(ngraph::element::Type_t::f32, ngraph::Shape{1, 3, 10, 10}); parameter->set_friendly_name("parameter"); parameter->get_output_tensor(0).set_names({"input"}); auto relu_prev = std::make_shared<ov::opset8::Relu>(parameter); relu_prev->set_friendly_name("relu_prev"); relu_prev->get_output_tensor(0).set_names({"relu_prev_t", "identity_prev_t"}); auto relu = std::make_shared<ov::opset8::Relu>(relu_prev); relu->set_friendly_name("relu"); relu->get_output_tensor(0).set_names({"relu,t", "identity"}); const ngraph::ResultVector results{std::make_shared<ov::opset8::Result>(relu)}; results[0]->set_friendly_name("out"); ngraph::ParameterVector params{parameter}; function = std::make_shared<ngraph::Function>(results, params, "TensorNames"); } ov::pass::Serialize(m_out_xml_path, m_out_bin_path).run_on_function(function); auto result = ov::test::readIR(m_out_xml_path, m_out_bin_path); const auto fc = FunctionsComparator::with_default() .enable(FunctionsComparator::ATTRIBUTES) .enable(FunctionsComparator::CONST_VALUES); const auto res = fc.compare(result, function); EXPECT_TRUE(res.valid) << res.message; }
923
357
/* * Copyright (c) 2012-2015 VMware, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, without * warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the * License for the specific language governing permissions and limitations * under the License. */ package com.vmware.identity.interop.directory; import com.sun.jna.ptr.PointerByReference; import com.sun.jna.ptr.IntByReference; public interface IDirectoryClientLibrary { void CreateServiceProviderInstance( String domainName, String administratorId, String password ); void CreateDirectoryInstance( String domainName, String administratorId, String password ); void CreateDirectoryInstanceRemote( String hostname, String domainName, String administratorId, String password ); void DeleteDirectoryInstance( String domainName, String administratorId, String password ); void DeleteDirectoryInstanceRemote( String hostname, String domainName, String administratorId, String password ); void SetPassword( String hostURI, String adminDN, String adminPassword, String userDN, String newPassword ); void ChangePassword( String hostURI, String userDN, String oldPassword, String newPassword ); String GeneratePassword( String hostURI, String upn, String pasword ); String ResetAccountPassword( String hostURI, String domainName, String accountUPN, String accountDN, String currentPwd, boolean bForceRefresh ); String GetLocalLduGuid(); void GetReplicationPartners( String hostName, String port, String userName, String password, PointerByReference replPartnerInfo, IntByReference numReplPartner ); void GetServers( String hostName, String port, String userName, String password, PointerByReference serverInfo, IntByReference numReplServer ); void AddReplicationAgreement ( int twoWayRepl, String srcHostName, String srcPort, String srcUserName, String srcPassword, String tgtHostName, String tgtPort, String tgtUserName, String tgtPassword ); void RemoveReplicationAgreement ( int twoWayRepl, String srcHostName, String srcPort, String srcUserName, String srcPassword, String tgtHostName, String tgtPort, String tgtUserName, String tgtPassword ); }
1,634
678
<reponame>bzxy/cydia /** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/DataAccess.framework/Frameworks/DAEAS.framework/DAEAS */ #import <DAEAS/XXUnknownSuperclass.h> @class NSString, ASEventUID; @interface ASMeetingResponseItem : XXUnknownSuperclass { NSString *_emailItemFolderId; // 4 = 0x4 NSString *_emailItemServerId; // 8 = 0x8 int _meetingResponse; // 12 = 0xc ASEventUID *_eventUID; // 16 = 0x10 NSString *_calEventServerId; // 20 = 0x14 int _status; // 24 = 0x18 id _context; // 28 = 0x1c } @property(retain) id context; // G=0x770d; S=0x7721; @synthesize=_context @property(assign) int status; // G=0x76ed; S=0x76fd; @synthesize=_status @property(retain) NSString *calEventServerId; // G=0x76b5; S=0x76c9; @synthesize=_calEventServerId @property(readonly, assign) ASEventUID *eventUID; // G=0x76a5; @synthesize=_eventUID @property(readonly, assign) int meetingResponse; // G=0x7695; @synthesize=_meetingResponse @property(readonly, assign) NSString *emailItemServerId; // G=0x7685; @synthesize=_emailItemServerId @property(readonly, assign) NSString *emailItemFolderId; // G=0x7675; @synthesize=_emailItemFolderId // declared property setter: - (void)setContext:(id)context; // 0x7721 // declared property getter: - (id)context; // 0x770d // declared property setter: - (void)setStatus:(int)status; // 0x76fd // declared property getter: - (int)status; // 0x76ed // declared property setter: - (void)setCalEventServerId:(id)anId; // 0x76c9 // declared property getter: - (id)calEventServerId; // 0x76b5 // declared property getter: - (id)eventUID; // 0x76a5 // declared property getter: - (int)meetingResponse; // 0x7695 // declared property getter: - (id)emailItemServerId; // 0x7685 // declared property getter: - (id)emailItemFolderId; // 0x7675 - (void)dealloc; // 0x75d9 - (id)description; // 0x7511 - (id)initWithEmailItemFolderId:(id)emailItemFolderId emailItemServerId:(id)anId meetingResponse:(int)response eventUID:(id)uid; // 0x746d @end
777
307
<gh_stars>100-1000 # automatically generated by the FlatBuffers compiler, do not modify # namespace: FBOutput import tdw.flatbuffers class MagnebotWheels(object): __slots__ = ['_tab'] @classmethod def GetRootAsMagnebotWheels(cls, buf, offset): n = tdw.flatbuffers.encode.Get(tdw.flatbuffers.packer.uoffset, buf, offset) x = MagnebotWheels() x.Init(buf, n + offset) return x # MagnebotWheels def Init(self, buf, pos): self._tab = tdw.flatbuffers.table.Table(buf, pos) # MagnebotWheels def Id(self): o = tdw.flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: return self._tab.Get(tdw.flatbuffers.number_types.Int32Flags, o + self._tab.Pos) return 0 # MagnebotWheels def Success(self): o = tdw.flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) if o != 0: return bool(self._tab.Get(tdw.flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) return False def MagnebotWheelsStart(builder): builder.StartObject(2) def MagnebotWheelsAddId(builder, id): builder.PrependInt32Slot(0, id, 0) def MagnebotWheelsAddSuccess(builder, success): builder.PrependBoolSlot(1, success, 0) def MagnebotWheelsEnd(builder): return builder.EndObject()
562
2,113
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- #include "sfx/null/sfxNullDevice.h" #include "sfx/null/sfxNullBuffer.h" #include "sfx/sfxInternal.h" SFXNullDevice::SFXNullDevice( SFXProvider* provider, String name, bool useHardware, S32 maxBuffers ) : SFXDevice( name, provider, useHardware, maxBuffers ) { mMaxBuffers = getMax( maxBuffers, 8 ); } SFXNullDevice::~SFXNullDevice() { } SFXBuffer* SFXNullDevice::createBuffer( const ThreadSafeRef< SFXStream >& stream, SFXDescription* description ) { SFXNullBuffer* buffer = new SFXNullBuffer( stream, description ); _addBuffer( buffer ); return buffer; } SFXVoice* SFXNullDevice::createVoice( bool is3D, SFXBuffer *buffer ) { // Don't bother going any further if we've // exceeded the maximum voices. if ( mVoices.size() >= mMaxBuffers ) return NULL; AssertFatal( buffer, "SFXNullDevice::createVoice() - Got null buffer!" ); SFXNullBuffer* nullBuffer = dynamic_cast<SFXNullBuffer*>( buffer ); AssertFatal( nullBuffer, "SFXNullDevice::createVoice() - Got bad buffer!" ); SFXNullVoice* voice = new SFXNullVoice( nullBuffer ); _addVoice( voice ); return voice; } void SFXNullDevice::update() { // Do nothing. Prevent SFXDevice from running // its thing. }
810
5,937
<filename>src/Microsoft.DotNet.Wpf/src/WpfGfx/core/meta/metabitmaprt.cpp<gh_stars>1000+ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //+----------------------------------------------------------------------------- // // // $TAG ENGR // $Module: win_mil_graphics_targets // $Keywords: // // $Description: // CMetaBitmapRenderTarget implementation // // This is a multiple or meta Render Target for rendering on multiple // offscreen surfaces. This is also a meta Bitmap Source that holds // references to IWGXBitmapSources specific to the sub Render Targets. // // $ENDTAG // //------------------------------------------------------------------------------ #include "precomp.hpp" MtDefine(CMetaBitmapRenderTarget, MILRender, "CMetaBitmapRenderTarget"); //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::operator new // // Synopsis: // Allocate memory for one rendertarget, plus additional memory for each // sub-render target // //------------------------------------------------------------------------------ void * __cdecl CMetaBitmapRenderTarget::operator new( size_t cb, // bytes of memory to allocate for render target size_t cRTs // number of sub-render targets ) { HRESULT hr = S_OK; void *pBuffer = NULL; size_t cbBufferSize = 0; IFC(SizeTMult(cRTs, sizeof(MetaData), &cbBufferSize)); IFC(SizeTAdd(cbBufferSize, cb, &cbBufferSize)); pBuffer = WPFAlloc( ProcessHeap, Mt(CMetaBitmapRenderTarget), cbBufferSize ); Cleanup: return pBuffer; } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::Create // // Synopsis: // Create a CMetaBitmapRenderTarget // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::Create( UINT uWidth, // Width of render targets UINT uHeight, // Height of render targets UINT cRTs, // Count of render targets __in_ecount(cRTs) MetaData *pMetaData, // Array of render target data __in_ecount(1) CDisplaySet const *pDisplaySet, IntermediateRTUsage usageInfo, MilRTInitialization::Flags dwFlags, __deref_out_ecount(1) CMetaBitmapRenderTarget **ppMetaRT // Location to return object pointer ) { HRESULT hr = S_OK; *ppMetaRT = NULL; // // Create the CMetaBitmapRenderTarget // *ppMetaRT = new(cRTs) CMetaBitmapRenderTarget(cRTs, pDisplaySet); IFCOOM(*ppMetaRT); (*ppMetaRT)->AddRef(); // CMetaBitmapRenderTarget::ctor sets ref count == 0 // // Call Init // IFC((*ppMetaRT)->Init( uWidth, uHeight, usageInfo, dwFlags, pMetaData )); Cleanup: if (FAILED(hr)) { ReleaseInterface(*ppMetaRT); } RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::CMetaBitmapRenderTarget // // Synopsis: // ctor // //------------------------------------------------------------------------------ #pragma warning( push ) #pragma warning( disable : 4355 ) CMetaBitmapRenderTarget::CMetaBitmapRenderTarget( UINT cMaxRTs, __inout_ecount(1) CDisplaySet const *pDisplaySet ) : CMetaRenderTarget( reinterpret_cast<MetaData *>(reinterpret_cast<BYTE *>(this) + sizeof(*this)), cMaxRTs, pDisplaySet ) { } #pragma warning( pop ) //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::~CMetaBitmapRenderTarget // // Synopsis: // dtor // //------------------------------------------------------------------------------ CMetaBitmapRenderTarget::~CMetaBitmapRenderTarget() { for (UINT i = 0; i < m_cRT; i++) { ReleaseInterface(m_rgMetaData[i].pIRTBitmap); } } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::HrFindInterface // // Synopsis: // HrFindInterface implementation // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::HrFindInterface( __in_ecount(1) REFIID riid, __deref_out void **ppvObject ) { HRESULT hr = E_INVALIDARG; if (ppvObject) { if (riid == IID_IMILRenderTargetBitmap) { *ppvObject = static_cast<IMILRenderTargetBitmap*>(this); hr = S_OK; } else if (riid == IID_IWGXBitmapSource) { *ppvObject = static_cast<IWGXBitmapSource*>(this); hr = S_OK; } else if (riid == IID_CMetaBitmapRenderTarget) { *ppvObject = this; hr = S_OK; } else { hr = CMetaRenderTarget::HrFindInterface(riid, ppvObject); } } return hr; } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::Init // // Synopsis: // Inits the meta render target and allocates the required resources // //------------------------------------------------------------------------------ HRESULT CMetaBitmapRenderTarget::Init( UINT uWidth, UINT uHeight, IntermediateRTUsage usageInfo, MilRTInitialization::Flags dwFlags, __in_xcount(m_cRTs) MetaData const *pMetaData ) { HRESULT hr = S_OK; // // Intialize basic members // m_uWidth = uWidth; m_uHeight = uHeight; // // Create bitmap RTs for each RT and remember // their source bitmaps. // Assert(m_cRT*sizeof(m_rgMetaData[0]) == RtlCompareMemoryUlong(m_rgMetaData, m_cRT*sizeof(m_rgMetaData[0]), 0)); // The width and height are converted to floats when clipping, // make sure we don't expect values TOO big as input. if (uWidth > SURFACE_RECT_MAX || uHeight > SURFACE_RECT_MAX) { IFC(WGXERR_UNSUPPORTEDTEXTURESIZE); } for (UINT i=0; i < m_cRT && SUCCEEDED(hr); i++) { // // Initialize the cache index to invalid. We only want the meta data // object which has a non-null pIRTBitmap to have a valid cache index. // m_rgMetaData[i].cacheIndex = CMILResourceCache::InvalidToken; #if DBG m_rgMetaData[i].uIndexOfRealRTBitmap = UINT_MAX; #endif if (pMetaData[i].fEnable) { ULONG curCacheIndex = pMetaData[i].pInternalRT->GetRealizationCacheIndex(); if (curCacheIndex == CMILResourceCache::InvalidToken) { curCacheIndex = CMILResourceCache::SwRealizationCacheIndex; } // Initialize the index 'pointer' to itself. m_rgMetaData[i].uIndexOfRealRTBitmap = i; // Future Consideration: We may want to revisit this sharing code. If it is cheap to share // textures (i.e. they have the same underlying video card and we have 9EX // devices) we may want to enable that. Currently this is only used in software // mode. // // Search for bitmap RTs created for other displays that we could // share. We allow sharing of RTs when the displays share a device. // [We use the cache index to differentiate devices.] We also allow // sharing of software bitmap render targets- we don't bother to // create hardware render targets when we already have a software // render target avaliable for use. // for (UINT j = 0; j < i; j++) { if ( m_rgMetaData[j].cacheIndex == curCacheIndex || m_rgMetaData[j].cacheIndex == CMILResourceCache::SwRealizationCacheIndex ) { // // Found a match. There is no need to create two identical // render targets so we will 'point' back to the matching // one. // m_rgMetaData[i].uIndexOfRealRTBitmap = j; break; } } if (m_rgMetaData[i].uIndexOfRealRTBitmap != i) { m_rgMetaData[i].cacheIndex = CMILResourceCache::InvalidToken; Assert(m_rgMetaData[i].fEnable == FALSE); } else { MIL_THR(pMetaData[i].pInternalRT->CreateRenderTargetBitmap( uWidth, uHeight, usageInfo, dwFlags, &m_rgMetaData[i].pIRTBitmap )); if (SUCCEEDED(hr)) { #if DBG if (pMetaData[i].pInternalRT->GetRealizationCacheIndex() == CMILResourceCache::InvalidToken) { // // Assert that CreateRenderTargetBitmap created a // software RT. This justifies setting curCacheIndex to // CMILResourceCache::SwRealizationCacheIndex above // Assert(curCacheIndex == CMILResourceCache::SwRealizationCacheIndex); // The DYNCAST does the assert DYNCAST(CSwRenderTargetBitmap, m_rgMetaData[i].pIRTBitmap); } #endif hr = THR(m_rgMetaData[i].pIRTBitmap->QueryInterface( IID_IRenderTargetInternal, (void **)&(m_rgMetaData[i].pInternalRT) )); } if (SUCCEEDED(hr)) { // // Enable rendering to the new RT upon success // m_rgMetaData[i].fEnable = TRUE; // // Set the cache index to the cache index of the newly // created bitmap render target. It is important not to use // the cache index of the original render target, as // hardware render targets are allowed to create software // render targets. // m_rgMetaData[i].cacheIndex = m_rgMetaData[i].pInternalRT->GetRealizationCacheIndex(); // Set the bounds either way Assert(m_rgMetaData[i].rcLocalDeviceRenderBounds.left == 0); Assert(m_rgMetaData[i].rcLocalDeviceRenderBounds.top == 0); m_rgMetaData[i].rcLocalDeviceRenderBounds.right = static_cast<LONG>(uWidth); m_rgMetaData[i].rcLocalDeviceRenderBounds.bottom = static_cast<LONG>(uHeight); m_rgMetaData[i].rcLocalDevicePresentBounds = m_rgMetaData[i].rcLocalDeviceRenderBounds; } } } } Cleanup: RRETURN(hr); } //+======================================================================== // IMILRenderTarget methods //========================================================================= //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetBounds // // Synopsis: // Return accumulated bounds of all render targets // //------------------------------------------------------------------------------ STDMETHODIMP_(VOID) CMetaBitmapRenderTarget::GetBounds( __out_ecount(1) MilRectF * const pBounds ) { CMilRectF rcAcc; rcAcc.SetEmpty(); for (UINT idx = 0; idx < m_cRT; idx++) { // Acuumulate bounds of all RTs as long as there is an RT if (m_rgMetaData[idx].pInternalRT) { m_rgMetaData[idx].pInternalRT->GetBounds(pBounds); rcAcc.Union(*pBounds); } } *pBounds = rcAcc; return; } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::Clear // // Synopsis: // Clear the surface to a given color. // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::Clear( __in_ecount_opt(1) const MilColorF *pColor, __in_ecount_opt(1) const CAliasedClip *pAliasedClip ) { return CMetaRenderTarget::Clear(pColor, pAliasedClip); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::Begin3D, End3D // // Synopsis: // Assert state then delegate to base class // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::Begin3D( __in_ecount(1) MilRectF const &rcBounds, MilAntiAliasMode::Enum AntiAliasMode, bool fUseZBuffer, FLOAT rZ ) { return CMetaRenderTarget::Begin3D(rcBounds, AntiAliasMode, fUseZBuffer, rZ); } STDMETHODIMP CMetaBitmapRenderTarget::End3D( ) { return CMetaRenderTarget::End3D(); } //+======================================================================== // IMILRenderTargetBitmap methods //========================================================================= //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetBitmapSource // // Synopsis: // Return a bitmap source interface to the internal meta bitmap that holds // separate RT specific bitmaps // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetBitmapSource( __deref_out_ecount(1) IWGXBitmapSource ** const ppIBitmapSource ) { Assert(m_rgMetaData); *ppIBitmapSource = this; (*ppIBitmapSource)->AddRef(); return S_OK; } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetCacheableBitmapSource // // Synopsis: // Return a bitmap source interface to the internal meta bitmap that holds // separate RT specific bitmaps // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetCacheableBitmapSource( __deref_out_ecount(1) IWGXBitmapSource ** const ppIBitmapSource ) { // To implement GetCacheableBitmapSource, we would need to go into each // surface bitmap & ensure those bitmaps are cacheable. This functionality // isn't currently supported because CMetaBitmapRenderTarget is not used // by any callers of GetCacheableBitmapSource. *ppIBitmapSource = NULL; RIP("CMetaBitmapRenderTarget::GetCacheableBitmapSource isn't implemented"); RRETURN(E_NOTIMPL); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetBitmap // // Synopsis: // Not implemented // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetBitmap( __deref_out_ecount(1) IWGXBitmap ** const ppIBitmap ) { RRETURN(WGXERR_NOTIMPLEMENTED); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetNumQueuedPresents // // Synopsis: // Forwards call to the CMetaRenderTarget member. // //------------------------------------------------------------------------------ HRESULT CMetaBitmapRenderTarget::GetNumQueuedPresents( __out_ecount(1) UINT *puNumQueuedPresents ) { RRETURN(CMetaRenderTarget::GetNumQueuedPresents(puNumQueuedPresents)); } //+======================================================================== // IWGXBitmapSource methods //========================================================================= //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetSize // // Synopsis: // Get pixel dimensions of bitmap // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetSize( __out_ecount(1) UINT *puWidth, __out_ecount(1) UINT *puHeight ) { *puWidth = m_uWidth; *puHeight = m_uHeight; return S_OK; } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetPixelFormat // // Synopsis: // Get pixel format of bitmap // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetPixelFormat( __out_ecount(1) MilPixelFormat::Enum *pPixelFormat ) { RRETURN(E_ACCESSDENIED); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetResolution // // Synopsis: // Not implemented // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetResolution( __out_ecount(1) double *pDpiX, __out_ecount(1) double *pDpiY ) { RRETURN(E_ACCESSDENIED); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::CopyPalette // // Synopsis: // Not implemented // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::CopyPalette( __inout_ecount(1) IWICPalette *pIPalette ) { RRETURN(E_ACCESSDENIED); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::CopyPixels // // Synopsis: // Access via CopyPixels method is not supported // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::CopyPixels( __in_ecount_opt(1) const MILRect *prc, UINT cbStride, UINT cbBufferSize, __out_ecount(cbBufferSize) BYTE *pvPixels ) { RRETURN(E_ACCESSDENIED); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetSubRenderTargetNoRef // // Synopsis: // Walks the internal render targets, finding the one that matches the // cache index and display id. // // The display id is optional, but if it exists it overrides the cache // index as a lookup mechanism. // // Returns an error if no rendertarget was found. // HRESULT CMetaBitmapRenderTarget::GetCompatibleSubRenderTargetNoRef( IMILResourceCache::ValidIndex uOptimalRealizationCacheIndex, DisplayId targetDestination, __deref_out_ecount(1) IMILRenderTargetBitmap **ppIRenderTargetNoRef ) { HRESULT hr = S_OK; IMILRenderTargetBitmap *pIRenderTargetNoRef = GetCompatibleSubRenderTargetNoRefInternal( uOptimalRealizationCacheIndex, targetDestination ); if (pIRenderTargetNoRef == NULL) { RIPW(L"No internal intermediate render target found matching realization cache index!"); MIL_THR(WGXERR_INTERNALERROR); } *ppIRenderTargetNoRef = pIRenderTargetNoRef; RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetCompatibleSubRenderTargetNoRefInternal // // Synopsis: // Walks the internal render targets, finding the one that matches the // cache index and display id. // // The display id is optional, but if it exists it overrides the cache // index as a lookup mechanism. // __out_ecount_opt(1) IMILRenderTargetBitmap * CMetaBitmapRenderTarget::GetCompatibleSubRenderTargetNoRefInternal( IMILResourceCache::ValidIndex uOptimalRealizationCacheIndex, DisplayId targetDestination ) { // PREfast should catch violations, but doesn't seem to today - so assert Assert(uOptimalRealizationCacheIndex != CMILResourceCache::InvalidToken); IMILRenderTargetBitmap *pIRenderTargetNoRef = NULL; if (targetDestination.IsNone()) { IMILResourceCache::ValidIndex uRealizationCacheIndexToLookFor = uOptimalRealizationCacheIndex; LookAgain: for (UINT i = 0; i < m_cRT; i++) { if (m_rgMetaData[i].fEnable) { UINT uRTRealizationIndex = m_rgMetaData[i].pInternalRT->GetRealizationCacheIndex(); // Meta bitmap RT should never be created with sub RT that has an // invalid cache index. Assert(uRTRealizationIndex != CMILResourceCache::InvalidToken); if (uRTRealizationIndex == uRealizationCacheIndexToLookFor) { pIRenderTargetNoRef = m_rgMetaData[i].pIRTBitmap; } } } if ( pIRenderTargetNoRef == NULL && uRealizationCacheIndexToLookFor != CMILResourceCache::SwRealizationCacheIndex ) { // // We were hoping to find a hardware intermediate, but no such // intermediate exists. Look for a software intermediate instead. // uRealizationCacheIndexToLookFor = CMILResourceCache::SwRealizationCacheIndex; goto LookAgain; } } else { UINT idx; Verify(SUCCEEDED(m_pDisplaySet->GetDisplayIndexFromDisplayId( targetDestination, OUT idx ))); idx = m_rgMetaData[idx].uIndexOfRealRTBitmap; Assert(idx < m_cRT); Assert(m_rgMetaData[idx].fEnable); Assert(m_rgMetaData[idx].pIRTBitmap); pIRenderTargetNoRef = m_rgMetaData[idx].pIRTBitmap; } return pIRenderTargetNoRef; }
8,860