max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,700
<reponame>aumuell/embree<filename>tutorials/embree_tests/common/algorithms/parallel_sort.cpp // Copyright 2009-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include "../../../external/catch.hpp" #include "../common/algorithms/parallel_sort.h" using namespace embree; namespace parallel_sort_unit_test { template<typename Key> bool run_sort_test() { bool passed = true; const size_t M = 10; for (size_t N = 10; N < 1000000; N = size_t(2.1 * N)) { std::vector<Key> src(N); memset(src.data(), 0, N * sizeof(Key)); std::vector<Key> tmp(N); memset(tmp.data(), 0, N * sizeof(Key)); for (size_t i = 0; i < N; i++) src[i] = uint64_t(rand()) * uint64_t(rand()); /* calculate checksum */ Key sum0 = 0; for (size_t i = 0; i < N; i++) sum0 += src[i]; /* sort numbers */ for (size_t i = 0; i < M; i++) { radix_sort<Key>(src.data(), tmp.data(), N); } /* calculate checksum */ Key sum1 = 0; for (size_t i = 0; i < N; i++) sum1 += src[i]; if (sum0 != sum1) passed = false; /* check if numbers are sorted */ for (size_t i = 1; i < N; i++) passed &= src[i - 1] <= src[i]; } return passed; } TEST_CASE("Test parallel_sort (uint32_t)", "[parallel_sort_uint32_t]") { REQUIRE(run_sort_test<uint64_t>()); } TEST_CASE("Test parallel_sort (uint64_t)", "[parallel_sort_uint64_t]") { REQUIRE(run_sort_test<uint64_t>()); } }
639
2,134
<reponame>dendisuhubdy/opentrack #include "runtime-libraries.hpp" #include "options/scoped.hpp" #include <QMessageBox> #include <QDebug> #ifdef __clang__ # pragma clang diagnostic ignored "-Wcomma" #endif runtime_libraries::runtime_libraries(QFrame* frame, dylibptr t, dylibptr p, dylibptr f) { auto error = [](const QString& msg) { return module_status_mixin::error(msg); }; module_status status = error(tr("Library load failure")); using namespace options; with_tracker_teardown sentinel; pProtocol = make_dylib_instance<IProtocol>(p); if (!pProtocol) { qDebug() << "protocol dylib load failure"; goto end; } if(status = pProtocol->initialize(), !status.is_ok()) { status = error(tr("Error occurred while loading protocol %1\n\n%2\n") .arg(p->name, status.error)); goto end; } pTracker = make_dylib_instance<ITracker>(t); pFilter = make_dylib_instance<IFilter>(f); if (!pTracker) { qDebug() << "tracker dylib load failure"; goto end; } if (f && f->Constructor && !pFilter) { qDebug() << "filter load failure"; goto end; } if (pFilter) if(status = pFilter->initialize(), !status.is_ok()) { status = error(tr("Error occurred while loading filter %1\n\n%2\n") .arg(f->name, status.error)); goto end; } if (status = pTracker->start_tracker(frame), !status.is_ok()) { status = error(tr("Error occurred while loading tracker %1\n\n%2\n") .arg(t->name, status.error)); goto end; } correct = true; return; end: pTracker = nullptr; pFilter = nullptr; pProtocol = nullptr; if (!status.is_ok()) QMessageBox::critical(nullptr, tr("Startup failure"), status.error, QMessageBox::Cancel, QMessageBox::NoButton); }
933
640
<reponame>qjiang310/PRNN-GRU<filename>include/prnn/detail/matrix/cudnn_descriptors.h /* \file CudnnDescriptors.h \date Thursday August 15, 2015 \author <NAME> <<EMAIL>> \brief The header file for the cudnn descriptor C++ wrappers. */ #pragma once // Standard Library Includes #include <memory> #include <vector> // Forward Declarations namespace prnn { namespace matrix { class Matrix; } } namespace prnn { namespace matrix { class Dimension; } } namespace prnn { namespace matrix { class Precision; } } namespace prnn { namespace matrix { class Allocation; } } typedef struct cudnnTensorStruct* cudnnTensorDescriptor_t; typedef struct cudnnFilterStruct* cudnnFilterDescriptor_t; typedef struct cudnnConvolutionStruct* cudnnConvolutionDescriptor_t; typedef struct cudnnPoolingStruct* cudnnPoolingDescriptor_t; typedef struct cudnnRNNStruct* cudnnRNNDescriptor_t; typedef struct cudnnDropoutStruct* cudnnDropoutDescriptor_t; namespace prnn { namespace matrix { class CudnnFilterDescriptor { public: CudnnFilterDescriptor(const Matrix& filter); ~CudnnFilterDescriptor(); public: cudnnFilterDescriptor_t descriptor() const; cudnnFilterDescriptor_t& descriptor(); public: void* data(); private: cudnnFilterDescriptor_t _descriptor; private: std::unique_ptr<Matrix> _filter; }; class CudnnFilterConstViewDescriptor { public: CudnnFilterConstViewDescriptor(const void* data, const Dimension& size, const Precision& precision); ~CudnnFilterConstViewDescriptor(); public: cudnnFilterDescriptor_t descriptor() const; cudnnFilterDescriptor_t& descriptor(); public: Dimension getDimensions() const; public: const void* data() const; public: std::string toString() const; public: CudnnFilterConstViewDescriptor& operator=(const CudnnFilterConstViewDescriptor&) = delete; CudnnFilterConstViewDescriptor(const CudnnFilterConstViewDescriptor&) = delete; private: cudnnFilterDescriptor_t _descriptor; private: const void* _data; }; class CudnnFilterViewDescriptor { public: CudnnFilterViewDescriptor(void* data, const Dimension& size, const Precision& precision); ~CudnnFilterViewDescriptor(); public: cudnnFilterDescriptor_t descriptor() const; cudnnFilterDescriptor_t& descriptor(); public: Dimension getDimensions() const; public: std::string toString() const; public: void* data() const; public: CudnnFilterViewDescriptor& operator=(const CudnnFilterViewDescriptor&) = delete; CudnnFilterViewDescriptor(const CudnnFilterViewDescriptor&) = delete; private: cudnnFilterDescriptor_t _descriptor; private: void* _data; }; class CudnnTensorDescriptor { public: CudnnTensorDescriptor(const Matrix& tensor); CudnnTensorDescriptor(const Dimension& size); ~CudnnTensorDescriptor(); public: cudnnTensorDescriptor_t descriptor() const; cudnnTensorDescriptor_t& descriptor(); public: void* data(); size_t bytes() const; private: cudnnTensorDescriptor_t _descriptor; private: std::unique_ptr<Matrix> _tensor; }; class CudnnTensorViewDescriptor { public: CudnnTensorViewDescriptor(void* data, const Dimension& size, const Dimension& strides, const Precision& precision); CudnnTensorViewDescriptor(); ~CudnnTensorViewDescriptor(); public: cudnnTensorDescriptor_t descriptor() const; cudnnTensorDescriptor_t& descriptor(); public: CudnnTensorViewDescriptor& operator=(const CudnnTensorViewDescriptor&) = delete; CudnnTensorViewDescriptor(const CudnnTensorViewDescriptor&) = delete; public: void* data() const; public: Dimension getDimensions() const; public: std::string toString() const; private: cudnnTensorDescriptor_t _descriptor; private: void* _data; }; class CudnnTensorViewDescriptorArray { public: CudnnTensorViewDescriptorArray(void* data, const Dimension& size, const Dimension& strides, size_t timesteps, const Precision& precision); ~CudnnTensorViewDescriptorArray(); public: cudnnTensorDescriptor_t* descriptors(); public: void* data() const; public: Dimension getDimensions() const; public: std::string toString() const; public: CudnnTensorViewDescriptorArray& operator=(const CudnnTensorViewDescriptorArray&) = delete; CudnnTensorViewDescriptorArray(const CudnnTensorViewDescriptorArray&) = delete; private: std::vector<cudnnTensorDescriptor_t> _descriptors; private: void* _data; }; class CudnnTensorConstViewDescriptorArray { public: CudnnTensorConstViewDescriptorArray(const void* data, const Dimension& size, const Dimension& strides, size_t timesteps, const Precision& precision); ~CudnnTensorConstViewDescriptorArray(); public: cudnnTensorDescriptor_t* descriptors(); public: const void* data() const; public: Dimension getDimensions() const; public: std::string toString() const; public: CudnnTensorConstViewDescriptorArray& operator=(const CudnnTensorConstViewDescriptorArray&) = delete; CudnnTensorConstViewDescriptorArray(const CudnnTensorConstViewDescriptorArray&) = delete; private: std::vector<cudnnTensorDescriptor_t> _descriptors; private: const void* _data; }; class CudnnTensorConstViewDescriptor { public: CudnnTensorConstViewDescriptor(const void* data, const Dimension& size, const Dimension& strides, const Precision& precision); CudnnTensorConstViewDescriptor(); ~CudnnTensorConstViewDescriptor(); public: cudnnTensorDescriptor_t descriptor() const; cudnnTensorDescriptor_t& descriptor(); public: const void* data() const; public: Dimension getDimensions() const; public: std::string toString() const; public: CudnnTensorConstViewDescriptor& operator=(const CudnnTensorConstViewDescriptor&) = delete; CudnnTensorConstViewDescriptor(const CudnnTensorConstViewDescriptor&) = delete; private: cudnnTensorDescriptor_t _descriptor; private: const void* _data; }; class CudnnScalar { public: CudnnScalar(double value, const Precision& p); ~CudnnScalar(); public: void* data(); private: double _doubleValue; float _floatValue; private: std::unique_ptr<Precision> _precision; }; class CudnnForwardWorkspace { public: CudnnForwardWorkspace(const CudnnTensorDescriptor& source, const CudnnFilterDescriptor& filter, cudnnConvolutionDescriptor_t convolutionDescriptor, const CudnnTensorDescriptor& result); public: int algorithm() const; void* data(); size_t size() const; private: int _algorithm; private: std::unique_ptr<Allocation> _data; }; class CudnnBackwardDataWorkspace { public: CudnnBackwardDataWorkspace(const CudnnFilterDescriptor& filter, const CudnnTensorDescriptor& outputDeltas, cudnnConvolutionDescriptor_t convolutionDescriptor, const CudnnTensorDescriptor& inputDeltas); public: int algorithm() const; void* data(); size_t size() const; private: int _algorithm; private: std::unique_ptr<Allocation> _data; }; class CudnnBackwardFilterWorkspace { public: CudnnBackwardFilterWorkspace(const CudnnTensorDescriptor& source, const CudnnTensorDescriptor& outputDeltas, cudnnConvolutionDescriptor_t convolutionDescriptor, const CudnnFilterDescriptor& filterGradient ); public: int algorithm() const; void* data(); size_t size() const; private: int _algorithm; private: std::unique_ptr<Allocation> _data; }; class CudnnPooling2dDescriptor { public: CudnnPooling2dDescriptor(size_t inputW, size_t inputH, size_t padW, size_t padH, size_t poolW, size_t poolH); ~CudnnPooling2dDescriptor(); public: cudnnPoolingDescriptor_t descriptor() const; cudnnPoolingDescriptor_t& descriptor(); public: CudnnPooling2dDescriptor& operator=(const CudnnPooling2dDescriptor&) = delete; CudnnPooling2dDescriptor(const CudnnPooling2dDescriptor&) = delete; private: cudnnPoolingDescriptor_t _descriptor; }; class CudnnRNNDescriptor { public: CudnnRNNDescriptor(int hiddenSize, int numLayers, int inputMode, int direction, int mode, int dataType); ~CudnnRNNDescriptor(); public: cudnnRNNDescriptor_t descriptor() const; cudnnRNNDescriptor_t& descriptor(); public: CudnnRNNDescriptor& operator=(const CudnnRNNDescriptor&) = delete; CudnnRNNDescriptor(const CudnnRNNDescriptor&) = delete; private: cudnnRNNDescriptor_t _descriptor; cudnnDropoutDescriptor_t _dropoutDescriptor; }; } }
3,355
5,169
{ "name": "SuggestionsBox", "version": "1.1", "summary": "SuggestionsBox helps you build better a product trough your user suggestions.", "description": "An iOS library to aggregate users feedback about suggestions, features or comments in order to help you build a better product.", "homepage": "https://github.com/manuelescrig/SuggestionsBox", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/manuelescrig/SuggestionsBox.git", "tag": "1.1" }, "platforms": { "ios": "8.0" }, "source_files": "SuggestionsBox/Classes/**/*" }
230
1,150
<filename>junior_class/chapter-3-Computer_Vision/code/train_MNIST.py # Copyright (c) 2020 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. ''' # LeNet在手写数字识别上的应用 # # LeNet网络的实现代码如下: ''' # 导入需要的包 import paddle import numpy as np import paddle.nn.functional as F from nets.LeNet import LeNet # 定义训练过程 def train(model): # 开启0号GPU训练 use_gpu = True paddle.set_device('gpu:0') if use_gpu else paddle.set_device('cpu') print('start training ... ') model.train() epoch_num = 5 opt = paddle.optimizer.Momentum( learning_rate=0.001, momentum=0.9, parameters=model.parameters()) # 使用Paddle自带的数据读取器 train_loader = paddle.batch(paddle.dataset.mnist.train(), batch_size=10) valid_loader = paddle.batch(paddle.dataset.mnist.test(), batch_size=10) for epoch in range(epoch_num): for batch_id, data in enumerate(train_loader()): # 调整输入数据形状和类型 x_data = np.array( [item[0] for item in data], dtype='float32').reshape(-1, 1, 28, 28) y_data = np.array( [item[1] for item in data], dtype='int64').reshape(-1, 1) # 将numpy.ndarray转化成Tensor img = paddle.to_tensor(x_data) label = paddle.to_tensor(y_data) # 计算模型输出 logits = model(img) # 计算损失函数 loss = F.softmax_with_cross_entropy(logits, label) avg_loss = paddle.mean(loss) if batch_id % 1000 == 0: print("epoch: {}, batch_id: {}, loss is: {}".format( epoch, batch_id, avg_loss.numpy())) avg_loss.backward() opt.step() opt.clear_grad() model.eval() accuracies = [] losses = [] for batch_id, data in enumerate(valid_loader()): # 调整输入数据形状和类型 x_data = np.array( [item[0] for item in data], dtype='float32').reshape(-1, 1, 28, 28) y_data = np.array( [item[1] for item in data], dtype='int64').reshape(-1, 1) # 将numpy.ndarray转化成Tensor img = paddle.to_tensor(x_data) label = paddle.to_tensor(y_data) # 计算模型输出 logits = model(img) pred = F.softmax(logits) # 计算损失函数 loss = F.softmax_with_cross_entropy(logits, label) acc = paddle.metric.accuracy(pred, label) accuracies.append(acc.numpy()) losses.append(loss.numpy()) print("[validation] accuracy/loss: {}/{}".format( np.mean(accuracies), np.mean(losses))) model.train() # 保存模型参数 paddle.save(model.state_dict(), 'mnist.pdparams') # 创建模型 model = LeNet(num_classes=10) # 启动训练过程 train(model)
1,877
458
/*! * Modifications Copyright 2017-2018 H2O.ai, Inc. */ #ifndef MATRIX_MATRIX_H_ #define MATRIX_MATRIX_H_ #include <memory> namespace h2o4gpu { template <typename T> class Matrix { protected: const size_t _m, _n, _mvalid; void *_info, *_infoy, *_vinfo, *_vinfoy, *_weightinfo; bool _done_init, _done_alloc, _done_equil; public: Matrix(size_t m, size_t n) : _m(m), _n(n), _mvalid(0), _info(0), _infoy(0), _vinfo(0), _vinfoy(0), _weightinfo(0), _done_init(false), _done_alloc(false), _done_equil(false) { }; Matrix(size_t m, size_t n, size_t mValid) : _m(m), _n(n), _mvalid(mValid), _info(0), _infoy(0), _vinfo(0), _vinfoy(0), _weightinfo(0), _done_init(false), _done_alloc(false), _done_equil(false) { }; virtual ~Matrix() { }; // Call this methods to initialize the matrix. virtual int Init() = 0; // Method to equilibrate and return equilibration vectors. virtual int Equil(bool equillocal) = 0; // Method to multiply by A and A^T. virtual int Mul(char trans, T alpha, const T *x, T beta, T *y) const = 0; // Get dimensions and check if initialized size_t Rows() const { return _m; } // trainX rows size_t Cols() const { return _n; } // trainX cols size_t ValidRows() const { return _mvalid; } // validX rows (validX has same columns as trainX) bool IsInit() const { return _done_init; } }; } // namespace h2o4gpu #endif // MATRIX_MATRIX_H_
546
476
<reponame>tejasvinu/hetu-core /* * Copyright (C) 2018-2021. Huawei Technologies Co., Ltd. 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 io.prestosql.plugin.hive; import com.google.common.collect.ImmutableList; import io.prestosql.plugin.hive.authentication.HiveIdentity; import io.prestosql.plugin.hive.metastore.HiveMetastore; import io.prestosql.plugin.hive.metastore.Partition; import io.prestosql.plugin.hive.metastore.PartitionWithStatistics; import io.prestosql.plugin.hive.metastore.Table; import io.prestosql.spi.connector.SchemaTableName; import io.prestosql.spi.connector.TableNotFoundException; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.Maps.immutableEntry; import static io.prestosql.plugin.hive.HivePartitionManager.extractPartitionValues; import static java.util.Objects.requireNonNull; public class HiveMetastoreClosure { private final HiveMetastore delegate; public HiveMetastoreClosure(HiveMetastore delegate) { this.delegate = requireNonNull(delegate, "delegate is null"); } public Table getExistingTable(HiveIdentity identity, String databaseName, String tableName) { return getTable(identity, databaseName, tableName) .orElseThrow(() -> new TableNotFoundException(new SchemaTableName(databaseName, tableName))); } public Optional<Table> getTable(HiveIdentity identity, String databaseName, String tableName) { return delegate.getTable(identity, databaseName, tableName); } public PartitionStatistics getTableStatistics(HiveIdentity identity, String databaseName, String tableName) { return delegate.getTableStatistics(identity, getExistingTable(identity, databaseName, tableName)); } public Map<String, PartitionStatistics> getPartitionStatistics(HiveIdentity identity, String databaseName, String tableName, Set<String> partitionNames) { Table table = getExistingTable(identity, databaseName, tableName); List<Partition> partitions = getExistingPartitionsByNames(identity, table, ImmutableList.copyOf(partitionNames)); return delegate.getPartitionStatistics(identity, table, partitions); } private List<Partition> getExistingPartitionsByNames(HiveIdentity identity, Table table, List<String> partitionNames) { Map<String, Partition> partitions = delegate.getPartitionsByNames(identity, table.getDatabaseName(), table.getTableName(), partitionNames).entrySet().stream() .map(entry -> immutableEntry(entry.getKey(), entry.getValue().orElseThrow(() -> new PartitionNotFoundException(table.getSchemaTableName(), extractPartitionValues(entry.getKey()))))) .collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)); return partitionNames.stream() .map(partitions::get) .collect(toImmutableList()); } public void updateTableStatistics(HiveIdentity identity, String databaseName, String tableName, Function<PartitionStatistics, PartitionStatistics> update) { delegate.updateTableStatistics(identity, databaseName, tableName, update); } public void updatePartitionStatistics(HiveIdentity identity, String databaseName, String tableName, String partitionName, Function<PartitionStatistics, PartitionStatistics> update) { delegate.updatePartitionStatistics(identity, databaseName, tableName, partitionName, update); } public void addPartitions(HiveIdentity identity, String databaseName, String tableName, List<PartitionWithStatistics> partitions) { delegate.addPartitions(identity, databaseName, tableName, partitions); } public void dropPartition(HiveIdentity identity, String databaseName, String tableName, List<String> parts, boolean deleteData) { delegate.dropPartition(identity, databaseName, tableName, parts, deleteData); } public void alterPartition(HiveIdentity identity, String databaseName, String tableName, PartitionWithStatistics partition) { delegate.alterPartition(identity, databaseName, tableName, partition); } public Optional<Partition> getPartition(HiveIdentity identity, String databaseName, String tableName, List<String> partitionValues) { return delegate.getPartition(identity, databaseName, tableName, partitionValues); } }
1,652
601
<reponame>alexbosy/spring-data-jdbc /* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.jdbc.repository; import static org.assertj.core.api.Assertions.*; import lombok.AllArgsConstructor; import lombok.Data; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.dao.DataAccessException; import org.springframework.dao.RecoverableDataAccessException; import org.springframework.data.annotation.Id; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.jdbc.repository.support.JdbcRepositoryFactory; import org.springframework.data.jdbc.testing.TestConfiguration; import org.springframework.data.repository.CrudRepository; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; import org.springframework.transaction.annotation.Transactional; /** * Very simple use cases for creation and usage of {@link ResultSetExtractor}s in JdbcRepository. * * @author <NAME> */ @ContextConfiguration @Transactional @ExtendWith(SpringExtension.class) public class JdbcRepositoryResultSetExtractorIntegrationTests { @Configuration @Import(TestConfiguration.class) static class Config { @Autowired JdbcRepositoryFactory factory; @Bean Class<?> testClass() { return JdbcRepositoryResultSetExtractorIntegrationTests.class; } @Bean PersonRepository personEntityRepository() { return factory.getRepository(PersonRepository.class); } } @Autowired NamedParameterJdbcTemplate template; @Autowired PersonRepository personRepository; @Test // DATAJDBC-290 public void findAllPeopleWithAdressesReturnsEmptyWhenNoneFound() { // NOT saving anything, so DB is empty assertThat(personRepository.findAllPeopleWithAddresses()).isEmpty(); } @Test // DATAJDBC-290 public void findAllPeopleWithAddressesReturnsOnePersonWithoutAddresses() { personRepository.save(new Person(null, "Joe", null)); assertThat(personRepository.findAllPeopleWithAddresses()).hasSize(1); } @Test // DATAJDBC-290 public void findAllPeopleWithAddressesReturnsOnePersonWithAddresses() { final String personName = "Joe"; Person savedPerson = personRepository.save(new Person(null, personName, null)); String street1 = "Some Street"; String street2 = "Some other Street"; MapSqlParameterSource paramsAddress1 = buildAddressParameters(savedPerson.getId(), street1); template.update("insert into address (street, person_id) values (:street, :personId)", paramsAddress1); MapSqlParameterSource paramsAddress2 = buildAddressParameters(savedPerson.getId(), street2); template.update("insert into address (street, person_id) values (:street, :personId)", paramsAddress2); List<Person> people = personRepository.findAllPeopleWithAddresses(); assertThat(people).hasSize(1); Person person = people.get(0); assertThat(person.getName()).isEqualTo(personName); assertThat(person.getAddresses()).hasSize(2); assertThat(person.getAddresses()).extracting(a -> a.getStreet()).containsExactlyInAnyOrder(street1, street2); } private MapSqlParameterSource buildAddressParameters(Long id, String streetName) { MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("street", streetName, Types.VARCHAR); params.addValue("personId", id, Types.NUMERIC); return params; } interface PersonRepository extends CrudRepository<Person, Long> { @Query( value = "select p.id, p.name, a.id addrId, a.street from person p left join address a on(p.id = a.person_id)", resultSetExtractorClass = PersonResultSetExtractor.class) List<Person> findAllPeopleWithAddresses(); } @Data @AllArgsConstructor static class Person { @Id private Long id; private String name; private List<Address> addresses; } @Data @AllArgsConstructor static class Address { @Id private Long id; private String street; } static class PersonResultSetExtractor implements ResultSetExtractor<List<Person>> { @Override public List<Person> extractData(ResultSet rs) throws SQLException, DataAccessException { Map<Long, Person> peopleById = new HashMap<>(); while (rs.next()) { long personId = rs.getLong("id"); Person currentPerson = peopleById.computeIfAbsent(personId, t -> { try { return new Person(personId, rs.getString("name"), new ArrayList<>()); } catch (SQLException e) { throw new RecoverableDataAccessException("Error mapping Person", e); } }); if (currentPerson.getAddresses() == null) { currentPerson.setAddresses(new ArrayList<>()); } long addrId = rs.getLong("addrId"); if (!rs.wasNull()) { currentPerson.getAddresses().add(new Address(addrId, rs.getString("street"))); } } return new ArrayList<>(peopleById.values()); } } }
1,973
347
<gh_stars>100-1000 package org.ovirt.engine.ui.common.view; import com.gwtplatform.mvp.client.view.CenterPopupPositioner; public class OvirtCenterPopupPositioner extends CenterPopupPositioner { public OvirtCenterPopupPositioner() { super(); } @Override protected int getLeft(int popupWidth) { int left = super.getLeft(popupWidth); return left < 0 ? 0 : left; } @Override protected int getTop(int popupHeight) { int top = super.getTop(popupHeight); return top < 0 ? 0 : top; } }
219
7,158
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #ifndef __OPENCV_ALPHAMAT_CM_H__ #define __OPENCV_ALPHAMAT_CM_H__ namespace cv { namespace alphamat { using namespace Eigen; using namespace nanoflann; void cm(Mat& image, Mat& tmap, SparseMatrix<double>& Wcm, SparseMatrix<double>& Dcm); }} #endif
156
6,140
import warnings from ..middleware.profiler import * # noqa: F401, F403 warnings.warn( "'werkzeug.contrib.profiler' has moved to" "'werkzeug.middleware.profiler'. This import is deprecated as of" "version 0.15 and will be removed in version 1.0.", DeprecationWarning, stacklevel=2, ) class MergeStream(object): """An object that redirects ``write`` calls to multiple streams. Use this to log to both ``sys.stdout`` and a file:: f = open('profiler.log', 'w') stream = MergeStream(sys.stdout, f) profiler = ProfilerMiddleware(app, stream) .. deprecated:: 0.15 Use the ``tee`` command in your terminal instead. This class will be removed in 1.0. """ def __init__(self, *streams): warnings.warn( "'MergeStream' is deprecated as of version 0.15 and will be removed in" " version 1.0. Use your terminal's 'tee' command instead.", DeprecationWarning, stacklevel=2, ) if not streams: raise TypeError("At least one stream must be given.") self.streams = streams def write(self, data): for stream in self.streams: stream.write(data)
497
3,269
<filename>C++/largest-number-after-mutating-substring.cpp // Time: O(n) // Space: O(1) class Solution { public: string maximumNumber(string num, vector<int>& change) { bool mutated = false; for (int i = 0; i < size(num); ++i) { int d = num[i] - '0'; if (change[d] < d) { if (mutated) { break; } } else if (change[d] > d) { num[i] = '0' + change[d]; mutated = true; } } return num; } };
321
3,301
<filename>core/src/main/java/com/alibaba/alink/common/dl/BaseKerasSequentialTrainBatchOp.java package com.alibaba.alink.common.dl; import org.apache.flink.annotation.Internal; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.common.typeinfo.Types; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.operators.FlatMapOperator; import org.apache.flink.ml.api.misc.param.Params; import org.apache.flink.types.Row; import org.apache.flink.util.StringUtils; import com.alibaba.alink.common.linalg.tensor.TensorTypes; import com.alibaba.alink.common.utils.DataSetConversionUtil; import com.alibaba.alink.common.utils.JsonConverter; import com.alibaba.alink.common.utils.TableUtil; import com.alibaba.alink.operator.batch.BatchOperator; import com.alibaba.alink.operator.batch.source.NumSeqSourceBatchOp; import com.alibaba.alink.operator.batch.source.TableSourceBatchOp; import com.alibaba.alink.operator.batch.tensorflow.TF2TableModelTrainBatchOp; import com.alibaba.alink.operator.common.tensorflow.CommonUtils; import com.alibaba.alink.operator.common.tensorflow.CommonUtils.ConstructModelFlatMapFunction; import com.alibaba.alink.operator.common.tensorflow.CommonUtils.CountLabelsMapFunction; import com.alibaba.alink.operator.common.classification.tensorflow.TFTableModelClassificationModelDataConverter; import com.alibaba.alink.operator.common.regression.tensorflow.TFTableModelRegressionModelDataConverter; import com.alibaba.alink.params.dl.HasTaskType; import com.alibaba.alink.params.tensorflow.kerasequential.BaseKerasSequentialTrainParams; import java.util.HashMap; import java.util.List; import java.util.Map; @Internal public class BaseKerasSequentialTrainBatchOp<T extends BaseKerasSequentialTrainBatchOp <T>> extends BatchOperator <T> implements BaseKerasSequentialTrainParams <T> { static final String TF_OUTPUT_SIGNATURE_DEF_CLASSIFICATION = "probs"; static final String TF_OUTPUT_SIGNATURE_DEF_REGRESSION = "y"; static final TypeInformation <?> TF_OUTPUT_SIGNATURE_TYPE = TensorTypes.FLOAT_TENSOR; private static final String[] RES_PY_FILES = new String[] { "res:///tf_algos/train_keras_sequential.py" }; // `mainScriptFileName` and `entryFuncName` are the main file and its entrypoint provided by our wrapping private static final String MAIN_SCRIPT_FILE_NAME = "res:///tf_algos/train_keras_sequential.py"; public BaseKerasSequentialTrainBatchOp() { this(null); } public BaseKerasSequentialTrainBatchOp(Params params) { super(params); } public static String getTfOutputSignatureDef(TaskType taskType) { return TaskType.CLASSIFICATION.equals(taskType) ? TF_OUTPUT_SIGNATURE_DEF_CLASSIFICATION : TF_OUTPUT_SIGNATURE_DEF_REGRESSION; } @Override public T linkFrom(BatchOperator <?>... inputs) { BatchOperator <?> in = inputs[0]; Params params = getParams(); TaskType taskType = params.get(HasTaskType.TASK_TYPE); boolean isReg = TaskType.REGRESSION.equals(taskType); String tensorCol = getTensorCol(); String labelCol = getLabelCol(); TypeInformation <?> labelType = TableUtil.findColTypeWithAssertAndHint(in.getSchema(), labelCol); DataSet <List <Object>> sortedLabels = null; BatchOperator<?> numLabelsOp = null; if (!isReg) { sortedLabels = in.select(labelCol).distinct().getDataSet() .reduceGroup(new CommonUtils.SortLabelsReduceGroupFunction()); in = CommonUtils.mapLabelToIndex(in, labelCol, sortedLabels); numLabelsOp = new TableSourceBatchOp( DataSetConversionUtil.toTable( getMLEnvironmentId(), sortedLabels.map(new CountLabelsMapFunction()), new String[] {"count"}, new TypeInformation <?>[] {Types.INT} )).setMLEnvironmentId(getMLEnvironmentId()); } Boolean removeCheckpointBeforeTraining = getRemoveCheckpointBeforeTraining(); if (null == removeCheckpointBeforeTraining) { // default to clean checkpoint removeCheckpointBeforeTraining = true; } Map <String, Object> modelConfig = new HashMap <>(); modelConfig.put("layers", getLayers()); Map <String, String> userParams = new HashMap <>(); if (removeCheckpointBeforeTraining) { userParams.put(DLConstants.REMOVE_CHECKPOINT_BEFORE_TRAINING, "true"); } userParams.put("tensor_cols", JsonConverter.toJson(new String[] {tensorCol})); userParams.put("label_col", labelCol); userParams.put("label_type", "float"); userParams.put("batch_size", String.valueOf(getBatchSize())); userParams.put("num_epochs", String.valueOf(getNumEpochs())); userParams.put("model_config", JsonConverter.toJson(modelConfig)); userParams.put("optimizer", getOptimizer()); if (!StringUtils.isNullOrWhitespaceOnly(getCheckpointFilePath())) { userParams.put("model_dir", getCheckpointFilePath()); } TF2TableModelTrainBatchOp trainBatchOp = new TF2TableModelTrainBatchOp(params) .setSelectedCols(new String[] {tensorCol, labelCol}) .setUserFiles(RES_PY_FILES) .setMainScriptFile(MAIN_SCRIPT_FILE_NAME) .setUserParams(JsonConverter.toJson(userParams)) .setIntraOpParallelism(getIntraOpParallelism()) .setNumPSs(getNumPSs()) .setNumWorkers(getNumWorkers()) .setPythonEnv(getPythonEnv()); if (isReg) { trainBatchOp = trainBatchOp.linkFrom(in); } else { trainBatchOp = trainBatchOp.linkFrom(in, numLabelsOp); } String tfOutputSignatureDef = getTfOutputSignatureDef(taskType); FlatMapOperator <Row, Row> constructModelFlatMapOperator = new NumSeqSourceBatchOp().setFrom(0).setTo(0) .setMLEnvironmentId(getMLEnvironmentId()) .getDataSet() .flatMap(new ConstructModelFlatMapFunction(params, new String[]{tensorCol}, new String[0], tfOutputSignatureDef, TF_OUTPUT_SIGNATURE_TYPE, null)) .withBroadcastSet(trainBatchOp.getDataSet(), CommonUtils.TF_MODEL_BC_NAME); BatchOperator <?> modelOp; if (isReg) { DataSet <Row> modelDataSet = constructModelFlatMapOperator; modelOp = new TableSourceBatchOp( DataSetConversionUtil.toTable( getMLEnvironmentId(), modelDataSet, new TFTableModelRegressionModelDataConverter(labelType).getModelSchema() )).setMLEnvironmentId(getMLEnvironmentId()); } else { DataSet <Row> modelDataSet = constructModelFlatMapOperator .withBroadcastSet(sortedLabels, CommonUtils.SORTED_LABELS_BC_NAME); modelOp = new TableSourceBatchOp( DataSetConversionUtil.toTable( getMLEnvironmentId(), modelDataSet, new TFTableModelClassificationModelDataConverter(labelType).getModelSchema() )).setMLEnvironmentId(getMLEnvironmentId()); } this.setOutputTable(modelOp.getOutputTable()); return (T) this; } }
2,455
2,023
# -*- coding: utf-8 -*- """ Created on Mon Jul 9 20:57:29 2012 @author: garrett @email: <EMAIL> original pygmail from: https://github.com/vinod85/pygmail/blob/master/pygmail.py """ import imaplib, smtplib import re from email.mime.text import MIMEText class pygmail(object): IMAP_SERVER='imap.gmail.com' IMAP_PORT=993 SMTP_SERVER = 'smtp.gmail.com' SMTP_PORT=465 def __init__(self): self.M = None self.response = None self.mailboxes = [] def login(self, username, password): self.M = imaplib.IMAP4_SSL(self.IMAP_SERVER, self.IMAP_PORT) self.S = smtplib.SMTP_SSL(self.SMTP_SERVER, self.SMTP_PORT) rc, self.response = self.M.login(username, password) sc, self.response_s = self.S.login(username, password) self.username = username return rc, sc def send_mail(self, to_addrs, msg, subject = None): msg = MIMEText(msg) if subject != None: msg['Subject'] = subject msg['From'] = self.username msg['To'] = to_addrs return self.S.sendmail(self.username, to_addrs, msg.as_string()) def get_mailboxes(self): rc, self.response = self.M.list() for item in self.response: self.mailboxes.append(item.split()[-1]) return rc def get_mail_count(self, folder='Inbox'): rc, self.response = self.M.select(folder) return self.response[0] def get_unread_count(self, folder='Inbox'): rc, self.response = self.M.status(folder, "(UNSEEN)") unreadCount = re.search("UNSEEN (\d+)", self.response[0]).group(1) return unreadCount def get_imap_quota(self): quotaStr = self.M.getquotaroot("Inbox")[1][1][0] r = re.compile('\d+').findall(quotaStr) if r == []: r.append(0) r.append(0) return float(r[1])/1024, float(r[0])/1024 def get_mails_from(self, uid, folder='Inbox'): status, count = self.M.select(folder, readonly=1) status, response = self.M.search(None, 'FROM', uid) email_ids = [e_id for e_id in response[0].split()] return email_ids def get_mail_from_id(self, id): status, response = self.M.fetch(id, '(body[header.fields (subject)])') return response def rename_mailbox(self, oldmailbox, newmailbox): rc, self.response = self.M.rename(oldmailbox, newmailbox) return rc def create_mailbox(self, mailbox): rc, self.response = self.M.create(mailbox) return rc def delete_mailbox(self, mailbox): rc, self.response = self.M.delete(mailbox) return rc def logout(self): self.M.logout() self.S.quit() if __name__ == '__main__': user = '<EMAIL>' pwd = '<PASSWORD>' gm = pygmail() gm.login(user, pwd) send_to = '<EMAIL>' msg = 'Hi there, have you ever thought about the suffering of animals? Go vegan!' gm.send_mail(send_to, msg, 'peace')
1,416
780
#include "test.h" int main() { return 0; }
16
5,535
/*------------------------------------------------------------------------- * * pg_tablespace.h * definition of the "tablespace" system catalog (pg_tablespace) * * * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/catalog/pg_tablespace.h * * NOTES * The Catalog.pm module reads this file and derives schema * information. * *------------------------------------------------------------------------- */ #ifndef PG_TABLESPACE_H #define PG_TABLESPACE_H #include "catalog/genbki.h" #include "catalog/pg_tablespace_d.h" /* ---------------- * pg_tablespace definition. cpp turns this into * typedef struct FormData_pg_tablespace * ---------------- */ CATALOG(pg_tablespace,1213,TableSpaceRelationId) BKI_SHARED_RELATION { Oid oid; /* oid */ NameData spcname; /* tablespace name */ Oid spcowner; /* owner of tablespace */ #ifdef CATALOG_VARLEN /* variable-length fields start here */ aclitem spcacl[1]; /* access permissions */ text spcoptions[1]; /* per-tablespace options */ #endif } FormData_pg_tablespace; /* GPDB added foreign key definitions for gpcheckcat. */ FOREIGN_KEY(spcowner REFERENCES pg_authid(oid)); /* ---------------- * Form_pg_tablespace corresponds to a pointer to a tuple with * the format of pg_tablespace relation. * ---------------- */ typedef FormData_pg_tablespace *Form_pg_tablespace; #endif /* PG_TABLESPACE_H */
505
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. * *************************************************************/ #ifndef _CONTENT_RESULTSET_WRAPPER_HXX #define _CONTENT_RESULTSET_WRAPPER_HXX #include <rtl/ustring.hxx> #include <ucbhelper/macros.hxx> #include <osl/mutex.hxx> #include <cppuhelper/weak.hxx> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/sdbc/XCloseable.hpp> #include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp> #include <com/sun/star/sdbc/XResultSet.hpp> #include <com/sun/star/sdbc/XRow.hpp> #include <com/sun/star/ucb/XContentAccess.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/lang/DisposedException.hpp> #include <cppuhelper/interfacecontainer.hxx> //========================================================================= class ContentResultSetWrapperListener; class ContentResultSetWrapper : public cppu::OWeakObject , public com::sun::star::lang::XComponent , public com::sun::star::sdbc::XCloseable , public com::sun::star::sdbc::XResultSetMetaDataSupplier , public com::sun::star::beans::XPropertySet , public com::sun::star::ucb::XContentAccess , public com::sun::star::sdbc::XResultSet , public com::sun::star::sdbc::XRow { protected: //-------------------------------------------------------------------------- //class PropertyChangeListenerContainer_Impl. struct equalStr_Impl { bool operator()( const rtl::OUString& s1, const rtl::OUString& s2 ) const { return !!( s1 == s2 ); } }; struct hashStr_Impl { size_t operator()( const rtl::OUString& rName ) const { return rName.hashCode(); } }; typedef cppu::OMultiTypeInterfaceContainerHelperVar < rtl::OUString , hashStr_Impl , equalStr_Impl > PropertyChangeListenerContainer_Impl; //-------------------------------------------------------------------------- // class ReacquireableGuard class ReacquireableGuard { protected: osl::Mutex* pT; public: ReacquireableGuard(osl::Mutex * t) : pT(t) { pT->acquire(); } ReacquireableGuard(osl::Mutex& t) : pT(&t) { pT->acquire(); } /** Releases mutex. */ ~ReacquireableGuard() { if (pT) pT->release(); } /** Releases mutex. */ void clear() { if(pT) { pT->release(); pT = NULL; } } /** Reacquire mutex. */ void reacquire() { if(pT) { pT->acquire(); } } }; //----------------------------------------------------------------- //members //my Mutex osl::Mutex m_aMutex; //different Interfaces from Origin: com::sun::star::uno::Reference< com::sun::star::sdbc::XResultSet > m_xResultSetOrigin; com::sun::star::uno::Reference< com::sun::star::sdbc::XRow > m_xRowOrigin; //XRow-interface from m_xOrigin //!! call impl_init_xRowOrigin() bevor you access this member com::sun::star::uno::Reference< com::sun::star::ucb::XContentAccess > m_xContentAccessOrigin; //XContentAccess-interface from m_xOrigin //!! call impl_init_xContentAccessOrigin() bevor you access this member com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet > m_xPropertySetOrigin; //XPropertySet-interface from m_xOrigin //!! call impl_init_xPropertySetOrigin() bevor you access this member com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > m_xPropertySetInfo; //call impl_initPropertySetInfo() bevor you access this member sal_Int32 m_nForwardOnly; private: com::sun::star::uno::Reference< com::sun::star::beans::XPropertyChangeListener > m_xMyListenerImpl; ContentResultSetWrapperListener* m_pMyListenerImpl; com::sun::star::uno::Reference< com::sun::star::sdbc::XResultSetMetaData > m_xMetaDataFromOrigin; //XResultSetMetaData from m_xOrigin //management of listeners sal_Bool m_bDisposed; ///Dispose call ready. sal_Bool m_bInDispose;///In dispose call osl::Mutex m_aContainerMutex; cppu::OInterfaceContainerHelper* m_pDisposeEventListeners; PropertyChangeListenerContainer_Impl* m_pPropertyChangeListeners; PropertyChangeListenerContainer_Impl* m_pVetoableChangeListeners; //----------------------------------------------------------------- //methods: private: PropertyChangeListenerContainer_Impl* SAL_CALL impl_getPropertyChangeListenerContainer(); PropertyChangeListenerContainer_Impl* SAL_CALL impl_getVetoableChangeListenerContainer(); protected: //----------------------------------------------------------------- ContentResultSetWrapper( com::sun::star::uno::Reference< com::sun::star::sdbc::XResultSet > xOrigin ); virtual ~ContentResultSetWrapper(); void SAL_CALL impl_init(); void SAL_CALL impl_deinit(); //-- void SAL_CALL impl_init_xRowOrigin(); void SAL_CALL impl_init_xContentAccessOrigin(); void SAL_CALL impl_init_xPropertySetOrigin(); //-- virtual void SAL_CALL impl_initPropertySetInfo(); //helping XPropertySet void SAL_CALL impl_EnsureNotDisposed() throw( com::sun::star::lang::DisposedException, com::sun::star::uno::RuntimeException ); void SAL_CALL impl_notifyPropertyChangeListeners( const com::sun::star::beans::PropertyChangeEvent& rEvt ); void SAL_CALL impl_notifyVetoableChangeListeners( const com::sun::star::beans::PropertyChangeEvent& rEvt ) throw( com::sun::star::beans::PropertyVetoException, com::sun::star::uno::RuntimeException ); sal_Bool SAL_CALL impl_isForwardOnly(); public: //----------------------------------------------------------------- // XInterface //----------------------------------------------------------------- virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type & rType ) throw( com::sun::star::uno::RuntimeException ); //----------------------------------------------------------------- // XComponent //----------------------------------------------------------------- virtual void SAL_CALL dispose() throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL addEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& Listener ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& Listener ) throw( com::sun::star::uno::RuntimeException ); //----------------------------------------------------------------- //XCloseable //----------------------------------------------------------------- virtual void SAL_CALL close() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); //----------------------------------------------------------------- //XResultSetMetaDataSupplier //----------------------------------------------------------------- virtual com::sun::star::uno::Reference< com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); //----------------------------------------------------------------- // XPropertySet //----------------------------------------------------------------- virtual com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setPropertyValue( const rtl::OUString& aPropertyName, const com::sun::star::uno::Any& aValue ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::beans::PropertyVetoException, com::sun::star::lang::IllegalArgumentException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Any SAL_CALL getPropertyValue( const rtl::OUString& PropertyName ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL addPropertyChangeListener( const rtl::OUString& aPropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XPropertyChangeListener >& xListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removePropertyChangeListener( const rtl::OUString& aPropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XPropertyChangeListener >& aListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL addVetoableChangeListener( const rtl::OUString& PropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XVetoableChangeListener >& aListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeVetoableChangeListener( const rtl::OUString& PropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XVetoableChangeListener >& aListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); //----------------------------------------------------------------- // own methods //----------------------------------------------------------------- virtual void SAL_CALL impl_disposing( const com::sun::star::lang::EventObject& Source ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL impl_propertyChange( const com::sun::star::beans::PropertyChangeEvent& evt ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL impl_vetoableChange( const com::sun::star::beans::PropertyChangeEvent& aEvent ) throw( com::sun::star::beans::PropertyVetoException, com::sun::star::uno::RuntimeException ); //----------------------------------------------------------------- // XContentAccess //----------------------------------------------------------------- virtual rtl::OUString SAL_CALL queryContentIdentifierString() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier > SAL_CALL queryContentIdentifier() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent > SAL_CALL queryContent() throw( com::sun::star::uno::RuntimeException ); //----------------------------------------------------------------- // XResultSet //----------------------------------------------------------------- virtual sal_Bool SAL_CALL next() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL isBeforeFirst() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL isAfterLast() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL isFirst() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL isLast() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL beforeFirst() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL afterLast() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL first() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL last() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL getRow() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL absolute( sal_Int32 row ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL relative( sal_Int32 rows ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL previous() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL refreshRow() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL rowUpdated() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL rowInserted() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL rowDeleted() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL getStatement() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); //----------------------------------------------------------------- // XRow //----------------------------------------------------------------- virtual sal_Bool SAL_CALL wasNull() throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual rtl::OUString SAL_CALL getString( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL getBoolean( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Int8 SAL_CALL getByte( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Int16 SAL_CALL getShort( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL getInt( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual sal_Int64 SAL_CALL getLong( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual float SAL_CALL getFloat( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual double SAL_CALL getDouble( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getBytes( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::util::Date SAL_CALL getDate( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::util::Time SAL_CALL getTime( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::util::DateTime SAL_CALL getTimestamp( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > SAL_CALL getBinaryStream( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > SAL_CALL getCharacterStream( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Any SAL_CALL getObject( sal_Int32 columnIndex, const com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& typeMap ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::sdbc::XRef > SAL_CALL getRef( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::sdbc::XBlob > SAL_CALL getBlob( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::sdbc::XClob > SAL_CALL getClob( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::sdbc::XArray > SAL_CALL getArray( sal_Int32 columnIndex ) throw( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException ); }; //========================================================================= class ContentResultSetWrapperListener : public cppu::OWeakObject , public com::sun::star::beans::XPropertyChangeListener , public com::sun::star::beans::XVetoableChangeListener { protected: ContentResultSetWrapper* m_pOwner; public: ContentResultSetWrapperListener( ContentResultSetWrapper* pOwner ); virtual ~ContentResultSetWrapperListener(); //----------------------------------------------------------------- // XInterface //----------------------------------------------------------------- XINTERFACE_DECL() //----------------------------------------------------------------- //XEventListener //----------------------------------------------------------------- virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw( com::sun::star::uno::RuntimeException ); //----------------------------------------------------------------- //XPropertyChangeListener //----------------------------------------------------------------- virtual void SAL_CALL propertyChange( const com::sun::star::beans::PropertyChangeEvent& evt ) throw( com::sun::star::uno::RuntimeException ); //----------------------------------------------------------------- //XVetoableChangeListener //----------------------------------------------------------------- virtual void SAL_CALL vetoableChange( const com::sun::star::beans::PropertyChangeEvent& aEvent ) throw( com::sun::star::beans::PropertyVetoException, com::sun::star::uno::RuntimeException ); //----------------------------------------------------------------- // own methods: void SAL_CALL impl_OwnerDies(); }; #endif
6,693
3,102
// RUN: rm -rf %t // RUN: %clang_cc1 -x c++ -fmodules %S/Inputs/explicit-build-overlap/def.map -fmodule-name=a -emit-module -o %t/a.pcm // RUN: %clang_cc1 -x c++ -fmodules %S/Inputs/explicit-build-overlap/def.map -fmodule-name=b -emit-module -o %t/ba.pcm -fmodule-file=%t/a.pcm // RUN: %clang_cc1 -x c++ -fmodules -fmodule-map-file=%S/Inputs/explicit-build-overlap/use.map -fmodule-name=use -fmodule-file=%t/ba.pcm %s -verify -I%S/Inputs/explicit-build-overlap -fmodules-decluse // // RUN: %clang_cc1 -x c++ -fmodules %S/Inputs/explicit-build-overlap/def.map -fmodule-name=b -emit-module -o %t/b.pcm // RUN: %clang_cc1 -x c++ -fmodules %S/Inputs/explicit-build-overlap/def.map -fmodule-name=a -emit-module -o %t/ab.pcm -fmodule-file=%t/b.pcm // RUN: %clang_cc1 -x c++ -fmodules -fmodule-map-file=%S/Inputs/explicit-build-overlap/use.map -fmodule-name=use -fmodule-file=%t/ab.pcm %s -verify -I%S/Inputs/explicit-build-overlap -fmodules-decluse // expected-no-diagnostics #include "a.h" A a; B b;
531
1,094
#include "storage_engine/column_store.h" #include "perftest_tools.h" #include "datetime.h" #include <iostream> #include <fstream> #include <sstream> #include <cstdlib> #include <algorithm> #include <zlib.h> #include <cstring> #include <map> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; using namespace Akumuli; //! Generate time-series from random walk struct RandomWalk { std::random_device randdev; std::mt19937 generator; std::normal_distribution<double> distribution; size_t N; std::vector<double> values; RandomWalk(double start, double mean, double stddev, size_t N) : generator(randdev()) , distribution(mean, stddev) , N(N) { values.resize(N, start); } double generate(aku_ParamId id) { values.at(id) += 0.01;// distribution(generator); return sin(values.at(id)); } void add_anomaly(aku_ParamId id, double value) { values.at(id) += value; } }; UncompressedChunk read_data(fs::path path) { UncompressedChunk res; std::fstream in(path.c_str()); std::string line; aku_ParamId base_pid = 1; std::map<std::string, aku_ParamId> pid_map; while(std::getline(in, line)) { std::istringstream lstr(line); std::string series, timestamp, value; std::getline(lstr, series, ','); std::getline(lstr, timestamp, ','); std::getline(lstr, value, ','); aku_ParamId id; auto pid_it = pid_map.find(series); if (pid_it == pid_map.end()) { pid_map[series] = base_pid; id = base_pid; base_pid++; } else { id = pid_it->second; } res.paramids.push_back(id); res.timestamps.push_back(DateTimeUtil::from_iso_string(timestamp.c_str())); res.values.push_back(std::stod(value)); } return res; } struct TestRunResults { // Akumuli stats std::string file_name; size_t uncompressed; size_t compressed; size_t nelements; double bytes_per_element; double compression_ratio; // Gzip stats double gz_bytes_per_element; double gz_compression_ratio; double gz_compressed; // Performance std::vector<double> perf; std::vector<double> gz_perf; }; TestRunResults run_tests(fs::path path) { TestRunResults runresults; runresults.file_name = fs::basename(path); auto header = read_data(path); const size_t UNCOMPRESSED_SIZE = header.paramids.size()*8 // Didn't count lengths and offsets + header.timestamps.size()*8 // because because this arrays contains + header.values.size()*8; // no information and should be compressed // to a few bytes auto bstore = StorageEngine::BlockStoreBuilder::create_memstore(); auto cstore = std::make_shared<StorageEngine::ColumnStore>(bstore); aku_ParamId previd = 0; std::vector<u64> rpoints; for (size_t i = 0; i < header.paramids.size(); i++) { aku_Sample sample = {}; sample.payload.type = AKU_PAYLOAD_FLOAT; sample.paramid = header.paramids[i]; sample.timestamp = header.timestamps[i]; sample.payload.float64 = header.values[i]; if (previd != sample.paramid) { cstore->create_new_column(sample.paramid); } cstore->write(sample, &rpoints, nullptr); } auto store_stats = bstore->get_stats(); auto uncommitted = cstore->_get_uncommitted_memory(); cstore->close(); //std::cout << "Block store: " << store_stats.nblocks << // " blocks used, uncommitted size: " << uncommitted << std::endl; // Compress using zlib const size_t COMPRESSED_SIZE = store_stats.nblocks*store_stats.block_size + uncommitted; const float BYTES_PER_EL = float(COMPRESSED_SIZE)/header.paramids.size(); const float COMPRESSION_RATIO = float(UNCOMPRESSED_SIZE)/COMPRESSED_SIZE; // Save compression stats runresults.uncompressed = UNCOMPRESSED_SIZE; runresults.compressed = COMPRESSED_SIZE; runresults.nelements = header.timestamps.size(); runresults.bytes_per_element = BYTES_PER_EL; runresults.compression_ratio = COMPRESSION_RATIO; // Try to decompress // TBD return runresults; } int main(int argc, char** argv) { if (argc < 2) { std::cout << "Path to dataset required" << std::endl; exit(1); } // Iter directory fs::path dir{argv[1]}; fs::directory_iterator begin(dir), end; std::vector<fs::path> files; std::list<TestRunResults> results; for (auto it = begin; it != end; it++) { if (it->path().extension() == ".csv") { files.push_back(*it); } } std::sort(files.begin(), files.end()); for (auto fname: files) { //std::cout << "Run tests for " << fs::basename(fname) << std::endl; results.push_back(run_tests(fname)); } // Write table std::cout << "| File name | num elements | uncompressed | compressed | ratio | bytes/el |" << std::endl; std::cout << "| ----- | ---- | ----- | ---- | ----- | ---- | " << std::endl; for (auto const& run: results) { std::cout << run.file_name << " | " << run.nelements << " | " << run.uncompressed << " | " << run.compressed << " | " << run.compression_ratio << " | " << run.bytes_per_element << " | " << std::endl; } }
2,614
3,227
/*! \ingroup PkgKernelDKernelConcept \cgalConcept */ class Kernel_d::Oriented_side_d { public: /// \name Operations /// A model of this concept must provide: /// @{ /*! returns the side of \f$ p\f$ with respect to \f$ o\f$. `Kernel_object` may be any of `Kernel_d::Sphere_d` or `Kernel_d::Hyperplane_d`. \pre `p` and `o` have the same dimension. */ template <class Kernel_object> Oriented_side operator()(const Kernel_object& o, const Kernel_d::Point_d& p); /// @} }; /* end Kernel_d::Oriented_side_d */
196
371
<reponame>wuchunfu/EngineX package com.risk.riskmanage.rule.model.request; import com.risk.riskmanage.rule.model.RuleInfo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class RuleListParamV2 { protected Integer pageNum = 1; // 第几页 protected Integer pageSize = 10; // 每页的数量 // protected Boolean search = false; // 是否搜索 protected RuleInfo ruleInfo;//查询实体对象 // protected Integer parentId = 0; // 文件夹的id }
224
5,098
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Data loader factory.""" from typing import Any, Mapping from absl import logging from load_test.data import data_loader from load_test.data import synthetic_bert from load_test.data import synthetic_image def get_data_loader( name: str, **kwargs: Mapping[str, Any]) -> data_loader.DataLoader: if name == "synthetic_images": logging.info("Creating synthetic image data loader.") return synthetic_image.SyntheticImageDataLoader(**kwargs) elif name == "synthetic_bert": logging.info("Creating synthetic bert data loader.") return synthetic_bert.SyntheticBertLoader(**kwargs) else: raise ValueError("Unsupported data loader type.")
365
1,576
package org.commonmark.internal.renderer; import org.commonmark.node.Node; import org.commonmark.renderer.NodeRenderer; import java.util.HashMap; import java.util.Map; public class NodeRendererMap { private final Map<Class<? extends Node>, NodeRenderer> renderers = new HashMap<>(32); public void add(NodeRenderer nodeRenderer) { for (Class<? extends Node> nodeType : nodeRenderer.getNodeTypes()) { // Overwrite existing renderer renderers.put(nodeType, nodeRenderer); } } public void render(Node node) { NodeRenderer nodeRenderer = renderers.get(node.getClass()); if (nodeRenderer != null) { nodeRenderer.render(node); } } }
292
698
/** * Copyright (C) Zhang,Yuexiang (xfeep) * *For reuse some classes from tomcat8 we have to use this package */ package org.apache.coyote.http11; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Selector; import nginx.clojure.NginxHttpServerChannel; import org.apache.coyote.OutputBuffer; import org.apache.coyote.Response; import org.apache.coyote.http11.AbstractOutputBuffer; import org.apache.coyote.http11.Constants; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.NioEndpoint; import org.apache.tomcat.util.net.SocketWrapper; public class InternalNginxOutputBuffer extends AbstractOutputBuffer<NginxChannel> { protected NginxChannel socket; protected volatile boolean flipped = false; protected InternalNginxOutputBuffer(Response response, int headerBufferSize) { super(response, headerBufferSize); outputStreamOutputBuffer = new HttpChannelOutputBuffer(); } @Override public void init(SocketWrapper<NginxChannel> socketWrapper, AbstractEndpoint<NginxChannel> endpoint) throws IOException { socket = socketWrapper.getSocket(); } public void addActiveFilter(OutputFilter filter) { //by default socket.ignoreNginxFilter is true we will use nginx filter instead of tomcat filter if (socket.ignoreNginxFilter) { super.addActiveFilter(filter); } } @Override public void sendAck() throws IOException { if (!committed) { socket.getBufHandler().getWriteBuffer().put( Constants.ACK_BYTES, 0, Constants.ACK_BYTES.length); int result = writeToSocket(socket.getBufHandler().getWriteBuffer(), true, true); if (result < 0) { throw new IOException(sm.getString("iob.failedwrite.ack")); } } } protected synchronized int writeToSocket(byte[] buf, int pos, int len) throws IOException { try { socket.getIOChannel().send(buf, pos, len, true, false); }catch(RuntimeException e) { throw new IOException(e.getMessage(), e); } return len; } protected synchronized int writeToSocket(ByteBuffer bytebuffer, boolean block, boolean flip) throws IOException { if ( flip ) { bytebuffer.flip(); flipped = true; } int written = bytebuffer.remaining(); NginxEndpoint.KeyAttachment att = (NginxEndpoint.KeyAttachment)socket.getAttachment(); if ( att == null ) throw new IOException("Key must be cancelled"); socket.getIOChannel().send(bytebuffer, true, false); if ( block || bytebuffer.remaining()==0) { //blocking writes must empty the buffer //and if remaining==0 then we did empty it bytebuffer.clear(); flipped = false; } // If there is data left in the buffer the socket will be registered for // write further up the stack. This is to ensure the socket is only // registered for write once as both container and user code can trigger // write registration. return written; } @Override protected void commit() throws IOException { // The response is now committed committed = true; response.setCommitted(true); if (pos > 0 && (!socket.isSendFile() || socket.getIOChannel().isIgnoreFilter())) { socket.getIOChannel().sendHeader(headerBuffer, 0, pos, true, false); } } @Override public void endRequest() throws IOException { if (finished) { return; } super.endRequest(); if (!socket.isSendFile() || socket.getIOChannel().isIgnoreFilter()) { socket.close(); } } @Override protected boolean hasMoreDataToFlush() { return false; } @Override protected void registerWriteInterest() throws IOException { } @Override protected boolean flushBuffer(boolean block) throws IOException { try { socket.getIOChannel().flush(); }catch(RuntimeException e) { throw new IOException(e.getMessage(), e); } return false; } protected class HttpChannelOutputBuffer implements OutputBuffer { public HttpChannelOutputBuffer() { } @Override public long getBytesWritten() { return byteCount; } @Override public int doWrite(ByteChunk chunk, Response response) throws IOException { int c = writeToSocket(chunk.getBuffer(), chunk.getStart(), chunk.getLength()); byteCount += c; return c; } } }
1,622
1,968
<filename>platform/android/ndk/Rtt_AndroidRuntimeDelegate.h ////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: <EMAIL> // ////////////////////////////////////////////////////////////////////////////// #ifndef _Rtt_AndroidRuntimeDelegate_H__ #define _Rtt_AndroidRuntimeDelegate_H__ #include "Rtt_RuntimeDelegatePlayer.h" class NativeToJavaBridge; namespace Rtt { /// Delegate used to receive events from the Corona Runtime. /// This is done by assigning an instance of this class to the Runtime.SetDelegate() function. class AndroidRuntimeDelegate : public RuntimeDelegatePlayer { public: AndroidRuntimeDelegate(NativeToJavaBridge *ntjb, bool isCoronaKit); virtual ~AndroidRuntimeDelegate(); virtual void DidInitLuaLibraries( const Runtime& sender ) const; virtual bool HasDependencies( const Runtime& sender ) const; virtual void WillLoadMain(const Runtime& sender) const; virtual void DidLoadMain(const Runtime& sender) const; virtual void WillLoadConfig(const Runtime& sender, lua_State *L) const; virtual void DidLoadConfig(const Runtime& sender, lua_State *L) const; virtual void InitializeConfig(const Runtime& sender, lua_State *L) const; private: NativeToJavaBridge *fNativeToJavaBridge; bool fIsCoronaKit; }; } // namespace Rtt #endif // _Rtt_AndroidRuntimeDelegate_H__
431
372
/* * Copyright © BeyondTrust Software 2004 - 2019 * 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. * * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE, * NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT * BEYONDTRUST AT beyondtrust.com/contact */ #include <unity.h> #include "lwerror.h" #include "Mocklwreg.h" #include "djregistry.h" void testWhenRegServerOpenFailsDeleteValueFails() { DWORD dwError = ERROR_SUCCESS; LwRegOpenServer_IgnoreAndReturn(ERROR_OUT_OF_PAPER); dwError = DeleteValueFromRegistry("path", "name"); TEST_ASSERT_EQUAL_INT(ERROR_OUT_OF_PAPER, dwError); } void testWhenCalledWithNonExistentValueDeleteValueSucceeds() { DWORD dwError = ERROR_SUCCESS; // we don't care about the reg open, root key ops for this test LwRegOpenServer_IgnoreAndReturn(ERROR_SUCCESS); LwRegOpenKeyExA_IgnoreAndReturn(ERROR_SUCCESS); LwRegDeleteKeyValueA_ExpectAndReturn(NULL, NULL, "path", "name", LWREG_ERROR_NO_SUCH_KEY_OR_VALUE); LwRegDeleteKeyValueA_IgnoreArg_hKey(); LwRegCloseKey_IgnoreAndReturn(ERROR_SUCCESS); LwRegCloseServer_Ignore(); dwError = DeleteValueFromRegistry("path", "name"); TEST_ASSERT_EQUAL_INT(ERROR_SUCCESS, dwError); } void testWhenDeletingDefaultValueSucceeds() { DWORD dwError = ERROR_SUCCESS; // we don't care about the reg open, root key ops for this test LwRegOpenServer_IgnoreAndReturn(ERROR_SUCCESS); LwRegOpenKeyExA_IgnoreAndReturn(ERROR_SUCCESS); LwRegDeleteKeyValueA_ExpectAndReturn(NULL, NULL, "path", "name", LWREG_ERROR_DELETE_DEFAULT_VALUE_NOT_ALLOWED); LwRegDeleteKeyValueA_IgnoreArg_hKey(); LwRegCloseKey_IgnoreAndReturn(ERROR_SUCCESS); LwRegCloseServer_Ignore(); dwError = DeleteValueFromRegistry("path", "name"); TEST_ASSERT_EQUAL_INT(ERROR_SUCCESS, dwError); } void testWhenEncounteringAnErrorDeleteValueFails() { DWORD dwError = LW_ERROR_SUCCESS; // we don't care about the reg open, root key ops for this test LwRegOpenServer_IgnoreAndReturn(LW_ERROR_SUCCESS); LwRegOpenKeyExA_IgnoreAndReturn(LW_ERROR_SUCCESS); LwRegDeleteKeyValueA_ExpectAndReturn(NULL, NULL, "path", "name", LWREG_ERROR_FAILED_DELETE_HAS_SUBKEY); LwRegDeleteKeyValueA_IgnoreArg_hKey(); LwRegCloseKey_IgnoreAndReturn(LW_ERROR_SUCCESS); LwRegCloseServer_Ignore(); dwError = DeleteValueFromRegistry("path", "name"); TEST_ASSERT_EQUAL_INT(LWREG_ERROR_FAILED_DELETE_HAS_SUBKEY, dwError); }
1,209
443
<reponame>vault-the/changes from __future__ import absolute_import from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.api.serializer.models.job import JobWithBuildCrumbler from changes.models.job import Job from changes.models.jobplan import JobPlan from changes.models.snapshot import Snapshot class SnapshotJobIndexAPIView(APIView): """Defines the endpoint for fetching jobs that use a given snapshot.""" def get(self, snapshot_id): snapshot = Snapshot.query.get(snapshot_id) if snapshot is None: return self.respond({}, status_code=404) snapshot_image_ids = [image.id for image in snapshot.images] jobs = Job.query.join( JobPlan, JobPlan.job_id == Job.id, ).options( joinedload(Job.build, innerjoin=True), ).filter( JobPlan.snapshot_image_id.in_(snapshot_image_ids), ).order_by(Job.date_created.desc()) return self.paginate(jobs, serializers={ Job: JobWithBuildCrumbler(), })
416
386
<reponame>jkrude/charts<gh_stars>100-1000 /* * Copyright (c) 2018 by <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.hansolo.fx.charts; import eu.hansolo.fx.charts.series.Series; import javafx.beans.DefaultProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ObjectPropertyBase; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.geometry.Orientation; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.layout.FlowPane; import javafx.scene.layout.Region; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * User: hansolo * Date: 05.01.18 * Time: 21:04 */ @DefaultProperty("children") public class Legend extends FlowPane { private static final double PREFERRED_WIDTH = 250; private static final double PREFERRED_HEIGHT = 250; private static final double MINIMUM_WIDTH = 20; private static final double MINIMUM_HEIGHT = 18; private static final double MAXIMUM_WIDTH = 1024; private static final double MAXIMUM_HEIGHT = 1024; private double size; private double width; private double height; private ObservableList<LegendItem> legendItems; private ListChangeListener<LegendItem> itemListListener; // ******************** Constructors ************************************** public Legend() { this(new ArrayList<>()); } public Legend(final LegendItem... LEGEND_ITEMS) { this(Arrays.asList(LEGEND_ITEMS)); } public Legend(final List<LegendItem> LEGEND_ITEMS) { legendItems = FXCollections.observableArrayList(); legendItems.addAll(LEGEND_ITEMS); itemListListener = c -> { while (c.next()) { if (c.wasAdded()) { c.getAddedSubList().forEach(item -> getChildren().add(item)); } else if (c.wasRemoved()) { c.getRemoved().forEach(item -> getChildren().remove(item)); } } }; initGraphics(); registerListeners(); } // ******************** Initialization ************************************ private void initGraphics() { if (Double.compare(getPrefWidth(), 0.0) <= 0 || Double.compare(getPrefHeight(), 0.0) <= 0 || Double.compare(getWidth(), 0.0) <= 0 || Double.compare(getHeight(), 0.0) <= 0) { if (getPrefWidth() > 0 && getPrefHeight() > 0) { setPrefSize(getPrefWidth(), getPrefHeight()); } else { setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT); } } setHgap(3.168); setVgap(3.168); setOrientation(getOrientation()); setAlignment(Pos.TOP_LEFT); getChildren().addAll(legendItems); } private void registerListeners() { widthProperty().addListener(o -> resize()); heightProperty().addListener(o -> resize()); legendItems.addListener(itemListListener); } // ******************** Methods ******************************************* @Override public void layoutChildren() { super.layoutChildren(); } @Override protected double computeMinWidth(final double HEIGHT) { return MINIMUM_WIDTH; } @Override protected double computeMinHeight(final double WIDTH) { return MINIMUM_HEIGHT; } @Override protected double computePrefWidth(final double HEIGHT) { return super.computePrefWidth(HEIGHT); } @Override protected double computePrefHeight(final double WIDTH) { return super.computePrefHeight(WIDTH); } @Override protected double computeMaxWidth(final double HEIGHT) { return MAXIMUM_WIDTH; } @Override protected double computeMaxHeight(final double WIDTH) { return MAXIMUM_HEIGHT; } private void handleControlPropertyChanged(final String PROPERTY) { if ("".equals(PROPERTY)) { } } @Override public ObservableList<Node> getChildren() { return super.getChildren(); } public void dispose() { legendItems.removeListener(itemListListener); } public ObservableList<LegendItem> getLegendItems() { return legendItems; } public void setLegendItems(final LegendItem... LEGEND_ITEMS) { setLegendItems(Arrays.asList(LEGEND_ITEMS)); } public void setLegendItems(final List<LegendItem> LEGEND_ITEMS) { legendItems.setAll(LEGEND_ITEMS); } public void addLegendItem(final LegendItem ITEM) { if (!legendItems.contains(ITEM)) { legendItems.add(ITEM); } } public void removeLegendItem(final LegendItem ITEM) { if (legendItems.contains(ITEM)) { legendItems.remove(ITEM); } } public void createFromListOfSeries(final List<Series> SERIES) { legendItems.clear(); SERIES.forEach(series -> legendItems.add(new LegendItem(series.getSymbol(), series.getName(), series.getSymbolFill(), series.getSymbolStroke()))); } private double getItemHeight() { if (legendItems.size() == 0) return 0; return legendItems.get(0).getHeight(); } // ******************** Resizing ****************************************** private void resize() { width = getWidth() - getInsets().getLeft() - getInsets().getRight(); height = getHeight() - getInsets().getTop() - getInsets().getBottom(); size = width < height ? width : height; if (width > 0 && height > 0) { setHgap(getItemHeight() * 0.22); setVgap(getItemHeight() * 0.22); redraw(); } } private void redraw() { } }
2,582
1,149
<reponame>thunderbiscuit/Learning-Bitcoin-from-the-Command-Line #include <stdio.h> #include "wally_core.h" int main(void) { int lw_response; lw_response = wally_init(0); printf("Startup: %d\n",lw_response); wally_cleanup(0); }
108
443
"""Add SystemOption Revision ID: 19910015c867 Revises: <KEY> Create Date: 2014-07-11 15:48:26.276042 """ # revision identifiers, used by Alembic. revision = '19910015c867' down_revision = '<KEY>' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'systemoption', sa.Column('id', sa.GUID(), nullable=False), sa.Column('name', sa.String(length=64), nullable=False), sa.Column('value', sa.Text(), nullable=False), sa.Column('date_created', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) def downgrade(): op.drop_table('systemoption')
280
1,444
<reponame>amc8391/mage package mage.cards.c; import mage.abilities.costs.mana.GenericManaCost; import mage.abilities.effects.common.CounterUnlessPaysEffect; import mage.abilities.effects.keyword.AmassEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.target.TargetSpell; import java.util.UUID; /** * @author TheElk801 */ public final class CrushDissent extends CardImpl { public CrushDissent(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{3}{U}"); // Counter target spell unless its controller pays {2}. this.getSpellAbility().addEffect(new CounterUnlessPaysEffect(new GenericManaCost(2))); this.getSpellAbility().addTarget(new TargetSpell()); // Amass 2. this.getSpellAbility().addEffect(new AmassEffect(2)); } private CrushDissent(final CrushDissent card) { super(card); } @Override public CrushDissent copy() { return new CrushDissent(this); } }
389
412
/*******************************************************************\ Author: Diffblue \*******************************************************************/ /// \file /// Utilities for printing location info steps in the trace in a format /// agnostic way #ifndef CPROVER_GOTO_PROGRAMS_STRUCTURED_TRACE_UTIL_H #define CPROVER_GOTO_PROGRAMS_STRUCTURED_TRACE_UTIL_H #include "goto_program.h" #include <string> class goto_trace_stept; /// There are two kinds of step for location markers - location-only and /// loop-head (for locations associated with the first step of a loop). enum class default_step_kindt { LOCATION_ONLY, LOOP_HEAD }; /// Identify for a given instruction whether it is a loophead or just a location /// /// Loopheads are determined by whether there is backwards jump to them. This /// matches the loop detection used for loop IDs /// \param instruction: The instruction to inspect. /// \return LOOP_HEAD if this is a loop head, otherwise LOCATION_ONLY default_step_kindt default_step_kind(const goto_programt::instructiont &instruction); /// Turns a \ref default_step_kindt into a string that can be used in the trace /// \param step_type: The kind of step, deduced from \ref default_step_kind /// \return Either "loop-head" or "location-only" std::string default_step_name(const default_step_kindt &step_type); struct default_trace_stept { default_step_kindt kind; bool hidden; unsigned thread_number; std::size_t step_number; source_locationt location; }; optionalt<default_trace_stept> default_step( const goto_trace_stept &step, const source_locationt &previous_source_location); #endif // CPROVER_GOTO_PROGRAMS_STRUCTURED_TRACE_UTIL_H
502
8,844
<gh_stars>1000+ class Dinosaur { Disposable(Disposable... resources) { } }
34
839
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.profile; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; /** * */ public final class EndpointCreationLoop { private GenericApplicationContext applicationContext; private EndpointCreationLoop() { } private void readBeans(Resource beanResource) { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader( applicationContext); reader.loadBeanDefinitions(beanResource); } private void iteration() { applicationContext = new GenericApplicationContext(); readBeans(new ClassPathResource("extrajaxbclass.xml")); applicationContext.refresh(); applicationContext.close(); } /** * @param args */ public static void main(String[] args) { EndpointCreationLoop ecl = new EndpointCreationLoop(); int count = Integer.parseInt(args[0]); for (int x = 0; x < count; x++) { ecl.iteration(); } } }
618
729
package com.mapbox.mapboxandroiddemo.examples.styles; import android.graphics.Color; import android.os.Bundle; import com.mapbox.mapboxandroiddemo.R; import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.maps.MapView; import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.mapboxsdk.maps.OnMapReadyCallback; import com.mapbox.mapboxsdk.maps.Style; import com.mapbox.mapboxsdk.style.layers.FillLayer; import com.mapbox.mapboxsdk.style.sources.GeoJsonSource; import java.net.URI; import java.net.URISyntaxException; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillColor; import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillOpacity; /** * Using the second argument of addLayer, you can add a layer below existing one */ public class GeojsonLayerInStackActivity extends AppCompatActivity { private MapView mapView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Mapbox access token is configured here. This needs to be called either in your application // object or in the same activity which contains the mapview. Mapbox.getInstance(this, getString(R.string.access_token)); // This contains the MapView in XML and needs to be called after the access token is configured. setContentView(R.layout.activity_style_geojson_layer_in_stack); mapView = findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull final MapboxMap mapboxMap) { mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { try { GeoJsonSource urbanAreasSource = new GeoJsonSource("urban-areas", new URI("https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_urban_areas.geojson")); style.addSource(urbanAreasSource); FillLayer urbanArea = new FillLayer("urban-areas-fill", "urban-areas"); urbanArea.setProperties( fillColor(Color.parseColor("#ff0088")), fillOpacity(0.4f) ); style.addLayerBelow(urbanArea, "water"); } catch (URISyntaxException uriSyntaxException) { uriSyntaxException.printStackTrace(); } } }); } }); } @Override public void onResume() { super.onResume(); mapView.onResume(); } @Override protected void onStart() { super.onStart(); mapView.onStart(); } @Override protected void onStop() { super.onStop(); mapView.onStop(); } @Override public void onPause() { super.onPause(); mapView.onPause(); } @Override public void onLowMemory() { super.onLowMemory(); mapView.onLowMemory(); } @Override protected void onDestroy() { super.onDestroy(); mapView.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } }
1,271
2,963
<filename>Compiler/Functions/Initializer.cpp<gh_stars>1000+ // // Initializer.cpp // EmojicodeCompiler // // Created by <NAME> on 22/08/2017. // Copyright © 2017 <NAME>. All rights reserved. // #include "Initializer.hpp" namespace EmojicodeCompiler { } // namespace EmojicodeCompiler
105
1,168
<reponame>wcalandro/kythe<filename>kythe/cxx/indexer/cxx/testdata/rec/rec_union.cc<gh_stars>1000+ // Checks that unions are recorded as records. //- @U defines/binding UUnion //- UUnion.complete definition //- UUnion.subkind union //- UUnion.node/kind record union U { };
95
1,602
from django import http def test_view(request): return http.HttpResponse()
25
984
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.phoenix.execute; import static org.junit.Assert.assertTrue; import org.apache.hadoop.hbase.util.Bytes; import org.apache.phoenix.util.ByteUtil; import org.junit.Test; public class DescVarLengthFastByteComparisonsTest { @Test public void testNullIsSmallest() { byte[] b1 = ByteUtil.EMPTY_BYTE_ARRAY; byte[] b2 = Bytes.toBytes("a"); int cmp = DescVarLengthFastByteComparisons.compareTo(b1, 0, b1.length, b2, 0, b2.length); assertTrue(cmp < 0); cmp = DescVarLengthFastByteComparisons.compareTo(b2, 0, b2.length, b1, 0, b1.length); assertTrue(cmp > 0); } @Test public void testShorterSubstringIsBigger() { byte[] b1 = Bytes.toBytes("ab"); byte[] b2 = Bytes.toBytes("a"); int cmp = DescVarLengthFastByteComparisons.compareTo(b1, 0, b1.length, b2, 0, b2.length); assertTrue(cmp < 0); } }
600
335
{ "word": "Main", "definitions": [ "A principal pipe carrying water or gas to buildings, or taking sewage from them.", "A principal cable carrying electricity.", "The source of public water, gas, or electricity supply through pipes or cables.", "The open ocean." ], "parts-of-speech": "Noun" }
120
692
#include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <assert.h> #include "core/util.h" #include "core/adios_logger.h" #include "core/transforms/adios_transforms_hooks_read.h" #include "core/transforms/adios_transforms_reqgroup.h" #include "public/adios_error.h" #ifdef ALACRITY #include "alacrity.h" #include "adios_transform_alacrity_common.h" #include "adios_transform_identity_read.h" // used to read original data int adios_transform_alacrity_is_implemented (void) {return 1;} typedef struct { adios_transform_alacrity_metadata alac_meta; void *identity_internal; } alac_pg_read_req_info; int adios_transform_alacrity_generate_read_subrequests(adios_transform_read_request *reqgroup, adios_transform_pg_read_request *pg_reqgroup) { uint64_t read_buffer_size; alac_pg_read_req_info *pg_internal = (alac_pg_read_req_info*)malloc(sizeof(alac_pg_read_req_info)); const int metagood = read_alacrity_transform_metadata( pg_reqgroup->transform_metadata_len, pg_reqgroup->transform_metadata, &pg_internal->alac_meta); if (!metagood) { log_warn("Invalid ALACRITY transform metadata found for PG %d; input file " "is likely corrupt or written using an old version of ALACRITY\n", pg_reqgroup->blockidx); free(pg_internal); return 1; } // Based on the format of the ALACRITY partition, schedule the required read requests if (pg_internal->alac_meta.has_origdata) { // Original data is available, use identity transform read // Use the Identity method for doing this, since it's just reading original data adios_transform_generate_read_subrequests_over_original_data( pg_internal->alac_meta.origdata_offset, 1, // sieve points reqgroup, pg_reqgroup ); // Wrap the identity-specific internal information so we can reproduce it later pg_internal->identity_internal = pg_reqgroup->transform_internal; } else if (pg_internal->alac_meta.has_lob) { // No original data, but low-order bytes are available, so we can decode the partition // Read the whole partition to do this void *buf = malloc(pg_reqgroup->raw_var_length); adios_transform_raw_read_request *subreq = adios_transform_raw_read_request_new_whole_pg(pg_reqgroup, buf); adios_transform_raw_read_request_append(pg_reqgroup, subreq); } else { // No original data or low-order bytes, must use approximate index decoding adios_error(err_unspecified, "Attempt to read from ALACRITY-transformed data with " "no original data and no low-order bytes encoded. This " "function is currently unimplemented.\n"); return 1; } pg_reqgroup->transform_internal = pg_internal; // Store necessary information for interpreting the read return 0; } // Do nothing for individual subrequest adios_datablock * adios_transform_alacrity_subrequest_completed(adios_transform_read_request *reqgroup, adios_transform_pg_read_request *pg_reqgroup, adios_transform_raw_read_request *completed_subreq) { return NULL; } adios_datablock * adios_transform_alacrity_pg_reqgroup_completed(adios_transform_read_request *reqgroup, adios_transform_pg_read_request *completed_pg_reqgroup) { alac_pg_read_req_info *pg_internal = (alac_pg_read_req_info*)completed_pg_reqgroup->transform_internal; if (pg_internal->alac_meta.has_origdata) { // If this is an original data read, we delegate to the Identity implementation // Temporarily restore the pg_reqgroup->transform_internal to what the Identity implementation is expecting completed_pg_reqgroup->transform_internal = pg_internal->identity_internal; // Invoke the Identity read implementation adios_datablock *ret = adios_transform_pg_reqgroup_completed_over_original_data(reqgroup, completed_pg_reqgroup); // Revert to our internal info, so it will be free'd by the Transform framework completed_pg_reqgroup->transform_internal = pg_internal; // Return return ret; } else if (pg_internal->alac_meta.has_lob) { // If this is a LOB data read, decode the partition // Get the buffer with the transformed data that was read (it's in the // single child raw read request) void *raw_buff = completed_pg_reqgroup->subreqs->data; // Compute the size of the original data so we can allocate a buffer uint64_t orig_size = adios_get_type_size(reqgroup->transinfo->orig_type, ""); int d; for(d = 0; d < reqgroup->transinfo->orig_ndim; d++) orig_size *= (uint64_t)(completed_pg_reqgroup->orig_varblock->count[d]); // Allocate a buffer to decode into void* orig_data_buff = malloc(orig_size); ALPartitionData output_partition; uint64_t numElements = 0; // Deserialize the ALACRITY partition from the read buffer into a struct memstream_t ms = memstreamInitReturn(raw_buff); memstreamSkip(&ms, pg_internal->alac_meta.meta_offset); ALDeserializeMetadata(&output_partition.metadata, &ms); memstreamReset(&ms); memstreamSkip(&ms, pg_internal->alac_meta.index_offset); ALDeserializeIndex(&output_partition.index, &output_partition.metadata, &ms); memstreamReset(&ms); memstreamSkip(&ms, pg_internal->alac_meta.lob_offset); ALDeserializeData(&output_partition.data, &output_partition.metadata, &ms); memstreamReset(&ms); memstreamDestroy(&ms, false); // The deserialize functions above allocate their own buffers output_partition.ownsBuffers = true; // Free the read buffer for transformed data (this would be done automatically // by the transform framework, but do it here to be safe) free(completed_pg_reqgroup->subreqs->data); completed_pg_reqgroup->subreqs->data = NULL; // Decode the ALPartitionData into an output buffer int rtn = ALDecode(&output_partition, orig_data_buff, &numElements); if (ALErrorNone != rtn) { free(orig_data_buff); return NULL; } ALPartitionDataDestroy(&output_partition); return adios_datablock_new_whole_pg(reqgroup, completed_pg_reqgroup, orig_data_buff); } else { abort(); // Should not happen, since no reads should be scheduled in such a case return NULL; } } adios_datablock * adios_transform_alacrity_reqgroup_completed(adios_transform_read_request *completed_reqgroup) { return NULL; } #else DECLARE_TRANSFORM_READ_METHOD_UNIMPL(alacrity); #endif
2,447
348
<gh_stars>100-1000 {"nom":"Saint-Silvain-sous-Toulx","dpt":"Creuse","inscrits":116,"abs":25,"votants":91,"blancs":2,"nuls":1,"exp":88,"res":[{"panneau":"1","voix":60},{"panneau":"2","voix":28}]}
85
333
from subprocess import check_output def run_shell_script(script, print_output=False): if '"' in script: assert Exception("Docker shell script cannot contain double quotes, turn it into a single quote!") output = check_output([ "docker", "exec", "-it", "django", "bash", "-c", 'echo "{}" | python manage.py shell_plus'.format(script) ]) if print_output: print output return output
195
1,305
<filename>IGraphics/Controls/Test/TestColorControl.h /* ============================================================================== This file is part of the iPlug 2 library. Copyright (C) the iPlug 2 developers. See LICENSE.txt for more info. ============================================================================== */ #pragma once /** * @file * @copydoc TestColorControl */ #include "IControl.h" /** Control to colors * @ingroup TestControls */ class TestColorControl : public IControl { public: TestColorControl(const IRECT& rect) : IControl(rect) { SetTooltip("TestColorControl"); } void OnResize() override { mPattern = IPattern::CreateLinearGradient(mRECT.L, mRECT.MH(), mRECT.R, mRECT.MH()); const int nstops = 7; for (int i=0; i<nstops; i++) { float pos = (1.f/(float) nstops) * i; mPattern.AddStop(IColor::FromHSLA(pos, 1., 0.5), pos); } } void Draw(IGraphics& g) override { g.DrawDottedRect(COLOR_BLACK, mRECT); #ifndef IGRAPHICS_NANOVG g.PathRect(mRECT); g.PathFill(mPattern); #else g.DrawText(mText, "UNSUPPORTED", mRECT); #endif } private: IPattern mPattern = IPattern(EPatternType::Linear); };
443
3,262
/* * Tencent is pleased to support the open source community by making Angel available. * * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. 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 * * https://opensource.org/licenses/Apache-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.tencent.angel.ps.storage.partitioner; import com.tencent.angel.conf.AngelConf; import com.tencent.angel.exception.AngelException; import com.tencent.angel.master.app.AMContext; import com.tencent.angel.ml.matrix.MatrixContext; import com.tencent.angel.ml.matrix.PartitionMeta; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; /** * Base class of range partitioner */ public class HashPartitioner implements Partitioner { private static final Log LOG = LogFactory.getLog(HashPartitioner.class); /** * Matrix context */ protected MatrixContext mContext; /** * AMContext context */ protected AMContext context; /** * Application configuration */ protected Configuration conf; /** * Partition number per server */ protected int partNumPerServer; /** * Part id to ps id map */ protected int[] partId2serverIndex; @Override public void init(MatrixContext mContext, AMContext context) { this.mContext = mContext; this.context = context; this.conf = context.getConf(); // Partition number use set int totalPartNum = mContext.getPartitionNum(); int psNum = conf.getInt(AngelConf.ANGEL_PS_NUMBER, AngelConf.DEFAULT_ANGEL_PS_NUMBER); if(totalPartNum > 0) { // Use total partition number if set partNumPerServer = Math.max(totalPartNum / psNum, 1); LOG.info("Use set partition number=" + totalPartNum + ", ps number=" + psNum + ", partition per server=" + partNumPerServer + ", total partition number adjust to " + partNumPerServer * psNum); mContext.setPartitionNum(partNumPerServer * psNum); } else { // Use partition number per server partNumPerServer = conf.getInt(AngelConf.ANGEL_MODEL_PARTITIONER_PARTITION_NUM_PERSERVER, AngelConf.DEFAULT_ANGEL_MODEL_PARTITIONER_PARTITION_NUM_PERSERVER); } if(partNumPerServer <= 0) { throw new AngelException("Partition number per server " + partNumPerServer + " is not valid"); } this.partId2serverIndex = new int[psNum * partNumPerServer]; } @Override public List<PartitionMeta> getPartitions() { int psNum = conf.getInt(AngelConf.ANGEL_PS_NUMBER, AngelConf.DEFAULT_ANGEL_PS_NUMBER); List<PartitionMeta> partitions = new ArrayList<>(psNum * partNumPerServer); int matrixId = mContext.getMatrixId(); for(int psIndex = 0; psIndex < psNum; psIndex++) { for(int partIndex = 0; partIndex < partNumPerServer; partIndex++) { int partId = psIndex * partNumPerServer + partIndex; PartitionMeta partMeta = new PartitionMeta(matrixId, partId, 0, mContext.getRowNum(), partId, partId + 1); partitions.add(partMeta); partId2serverIndex[partId] = partId % psNum; } } return partitions; } @Override public int assignPartToServer(int partId) { return partId2serverIndex[partId]; } @Override public PartitionType getPartitionType() { return PartitionType.HASH_PARTITION; } }
1,315
2,023
import sys, os from tempfile import mkstemp from getopt import getopt, GetoptError from subprocess import call as oscall from depgraph2dot import pydepgraphdot from py2depgraph import mymf def genDepGraph(inScript, options): path = sys.path[:] debug = 0 mf = mymf(path, debug, options.exclude) mf.run_script(inScript) # find all modules in standard lib and set them aside for later; # assume that modules that don't have a filename are from stdlib ignore = set() for moduleName, module in mf.modules.iteritems(): ign = False if options.ignoreNoFile and (not module.__file__): ign = True if options.ignoreStdlib and module.__file__: path1 = os.path.abspath(os.path.dirname(module.__file__)).lower() path2 = os.path.abspath('c:\python24\lib').lower() if path1 == path2: ign = True if ign: ignore.add(moduleName) return dict(depgraph=mf._depgraph, types=mf._types), ignore class MyDepGraphDot(pydepgraphdot): def __init__(self, buffer, ignore=None): self.__depgraph = buffer['depgraph'] self.__types = buffer['types'] tmpfd, tmpname = mkstemp('.dot', 'depgraph_') os.close(tmpfd) self.__output = file(tmpname, 'w') self.__output_name = tmpname self.__ignore = ignore or set() #print 'Will ignore modules:', self.__ignore def toocommon(self, s, type): if s in self.__ignore: return 1 return pydepgraphdot.toocommon(self, s, type) def get_data(self): return self.__depgraph, self.__types def get_output_file(self): return self.__output def get_output_name(self): self.__output.close() return self.__output_name class Options: def __init__(self): self.exclude = [] # list of module names to exclude from analysis self.ignoreStdlib = True # modules from Python's stdlib will not be in graph self.ignoreNoFile = True # modules that don't have an associated file will not be in graph self.dotPath = r'C:\Program Files\Graphviz2.16\bin\dot' self.args = sys.argv[1] print 'Will %sinclude stdlib modules' % (self.ignoreStdlib and 'NOT ' or '') print 'Will %sinclude "file-less" modules' % (self.ignoreNoFile and 'NOT ' or '') print 'Will exclude the following modules and anything imported by them:', self.exclude print 'Will use "%s" as dot' % self.dotPath # Process command line args options = Options() # start processing script for dependencies inScript = options.args[0] try: buffer, ignore = genDepGraph(inScript, options) except IOError, exc: print 'ERROR:', exc sys.exit(-1) if not buffer['depgraph']: print 'NO dependencies of interest! Nothing to generate, exiting.' sys.exit() dotdep = MyDepGraphDot(buffer, ignore) dotdep.main( sys.argv ) # convert to png basename = os.path.splitext(os.path.basename(inScript))[0] pngOutput = basename + '_depgraph.png' print 'Generating %s from %s' % (pngOutput, dotdep.get_output_name()) oscall([ options.dotPath, '-Tpng', '-o', pngOutput, dotdep.get_output_name()] ) # cleanup os.remove(dotdep.get_output_name())
1,354
764
<gh_stars>100-1000 { "symbol": "JinZu", "address": "0x55cA65946818F0b02B267c935887b1082E4D829b", "overview": { "zh": "随着世界数字化进程的不断加速,互联网传输速度的不断提升,分布式计算资源的不断积累,数学和密码学技术在数字化时代的大量实用,我们预见未来通过基于区块链去中心化、开放、自治、不可篡改、保护隐私等特性建设的适用于分布式征信、分布式债权登记、分布式财富管理、分布式资产交易的底层公链,会让全球不同国 家、地区、商业场景的参与者具有简便的提供金融服务的能力。基于区块链技术的新型虚拟机构“分布式银行”JinZu就此诞生,分布式银行不是传统银行,而是分布式金融业务的集合生态。" }, "email": "<EMAIL>", "website": "http://www.jinzu.shop/", "state": "LOCKED | NORMAL", "published_on": "2020-06-05", "links": { "media": "https://www.jinse.com/blockchain/709464.html" } }
682
427
<gh_stars>100-1000 //===-- XCoreTargetTransformInfo.h - XCore specific TTI ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file a TargetTransformInfo::Concept conforming object specific to the /// XCore target machine. It uses the target's detailed information to /// provide more precise answers to certain TTI queries, while letting the /// target independent and default TTI implementations handle the rest. /// //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_TARGET_XCORE_XCORETARGETTRANSFORMINFO_H #define LLVM_LIB_TARGET_XCORE_XCORETARGETTRANSFORMINFO_H #include "XCore.h" #include "XCoreTargetMachine.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/CodeGen/BasicTTIImpl.h" #include "llvm/Target/TargetLowering.h" namespace llvm { class XCoreTTIImpl : public BasicTTIImplBase<XCoreTTIImpl> { typedef BasicTTIImplBase<XCoreTTIImpl> BaseT; typedef TargetTransformInfo TTI; friend BaseT; const XCoreSubtarget *ST; const XCoreTargetLowering *TLI; const XCoreSubtarget *getST() const { return ST; } const XCoreTargetLowering *getTLI() const { return TLI; } public: explicit XCoreTTIImpl(const XCoreTargetMachine *TM, const Function &F) : BaseT(TM, F.getParent()->getDataLayout()), ST(TM->getSubtargetImpl()), TLI(ST->getTargetLowering()) {} unsigned getNumberOfRegisters(bool Vector) { if (Vector) { return 0; } return 12; } }; } // end namespace llvm #endif
559
317
from mdecbase import Service from binaryninja import * license = open('/opt/binaryninja/license.txt').read() core_set_license(license) class BinjaService(Service): """ Binary Ninja decompiler as a service """ def decompile(self, path: str) -> str: """ Decompile all the functions in the binary located at `path`. Based on https://github.com/Vector35/binaryninja-api/blob/2845ba6208ce3c29998a48df5073ed15a11ead77/rust/examples/decompile/src/main.rs - Where are the Python samples..... """ out = [] v = open_view(path) ds = DisassemblySettings() ds.set_option(DisassemblyOption.ShowAddress, False) ds.set_option(DisassemblyOption.WaitForIL, True) lv = LinearViewObject.language_representation(v, ds) for f in v.functions: c = LinearViewCursor(lv) c.seek_to_address(f.highest_address) last = v.get_next_linear_disassembly_lines(c.duplicate()) first = v.get_previous_linear_disassembly_lines(c) for line in (first + last): out.append(str(line)) return '\n'.join(out) def version(self) -> str: return core_version()
537
1,264
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.jsprit.core.util; import com.graphhopper.jsprit.core.problem.Location; import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder; import com.graphhopper.jsprit.core.problem.job.Shipment; import com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow; import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl; import com.graphhopper.jsprit.core.problem.vehicle.VehicleTypeImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * test instances for the capacitated vrp with pickup and deliveries and time windows. * instances are from li and lim and can be found at: * http://www.top.sintef.no/vrp/benchmarks.html * * @author <NAME> */ public class LiLimReader { static class CustomerData { public Coordinate coord; public double start; public double end; public double serviceTime; public CustomerData(Coordinate coord, double start, double end, double serviceTime) { super(); this.coord = coord; this.start = start; this.end = end; this.serviceTime = serviceTime; } } static class Relation { public String from; public String to; public int demand; public Relation(String from, String to, int demand) { super(); this.from = from; this.to = to; this.demand = demand; } } private static Logger logger = LoggerFactory.getLogger(LiLimReader.class); private Builder vrpBuilder; private int vehicleCapacity; private String depotId; private Map<String, CustomerData> customers; private Collection<Relation> relations; private double depotOpeningTime; private double depotClosingTime; private int fixCosts = 0; public LiLimReader(Builder vrpBuilder) { customers = new HashMap<String, CustomerData>(); relations = new ArrayList<Relation>(); this.vrpBuilder = vrpBuilder; } public LiLimReader(Builder builder, int fixCosts) { customers = new HashMap<String, CustomerData>(); relations = new ArrayList<Relation>(); this.vrpBuilder = builder; this.fixCosts = fixCosts; } public void read(InputStream inputStream) { readShipments(inputStream); buildShipments(); VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").addCapacityDimension(0, vehicleCapacity) .setCostPerDistance(1.0).setFixedCost(fixCosts).build(); VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle") .setEarliestStart(depotOpeningTime).setLatestArrival(depotClosingTime) .setStartLocation(Location.Builder.newInstance().setCoordinate(customers.get(depotId).coord).build()).setType(type).build(); vrpBuilder.addVehicle(vehicle); } private void buildShipments() { Integer counter = 0; for (Relation rel : relations) { counter++; String from = rel.from; String to = rel.to; int demand = rel.demand; Shipment s = Shipment.Builder.newInstance(counter.toString()).addSizeDimension(0, demand) .setPickupLocation(Location.Builder.newInstance().setCoordinate(customers.get(from).coord).build()).setPickupServiceTime(customers.get(from).serviceTime) .setPickupTimeWindow(TimeWindow.newInstance(customers.get(from).start, customers.get(from).end)) .setDeliveryLocation(Location.Builder.newInstance().setCoordinate(customers.get(to).coord).build()).setDeliveryServiceTime(customers.get(to).serviceTime) .setDeliveryTimeWindow(TimeWindow.newInstance(customers.get(to).start, customers.get(to).end)).build(); vrpBuilder.addJob(s); } } private BufferedReader getReader(InputStream inputStream) { return new BufferedReader(new InputStreamReader(inputStream)); } private void readShipments(InputStream inputStream) { BufferedReader reader = getReader(inputStream); String line = null; boolean firstLine = true; try { while ((line = reader.readLine()) != null) { line = line.replace("\r", ""); line = line.trim(); String[] tokens = line.split("\t"); if (firstLine) { int vehicleCapacity = getInt(tokens[1]); this.vehicleCapacity = vehicleCapacity; firstLine = false; continue; } else { String customerId = tokens[0]; Coordinate coord = makeCoord(tokens[1], tokens[2]); int demand = getInt(tokens[3]); double startTimeWindow = getDouble(tokens[4]); double endTimeWindow = getDouble(tokens[5]); double serviceTime = getDouble(tokens[6]); // vrpBuilder.addLocation(customerId, coord); customers.put(customerId, new CustomerData(coord, startTimeWindow, endTimeWindow, serviceTime)); if (customerId.equals("0")) { depotId = customerId; depotOpeningTime = startTimeWindow; depotClosingTime = endTimeWindow; } if (demand > 0) { relations.add(new Relation(customerId, tokens[8], demand)); } } } reader.close(); } catch (IOException e) { e.printStackTrace(); } } private Coordinate makeCoord(String xString, String yString) { double x = Double.parseDouble(xString); double y = Double.parseDouble(yString); return new Coordinate(x, y); } private double getDouble(String string) { return Double.parseDouble(string); } private int getInt(String string) { return Integer.parseInt(string); } }
2,904
301
/*- * #%L * Spring Auto REST Docs Json Doclet for JDK9+ * %% * Copyright (C) 2015 - 2021 Scalable Capital GmbH * %% * 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. * #L% */ package capital.scalable.restdocs.jsondoclet; import static java.util.Optional.ofNullable; import static capital.scalable.restdocs.jsondoclet.DocletUtils.cleanupDocComment; import com.sun.source.doctree.DocCommentTree; import com.sun.source.doctree.ParamTree; import javax.lang.model.element.Element; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import jdk.javadoc.doclet.DocletEnvironment; public final class ClassDocumentation { private String comment = ""; private final Map<String, FieldDocumentation> fields = new HashMap<>(); private final Map<String, MethodDocumentation> methods = new HashMap<>(); private ClassDocumentation() { // enforce usage of static factory method } public static ClassDocumentation fromClassDoc(DocletEnvironment docEnv, Element element) { ClassDocumentation cd = new ClassDocumentation(); cd.setComment(cleanupDocComment(docEnv.getElementUtils().getDocComment(element))); if ("RECORD".equals(element.getKind().name())) { ofNullable(docEnv.getDocTrees().getDocCommentTree(element)) .stream() .map(DocCommentTree::getBlockTags) .flatMap(List::stream) .filter(ParamTree.class::isInstance) .map(ParamTree.class::cast) .filter(p -> !p.isTypeParameter()) .forEach(p -> { String name = p.getName().getName().toString(); String desc = p.getDescription() .stream() .map(Object::toString) .collect(Collectors.joining(" ")) ; cd.fields.put(name, FieldDocumentation.fromString(desc)); }) ; } else { element.getEnclosedElements().forEach(fieldOrMethod -> { switch (fieldOrMethod.getKind()) { case FIELD: cd.addField(docEnv, fieldOrMethod); break; case METHOD: case CONSTRUCTOR: cd.addMethod(docEnv, fieldOrMethod); break; default: // Ignored break; } }); } return cd; } private void setComment(String comment) { this.comment = comment; } private void addField(DocletEnvironment docEnv, Element element) { this.fields.put(element.getSimpleName().toString(), FieldDocumentation.fromFieldDoc(docEnv, element)); } private void addMethod(DocletEnvironment docEnv, Element element) { this.methods.put(element.getSimpleName().toString(), MethodDocumentation.fromMethodDoc(docEnv, element)); } }
1,600
6,094
package com.antfortune.freeline.idea.actions; import com.antfortune.freeline.idea.utils.NotificationUtils; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.util.ui.UIUtil; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class SendFeedbackDialog extends JDialog implements OnRequestCallback { public static final int MAX_WIDTH = 600; public static final int MAX_HEIGHT = 450; private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; private JTextArea feedbackContentTextArea; public SendFeedbackDialog() { setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(buttonOK); setTitle("Freeline Send Feedback"); setResizable(false); setLocationCenter(); buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }); buttonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); contentPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } private void onOK() { String content = feedbackContentTextArea.getText(); if (content == null || content.length() == 0) { NotificationUtils.errorNotification("Feedback content can not be empty."); return; } ApplicationInfoEx appInfo = ApplicationInfoEx.getInstanceEx(); boolean eap = appInfo.isEAP(); String buildInfo = eap?appInfo.getBuild().asStringWithoutProductCode():appInfo.getBuild().asString(); String timezone = System.getProperty("user.timezone"); String desc = getDescription(); SendFeedbackAsync task = new SendFeedbackAsync(content, buildInfo + ";" + timezone + ";" + desc, this); ApplicationManager.getApplication().executeOnPooledThread(task); buttonOK.setEnabled(false); } private void onCancel() { dispose(); } public void setLocationCenter() { int windowWidth = MAX_WIDTH; int windowHeight = MAX_HEIGHT; Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screenSize = kit.getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; this.setLocation(screenWidth / 2 - windowWidth / 2, screenHeight / 2 - windowHeight / 2);//设置窗口居中显示 } public void showDialog() { pack(); setVisible(true); } private static String getDescription() { StringBuilder sb = new StringBuilder(); String javaVersion = System.getProperty("java.runtime.version", System.getProperty("java.version", "unknown")); sb.append(javaVersion); String archDataModel = System.getProperty("sun.arch.data.model"); if(archDataModel != null) { sb.append("x").append(archDataModel); } String javaVendor = System.getProperty("java.vm.vendor"); if(javaVendor != null) { sb.append(" ").append(javaVendor); } sb.append(", ").append(System.getProperty("os.name")); String osArch = System.getProperty("os.arch"); if(osArch != null) { sb.append("(").append(osArch).append(")"); } String osVersion = System.getProperty("os.version"); String osPatchLevel = System.getProperty("sun.os.patch.level"); if(osVersion != null) { sb.append(" v").append(osVersion); if(osPatchLevel != null) { sb.append(" ").append(osPatchLevel); } } if(!GraphicsEnvironment.isHeadless()) { GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); sb.append(" ("); for(int i = 0; i < devices.length; ++i) { if(i > 0) { sb.append(", "); } GraphicsDevice device = devices[i]; Rectangle bounds = device.getDefaultConfiguration().getBounds(); sb.append(bounds.width).append("x").append(bounds.height); } if(UIUtil.isRetina()) { sb.append(" R"); } sb.append(")"); } return sb.toString(); } public static void main(String[] args) { SendFeedbackDialog dialog = new SendFeedbackDialog(); dialog.pack(); dialog.setVisible(true); System.exit(0); } @Override public void onSuccess() { NotificationUtils.infoNotification("Submit succeeded, thanks!"); dispose(); } @Override public void onFailure(Exception e) { NotificationUtils.errorNotification("Submit failed: " + e.getMessage()); dispose(); } private static class SendFeedbackAsync implements Runnable { private String content; private String env; private OnRequestCallback callback; public SendFeedbackAsync(String content, String env, OnRequestCallback callback) { this.content = content; this.env = env; this.callback = callback; } @Override public void run() { try { URL url = new URL("https://www.freelinebuild.com/api/feedback"); //URL url = new URL("http://localhost:3000/api/feedback"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); StringBuilder builder = new StringBuilder(); builder.append(URLEncoder.encode("content", "UTF-8")); builder.append("="); builder.append(URLEncoder.encode(content, "UTF-8")); builder.append("&"); builder.append(URLEncoder.encode("env", "UTF-8")); builder.append("="); builder.append(URLEncoder.encode(env, "UTF-8")); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(builder.toString()); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode >= 400) { this.callback.onFailure(new Exception(conn.getResponseMessage())); } else { this.callback.onSuccess(); } conn.disconnect(); } catch (IOException e) { this.callback.onFailure(e); } } } }
3,425
2,151
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/display/manager/managed_display_info.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_CHROMEOS) #include "ui/display/manager/touch_device_manager.h" #endif namespace display { namespace { std::string GetModeSizeInDIP(const gfx::Size& size, float device_scale_factor, float ui_scale, bool is_internal) { ManagedDisplayMode mode(size, 0.0 /* refresh_rate */, false /* interlaced */, false /* native */, ui_scale, device_scale_factor); return mode.GetSizeInDIP(is_internal).ToString(); } } // namespace typedef testing::Test DisplayInfoTest; TEST_F(DisplayInfoTest, CreateFromSpec) { ManagedDisplayInfo info = ManagedDisplayInfo::CreateFromSpecWithID("200x100", 10); EXPECT_EQ(10, info.id()); EXPECT_EQ("0,0 200x100", info.bounds_in_native().ToString()); EXPECT_EQ("200x100", info.size_in_pixel().ToString()); EXPECT_EQ(Display::ROTATE_0, info.GetActiveRotation()); EXPECT_EQ("0,0,0,0", info.overscan_insets_in_dip().ToString()); EXPECT_EQ(1.0f, info.configured_ui_scale()); info = ManagedDisplayInfo::CreateFromSpecWithID("10+20-300x400*2/o", 10); EXPECT_EQ("10,20 300x400", info.bounds_in_native().ToString()); EXPECT_EQ("288x380", info.size_in_pixel().ToString()); EXPECT_EQ(Display::ROTATE_0, info.GetActiveRotation()); EXPECT_EQ("5,3,5,3", info.overscan_insets_in_dip().ToString()); info = ManagedDisplayInfo::CreateFromSpecWithID("10+20-300x400*2/ob", 10); EXPECT_EQ("10,20 300x400", info.bounds_in_native().ToString()); EXPECT_EQ("288x380", info.size_in_pixel().ToString()); EXPECT_EQ(Display::ROTATE_0, info.GetActiveRotation()); EXPECT_EQ("5,3,5,3", info.overscan_insets_in_dip().ToString()); info = ManagedDisplayInfo::CreateFromSpecWithID("10+20-300x400*2/or", 10); EXPECT_EQ("10,20 300x400", info.bounds_in_native().ToString()); EXPECT_EQ("380x288", info.size_in_pixel().ToString()); EXPECT_EQ(Display::ROTATE_90, info.GetActiveRotation()); // TODO(oshima): This should be rotated too. Fix this. EXPECT_EQ("5,3,5,3", info.overscan_insets_in_dip().ToString()); info = ManagedDisplayInfo::CreateFromSpecWithID("10+20-300x400*2/[email protected]", 10); EXPECT_EQ("10,20 300x400", info.bounds_in_native().ToString()); EXPECT_EQ(Display::ROTATE_270, info.GetActiveRotation()); EXPECT_EQ(1.5f, info.configured_ui_scale()); info = ManagedDisplayInfo::CreateFromSpecWithID( "200x200#300x200|200x200%59.9|100x100%60|150x100*2|150x150*1.25%30", 10); EXPECT_EQ("0,0 200x200", info.bounds_in_native().ToString()); EXPECT_EQ(5u, info.display_modes().size()); // Modes are sorted in DIP for external display. EXPECT_EQ("150x100", info.display_modes()[0].size().ToString()); EXPECT_EQ("100x100", info.display_modes()[1].size().ToString()); EXPECT_EQ("150x150", info.display_modes()[2].size().ToString()); EXPECT_EQ("200x200", info.display_modes()[3].size().ToString()); EXPECT_EQ("300x200", info.display_modes()[4].size().ToString()); EXPECT_EQ(0.0f, info.display_modes()[0].refresh_rate()); EXPECT_EQ(60.0f, info.display_modes()[1].refresh_rate()); EXPECT_EQ(30.0f, info.display_modes()[2].refresh_rate()); EXPECT_EQ(59.9f, info.display_modes()[3].refresh_rate()); EXPECT_EQ(0.0f, info.display_modes()[4].refresh_rate()); EXPECT_EQ(2.0f, info.display_modes()[0].device_scale_factor()); EXPECT_EQ(1.0f, info.display_modes()[1].device_scale_factor()); EXPECT_EQ(1.25f, info.display_modes()[2].device_scale_factor()); EXPECT_EQ(1.0f, info.display_modes()[3].device_scale_factor()); EXPECT_EQ(1.0f, info.display_modes()[4].device_scale_factor()); EXPECT_FALSE(info.display_modes()[0].native()); EXPECT_FALSE(info.display_modes()[1].native()); EXPECT_FALSE(info.display_modes()[2].native()); EXPECT_FALSE(info.display_modes()[3].native()); EXPECT_TRUE(info.display_modes()[4].native()); } TEST_F(DisplayInfoTest, ManagedDisplayModeGetSizeInDIPNormal) { gfx::Size size(1366, 768); EXPECT_EQ("1536x864", GetModeSizeInDIP(size, 1.0f, 1.125f, true)); EXPECT_EQ("1366x768", GetModeSizeInDIP(size, 1.0f, 1.0f, true)); EXPECT_EQ("1092x614", GetModeSizeInDIP(size, 1.0f, 0.8f, true)); EXPECT_EQ("853x480", GetModeSizeInDIP(size, 1.0f, 0.625f, true)); EXPECT_EQ("683x384", GetModeSizeInDIP(size, 1.0f, 0.5f, true)); } TEST_F(DisplayInfoTest, ManagedDisplayModeGetSizeInDIPHiDPI) { gfx::Size size(2560, 1700); EXPECT_EQ("2560x1700", GetModeSizeInDIP(size, 2.0f, 2.0f, true)); EXPECT_EQ("1920x1275", GetModeSizeInDIP(size, 2.0f, 1.5f, true)); EXPECT_EQ("1600x1062", GetModeSizeInDIP(size, 2.0f, 1.25f, true)); EXPECT_EQ("1440x956", GetModeSizeInDIP(size, 2.0f, 1.125f, true)); EXPECT_EQ("1280x850", GetModeSizeInDIP(size, 2.0f, 1.0f, true)); EXPECT_EQ("1024x680", GetModeSizeInDIP(size, 2.0f, 0.8f, true)); EXPECT_EQ("800x531", GetModeSizeInDIP(size, 2.0f, 0.625f, true)); EXPECT_EQ("640x425", GetModeSizeInDIP(size, 2.0f, 0.5f, true)); } TEST_F(DisplayInfoTest, ManagedDisplayModeGetSizeInDIP125) { gfx::Size size(1920, 1080); EXPECT_EQ("2400x1350", GetModeSizeInDIP(size, 1.25f, 1.25f, true)); EXPECT_EQ("1920x1080", GetModeSizeInDIP(size, 1.25f, 1.0f, true)); EXPECT_EQ("1536x864", GetModeSizeInDIP(size, 1.25f, 0.8f, true)); EXPECT_EQ("1200x675", GetModeSizeInDIP(size, 1.25f, 0.625f, true)); EXPECT_EQ("960x540", GetModeSizeInDIP(size, 1.25f, 0.5f, true)); } TEST_F(DisplayInfoTest, ManagedDisplayModeGetSizeForExternal4K) { gfx::Size size(3840, 2160); EXPECT_EQ("1920x1080", GetModeSizeInDIP(size, 2.0f, 1.0f, false)); EXPECT_EQ("3072x1728", GetModeSizeInDIP(size, 1.25f, 1.0f, false)); EXPECT_EQ("3840x2160", GetModeSizeInDIP(size, 1.0f, 1.0f, false)); } } // namespace display
2,587
5,954
import org.bytedeco.javacpp.FloatPointer; import org.bytedeco.javacv.CanvasFrame; import org.bytedeco.javacv.OpenCVFrameConverter; import org.bytedeco.opencv.opencv_core.*; import org.bytedeco.opencv.opencv_imgproc.*; import static org.bytedeco.opencv.global.opencv_core.*; import static org.bytedeco.opencv.global.opencv_imgcodecs.*; import static org.bytedeco.opencv.global.opencv_imgproc.*; /** * Created by <NAME> on 2018-09-21 * <p> * An example of how to use the perspective warp method in JavaCV. */ public class PerspectiveWarpDemo extends Thread { static CanvasFrame frame = new CanvasFrame("Perspective Warp Demo - warped image"); static CanvasFrame frameUnedited = new CanvasFrame("Perspective Warp Demo - Unedited image"); public static void main(String[] args) { Mat image = imread("shapes1.jpg"); Mat perspectiveWarpedImg = performPerspectiveWarp(image, 30, 0, 200, 0, 400, 250, 40, 260); OpenCVFrameConverter converter = new OpenCVFrameConverter.ToIplImage(); frame.showImage(converter.convert(perspectiveWarpedImg)); frameUnedited.showImage(converter.convert(image)); image.release(); perspectiveWarpedImg.release(); frameUnedited.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); frameUnedited.setLocationRelativeTo(null); frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); frame.setLocation(frameUnedited.getX()+frameUnedited.getWidth(), frameUnedited.getY()); } /** * Performs a perspective warp that takes four corners and stretches them to the corners of the image. * x1,y1 represents the top left corner, 2 top right, going clockwise. * This method does not release/deallocate the input image Mat, call inputMat.release() after this method * if you don't plan on using the input more after this method. * * @param imageMat The image to perform the stretch on * @return A stretched image mat. */ private static Mat performPerspectiveWarp(Mat imageMat, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { double originalImgWidth = imageMat.size().width(); double originalImgHeight = imageMat.size().height(); FloatPointer srcCorners = new FloatPointer( x1, y1, x2, y2, x3, y3, x4, y4); FloatPointer dstCorners = new FloatPointer( 0, 0, (int) originalImgWidth, 0, (int) originalImgWidth, (int) originalImgHeight, 0, (int) originalImgHeight); //create matrices with width 2 to hold the x,y values, and 4 rows, to hold the 4 different corners. Mat src = new Mat(new Size(2, 4), CV_32F, srcCorners); Mat dst = new Mat(new Size(2, 4), CV_32F, dstCorners); Mat perspective = getPerspectiveTransform(src, dst); Mat result = new Mat(); warpPerspective(imageMat, result, perspective, new Size((int) originalImgWidth, (int) originalImgHeight)); src.release(); dst.release(); srcCorners.deallocate(); dstCorners.deallocate(); return result; } }
1,288
995
// Copyright (C) 2016-2018 <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) #ifndef BOOST_YAP_CONFIG_HPP_INCLUDED #define BOOST_YAP_CONFIG_HPP_INCLUDED #ifndef BOOST_NO_CONSTEXPR_IF /** Indicates whether the compiler supports constexpr if. If the user does not define any value for this, we assume that the compiler does not have the necessary support. Note that this is a temporary hack; this should eventually be a Boost-wide macro. */ #define BOOST_NO_CONSTEXPR_IF #elif BOOST_NO_CONSTEXPR_IF == 0 #undef BOOST_NO_CONSTEXPR_IF #endif #endif
270
372
/* * 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 code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.apigee.v1.model; /** * Model definition for GoogleCloudApigeeV1QueryMetadata. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Apigee API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudApigeeV1QueryMetadata extends com.google.api.client.json.GenericJson { /** * Dimensions of the AsyncQuery. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> dimensions; /** * End timestamp of the query range. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String endTimestamp; /** * Metrics of the AsyncQuery. Example: ["name:message_count,func:sum,alias:sum_message_count"] * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> metrics; /** * Output format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String outputFormat; /** * Start timestamp of the query range. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String startTimestamp; /** * Query GroupBy time unit. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String timeUnit; /** * Dimensions of the AsyncQuery. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getDimensions() { return dimensions; } /** * Dimensions of the AsyncQuery. * @param dimensions dimensions or {@code null} for none */ public GoogleCloudApigeeV1QueryMetadata setDimensions(java.util.List<java.lang.String> dimensions) { this.dimensions = dimensions; return this; } /** * End timestamp of the query range. * @return value or {@code null} for none */ public java.lang.String getEndTimestamp() { return endTimestamp; } /** * End timestamp of the query range. * @param endTimestamp endTimestamp or {@code null} for none */ public GoogleCloudApigeeV1QueryMetadata setEndTimestamp(java.lang.String endTimestamp) { this.endTimestamp = endTimestamp; return this; } /** * Metrics of the AsyncQuery. Example: ["name:message_count,func:sum,alias:sum_message_count"] * @return value or {@code null} for none */ public java.util.List<java.lang.String> getMetrics() { return metrics; } /** * Metrics of the AsyncQuery. Example: ["name:message_count,func:sum,alias:sum_message_count"] * @param metrics metrics or {@code null} for none */ public GoogleCloudApigeeV1QueryMetadata setMetrics(java.util.List<java.lang.String> metrics) { this.metrics = metrics; return this; } /** * Output format. * @return value or {@code null} for none */ public java.lang.String getOutputFormat() { return outputFormat; } /** * Output format. * @param outputFormat outputFormat or {@code null} for none */ public GoogleCloudApigeeV1QueryMetadata setOutputFormat(java.lang.String outputFormat) { this.outputFormat = outputFormat; return this; } /** * Start timestamp of the query range. * @return value or {@code null} for none */ public java.lang.String getStartTimestamp() { return startTimestamp; } /** * Start timestamp of the query range. * @param startTimestamp startTimestamp or {@code null} for none */ public GoogleCloudApigeeV1QueryMetadata setStartTimestamp(java.lang.String startTimestamp) { this.startTimestamp = startTimestamp; return this; } /** * Query GroupBy time unit. * @return value or {@code null} for none */ public java.lang.String getTimeUnit() { return timeUnit; } /** * Query GroupBy time unit. * @param timeUnit timeUnit or {@code null} for none */ public GoogleCloudApigeeV1QueryMetadata setTimeUnit(java.lang.String timeUnit) { this.timeUnit = timeUnit; return this; } @Override public GoogleCloudApigeeV1QueryMetadata set(String fieldName, Object value) { return (GoogleCloudApigeeV1QueryMetadata) super.set(fieldName, value); } @Override public GoogleCloudApigeeV1QueryMetadata clone() { return (GoogleCloudApigeeV1QueryMetadata) super.clone(); } }
1,767
6,059
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #ifndef _FB_ANDROID_SERIALIZE_H #define _FB_ANDROID_SERIALIZE_H #include "utils/ByteOrder.h" #include "utils/Debug.h" #include "utils/Log.h" #include "utils/String16.h" #include "utils/String8.h" #include "utils/Unicode.h" #include "utils/Vector.h" namespace android { void align_vec(android::Vector<char>& cVec, size_t s); void push_short(android::Vector<char>& cVec, uint16_t data); void push_long(android::Vector<char>& cVec, uint32_t data); void push_u8_length(android::Vector<char>& cVec, size_t len); void encode_string8(android::Vector<char>& cVec, android::String8 s); void encode_string16(android::Vector<char>& cVec, android::String16 s); } #endif
309
322
<filename>vehicle/OVMS.V3/components/vehicle_bmwi3/ecu_definitions/ecu_sas_code.cpp // // Warning: don't edit - generated by generate_ecu_code.pl processing ../dev/sas_i1.json: SAS 22: Optional equipment system // This generated code makes it easier to process CANBUS messages from the SAS ecu in a BMW i3 // case I3_PID_SAS_LERNDATEN_RUECKSETZEN: { // 0xABC9 // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_SAS_VDC0_LESEN: { // 0xD817 if (datalen < 29) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_SAS_VDC0_LESEN", 29); break; } unsigned short STAT_VDC_SOLLSTROM_VL_WERT = (RXBUF_UINT(0)); // Target current of the VDC channel in the front left / Sollstrom des VDC Kanals vorne links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_SOLLSTROM_VL_WERT", STAT_VDC_SOLLSTROM_VL_WERT, "\"mA\""); unsigned short STAT_VDC_SOLLSTROM_VR_WERT = (RXBUF_UINT(2)); // Target current of the VDC channel in the front right / Sollstrom des VDC Kanals vorne rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_SOLLSTROM_VR_WERT", STAT_VDC_SOLLSTROM_VR_WERT, "\"mA\""); unsigned short STAT_VDC_SOLLSTROM_HL_WERT = (RXBUF_UINT(4)); // Target current of the VDC channel at the rear left / Sollstrom des VDC Kanals hinten links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_SOLLSTROM_HL_WERT", STAT_VDC_SOLLSTROM_HL_WERT, "\"mA\""); unsigned short STAT_VDC_SOLLSTROM_HR_WERT = (RXBUF_UINT(6)); // Set current of the VDC channel at the rear right / Sollstrom des VDC Kanals hinten rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_SOLLSTROM_HR_WERT", STAT_VDC_SOLLSTROM_HR_WERT, "\"mA\""); unsigned short STAT_VDC_ISTSTROM_VL_WERT = (RXBUF_UINT(8)); // Actual current of the VDC channel front left / Iststrom des VDC Kanals vorne links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_ISTSTROM_VL_WERT", STAT_VDC_ISTSTROM_VL_WERT, "\"mA\""); unsigned short STAT_VDC_ISTSTROM_VR_WERT = (RXBUF_UINT(10)); // Actual current of the VDC channel in the front right / Iststrom des VDC Kanals vorne rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_ISTSTROM_VR_WERT", STAT_VDC_ISTSTROM_VR_WERT, "\"mA\""); unsigned short STAT_VDC_ISTSTROM_HL_WERT = (RXBUF_UINT(12)); // Actual current of the VDC channel at the rear left / Iststrom des VDC Kanals hinten links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_ISTSTROM_HL_WERT", STAT_VDC_ISTSTROM_HL_WERT, "\"mA\""); unsigned short STAT_VDC_ISTSTROM_HR_WERT = (RXBUF_UINT(14)); // Actual current of the VDC channel at the rear right / Iststrom des VDC Kanals hinten rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_ISTSTROM_HR_WERT", STAT_VDC_ISTSTROM_HR_WERT, "\"mA\""); unsigned char STAT_VDC_STATUS_VL = (RXBUF_UCHAR(16)); // Status of the front left VDC channel / Status des VDC Kanals vorne links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_STATUS_VL", STAT_VDC_STATUS_VL, "\"0-n\""); unsigned char STAT_VDC_STATUS_VR = (RXBUF_UCHAR(17)); // Status of the VDC channel in the front right / Status des VDC Kanals vorne rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_STATUS_VR", STAT_VDC_STATUS_VR, "\"0-n\""); unsigned char STAT_VDC_STATUS_HL = (RXBUF_UCHAR(18)); // Status of the VDC channel in the back left / Status des VDC Kanals hinten links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_STATUS_HL", STAT_VDC_STATUS_HL, "\"0-n\""); unsigned char STAT_VDC_STATUS_HR = (RXBUF_UCHAR(19)); // Status of the VDC channel in the back right / Status des VDC Kanals hinten rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "SAS", "VDC0_LESEN", "STAT_VDC_STATUS_HR", STAT_VDC_STATUS_HR, "\"0-n\""); unsigned char STAT_KLEMMEN = (RXBUF_UCHAR(20)); // Internal status of terminal KL15 0 = KL15 OFF 1 = KL15 ON / Interner Status der Klemme KL15 0 = KL15 AUS 1 = // KL15 AN ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "SAS", "VDC0_LESEN", "STAT_KLEMMEN", STAT_KLEMMEN, "\"0-n\""); float STAT_WHL_SPD_VL_WERT = (RXBUF_UINT(21)*0.0156f-511.984); // Front left wheel speed (from FlexRay) / Radgeschwindigkeit vorne links (von FlexRay) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "SAS", "VDC0_LESEN", "STAT_WHL_SPD_VL_WERT", STAT_WHL_SPD_VL_WERT, "\"rad/s\""); float STAT_WHL_SPD_VR_WERT = (RXBUF_UINT(23)*0.0156f-511.984); // Wheel speed front right (from FlexRay) / Radgeschwindigkeit vorne rechts (von FlexRay) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "SAS", "VDC0_LESEN", "STAT_WHL_SPD_VR_WERT", STAT_WHL_SPD_VR_WERT, "\"rad/s\""); float STAT_WHL_SPD_HL_WERT = (RXBUF_UINT(25)*0.0156f-511.984); // Rear left wheel speed (from FlexRay) / Radgeschwindigkeit hinten links (von FlexRay) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "SAS", "VDC0_LESEN", "STAT_WHL_SPD_HL_WERT", STAT_WHL_SPD_HL_WERT, "\"rad/s\""); float STAT_WHL_SPD_HR_WERT = (RXBUF_UINT(27)*0.0156f-511.984); // Wheel speed rear right (from FlexRay) / Radgeschwindigkeit hinten rechts (von FlexRay) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "SAS", "VDC0_LESEN", "STAT_WHL_SPD_HR_WERT", STAT_WHL_SPD_HR_WERT, "\"rad/s\""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_SAS_VDC0_LESEN_0XD817: { // 0xD817 if (datalen < 29) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_SAS_VDC0_LESEN_0XD817", 29); break; } unsigned short STAT_VDC_SOLLSTROM_VL_WERT_0XD817 = (RXBUF_UINT(0)); // Target current of the VDC channel in the front left / Sollstrom des VDC Kanals vorne links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_SOLLSTROM_VL_WERT_0XD817", STAT_VDC_SOLLSTROM_VL_WERT_0XD817, "\"mA\""); unsigned short STAT_VDC_SOLLSTROM_VR_WERT_0XD817 = (RXBUF_UINT(2)); // Target current of the VDC channel in the front right / Sollstrom des VDC Kanals vorne rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_SOLLSTROM_VR_WERT_0XD817", STAT_VDC_SOLLSTROM_VR_WERT_0XD817, "\"mA\""); unsigned short STAT_VDC_SOLLSTROM_HL_WERT_0XD817 = (RXBUF_UINT(4)); // Target current of the VDC channel at the rear left / Sollstrom des VDC Kanals hinten links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_SOLLSTROM_HL_WERT_0XD817", STAT_VDC_SOLLSTROM_HL_WERT_0XD817, "\"mA\""); unsigned short STAT_VDC_SOLLSTROM_HR_WERT_0XD817 = (RXBUF_UINT(6)); // Set current of the VDC channel at the rear right / Sollstrom des VDC Kanals hinten rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_SOLLSTROM_HR_WERT_0XD817", STAT_VDC_SOLLSTROM_HR_WERT_0XD817, "\"mA\""); unsigned short STAT_VDC_ISTSTROM_VL_WERT_0XD817 = (RXBUF_UINT(8)); // Actual current of the VDC channel front left / Iststrom des VDC Kanals vorne links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_ISTSTROM_VL_WERT_0XD817", STAT_VDC_ISTSTROM_VL_WERT_0XD817, "\"mA\""); unsigned short STAT_VDC_ISTSTROM_VR_WERT_0XD817 = (RXBUF_UINT(10)); // Actual current of the VDC channel in the front right / Iststrom des VDC Kanals vorne rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_ISTSTROM_VR_WERT_0XD817", STAT_VDC_ISTSTROM_VR_WERT_0XD817, "\"mA\""); unsigned short STAT_VDC_ISTSTROM_HL_WERT_0XD817 = (RXBUF_UINT(12)); // Actual current of the VDC channel at the rear left / Iststrom des VDC Kanals hinten links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_ISTSTROM_HL_WERT_0XD817", STAT_VDC_ISTSTROM_HL_WERT_0XD817, "\"mA\""); unsigned short STAT_VDC_ISTSTROM_HR_WERT_0XD817 = (RXBUF_UINT(14)); // Actual current of the VDC channel at the rear right / Iststrom des VDC Kanals hinten rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_ISTSTROM_HR_WERT_0XD817", STAT_VDC_ISTSTROM_HR_WERT_0XD817, "\"mA\""); unsigned char STAT_VDC_STATUS_VL_0XD817 = (RXBUF_UCHAR(16)); // Status of the front left VDC channel / Status des VDC Kanals vorne links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_STATUS_VL_0XD817", STAT_VDC_STATUS_VL_0XD817, "\"0-n\""); unsigned char STAT_VDC_STATUS_VR_0XD817 = (RXBUF_UCHAR(17)); // Status of the VDC channel in the front right / Status des VDC Kanals vorne rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_STATUS_VR_0XD817", STAT_VDC_STATUS_VR_0XD817, "\"0-n\""); unsigned char STAT_VDC_STATUS_HL_0XD817 = (RXBUF_UCHAR(18)); // Status of the VDC channel in the back left / Status des VDC Kanals hinten links ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_STATUS_HL_0XD817", STAT_VDC_STATUS_HL_0XD817, "\"0-n\""); unsigned char STAT_VDC_STATUS_HR_0XD817 = (RXBUF_UCHAR(19)); // Status of the VDC channel in the back right / Status des VDC Kanals hinten rechts ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_VDC_STATUS_HR_0XD817", STAT_VDC_STATUS_HR_0XD817, "\"0-n\""); unsigned char STAT_KLEMMEN_0XD817 = (RXBUF_UCHAR(20)); // Internal status of terminal KL15 0 = KL15 OFF 1 = KL15 ON / Interner Status der Klemme KL15 0 = KL15 AUS 1 = // KL15 AN ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_KLEMMEN_0XD817", STAT_KLEMMEN_0XD817, "\"0-n\""); float STAT_WHL_SPD_VL_WERT_0XD817 = (RXBUF_UINT(21)*0.0156f-511.984); // Front left wheel speed (from FlexRay) / Radgeschwindigkeit vorne links (von FlexRay) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_WHL_SPD_VL_WERT_0XD817", STAT_WHL_SPD_VL_WERT_0XD817, "\"rad/s\""); float STAT_WHL_SPD_VR_WERT_0XD817 = (RXBUF_UINT(23)*0.0156f-511.984); // Wheel speed front right (from FlexRay) / Radgeschwindigkeit vorne rechts (von FlexRay) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_WHL_SPD_VR_WERT_0XD817", STAT_WHL_SPD_VR_WERT_0XD817, "\"rad/s\""); float STAT_WHL_SPD_HL_WERT_0XD817 = (RXBUF_UINT(25)*0.0156f-511.984); // Rear left wheel speed (from FlexRay) / Radgeschwindigkeit hinten links (von FlexRay) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_WHL_SPD_HL_WERT_0XD817", STAT_WHL_SPD_HL_WERT_0XD817, "\"rad/s\""); float STAT_WHL_SPD_HR_WERT_0XD817 = (RXBUF_UINT(27)*0.0156f-511.984); // Wheel speed rear right (from FlexRay) / Radgeschwindigkeit hinten rechts (von FlexRay) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "SAS", "VDC0_LESEN_0XD817", "STAT_WHL_SPD_HR_WERT_0XD817", STAT_WHL_SPD_HR_WERT_0XD817, "\"rad/s\""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_SAS_STATUS_SWC_VERSIONEN_LESEN_ANZAHL_DATENSAETZE: { // 0xDD33 if (datalen < 2) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_SAS_STATUS_SWC_VERSIONEN_LESEN_ANZAHL_DATENSAETZE", 2); break; } unsigned short STAT_INDEX_DATENSATZ_WERT = (RXBUF_UINT(0)); // - / - ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "SAS", "STATUS_SWC_VERSIONEN_LESEN_ANZAHL_DATENSAETZE", "STAT_INDEX_DATENSATZ_WERT", STAT_INDEX_DATENSATZ_WERT, ""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_SAS_READ_EXCEPTION_DATA: { // 0x4001 if (datalen < 50) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_SAS_READ_EXCEPTION_DATA", 50); break; } // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_SAS_CLEAR_EXCEPTION_DATA: { // 0xF000 // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; }
6,510
575
<filename>content/browser/media/session/media_session_controllers_manager.cc // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/media/session/media_session_controllers_manager.h" #include "base/stl_util.h" #include "content/browser/media/session/media_session_controller.h" #include "content/browser/web_contents/web_contents_impl.h" #include "media/base/media_switches.h" #include "services/media_session/public/cpp/features.h" namespace content { namespace { bool IsMediaSessionEnabled() { return base::FeatureList::IsEnabled( media_session::features::kMediaSessionService) || base::FeatureList::IsEnabled(media::kInternalMediaSession); } } // namespace MediaSessionControllersManager::MediaSessionControllersManager( WebContentsImpl* web_contents) : web_contents_(web_contents) {} MediaSessionControllersManager::~MediaSessionControllersManager() = default; void MediaSessionControllersManager::RenderFrameDeleted( RenderFrameHost* render_frame_host) { if (!IsMediaSessionEnabled()) return; base::EraseIf( controllers_map_, [render_frame_host](const ControllersMap::value_type& id_and_controller) { return render_frame_host->GetGlobalFrameRoutingId() == id_and_controller.first.frame_routing_id; }); } void MediaSessionControllersManager::OnMetadata( const MediaPlayerId& id, bool has_audio, bool has_video, media::MediaContentType media_content_type) { if (!IsMediaSessionEnabled()) return; MediaSessionController* const controller = FindOrCreateController(id); controller->SetMetadata(has_audio, has_video, media_content_type); } bool MediaSessionControllersManager::RequestPlay(const MediaPlayerId& id) { if (!IsMediaSessionEnabled()) return true; MediaSessionController* const controller = FindOrCreateController(id); return controller->OnPlaybackStarted(); } void MediaSessionControllersManager::OnPause(const MediaPlayerId& id, bool reached_end_of_stream) { if (!IsMediaSessionEnabled()) return; MediaSessionController* const controller = FindOrCreateController(id); controller->OnPlaybackPaused(reached_end_of_stream); } void MediaSessionControllersManager::OnEnd(const MediaPlayerId& id) { if (!IsMediaSessionEnabled()) return; controllers_map_.erase(id); } void MediaSessionControllersManager::OnMediaPositionStateChanged( const MediaPlayerId& id, const media_session::MediaPosition& position) { if (!IsMediaSessionEnabled()) return; MediaSessionController* const controller = FindOrCreateController(id); controller->OnMediaPositionStateChanged(position); } void MediaSessionControllersManager::PictureInPictureStateChanged( bool is_picture_in_picture) { if (!IsMediaSessionEnabled()) return; for (auto& entry : controllers_map_) entry.second->PictureInPictureStateChanged(is_picture_in_picture); } void MediaSessionControllersManager::WebContentsMutedStateChanged(bool muted) { if (!IsMediaSessionEnabled()) return; for (auto& entry : controllers_map_) entry.second->WebContentsMutedStateChanged(muted); } void MediaSessionControllersManager::OnPictureInPictureAvailabilityChanged( const MediaPlayerId& id, bool available) { if (!IsMediaSessionEnabled()) return; MediaSessionController* const controller = FindOrCreateController(id); controller->OnPictureInPictureAvailabilityChanged(available); } void MediaSessionControllersManager::OnAudioOutputSinkChanged( const MediaPlayerId& id, const std::string& raw_device_id) { if (!IsMediaSessionEnabled()) return; MediaSessionController* const controller = FindOrCreateController(id); controller->OnAudioOutputSinkChanged(raw_device_id); } void MediaSessionControllersManager::OnAudioOutputSinkChangingDisabled( const MediaPlayerId& id) { if (!IsMediaSessionEnabled()) return; MediaSessionController* const controller = FindOrCreateController(id); controller->OnAudioOutputSinkChangingDisabled(); } MediaSessionController* MediaSessionControllersManager::FindOrCreateController( const MediaPlayerId& id) { auto it = controllers_map_.find(id); if (it == controllers_map_.end()) { it = controllers_map_ .emplace(id, std::make_unique<MediaSessionController>( id, web_contents_)) .first; } return it->second.get(); } } // namespace content
1,485
3,195
<gh_stars>1000+ ''' Loss metric for QueryDet training Author: <NAME> ''' import numpy as np import mxnet as mx from core.detection_metric import EvalMetricWithSummary class LossMetric(EvalMetricWithSummary): def __init__(self, name, output_names, label_names, **kwargs): super().__init__(name, output_names, label_names, **kwargs) def update(self, labels, preds): self.sum_metric += preds[0].asnumpy().sum() self.num_inst += 1
181
10,225
package io.quarkus.kubernetes.deployment; import java.util.Map; import io.dekorate.kubernetes.config.Port; import io.dekorate.kubernetes.config.PortBuilder; public class PortConverter { public static Port convert(Map.Entry<String, PortConfig> e) { return convert(e.getValue()).withName(e.getKey()).build(); } private static PortBuilder convert(PortConfig port) { PortBuilder b = new PortBuilder(); port.path.ifPresent(v -> b.withPath(v)); port.hostPort.ifPresent(v -> b.withHostPort(v)); port.containerPort.ifPresent(v -> b.withContainerPort(v)); return b; } }
251
1,371
<filename>codegen/smithy-aws-go-codegen/src/main/java/software/amazon/smithy/aws/go/codegen/customization/S3ExportInternalFeatures.java<gh_stars>1000+ /* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.aws.go.codegen.customization; import software.amazon.smithy.codegen.core.Symbol; import software.amazon.smithy.codegen.core.SymbolProvider; import software.amazon.smithy.go.codegen.GoDelegator; import software.amazon.smithy.go.codegen.GoSettings; import software.amazon.smithy.go.codegen.GoWriter; import software.amazon.smithy.go.codegen.SmithyGoDependency; import software.amazon.smithy.go.codegen.SymbolUtils; import software.amazon.smithy.go.codegen.integration.GoIntegration; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ServiceShape; /** * Exports internal functionality from the s3shared package. */ public class S3ExportInternalFeatures implements GoIntegration { @Override public byte getOrder() { return 127; } @Override public void writeAdditionalFiles( GoSettings settings, Model model, SymbolProvider symbolProvider, GoDelegator goDelegator ) { ServiceShape service = settings.getService(model); if (!requiresCustomization(model, service)) { return; } goDelegator.useShapeWriter(service, writer -> { writeResponseErrorInterface(writer); writeGetHostIDWrapper(writer); }); } private void writeGetHostIDWrapper(GoWriter writer) { Symbol metadata = SymbolUtils.createPointableSymbolBuilder("Metadata", SmithyGoDependency.SMITHY_MIDDLEWARE).build(); Symbol getHostID = SymbolUtils.createValueSymbolBuilder("GetHostIDMetadata", AwsCustomGoDependency.S3_SHARED_CUSTOMIZATION).build(); writer.writeDocs("GetHostIDMetadata retrieves the host id from middleware metadata " + "returns host id as string along with a boolean indicating presence of " + "hostId on middleware metadata."); writer.openBlock("func GetHostIDMetadata(metadata $T) (string, bool) {", "}", metadata, () -> { writer.write("return $T(metadata)", getHostID); }); } private void writeResponseErrorInterface(GoWriter writer) { writer.writeDocs("ResponseError provides the HTTP centric error type wrapping the underlying error " + "with the HTTP response value and the deserialized RequestID."); writer.openBlock("type ResponseError interface {", "}", () -> { writer.write("error").write(""); writer.write("ServiceHostID() string"); writer.write("ServiceRequestID() string"); }).write(""); writer.write("var _ ResponseError = ($P)(nil)", SymbolUtils.createPointableSymbolBuilder("ResponseError", AwsCustomGoDependency.S3_SHARED_CUSTOMIZATION).build()); } // returns true if service is either s3 or s3 control private static boolean requiresCustomization(Model model, ServiceShape service) { return S3ModelUtils.isServiceS3(model, service) || S3ModelUtils.isServiceS3Control(model, service); } }
1,312
716
<filename>tools/flang1/flang1exe/commdf.c<gh_stars>100-1000 /* * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. * See https://llvm.org/LICENSE.txt for license information. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception * */ /** \file \brief Data definitions for communication data structures. */ #include "gbldefs.h" #include "global.h" #include "symtab.h" #include "soc.h" #include "semant.h" #include "ast.h" #include "gramtk.h" #include "comm.h" #include "symutl.h" #include "extern.h" TRANSFORM trans = {{NULL, 0, 0}, {NULL, 0, 0}, {NULL, 0, 0}, 0, 0, 0, NULL, NULL, 0, 0, 0, 0, 0}; struct arg_gbl arg_gbl = {0, 0, FALSE, FALSE}; struct forall_gbl forall_gbl = {0, 0, 0, 0, 0, 0}; struct pre_loop pre_loop = {0, 0, 0, 0}; struct comminfo comminfo = {0, 0, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0, 0, 0, 0}, 0}; struct tbl tbl = {NULL, 0, 0}; struct tbl pertbl = {NULL, 0, 0}; struct tbl gstbl = {NULL, 0, 0}; struct tbl brtbl = {NULL, 0, 0};
648
364
/* * .file example/oglplus/glx_main.cpp * Implements GLX-based program main function for running examples * * Copyright 2008-2019 <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) */ #include <oglplus/gl.hpp> #include <oglplus/glx/context.hpp> #include <oglplus/glx/fb_configs.hpp> #include <oglplus/glx/pixmap.hpp> #include <oglplus/glx/version.hpp> #include <oglplus/x11/color_map.hpp> #include <oglplus/x11/display.hpp> #include <oglplus/x11/visual_info.hpp> #include <oglplus/x11/window.hpp> #include <oglplus/config/fix_gl_extension.hpp> #include <oglplus/config/fix_gl_version.hpp> #include <oglplus/os/steady_clock.hpp> #include <oglplus/math/curve.hpp> #include <oglplus/math/vector.hpp> #include <oglplus/ext/ARB_debug_output.hpp> #include <cassert> #include <cstdlib> #include <cstring> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <stdexcept> #include <unordered_set> #include <vector> #include <condition_variable> #include <mutex> #include <thread> #include "example.hpp" #include "example_main.hpp" namespace oglplus { class ThreadSemaphore { private: unsigned _value; std::mutex _mutex; std::condition_variable _cv; void _decr() { std::unique_lock<std::mutex> lock(_mutex); while(_value == 0) _cv.wait(lock); --_value; } void _incr(unsigned n) { std::unique_lock<std::mutex> lock(_mutex); _value += n; _cv.notify_all(); } public: ThreadSemaphore(unsigned initial = 0) : _value(initial) {} void Wait(unsigned n = 1) { while(n--) _decr(); } void Signal(unsigned n = 1) { _incr(n); } }; struct ExampleThreadData { unsigned thread_index; ExampleThread* example_thread; std::string error_message; struct Common { Example* example; const ExampleParams& example_params; const ExampleClock& clock; const x11::ScreenNames& screen_names; const x11::Display& display; const glx::Context& ctx; ThreadSemaphore& thread_ready; ThreadSemaphore& master_ready; bool failure; bool done; } * _pcommon; Common& common() { assert(_pcommon); return *_pcommon; } }; struct ExampleOptions { const char* screenshot_path; const char* framedump_prefix; GLuint width; GLuint height; GLint samples; }; void example_thread_main(ExampleThreadData& data) { const ExampleThreadData::Common& common = data.common(); const x11::ScreenNames& sn = common.screen_names; // pick one of the available display screens // for this thread std::size_t disp_idx = data.thread_index; if(sn.size() > 1) ++disp_idx; disp_idx %= sn.size(); // open the picked display x11::Display display(sn[disp_idx].c_str()); // initialize the pixelmaps and the sharing context static int visual_attribs[] = {GLX_X_RENDERABLE, True, GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, 24, GLX_STENCIL_SIZE, 8, None}; glx::FBConfig fbc = glx::FBConfigs(display, visual_attribs).FindBest(display); x11::VisualInfo vi(display, fbc); x11::Pixmap xpm(display, vi, 8, 8); glx::Pixmap gpm(display, vi, xpm); bool debugging = true; bool compatibility = common.example_params.compat_context_threads.count( data.thread_index) != 0; glx::Context ctx(display, fbc, common.ctx, 3, 3, debugging, compatibility); ctx.MakeCurrent(gpm); // signal that the context is created common.thread_ready.Signal(); // wait for the example to be created // in the main thread common.master_ready.Wait(); // if something failed - quit if(common.failure) { common.thread_ready.Signal(); return; } else { try { assert(common.example); // call makeExampleThread std::unique_ptr<ExampleThread> example_thread(makeExampleThread( *common.example, data.thread_index, common.example_params)); data.example_thread = example_thread.get(); // signal that it is created common.thread_ready.Signal(); // wait for the main thread common.master_ready.Wait(); // if something failed - quit if(common.failure) return; // start rendering while(!common.done && !common.failure) { unsigned part_no = 0; double comp = 0.0; do { comp = example_thread->RenderPart(part_no++, common.clock); glFlush(); } while(comp < 1.0); } data.example_thread = nullptr; } catch(...) { data.example_thread = nullptr; throw; } } ctx.Release(display); } void call_example_thread_main(ExampleThreadData& data) { ExampleThreadData::Common& common = data.common(); struct main_wrapper { void (*main_func)(ExampleThreadData&); ExampleThreadData& data; int operator()() const { main_func(data); return 0; } } wrapped_main = {example_thread_main, data}; std::stringstream errstr; if(example_guarded_exec(wrapped_main, errstr) != 0) { common.failure = true; data.error_message = errstr.str(); common.thread_ready.Signal(); } } void do_run_example_loop( const x11::Display& display, const x11::Window& win, const glx::Context& ctx, std::unique_ptr<Example>& example, ExampleThreadData::Common& common, ExampleClock& clock, ExampleOptions& opts) { win.SelectInput(StructureNotifyMask | PointerMotionMask | KeyPressMask); XEvent event; os::steady_clock os_clock; bool done = false; while(!done && !common.failure) { clock.Update(ExampleTimePeriod::Seconds(os_clock.seconds())); if(!example->Continue(clock)) break; unsigned part_no = 0; double comp = 0.0; do { while(display.NextEvent(event)) { switch(event.type) { case ClientMessage: case DestroyNotify: done = true; break; case ConfigureNotify: opts.width = GLuint(event.xconfigure.width); opts.height = GLuint(event.xconfigure.height); example->Reshape(opts.width, opts.height); break; case MotionNotify: example->MouseMove( GLuint(event.xmotion.x), opts.height - GLuint(event.xmotion.y), opts.width, opts.height); break; case KeyPress: if(::XLookupKeysym(&event.xkey, 0) == XK_Escape) done = true; break; default:; } } comp = example->RenderPart(part_no++, clock); ctx.SwapBuffers(win); } while(!done && !common.failure && (comp < 1.0)); } } void run_example_loop( const x11::Display& display, const x11::Window& win, const glx::Context& ctx, std::unique_ptr<Example>& example, ExampleThreadData::Common& common, ExampleClock& clock, ExampleOptions& opts) { #if GL_ARB_debug_output ARB_debug_output dbg(false); // don't throw if(dbg.Available()) { ARB_debug_output_ToXML dbgprn(std::cout); ARB_debug_output_Unique dbgcb(dbgprn); ARB_debug_output::LogSink sink(dbgcb); dbg.Control( DebugOutputARBSource::DontCare, DebugOutputARBType::DontCare, DebugOutputARBSeverity::Low, true); dbg.InsertMessage( DebugOutputARBSource::Application, DebugOutputARBType::Other, 0, DebugOutputARBSeverity::Low, "Starting main loop"); do_run_example_loop(display, win, ctx, example, common, clock, opts); } else #endif // GL_ARB_debug_output { do_run_example_loop(display, win, ctx, example, common, clock, opts); } } void run_framedump_loop( const x11::Display& display, const x11::Window& win, const glx::Context& ctx, std::unique_ptr<Example>& example, ExampleClock& clock, const ExampleOptions& opts) { std::vector<char> txtbuf(1024); std::cin.getline(txtbuf.data(), std::streamsize(txtbuf.size())); if(std::strcmp(opts.framedump_prefix, txtbuf.data()) != 0) return; const std::size_t mouse_path_pts = 7; std::vector<Vec2f> mouse_path_pos(mouse_path_pts); std::vector<Vec2f> mouse_path_dir(mouse_path_pts); for(std::size_t p = 0; p != mouse_path_pts; ++p) { mouse_path_pos[p] = Vec2f( unsigned(std::rand()) % opts.width, unsigned(std::rand()) % opts.height); mouse_path_dir[p] = Vec2f( (std::rand() % 2 ? 1 : -1) * 10.0f * (0.2f + float(std::rand()) / float(RAND_MAX) * 0.8f), (std::rand() % 2 ? 1 : -1) * 10.0f * (0.2f + float(std::rand()) / float(RAND_MAX) * 0.8f)); } using Loop = CubicBezierLoop<Vec2f, double>; ExampleTimePeriod t = ExampleTimePeriod::Zero(); ExampleTimePeriod period = ExampleTimePeriod::Seconds(1.0 / 25.0); GLuint frame_no = 0; std::vector<char> pixels(opts.width * opts.height * 4); GLuint border = 32; bool done = false; XEvent event; while(!done) { while(display.NextEvent(event)) { switch(event.type) { case ClientMessage: case DestroyNotify: done = true; break; } } Vec2f mouse_pos = Loop(mouse_path_pos).Position(0.2 * t.Seconds()); for(std::size_t p = 0; p != mouse_path_pts; ++p) { Vec2f dir = mouse_path_dir[p]; Vec2f pos = mouse_path_pos[p]; if((pos.x() < border) && (dir.x() < 0.0)) dir = Vec2f(-dir.x(), dir.y()); if((pos.y() < border) && (dir.y() < 0.0)) dir = Vec2f(dir.x(), -dir.y()); if((pos.x() > opts.width - border) && (dir.x() > 0.0)) dir = Vec2f(-dir.x(), dir.y()); if((pos.y() > opts.height - border) && (dir.y() > 0.0)) dir = Vec2f(dir.x(), -dir.y()); mouse_path_dir[p] = dir; mouse_path_pos[p] = pos + dir; } float mouse_x = mouse_pos.x(); float mouse_y = mouse_pos.y(); if(mouse_x < 0.0f) mouse_x = 0.0f; if(mouse_y < 0.0f) mouse_y = 0.0f; if(mouse_x > opts.width) mouse_x = opts.width; if(mouse_y > opts.height) mouse_y = opts.height; example->MouseMove( GLuint(mouse_x), GLuint(mouse_y), opts.width, opts.height); t += period; clock.Update(t); if(!example->Continue(clock)) break; unsigned part_no = 0; double comp = 0.0; do { comp = example->RenderPart(part_no++, clock); } while(comp < 1.0); glFinish(); glReadPixels( 0, 0, GLsizei(opts.width), GLsizei(opts.height), GL_RGBA, GL_UNSIGNED_BYTE, pixels.data()); glFinish(); ctx.SwapBuffers(win); std::stringstream filename; filename << opts.framedump_prefix << std::setfill('0') << std::setw(6) << frame_no << ".rgba"; { std::ofstream file(filename.str()); file.write(pixels.data(), std::streamsize(pixels.size())); file.flush(); } std::cout << filename.str() << std::endl; ++frame_no; txtbuf.resize(filename.str().size() + 1); std::cin.getline(txtbuf.data(), std::streamsize(txtbuf.size())); if( std::strncmp(filename.str().c_str(), txtbuf.data(), txtbuf.size()) != 0) break; } while(display.NextEvent(event)) ; } void make_screenshot( const x11::Display& display, const x11::Window& win, const glx::Context& ctx, std::unique_ptr<Example>& example, ExampleClock& clock, const ExampleOptions& opts) { XEvent event; ExampleTimePeriod s = example->HeatUpTime(); ExampleTimePeriod t = example->ScreenshotTime(); ExampleTimePeriod dt = example->FrameTime(); clock.Update(s); // heat-up while(s < t) { while(display.NextEvent(event)) ; s += dt; clock.Update(s); unsigned part_no = 0; double comp = 0.0; do { comp = example->RenderPart(part_no++, clock); if(s < t) ctx.SwapBuffers(win); } while(comp < 1.0); } while(display.NextEvent(event)) ; glFinish(); // save it to a file std::vector<char> pixels(opts.width * opts.height * 3); glReadPixels( 0, 0, GLsizei(opts.width), GLsizei(opts.height), GL_RGB, GL_UNSIGNED_BYTE, pixels.data()); std::ofstream output(opts.screenshot_path); output.write(pixels.data(), std::streamsize(pixels.size())); ctx.SwapBuffers(win); } void run_example( const x11::Display& display, ExampleOptions& opts, int argc, char** argv) { glx::Version version(display); version.AssertAtLeast(1, 3); static int visual_attribs[] = {GLX_X_RENDERABLE, True, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, 24, GLX_STENCIL_SIZE, 8, GLX_DOUBLEBUFFER, True, GLX_SAMPLE_BUFFERS, (opts.samples > 0) ? 1 : 0, GLX_SAMPLES, (opts.samples > 0) ? opts.samples : 0, None}; glx::FBConfig fbc = glx::FBConfigs(display, visual_attribs).FindBest(display); x11::VisualInfo vi(display, fbc); x11::Window win( display, vi, x11::Colormap(display, vi), "OGLplus example", opts.width, opts.height); x11::ScreenNames screen_names; ExampleParams params(argc, argv); if(opts.framedump_prefix) { params.quality = 1.0; } params.max_threads = 128; params.num_gpus = unsigned(screen_names.size()); // TODO: something more reliable setupExample(params); params.Check(); glx::Context ctx(display, fbc, 3, 3); ctx.MakeCurrent(win); // The clock for animation timing ExampleClock clock; std::vector<std::thread> threads; ThreadSemaphore thread_ready, master_ready; ExampleThreadData::Common example_thread_common_data = { nullptr, params, clock, screen_names, display, ctx, thread_ready, master_ready, false /*failure*/, false /*done*/ }; try { // Initialize the GL API library (GLEW/GL3W/...) oglplus::GLAPIInitializer api_init; // things required for multi-threaded examples std::vector<ExampleThreadData> thread_data; // prepare the example data for(unsigned t = 0; t != params.num_threads; ++t) { ExampleThreadData example_thread_data = { t, nullptr, std::string(), &example_thread_common_data}; thread_data.push_back(example_thread_data); } // start the examples and let them // create their own contexts shared with // the main context for(unsigned t = 0; t != params.num_threads; ++t) { threads.emplace_back( call_example_thread_main, std::ref(thread_data[t])); // wait for the thread to create // an off-screen context thread_ready.Wait(); // check for errors if(!thread_data[t].error_message.empty()) { example_thread_common_data.failure = true; example_thread_common_data.master_ready.Signal(t); throw std::runtime_error(thread_data[t].error_message); } } // make the example std::unique_ptr<Example> example(makeExample(params)); // tell the threads about the example // and let them call makeExampleThread example_thread_common_data.example = example.get(); for(unsigned t = 0; t != params.num_threads; ++t) { // signal that the example is ready master_ready.Signal(); // wait for the threads to call makeExampleThread thread_ready.Wait(); } // check for potential errors and let // the example do additional thread-related preparations for(unsigned t = 0; t != params.num_threads; ++t) { if(!thread_data[t].error_message.empty()) { example_thread_common_data.failure = true; example_thread_common_data.master_ready.Signal( params.num_threads); throw std::runtime_error(thread_data[t].error_message); } assert(thread_data[t].example_thread); example->PrepareThread(t, *thread_data[t].example_thread); } // signal that the example threads may start // rendering master_ready.Signal(params.num_threads); if(opts.samples > 0) { // enable multisampling glEnable(GL_MULTISAMPLE); } example->Reshape(opts.width, opts.height); example->MouseMove( opts.width / 2, opts.height / 2, opts.width, opts.height); if(opts.screenshot_path) { make_screenshot(display, win, ctx, example, clock, opts); } else if(opts.framedump_prefix) { run_framedump_loop(display, win, ctx, example, clock, opts); } else { run_example_loop( display, win, ctx, example, example_thread_common_data, clock, opts); } example_thread_common_data.done = true; // cancel the example threads for(unsigned t = 0; t != params.num_threads; ++t) { if(thread_data[t].example_thread) thread_data[t].example_thread->Cancel(); } // join the example threads for(unsigned t = 0; t != params.num_threads; ++t) { threads[t].join(); } for(unsigned t = 0; t != params.num_threads; ++t) { if(!thread_data[t].error_message.empty()) throw std::runtime_error(thread_data[t].error_message); } } catch(...) { example_thread_common_data.failure = true; master_ready.Signal(params.num_threads); try { for(auto& thread : threads) thread.join(); } catch(...) { } throw; } ctx.Release(display); } } // namespace oglplus int glx_example_main(int argc, char** argv) { oglplus::ExampleOptions opts; opts.screenshot_path = nullptr; opts.framedump_prefix = nullptr; opts.width = 800; opts.height = 600; opts.samples = 0; int a = 1; while(a < argc) { short parsed = 0; if((std::strcmp(argv[a], "--screenshot")) == 0 && (a + 1 < argc)) { opts.screenshot_path = argv[a + 1]; parsed = 2; } else if( (std::strcmp(argv[a], "--frame-dump")) == 0 && (a + 1 < argc)) { opts.framedump_prefix = argv[a + 1]; parsed = 2; } else if((std::strcmp(argv[a], "--width")) == 0 && (a + 1 < argc)) { opts.width = GLuint(std::atoi(argv[a + 1])); parsed = 2; } else if((std::strcmp(argv[a], "--height")) == 0 && (a + 1 < argc)) { opts.height = GLuint(std::atoi(argv[a + 1])); parsed = 2; } else if((std::strcmp(argv[a], "--samples")) == 0 && (a + 1 < argc)) { opts.samples = GLint(std::atoi(argv[a + 1])); parsed = 2; } if(parsed == 2) { for(int b = a + 1; b < argc; ++b) { argv[b - 2] = argv[b]; } argc -= 2; } else if(parsed == 0) { ++a; } } // run the main loop oglplus::run_example(oglplus::x11::Display(), opts, argc, argv); return 0; } int main(int argc, char** argv) { return oglplus::example_main(glx_example_main, argc, argv); }
11,801
2,542
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #pragma once #include <string> #include <windows.h> class PathHelper { public: static std::wstring GetDirectoryName(const std::wstring& path); // Returns the name and extension parts of the given path. The resulting // string contains the characters of path that follow the last // backslash ("\"), slash ("/"), or colon (":") character in // path. The resulting string is the entire path if path // contains no backslash after removing trailing slashes, slash, or colon characters. The resulting // string is null if path is null. static std::wstring GetFileName(std::wstring const & path); static void CombineInPlace(std::wstring& path1, const std::wstring& path2); static std::wstring Combine(const std::wstring& path1, const std::wstring& path2); static std::wstring GetModuleLocation(); static std::wstring GetCurrentDirectory(); private: // Returns the path to the module HMODULE // This is a wrapper around GetModuleFileName static std::wstring GetModuleLocation(HMODULE hModule); };
340
718
<reponame>RPUTHUMA/Skater<filename>skater/tests/test_feature_importance.py import unittest import numpy as np from scipy.stats import norm from scipy.special import expit from sklearn.linear_model import LinearRegression, LogisticRegression from sklearn.ensemble import GradientBoostingClassifier from sklearn import datasets from functools import partial from skater.core.explanations import Interpretation from skater.util import exceptions from skater.tests.arg_parser import create_parser from skater.model import InMemoryModel, DeployedModel class TestFeatureImportance(unittest.TestCase): def setUp(self): args = create_parser().parse_args() debug = args.debug self.seed = args.seed self.n = args.n self.dim = args.dim self.features = [str(i) for i in range(self.dim)] self.X = norm.rvs(0, 1, size=(self.n, self.dim), random_state=self.seed) self.B = np.array([-10.1, 2.2, 6.1]) self.y = np.dot(self.X, self.B) self.y_as_int = np.round(expit(self.y)) self.y_as_string = np.array([str(i) for i in self.y_as_int]) # example dataset for y = B.X # X = array([[ 1.62434536, -0.61175641, -0.52817175], ... [-0.15065961, -1.40002289, -1.30106608]]) (1000 * 3) # B = array([-10.1, 2.2, 6.1]) # y = array([ -2.09736000e+01, -1.29850618e+00, -1.73511155e+01, ...]) (1000 * 1) # features = ['0', '1', '2'] ## # Other output types: # y_as_int = array[ 0., 0., 0., 0., 1., 1., 0., 0., 0., 1., 1., 1., 1., ...] # y_as_string = array['0.0', '0.0', '0.0', '0.0', '1.0', '1.0', '0.0', '0.0', '0.0', ... ] # Another set of input # sample data self.sample_x = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]) self.sample_y = np.array([-1, -1, -1, 1, 1, 1]) self.sample_feature_name = [str(i) for i in range(self.sample_x.shape[1])] if debug: self.interpreter = Interpretation(training_data=self.X, feature_names=self.features, log_level='DEBUG') else: self.interpreter = Interpretation(training_data=self.X, feature_names=self.features) # default level is 'WARNING' self.regressor = LinearRegression() self.regressor.fit(self.X, self.y) self.regressor_predict_fn = InMemoryModel(self.regressor.predict, examples=self.X) self.classifier = LogisticRegression() self.classifier.fit(self.X, self.y_as_int) self.classifier_predict_fn = InMemoryModel(self.classifier.predict, examples=self.X, unique_values=self.classifier.classes_, probability=False) self.classifier_predict_proba_fn = InMemoryModel(self.classifier.predict_proba, examples=self.X, probability=True) self.string_classifier = LogisticRegression() self.string_classifier.fit(self.X, self.y_as_string) self.string_classifier_predict_fn = InMemoryModel(self.string_classifier.predict_proba, examples=self.X, probability=True) @staticmethod def feature_column_name_formatter(columnname): return "feature: {}".format(columnname) def test_feature_importance(self): importances = self.interpreter.feature_importance.feature_importance(self.regressor_predict_fn, n_jobs=1, progressbar=False) self.assertEquals(np.isclose(importances.sum(), 1), True) importances = self.interpreter.feature_importance.feature_importance(self.regressor_predict_fn, n_jobs=2, progressbar=False) self.assertEquals(np.isclose(importances.sum(), 1), True) def test_feature_importance_progressbar(self): importances = self.interpreter.feature_importance.feature_importance(self.regressor_predict_fn, progressbar=False) self.assertEquals(np.isclose(importances.sum(), 1), True) def test_feature_importance_entropy_with_and_without_scaling(self): importances = self.interpreter.feature_importance.feature_importance(self.regressor_predict_fn, progressbar=False, use_scaling=True) self.assertEquals(np.isclose(importances.sum(), 1), True) importances = self.interpreter.feature_importance.feature_importance(self.regressor_predict_fn, progressbar=True, use_scaling=False) self.assertEquals(np.isclose(importances.sum(), 1), True) def test_feature_importance_regression_via_preformance_decrease(self): interpreter = Interpretation(self.X, feature_names=self.features, training_labels=self.y) importances = interpreter.feature_importance.feature_importance(self.regressor_predict_fn, method='model-scoring', use_scaling=False) self.assertEquals(np.isclose(importances.sum(), 1), True) importances = interpreter.feature_importance.feature_importance(self.regressor_predict_fn, method='model-scoring', use_scaling=True) self.assertEquals(np.isclose(importances.sum(), 1), True) def test_feature_importance_classifier_via_preformance_decrease(self): interpreter = Interpretation(self.X, feature_names=self.features, training_labels=self.y_as_int) importances = interpreter.feature_importance.feature_importance(self.classifier_predict_fn, method='model-scoring', use_scaling=False) self.assertEquals(np.isclose(importances.sum(), 1), True) importances = interpreter.feature_importance.feature_importance(self.classifier_predict_fn, method='model-scoring', use_scaling=True) self.assertEquals(np.isclose(importances.sum(), 1), True) def test_feature_importance_classifier_proba_via_preformance_decrease(self): interpreter = Interpretation(self.X, feature_names=self.features, training_labels=self.y_as_int) importances = interpreter.feature_importance.feature_importance(self.classifier_predict_proba_fn, method='model-scoring', use_scaling=False) self.assertEquals(np.isclose(importances.sum(), 1), True) importances = interpreter.feature_importance.feature_importance(self.classifier_predict_proba_fn, method='model-scoring', use_scaling=True) self.assertEquals(np.isclose(importances.sum(), 1), True) @unittest.skip("Related to plotting ...") def test_plot_feature_importance(self): self.interpreter.feature_importance.plot_feature_importance(self.regressor_predict_fn) def test_feature_importance_sampling(self): """ We should be able to sample the data and use training labels. :return: """ interpreter = Interpretation(self.X, feature_names=self.features, training_labels=self.y_as_int) importances = interpreter.feature_importance.feature_importance(self.classifier_predict_proba_fn, n_samples=len(self.X) - 1, method='model-scoring', use_scaling=True) self.assertEquals(np.isclose(importances.sum(), 1), True) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestFeatureImportance) unittest.TextTestRunner(verbosity=2).run(suite)
4,940
1,383
<gh_stars>1000+ // ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: <NAME> // ============================================================================= // // Wrapper classes for modeling an entire mrole vehicle assembly // (including the vehicle itself, the powertrain, and the tires). // // ============================================================================= #include "chrono/ChConfig.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_models/vehicle/mrole/mrole.h" #include "chrono_models/vehicle/mrole/mrole_Powertrain.h" #include "chrono_models/vehicle/mrole/mrole_RigidTire.h" #include "chrono_models/vehicle/mrole/mrole_SimpleMapPowertrain.h" #include "chrono_models/vehicle/mrole/mrole_SimplePowertrain.h" #include "chrono_models/vehicle/mrole/mrole_SimpleCVTPowertrain.h" #include "chrono_models/vehicle/mrole/mrole_TMeasyTire.h" namespace chrono { namespace vehicle { namespace mrole { // ----------------------------------------------------------------------------- mrole::mrole() : m_system(nullptr), m_vehicle(nullptr), m_contactMethod(ChContactMethod::NSC), m_chassisCollisionType(CollisionType::NONE), m_fixed(false), m_brake_locking(false), m_brake_type(BrakeType::SIMPLE), m_driveType(DrivelineTypeWV::AWD), m_powertrainType(PowertrainModelType::SHAFTS), m_tireType(TireModelType::RIGID), m_tire_collision_type(ChTire::CollisionType::SINGLE_POINT), m_tire_step_size(-1), m_initFwdVel(0), m_initPos(ChCoordsys<>(ChVector<>(0, 0, 1), QUNIT)), m_initOmega({0, 0, 0, 0}), m_ctis(CTIS::ROAD), m_apply_drag(false) {} mrole::mrole(ChSystem* system) : m_system(system), m_vehicle(nullptr), m_contactMethod(ChContactMethod::NSC), m_chassisCollisionType(CollisionType::NONE), m_fixed(false), m_brake_locking(false), m_brake_type(BrakeType::SIMPLE), m_driveType(DrivelineTypeWV::AWD), m_powertrainType(PowertrainModelType::SHAFTS), m_tireType(TireModelType::RIGID), m_tire_collision_type(ChTire::CollisionType::SINGLE_POINT), m_tire_step_size(-1), m_initFwdVel(0), m_initPos(ChCoordsys<>(ChVector<>(0, 0, 1), QUNIT)), m_initOmega({0, 0, 0, 0}), m_ctis(CTIS::ROAD), m_apply_drag(false) {} mrole::~mrole() { delete m_vehicle; } // ----------------------------------------------------------------------------- void mrole::SetAerodynamicDrag(double Cd, double area, double air_density) { m_Cd = Cd; m_area = area; m_air_density = air_density; m_apply_drag = true; } // ----------------------------------------------------------------------------- void mrole::Initialize() { // Create and initialize the mrole vehicle m_vehicle = CreateVehicle(); m_vehicle->SetInitWheelAngVel(m_initOmega); m_vehicle->Initialize(m_initPos, m_initFwdVel); // If specified, enable aerodynamic drag if (m_apply_drag) { m_vehicle->GetChassis()->SetAerodynamicDrag(m_Cd, m_area, m_air_density); } // Create and initialize the powertrain system switch (m_powertrainType) { case PowertrainModelType::SHAFTS: { auto powertrain = chrono_types::make_shared<mrole_Powertrain>("Powertrain"); m_vehicle->InitializePowertrain(powertrain); break; } case PowertrainModelType::SIMPLE_MAP: { auto powertrain = chrono_types::make_shared<mrole_SimpleMapPowertrain>("Powertrain"); m_vehicle->InitializePowertrain(powertrain); break; } case PowertrainModelType::SIMPLE: { auto powertrain = chrono_types::make_shared<mrole_SimplePowertrain>("Powertrain"); m_vehicle->InitializePowertrain(powertrain); break; } case PowertrainModelType::SIMPLE_CVT: { auto powertrain = chrono_types::make_shared<mrole_SimpleCVTPowertrain>("Powertrain"); m_vehicle->InitializePowertrain(powertrain); break; } } // Create the tires and set parameters depending on type. switch (m_tireType) { case TireModelType::RIGID: case TireModelType::RIGID_MESH: { bool use_mesh = (m_tireType == TireModelType::RIGID_MESH); auto tire_FL1 = chrono_types::make_shared<mrole_RigidTire>("FL1", use_mesh); auto tire_FR1 = chrono_types::make_shared<mrole_RigidTire>("FR1", use_mesh); auto tire_FL2 = chrono_types::make_shared<mrole_RigidTire>("FL2", use_mesh); auto tire_FR2 = chrono_types::make_shared<mrole_RigidTire>("FR2", use_mesh); auto tire_RL1 = chrono_types::make_shared<mrole_RigidTire>("RL1", use_mesh); auto tire_RR1 = chrono_types::make_shared<mrole_RigidTire>("RR1", use_mesh); auto tire_RL2 = chrono_types::make_shared<mrole_RigidTire>("RL2", use_mesh); auto tire_RR2 = chrono_types::make_shared<mrole_RigidTire>("RR2", use_mesh); m_vehicle->InitializeTire(tire_FL1, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR1, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FL2, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR2, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL1, m_vehicle->GetAxle(2)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR1, m_vehicle->GetAxle(2)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL2, m_vehicle->GetAxle(3)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR2, m_vehicle->GetAxle(3)->m_wheels[RIGHT], VisualizationType::NONE); m_tire_mass = tire_FL1->ReportMass(); break; } /* case TireModelType::LUGRE: { auto tire_FL = chrono_types::make_shared<mrole_LugreTire>("FL"); auto tire_FR = chrono_types::make_shared<mrole_LugreTire>("FR"); auto tire_RL = chrono_types::make_shared<mrole_LugreTire>("RL"); auto tire_RR = chrono_types::make_shared<mrole_LugreTire>("RR"); m_vehicle->InitializeTire(tire_FL, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE); m_tire_mass = tire_FL->ReportMass(); break; } case TireModelType::FIALA: { auto tire_FL = chrono_types::make_shared<mrole_FialaTire>("FL"); auto tire_FR = chrono_types::make_shared<mrole_FialaTire>("FR"); auto tire_RL = chrono_types::make_shared<mrole_FialaTire>("RL"); auto tire_RR = chrono_types::make_shared<mrole_FialaTire>("RR"); m_vehicle->InitializeTire(tire_FL, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE); m_tire_mass = tire_FL->ReportMass(); break; } */ case TireModelType::TMEASY: { switch (m_ctis) { case CTIS::ROAD: { auto tire_FL1 = chrono_types::make_shared<mrole_TMeasyTire>("FL1"); auto tire_FR1 = chrono_types::make_shared<mrole_TMeasyTire>("FR1"); auto tire_FL2 = chrono_types::make_shared<mrole_TMeasyTire>("FL2"); auto tire_FR2 = chrono_types::make_shared<mrole_TMeasyTire>("FR2"); auto tire_RL1 = chrono_types::make_shared<mrole_TMeasyTire>("RL1"); auto tire_RR1 = chrono_types::make_shared<mrole_TMeasyTire>("RR1"); auto tire_RL2 = chrono_types::make_shared<mrole_TMeasyTire>("RL2"); auto tire_RR2 = chrono_types::make_shared<mrole_TMeasyTire>("RR2"); m_vehicle->InitializeTire(tire_FL1, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR1, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FL2, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR2, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL1, m_vehicle->GetAxle(2)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR1, m_vehicle->GetAxle(2)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL2, m_vehicle->GetAxle(3)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR2, m_vehicle->GetAxle(3)->m_wheels[RIGHT], VisualizationType::NONE); m_tire_mass = tire_FL1->ReportMass(); } break; case CTIS::OFFROAD_SOIL: { auto tire_FL1 = chrono_types::make_shared<mrole_TMeasyTireSoil>("FL1"); auto tire_FR1 = chrono_types::make_shared<mrole_TMeasyTireSoil>("FR1"); auto tire_FL2 = chrono_types::make_shared<mrole_TMeasyTireSoil>("FL2"); auto tire_FR2 = chrono_types::make_shared<mrole_TMeasyTireSoil>("FR2"); auto tire_RL1 = chrono_types::make_shared<mrole_TMeasyTireSoil>("RL1"); auto tire_RR1 = chrono_types::make_shared<mrole_TMeasyTireSoil>("RR1"); auto tire_RL2 = chrono_types::make_shared<mrole_TMeasyTireSoil>("RL2"); auto tire_RR2 = chrono_types::make_shared<mrole_TMeasyTireSoil>("RR2"); m_vehicle->InitializeTire(tire_FL1, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR1, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FL2, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR2, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL1, m_vehicle->GetAxle(2)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR1, m_vehicle->GetAxle(2)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL2, m_vehicle->GetAxle(3)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR2, m_vehicle->GetAxle(3)->m_wheels[RIGHT], VisualizationType::NONE); m_tire_mass = tire_FL1->ReportMass(); } break; case CTIS::OFFROAD_SAND: { auto tire_FL1 = chrono_types::make_shared<mrole_TMeasyTireSand>("FL1"); auto tire_FR1 = chrono_types::make_shared<mrole_TMeasyTireSand>("FR1"); auto tire_FL2 = chrono_types::make_shared<mrole_TMeasyTireSand>("FL2"); auto tire_FR2 = chrono_types::make_shared<mrole_TMeasyTireSand>("FR2"); auto tire_RL1 = chrono_types::make_shared<mrole_TMeasyTireSand>("RL1"); auto tire_RR1 = chrono_types::make_shared<mrole_TMeasyTireSand>("RR1"); auto tire_RL2 = chrono_types::make_shared<mrole_TMeasyTireSand>("RL2"); auto tire_RR2 = chrono_types::make_shared<mrole_TMeasyTireSand>("RR2"); m_vehicle->InitializeTire(tire_FL1, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR1, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FL2, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR2, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL1, m_vehicle->GetAxle(2)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR1, m_vehicle->GetAxle(2)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL2, m_vehicle->GetAxle(3)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR2, m_vehicle->GetAxle(3)->m_wheels[RIGHT], VisualizationType::NONE); m_tire_mass = tire_FL1->ReportMass(); } break; } break; } /* case TireModelType::PAC89: { auto tire_FL = chrono_types::make_shared<mrole_Pac89Tire>("FL"); auto tire_FR = chrono_types::make_shared<mrole_Pac89Tire>("FR"); auto tire_RL = chrono_types::make_shared<mrole_Pac89Tire>("RL"); auto tire_RR = chrono_types::make_shared<mrole_Pac89Tire>("RR"); m_vehicle->InitializeTire(tire_FL, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE); m_tire_mass = tire_FL->ReportMass(); break; } case TireModelType::PAC02: { auto tire_FL = chrono_types::make_shared<mrole_Pac02Tire>("FL"); auto tire_FR = chrono_types::make_shared<mrole_Pac02Tire>("FR"); auto tire_RL = chrono_types::make_shared<mrole_Pac02Tire>("RL"); auto tire_RR = chrono_types::make_shared<mrole_Pac02Tire>("RR"); m_vehicle->InitializeTire(tire_FL, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE); m_tire_mass = tire_FL->ReportMass(); break; } case TireModelType::PACEJKA: { auto tire_FL = chrono_types::make_shared<mrole_PacejkaTire>("FL"); auto tire_FR = chrono_types::make_shared<mrole_PacejkaTire>("FR"); auto tire_RL = chrono_types::make_shared<mrole_PacejkaTire>("RL"); auto tire_RR = chrono_types::make_shared<mrole_PacejkaTire>("RR"); tire_FL->SetDrivenWheel(false); tire_FR->SetDrivenWheel(false); tire_RL->SetDrivenWheel(true); tire_RR->SetDrivenWheel(true); m_vehicle->InitializeTire(tire_FL, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE); m_tire_mass = tire_FL->ReportMass(); break; } case TireModelType::ANCF: { auto tire_FL = chrono_types::make_shared<mrole_ANCFTire>("FL"); auto tire_FR = chrono_types::make_shared<mrole_ANCFTire>("FR"); auto tire_RL = chrono_types::make_shared<mrole_ANCFTire>("RL"); auto tire_RR = chrono_types::make_shared<mrole_ANCFTire>("RR"); m_vehicle->InitializeTire(tire_FL, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE); m_tire_mass = tire_FL->ReportMass(); break; } case TireModelType::REISSNER: { auto tire_FL = chrono_types::make_shared<mrole_ReissnerTire>("FL"); auto tire_FR = chrono_types::make_shared<mrole_ReissnerTire>("FR"); auto tire_RL = chrono_types::make_shared<mrole_ReissnerTire>("RL"); auto tire_RR = chrono_types::make_shared<mrole_ReissnerTire>("RR"); m_vehicle->InitializeTire(tire_FL, m_vehicle->GetAxle(0)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_FR, m_vehicle->GetAxle(0)->m_wheels[RIGHT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RL, m_vehicle->GetAxle(1)->m_wheels[LEFT], VisualizationType::NONE); m_vehicle->InitializeTire(tire_RR, m_vehicle->GetAxle(1)->m_wheels[RIGHT], VisualizationType::NONE); m_tire_mass = tire_FL->ReportMass(); break; } */ default: break; } for (auto& axle : m_vehicle->GetAxles()) { for (auto& wheel : axle->GetWheels()) { wheel->GetTire()->SetCollisionType(m_tire_collision_type); if (m_tire_step_size > 0) wheel->GetTire()->SetStepsize(m_tire_step_size); } } m_vehicle->EnableBrakeLocking(m_brake_locking); } double mrole::GetMaxTireSpeed() { switch (m_ctis) { default: case CTIS::ROAD: return 110.0 / 3.6; case CTIS::OFFROAD_SOIL: return 70.0 / 3.6; case CTIS::OFFROAD_SAND: return 30.0 / 3.6; } } // ----------------------------------------------------------------------------- void mrole::Synchronize(double time, const ChDriver::Inputs& driver_inputs, const ChTerrain& terrain) { m_vehicle->Synchronize(time, driver_inputs, terrain); } // ----------------------------------------------------------------------------- void mrole::Advance(double step) { m_vehicle->Advance(step); } // ----------------------------------------------------------------------------- double mrole::GetTotalMass() const { return m_vehicle->GetVehicleMass() + 8 * m_tire_mass; } // ============================================================================= mrole_Vehicle* mrole_Full::CreateVehicle() { if (m_system) { return new mrole_VehicleFull(m_system, m_fixed, m_driveType, m_brake_type, m_steeringType, m_rigidColumn, m_chassisCollisionType); } return new mrole_VehicleFull(m_fixed, m_driveType, m_brake_type, m_steeringType, m_rigidColumn, m_contactMethod, m_chassisCollisionType); } mrole_Vehicle* mrole_Reduced::CreateVehicle() { if (m_system) { return new mrole_VehicleReduced(m_system, m_fixed, m_driveType, m_brake_type, m_chassisCollisionType); } return new mrole_VehicleReduced(m_fixed, m_driveType, m_brake_type, m_contactMethod, m_chassisCollisionType); } } // namespace mrole } // end namespace vehicle } // end namespace chrono
10,288
348
{"nom":"Azincourt","circ":"4ème circonscription","dpt":"Pas-de-Calais","inscrits":227,"abs":81,"votants":146,"blancs":0,"nuls":3,"exp":143,"res":[{"nuance":"LR","nom":"<NAME>","voix":108},{"nuance":"REM","nom":"<NAME>","voix":35}]}
94
45,293
package test; class GenericArray { public static void ggff() { String[] s = GenericArrayKt.ffgg(new String[0]); } }
54
408
<filename>pywick/gridsearch/grid_test.py import json from .gridsearch import GridSearch my_args = { 'shape': '+plus+', 'animal':['cat', 'mouse', 'dog'], 'number':[4, 5, 6], 'device':['CUP', 'MUG', 'TPOT'], 'flower' : '=Rose=' } def tryme(args_dict): print(json.dumps(args_dict, indent=4)) def tryme_vars(animal='', number=0, device='', shape='', flower=''): print(animal + " : " + str(number) + " : " + device + " : " + shape + " : " + flower) def main(): grids = GridSearch(tryme, grid_params=my_args, search_behavior='exhaustive', args_as_dict=True) print('-------- INITIAL SETTINGS ---------') tryme(my_args) print('-------------- END ----------------') print('-------------- --- ----------------') print() print('+++++++++++ Dict Result ++++++++++') grids.run() print('+++++++++++++ End Dict Result +++++++++++\n\n') grids = GridSearch(tryme_vars, grid_params=my_args, search_behavior='sampled_0.5', args_as_dict=False) print('========== Vars Result ==========') grids.run() print('========== End Vars Result ==========') # exit() if __name__ == '__main__': main()
443
881
<filename>dev/restinio/http_server_run.hpp /* * restinio */ /*! * \file * \brief Helper function for simple run of HTTP server. */ #pragma once #include <restinio/impl/ioctx_on_thread_pool.hpp> #include <restinio/http_server.hpp> namespace restinio { // // break_signal_handling_t // /*! * @brief Indication of usage of break signal handlers for some forms * of run functions. * * @since v.0.5.1 */ enum class break_signal_handling_t { //! Signal handler should be used by run() function. used, //! Signal handler should not be used by run() function. skipped }; /*! * @brief Make the indicator for usage of break signal handler. * * Usage example: * @code * restinio::run( restinio::on_thread_pool( * std::thread::hardware_concurrency(), * restinio::use_break_signal_handling(), * my_server) ); * @endcode * * @since v.0.5.1 */ inline constexpr break_signal_handling_t use_break_signal_handling() noexcept { return break_signal_handling_t::used; } /*! * @brief Make the indicator for absence of break signal handler. * * Usage example: * @code * restinio::run( restinio::on_thread_pool( * std::thread::hardware_concurrency(), * restinio::skip_break_signal_handling(), * my_server) ); * @endcode * * @since v.0.5.1 */ inline constexpr break_signal_handling_t skip_break_signal_handling() noexcept { return break_signal_handling_t::skipped; } // // run_on_this_thread_settings_t // /*! * \brief Settings for the case when http_server must be run * on the context of the current thread. * * \note * Shouldn't be used directly. Only as result of on_this_thread() * function as parameter for run(). */ template<typename Traits> class run_on_this_thread_settings_t final : public basic_server_settings_t< run_on_this_thread_settings_t<Traits>, Traits> { using base_type_t = basic_server_settings_t< run_on_this_thread_settings_t<Traits>, Traits>; public: // Inherit constructors from base class. using base_type_t::base_type_t; }; // // on_this_thread // /*! * \brief A special marker for the case when http_server must be * run on the context of the current thread. * * Usage example: * \code * // Run with the default traits. * run( restinio::on_this_thread() * .port(8080) * .address("localhost") * .request_handler(...) ); * \endcode * For a case when some custom traits must be used: * \code * run( restinio::on_this_thread<my_server_traits_t>() * .port(8080) * .address("localhost") * .request_handler(...) ); * \endcode */ template<typename Traits = default_single_thread_traits_t> run_on_this_thread_settings_t<Traits> on_this_thread() { return run_on_this_thread_settings_t<Traits>{}; } // // run_on_thread_pool_settings_t // /*! * \brief Settings for the case when http_server must be run * on the context of the current thread. * * \note * Shouldn't be used directly. Only as result of on_thread_pool() * function as parameter for run(). */ template<typename Traits> class run_on_thread_pool_settings_t final : public basic_server_settings_t< run_on_thread_pool_settings_t<Traits>, Traits> { //! Size of the pool. std::size_t m_pool_size; public: //! Constructor. run_on_thread_pool_settings_t( //! Size of the pool. std::size_t pool_size ) : m_pool_size(pool_size) {} //! Get the pool size. std::size_t pool_size() const { return m_pool_size; } }; // // on_thread_pool // /*! * \brief A special marker for the case when http_server must be * run on an thread pool. * * Usage example: * \code * // Run with the default traits. * run( restinio::on_thread_pool(16) // 16 -- is the pool size. * .port(8080) * .address("localhost") * .request_handler(...) ); * \endcode * For a case when some custom traits must be used: * \code * run( restinio::on_thread_pool<my_server_traits_t>(16) * .port(8080) * .address("localhost") * .request_handler(...) ); * \endcode */ template<typename Traits = default_traits_t> run_on_thread_pool_settings_t<Traits> on_thread_pool( //! Size of the pool. std::size_t pool_size ) { return run_on_thread_pool_settings_t<Traits>( pool_size ); } // // run() // //! Helper function for running http server until ctrl+c is hit. /*! * Can be useful when RESTinio server should be run on the user's * own io_context instance. * * For example: * \code * asio::io_context iosvc; * ... // iosvc used by user. * restinio::run(iosvc, * restinio::on_this_thread<my_traits>() * .port(8080) * .address("localhost") * .request_handler([](auto req) {...})); * \endcode * * \since * v.0.4.2 */ template<typename Traits> inline void run( //! Asio's io_context to be used. //! Note: this reference should remain valid until RESTinio server finished. asio_ns::io_context & ioctx, //! Settings for that server instance. run_on_this_thread_settings_t<Traits> && settings ) { using settings_t = run_on_this_thread_settings_t<Traits>; using server_t = http_server_t<Traits>; server_t server{ restinio::external_io_context( ioctx ), std::forward<settings_t>(settings) }; std::exception_ptr exception_caught; asio_ns::signal_set break_signals{ server.io_context(), SIGINT }; break_signals.async_wait( [&]( const asio_ns::error_code & ec, int ){ if( !ec ) { server.close_async( [&]{ // Stop running io_service. ioctx.stop(); }, [&exception_caught]( std::exception_ptr ex ){ // We can't throw an exception here! // Store it to rethrow later. exception_caught = ex; } ); } } ); server.open_async( []{ /* Ok. */}, [&ioctx, &exception_caught]( std::exception_ptr ex ){ // Stop running io_service. // We can't throw an exception here! // Store it to rethrow later. ioctx.stop(); exception_caught = ex; } ); ioctx.run(); // If an error was detected it should be propagated. if( exception_caught ) std::rethrow_exception( exception_caught ); } //! Helper function for running http server until ctrl+c is hit. /*! * This function creates its own instance of Asio's io_context and * uses it exclusively. * * Usage example: * \code * restinio::run( * restinio::on_this_thread<my_traits>() * .port(8080) * .address("localhost") * .request_handler([](auto req) {...})); * \endcode */ template<typename Traits> inline void run( run_on_this_thread_settings_t<Traits> && settings ) { asio_ns::io_context io_context; run( io_context, std::move(settings) ); } namespace impl { /*! * \brief An implementation of run-function for thread pool case. * * This function receives an already created thread pool object and * creates and runs http-server on this thread pool. * * \since * v.0.4.2 */ template<typename Io_Context_Holder, typename Traits> void run( ioctx_on_thread_pool_t<Io_Context_Holder> & pool, run_on_thread_pool_settings_t<Traits> && settings ) { using settings_t = run_on_thread_pool_settings_t<Traits>; using server_t = http_server_t<Traits>; server_t server{ restinio::external_io_context( pool.io_context() ), std::forward<settings_t>(settings) }; std::exception_ptr exception_caught; asio_ns::signal_set break_signals{ server.io_context(), SIGINT }; break_signals.async_wait( [&]( const asio_ns::error_code & ec, int ){ if( !ec ) { server.close_async( [&]{ // Stop running io_service. pool.stop(); }, [&exception_caught]( std::exception_ptr ex ){ // We can't throw an exception here! // Store it to rethrow later. exception_caught = ex; } ); } } ); server.open_async( []{ /* Ok. */}, [&pool, &exception_caught]( std::exception_ptr ex ){ // Stop running io_service. // We can't throw an exception here! // Store it to rethrow later. pool.stop(); exception_caught = ex; } ); pool.start(); pool.wait(); // If an error was detected it should be propagated. if( exception_caught ) std::rethrow_exception( exception_caught ); } } /* namespace impl */ //! Helper function for running http server until ctrl+c is hit. /*! * This function creates its own instance of Asio's io_context and * uses it exclusively. * * Usage example: * \code * restinio::run( * restinio::on_thread_pool<my_traits>(4) * .port(8080) * .address("localhost") * .request_handler([](auto req) {...})); * \endcode */ template<typename Traits> inline void run( run_on_thread_pool_settings_t<Traits> && settings ) { using thread_pool_t = impl::ioctx_on_thread_pool_t< impl::own_io_context_for_thread_pool_t >; thread_pool_t pool( settings.pool_size() ); impl::run( pool, std::move(settings) ); } //! Helper function for running http server until ctrl+c is hit. /*! * Can be useful when RESTinio server should be run on the user's * own io_context instance. * * For example: * \code * asio::io_context iosvc; * ... // iosvc used by user. * restinio::run(iosvc, * restinio::on_thread_pool<my_traits>(4) * .port(8080) * .address("localhost") * .request_handler([](auto req) {...})); * \endcode * * \since * v.0.4.2 */ template<typename Traits> inline void run( //! Asio's io_context to be used. //! Note: this reference should remain valid until RESTinio server finished. asio_ns::io_context & ioctx, //! Settings for that server instance. run_on_thread_pool_settings_t<Traits> && settings ) { using thread_pool_t = impl::ioctx_on_thread_pool_t< impl::external_io_context_for_thread_pool_t >; thread_pool_t pool{ settings.pool_size(), ioctx }; impl::run( pool, std::move(settings) ); } // // run_existing_server_on_thread_pool_t // /*! * @brief Helper type for holding parameters necessary for running * HTTP-server on a thread pool. * * @note This class is not intended for direct use. It is used by * RESTinio itself. * * @since v.0.5.1 */ template<typename Traits> class run_existing_server_on_thread_pool_t { //! Size of thread pool. std::size_t m_pool_size; //! Should break signal handler be used? break_signal_handling_t m_break_handling; //! HTTP-server to be used on a thread pool. /*! * We assume that this pointer will be valid pointer. */ http_server_t<Traits> * m_server; public: //! Initializing constructor. run_existing_server_on_thread_pool_t( //! Size of the pool. std::size_t pool_size, //! Should break signal handler be used? break_signal_handling_t break_handling, //! A reference to HTTP-server to be run on a thread pool. //! This reference should outlive an instance of //! run_existing_server_on_thread_pool_t. http_server_t<Traits> & server ) : m_pool_size{ pool_size } , m_break_handling{ break_handling } , m_server{ &server } {} std::size_t pool_size() const noexcept { return m_pool_size; } break_signal_handling_t break_handling() const noexcept { return m_break_handling; } http_server_t<Traits> & server() const noexcept { return *m_server; } }; /*! * @brief Helper function for running an existing HTTP-server on * a thread pool. * * Usage example: * @code * using my_server_t = restinio::http_server_t< my_server_traits_t >; * my_server_t server{ * restinio::own_io_context(), * [](auto & settings) { * settings.port(...); * settings.address(...); * settings.request_handler(...); * ... * } * }; * ... * restinio::run( restinio::on_thread_pool( * std::thread::hardware_concurrency(), * restinio::use_break_signal_handling(), * server) ); * @endcode * * @since v.0.5.1 */ template<typename Traits> run_existing_server_on_thread_pool_t<Traits> on_thread_pool( std::size_t pool_size, break_signal_handling_t break_handling, http_server_t<Traits> & server ) { return { pool_size, break_handling, server }; } namespace impl { /*! * \brief An implementation of run-function for thread pool case * with existing http_server instance. * * This function receives an already created thread pool object and * already created http-server and run it on this thread pool. * * \attention * This function installs break signal handler and stops server when * break signal is raised. * * \since * v.0.5.1 */ template<typename Io_Context_Holder, typename Traits> void run_with_break_signal_handling( ioctx_on_thread_pool_t<Io_Context_Holder> & pool, http_server_t<Traits> & server ) { std::exception_ptr exception_caught; asio_ns::signal_set break_signals{ server.io_context(), SIGINT }; break_signals.async_wait( [&]( const asio_ns::error_code & ec, int ){ if( !ec ) { server.close_async( [&]{ // Stop running io_service. pool.stop(); }, [&exception_caught]( std::exception_ptr ex ){ // We can't throw an exception here! // Store it to rethrow later. exception_caught = ex; } ); } } ); server.open_async( []{ /* Ok. */}, [&pool, &exception_caught]( std::exception_ptr ex ){ // Stop running io_service. // We can't throw an exception here! // Store it to rethrow later. pool.stop(); exception_caught = ex; } ); pool.start(); pool.wait(); // If an error was detected it should be propagated. if( exception_caught ) std::rethrow_exception( exception_caught ); } /*! * \brief An implementation of run-function for thread pool case * with existing http_server instance. * * This function receives an already created thread pool object and * already created http-server and run it on this thread pool. * * \note * This function doesn't install break signal handlers. * * \since * v.0.5.1 */ template<typename Io_Context_Holder, typename Traits> void run_without_break_signal_handling( ioctx_on_thread_pool_t<Io_Context_Holder> & pool, http_server_t<Traits> & server ) { std::exception_ptr exception_caught; server.open_async( []{ /* Ok. */}, [&pool, &exception_caught]( std::exception_ptr ex ){ // Stop running io_service. // We can't throw an exception here! // Store it to rethrow later. pool.stop(); exception_caught = ex; } ); pool.start(); pool.wait(); // If an error was detected it should be propagated. if( exception_caught ) std::rethrow_exception( exception_caught ); } } /* namespace impl */ /*! * @brief Helper function for running an existing HTTP-server on * a thread pool. * * Usage example: * @code * using my_server_t = restinio::http_server_t< my_server_traits_t >; * my_server_t server{ * restinio::own_io_context(), * [](auto & settings) { * settings.port(...); * settings.address(...); * settings.request_handler(...); * ... * } * }; * ... * // run() returns if Ctrl+C is pressed or if HTTP-server will * // be shut down from elsewhere. * restinio::run( restinio::on_thread_pool( * std::thread::hardware_concurrency(), * restinio::use_break_signal_handling(), * server) ); * @endcode * * @since v.0.5.1 */ template<typename Traits> inline void run( run_existing_server_on_thread_pool_t<Traits> && params ) { using thread_pool_t = impl::ioctx_on_thread_pool_t< impl::external_io_context_for_thread_pool_t >; thread_pool_t pool{ params.pool_size(), params.server().io_context() }; if( break_signal_handling_t::used == params.break_handling() ) impl::run_with_break_signal_handling( pool, params.server() ); else impl::run_without_break_signal_handling( pool, params.server() ); } // // initiate_shutdown // /*! * @brief Helper function for initiation of server shutdown. * * Can be useful if an existing HTTP-server is run via run() function. * For example: * @code * restinio::http_server_t< my_traits > server{ ... }; * // Launch another thread that will perform some application logic. * std::thread app_logic_thread{ [&server] { * while(some_condition) { * ... * if(exit_case) { * // HTTP-server should be shut down. * restinio::initiate_shutdown( server ); * // Our work should be finished. * return; * } * } * } }; * // Start HTTP-server. The current thread will be blocked until * // run() returns. * restinio::run( restinio::on_thread_pool( * 4, * restinio::skip_break_signal_handling(), * server) ); * // Now app_logic_thread can be joined. * app_logic_thread.join(); * @endcode * * @since v.0.5.1 */ template<typename Traits> inline void initiate_shutdown( http_server_t<Traits> & server ) { server.io_context().post( [&server] { server.close_sync(); server.io_context().stop(); } ); } // // on_pool_runner_t // /*! * @brief Helper class for running an existing HTTP-server on a thread pool * without blocking the current thread. * * Usage of run() functions has some drawbacks. For example, the current thread * on that run() is called, will be blocked until run() returns. * * Sometimes it is not appropriate and leads to tricks like that: * @code * // HTTP-server to be run on a thread pool. * restinio::http_server_t< my_traits > server{...}; * * // Separate worker thread for calling restinio::run(). * std::thread run_thread{ [&server] { * restinio::run( restinio::on_thread_pool( * 16, * restinio::skip_break_signal_handling(), * server) ); * // Now this thread is blocked until HTTP-server will be finished. * } }; * * ... // Some application specific code here. * * // Now the server can be stopped. * restinio::initiate_shutdown( server ); * run_thread.join(); * @endcode * * Writing such code is a boring and error-prone task. The class * on_pool_runner_t can be used instead: * @code * // HTTP-server to be run on a thread pool. * restinio::http_server_t< my_traits > server{...}; * * // Launch HTTP-server on a thread pool. * restinio::on_pool_runner_t< restinio::http_server_t<my_traits> > runner{ * 16, * server * }; * runner.start(); * * ... // Some application specific code here. * * // Now the server can be stopped. * runner.stop(); // (1) * runner.wait(); * @endcode * * Moreover the code at point (1) in the example above it not necessary * because on_pool_runner_t automatically stops the server in the destructor. * * @since v.0.5.1 */ template<typename Http_Server> class on_pool_runner_t { //! HTTP-server to be run. Http_Server & m_server; //! Thread pool for running the server. impl::ioctx_on_thread_pool_t< impl::external_io_context_for_thread_pool_t > m_pool; public : on_pool_runner_t( const on_pool_runner_t & ) = delete; on_pool_runner_t( on_pool_runner_t && ) = delete; //! Initializing constructor. on_pool_runner_t( //! Size of thread pool. std::size_t pool_size, //! Server instance to be run. //! NOTE. This reference must be valid for all life-time //! of on_pool_runner instance. Http_Server & server ) : m_server{ server } , m_pool{ pool_size, server.io_context() } {} /*! * @brief Start the server with callbacks that will be called on * success or failure. * * The @a on_ok should be a function/functor with the format: * @code * void () noexcept; * @endcode * * The @a on_error should be a function/functor with the format: * @code * void (std::exception_ptr) noexcept; * @endcode * * @note * Both callbacks will be passed to http_server_t::open_async method. * It means that @a on_error callback will be called for errors detected * by open_async() methods. * * @attention * Both callbacks should be noexcept functions/functors. * * Usage example: * @code * using my_http_server = restinio::http_server_t<some_traits>; * * my_http_server server{...}; * restinio::on_pool_runner_t<my_http_server> runner{16, server}; * * std::promise<void> run_promise; * auto run_future = run_promise.get_future(); * runner.start( * // Ok callback. * [&run_promise]() noexcept { * run_promise.set_value(); * }, * // Error callback. * [&run_promise](std::exception_ptr ex) noexcept { * run_promise.set_exception(std::move(ex)); * }); * // Wait while HTTP-server started (or start failed). * run_future.get(); * @endcode * * @since v.0.6.7 */ template< typename On_Ok_Callback, typename On_Error_Callback > void start( //! A callback to be called if HTTP-server started successfully. On_Ok_Callback && on_ok, //! A callback to be called if HTTP-server is not started by //! some reasons. Please note that this callback is passed //! to http_server_t::open_async() and will be called only //! for errors detected by open_async() methods. //! If some error is detected outside of open_async() (for //! example a failure to start a thread pool) then on_error //! callback won't be called. On_Error_Callback && on_error ) { static_assert( noexcept(on_ok()), "On_Ok_Callback should be noexcept" ); static_assert( noexcept(on_error(std::declval<std::exception_ptr>())), "On_Error_Callback should be noexcept" ); m_server.open_async( [callback = std::move(on_ok)]{ callback(); }, [this, callback = std::move(on_error)]( std::exception_ptr ex ){ // There is no sense to run pool. m_pool.stop(); callback( std::move(ex) ); } ); m_pool.start(); } //! Start the server. /*! * It just a shorthand for a version of `start` method with callbacks * where all callbacks to nothing. */ void start() { this->start( []() noexcept { /* nothing to do */ }, []( std::exception_ptr ) noexcept { /* nothing to do */ } ); } //! Is server started. bool started() const noexcept { return m_pool.started(); } //FIXME: there should be a version of stop() with callbacks like //for start() method above. //! Stop the server. /*! * @note * This method is noexcept since v.0.6.7 */ void stop() noexcept { m_server.close_async( [this]{ // Stop running io_service. m_pool.stop(); }, []( std::exception_ptr /*ex*/ ){ //FIXME: the exception should be stored to be handled //later in wait() method. //NOTE: this fix is planned for v.0.7.0. //std::rethrow_exception( ex ); } ); } //FIXME this method should be replaced by two new method in v.0.7.0: // // enum class action_on_exception_t { drop, rethrow }; // wait(action_on_exception_t action); // // template<typename Exception_Handler> // wait(Exception_Handler && on_exception); // //! Wait for full stop of the server. /*! * @note * This method is noexcept since v.0.6.7 */ void wait() noexcept { m_pool.wait(); } }; // Forward declaration. // It's necessary for running_server_handle_t. template< typename Http_Server > class running_server_instance_t; // // running_server_handle_t // /*! * @brief The type to be used as a handle for running server instance. * * The handle should be seen as a Moveable and not Copyable type. * * @since v.0.6.7 */ template< typename Traits > using running_server_handle_t = std::unique_ptr< running_server_instance_t< http_server_t<Traits> > >; // // running_server_instance_t // /*! * @brief A helper class used in an implementation of #run_async function. * * An instance of that class holds an HTTP-server and thread pool on that * this HTTP-server is launched. * * The HTTP-server will automatically be stopped in the destructor. * However, a user can stop the HTTP-server manually by using * stop() and wait() methods. * * @since v.0.6.7 */ template< typename Http_Server > class running_server_instance_t { template< typename Traits > friend running_server_handle_t<Traits> run_async( io_context_holder_t, server_settings_t<Traits> &&, std::size_t thread_pool_size ); //! Actual server instance. Http_Server m_server; //! The runner of the server. on_pool_runner_t< Http_Server > m_runner; //! Initializing constructor. running_server_instance_t( io_context_holder_t io_context, server_settings_t< typename Http_Server::traits_t > && settings, std::size_t thread_pool_size ) : m_server{ std::move(io_context), std::move(settings) } , m_runner{ thread_pool_size, m_server } {} //! Start the HTTP-server. /*! * Returns when HTTP-server started or some startup failure detected. * It means that the caller thread will be blocked until HTTP-server * calls on_ok or on_error callback. * * Throws an exception on an error. */ void start() { std::promise<void> p; auto f = p.get_future(); m_runner.start( [&p]() noexcept { p.set_value(); }, [&p]( std::exception_ptr ex ) noexcept { p.set_exception( std::move(ex) ); } ); f.get(); } public : /*! * Stop the HTTP-server. * * This method initiates shutdown procedure that can take some * time. But stop() returns without the waiting for the completeness * of the shutdown. To wait for the completeness use wait() method: * * @code * auto server = restinio::run_async(...); * ... * server->stop(); // Returns without the waiting. * ... // Some other actions. * server->wait(); // Returns only when HTTP-server stopped. * @endcode * * @attention * The current version doesn't guarantee that stop() can be called * safely several times. Please take care of that and call stop() * only once. */ void stop() noexcept { m_runner.stop(); } /*! * @brief Wait for the shutdown of HTTP-server. * * @note * Method stop() should be called before the call to wait(): * @code * auto server = restinio::run_async(...); * ... * server->stop(); // Initiates the shutdown and returns without the waiting. * server->wait(); // Returns only when HTTP-server stopped. * @endcode * * @attention * The current version doesn't guarantee that wait() can be called * safely several times. Please take care of that and call wait() * only once. */ void wait() noexcept { m_runner.wait(); } }; // // run_async // /*! * @brief Creates an instance of HTTP-server and launches it on a * separate thread or thread pool. * * Usage example: * @code * int main() { * auto server = restinio::run_async( * // Asio's io_context to be used. * // HTTP-server will use own Asio's io_context object. * restinio::own_io_context(), * // The settings for the HTTP-server. * restinio::server_settings_t{} * .address("127.0.0.1") * .port(8080) * .request_handler(...), * // The size of thread-pool for the HTTP-server. * 16); * // If we are here and run_async doesn't throw then HTTP-server * // is started. * * ... // Some other actions. * * // No need to stop HTTP-server manually. It will be automatically * // stopped in the destructor of `server` object. * } * @endcode * Or, if user-defined traits should be used: * @code * int main() { * struct my_traits : public restinio::default_traits_t { * ... * }; * * auto server = restinio::run_async<my_traits>( * restinio::own_io_context(), * restinio::server_settings_t<my_traits>{} * .address(...) * .port(...) * .request_handler(...), * // Use just one thread for the HTTP-server. * 1u); * * ... // Some other actions. * } * @endcode * * run_async() returns control when HTTP-server is started or some * startup failure is detected. But if a failure is detected then an * exception is thrown. So if run_async() returns successfuly then * HTTP-server is working. * * The started HTTP-server will be automatically stopped at the * destruction of the returned value. Because of that the returned * value should be stored for the time while HTTP-server is needed. * * The started HTTP-server can be stopped manually by calling * stop() and wait() methods: * @code * auto server = restinio::run_async(...); * ... * server->stop(); // Returns without the waiting. * ... // Some other actions. * server->wait(); // Returns only when HTTP-server stopped. * @endcode * * @since v.0.6.7 */ template< typename Traits = default_traits_t > RESTINIO_NODISCARD running_server_handle_t< Traits > run_async( io_context_holder_t io_context, server_settings_t< Traits > && settings, std::size_t thread_pool_size ) { running_server_handle_t< Traits > handle{ new running_server_instance_t< http_server_t<Traits> >{ std::move(io_context), std::move(settings), thread_pool_size } }; handle->start(); return handle; } } /* namespace restinio */
10,427
440
<filename>include/options.h #pragma once #include <string> #include "translate.h" class OptionsContext { public: OptionsContext(); virtual ~OptionsContext(); bool Load(); bool Save(); const bool GetIgnoreFirmwareVersion() const { return m_ignoreFirmwareVersion; } const Language& GetLanguage() const { return m_language; } protected: bool m_ignoreFirmwareVersion; Language m_language; }; const OptionsContext& Options();
174
776
package act.ws; /*- * #%L * ACT Framework * %% * Copyright (C) 2014 - 2017 ActFramework * %% * 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. * #L% */ import act.app.ActionContext; import act.app.App; import act.util.ActContext; import act.xio.WebSocketConnection; import com.alibaba.fastjson.JSON; import org.osgl.$; import org.osgl.concurrent.ContextLocal; import org.osgl.http.H; import org.osgl.util.E; import org.osgl.util.S; import java.util.*; public class WebSocketContext extends ActContext.Base<WebSocketContext> implements WebSocketConnection { private WebSocketConnection connection; private WebSocketConnectionManager manager; private ActionContext actionContext; private String url; private String stringMessage; private boolean isJson; private Map<String, List<String>> queryParams; private static final ContextLocal<WebSocketContext> _local = $.contextLocal(); public WebSocketContext( String url, WebSocketConnection connection, WebSocketConnectionManager manager, ActionContext actionContext, App app ) { super(app); this.url = url; this.connection = $.requireNotNull(connection); this.manager = $.requireNotNull(manager); this.actionContext = $.requireNotNull(actionContext); _local.set(this); } public String url() { return url; } @Override public String sessionId() { return connection.sessionId(); } public H.Session session() { return actionContext.session(); } @Override public String username() { return connection.username(); } public WebSocketConnectionManager manager() { return manager; } public WebSocketConnection connection() { return connection; } public ActionContext actionContext() { return actionContext; } /** * Called when remote end send a message to this connection * @param receivedMessage the message received * @return this context */ public WebSocketContext messageReceived(String receivedMessage) { this.stringMessage = S.string(receivedMessage).trim(); isJson = stringMessage.startsWith("{") || stringMessage.startsWith("]"); tryParseQueryParams(); return this; } /** * Tag the websocket connection hold by this context with label specified * @param label the label used to tag the websocket connection * @return this context */ public WebSocketContext tag(String label) { manager.tagRegistry().register(label, connection); return this; } /** * Re-Tag the websocket connection hold by this context with label specified. * This method will remove all previous tags on the websocket connection and then * tag it with the new label. * @param label the label. * @return this websocket conext. */ public WebSocketContext reTag(String label) { WebSocketConnectionRegistry registry = manager.tagRegistry(); registry.signOff(connection); registry.signIn(label, connection); return this; } /** * Remove the websocket connection hold by this context from label specified * @param label the label previously tagged the websocket connection * @return this context */ public WebSocketContext removeTag(String label) { manager.tagRegistry().deRegister(label, connection); return this; } public String stringMessage() { return stringMessage; } public boolean isJson() { return isJson; } /** * Send a message to the connection of this context * @param message the message to be sent * @return this context */ public WebSocketContext sendToSelf(String message) { send(message); return this; } /** * Send JSON representation of a data object to the connection of this context * @param data the data to be sent * @return this context */ public WebSocketContext sendJsonToSelf(Object data) { send(JSON.toJSONString(data)); return this; } /** * Send message to all connections connected to the same URL of this context with * the connection of this context excluded * * @param message the message to be sent * @return this context */ public WebSocketContext sendToPeers(String message) { return sendToPeers(message, false); } /** * Send message to all connections connected to the same URL of this context * * @param message the message to be sent * @param excludeSelf whether the connection of this context should be sent to * @return this context */ public WebSocketContext sendToPeers(String message, boolean excludeSelf) { return sendToConnections(message, url, manager.urlRegistry(), excludeSelf); } /** * Send JSON representation of a data object to all connections connected to * the same URL of this context with the connection of this context excluded * * @param data the data to be sent * @return this context */ public WebSocketContext sendJsonToPeers(Object data) { return sendToPeers(JSON.toJSONString(data)); } /** * Send JSON representation of a data object to all connections connected to * the same URL of this context with the connection of this context excluded * * @param data the data to be sent * @param excludeSelf whether it should send to the connection of this context * @return this context */ public WebSocketContext sendJsonToPeers(Object data, boolean excludeSelf) { return sendToPeers(JSON.toJSONString(data), excludeSelf); } /** * Send message to all connections labeled with tag specified * with self connection excluded * * @param message the message to be sent * @param tag the string that tag the connections to be sent * @return this context */ public WebSocketContext sendToTagged(String message, String tag) { return sendToTagged(message, tag, false); } /** * Send message to all connections labeled with tag specified. * * @param message the message to be sent * @param tag the string that tag the connections to be sent * @param excludeSelf specify whether the connection of this context should be send * @return this context */ public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) { return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf); } /** * Send JSON representation of a data object to all connections connected to * the same URL of this context with the connection of this context excluded * * @param data the data to be sent * @param tag the tag label * @return this context */ public WebSocketContext sendJsonToTagged(Object data, String tag) { return sendToTagged(JSON.toJSONString(data), tag); } /** * Send JSON representation of a data object to all connections connected to * the same URL of this context with the connection of this context excluded * * @param data the data to be sent * @param tag the tag label * @param excludeSelf whether it should send to the connection of this context * @return this context */ public WebSocketContext sendJsonToTagged(Object data, String tag, boolean excludeSelf) { return sendToTagged(JSON.toJSONString(data), tag, excludeSelf); } /** * Send message to all connections of a certain user * * @param message the message to be sent * @param username the username * @return this context */ public WebSocketContext sendToUser(String message, String username) { return sendToConnections(message, username, manager.usernameRegistry(), true); } /** * Send JSON representation of a data object to all connections of a certain user * * @param data the data to be sent * @param username the username * @return this context */ public WebSocketContext sendJsonToUser(Object data, String username) { return sendToTagged(JSON.toJSONString(data), username); } private WebSocketContext sendToConnections(String message, String key, WebSocketConnectionRegistry registry, boolean excludeSelf) { for (WebSocketConnection conn : registry.get(key)) { if (!excludeSelf || connection != conn) { conn.send(message); } } return this; } @Override public void send(String message) { connection.send(message); } @Override public void close() { connection.close(); } @Override public boolean closed() { return connection.closed(); } private void tryParseQueryParams() { queryParams = new HashMap<>(); List<String> stringMessageList = new ArrayList<>(); stringMessageList.add(stringMessage); queryParams.put("_body", stringMessageList); if (isJson) { return; } String[] sa = stringMessage.split("&"); for (String si : sa) { String[] pair = si.split("="); if (pair.length == 2) { String key = pair[0]; String val = pair[1]; List<String> list = queryParams.get(key); if (null == list) { list = new ArrayList<>(); queryParams.put(key, list); } list.add(val); } } } @Override public WebSocketContext accept(H.Format fmt) { throw E.unsupport(); } @Override public H.Format accept() { throw E.unsupport(); } @Override public String methodPath() { throw E.unsupport(); } @Override public Set<String> paramKeys() { return queryParams.keySet(); } @Override public String paramVal(String key) { List<String> vals = queryParams.get(key); return null == vals || vals.isEmpty() ? null : vals.get(0); } @Override public String[] paramVals(String key) { List<String> vals = queryParams.get(key); return null == vals ? new String[0] : vals.toArray(new String[vals.size()]); } public static WebSocketContext current() { return _local.get(); } public static void current(WebSocketContext ctx) { _local.set(ctx); } }
4,027
28,056
package com.alibaba.fastjson.deserializer.issues3796.bean; import java.util.List; public class ObjectZ1 { private int a; private int b; private int c; private int d; private int e; private List<Integer> f; private List<Integer> g; private List<Integer> h; private List<ObjectZ1_A> i; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public List<Integer> getF() { return f; } public void setF(List<Integer> f) { this.f = f; } public List<Integer> getG() { return g; } public void setG(List<Integer> g) { this.g = g; } public List<Integer> getH() { return h; } public void setH(List<Integer> h) { this.h = h; } public List<ObjectZ1_A> getI() { return i; } public void setI(List<ObjectZ1_A> i) { this.i = i; } }
690
323
<gh_stars>100-1000 void __declspec(noinline) __declspec(noreturn) NoReturn() { __asm int 3; } void __declspec(noinline) __declspec(noreturn) __declspec(naked) Parent() { __asm call NoReturn; } int main() { Parent(); }
100
1,233
<reponame>ItsMattL/glazier # Lint as: python3 # Copyright 2020 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. """Tests for glazier.lib.errors.""" from absl.testing import absltest from glazier.lib import errors class ErrorsTest(absltest.TestCase): def test_glazier_reserved_error_replacements(self): self.assertEqual( str(errors.GReservedError('exception', [1, 2, 3])), 'Reserved 1 2 3 (1337): exception') def test_glazier_reserved_error_no_replacements(self): self.assertEqual( str(errors.GUncaughtError('exception')), 'Uncaught exception (4000): exception') def test_glazier_error_str(self): self.assertEqual( str(errors.GlazierError('exception')), 'Unknown Exception (4000): exception') if __name__ == '__main__': absltest.main()
450
3,269
# Time: add: O(logn) # get: O(logn) # Space: O(n) from sortedcontainers import SortedList class SORTracker(object): def __init__(self): self.__sl = SortedList() self.__i = 0 def add(self, name, score): """ :type name: str :type score: int :rtype: None """ self.__sl.add((-score, name)) def get(self): """ :rtype: str """ self.__i += 1 return self.__sl[self.__i-1][1]
273
2,151
<filename>src/compiler/glsl/glcpp/tests/066-if-nospace-expression.c #if(1) success #endif
39
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.modules.apisupport.project.queries; import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.swing.event.ChangeListener; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.java.queries.BinaryForSourceQuery; import org.netbeans.api.java.queries.BinaryForSourceQuery.Result; import org.netbeans.modules.apisupport.project.NbModuleProject; import org.netbeans.spi.java.queries.BinaryForSourceQueryImplementation; import org.openide.filesystems.FileObject; import org.openide.util.Exceptions; import org.openide.util.Parameters; import org.openide.util.Utilities; /** * * @author <NAME> */ public class BinaryForSourceImpl implements BinaryForSourceQueryImplementation { private final NbModuleProject project; private final ConcurrentMap<URI, Result> cache; public BinaryForSourceImpl(@NonNull final NbModuleProject project) { Parameters.notNull("project", project); //NOI18N this.project = project; this.cache = new ConcurrentHashMap<URI, Result>(); } @Override public Result findBinaryRoots(@NonNull final URL sourceRoot) { try { final URI key = sourceRoot.toURI(); Result res = cache.get(key); if (res == null) { URL binRoot = null; //Try project sources final FileObject srcDir = project.getSourceDirectory(); if (srcDir != null && srcDir.toURI().equals(key)) { binRoot = Utilities.toURI(project.getClassesDirectory()).toURL(); } //Try project generated sources if (binRoot == null) { final File genSrcDir = project.getGeneratedClassesDirectory(); if (genSrcDir != null && Utilities.toURI(genSrcDir).equals(key)) { binRoot = Utilities.toURI(project.getClassesDirectory()).toURL(); } } //Try unit tests if (binRoot == null) { for (final String testKind : project.supportedTestTypes()) { final FileObject testSrcDir = project.getTestSourceDirectory(testKind); if (testSrcDir != null && testSrcDir.toURI().equals(key)) { binRoot = Utilities.toURI(project.getTestClassesDirectory(testKind)).toURL(); break; } final File testGenSrcDir = project.getTestGeneratedClassesDirectory(testKind); if (testGenSrcDir != null && Utilities.toURI(testGenSrcDir).equals(key)) { binRoot = Utilities.toURI(project.getTestClassesDirectory(testKind)).toURL(); break; } } } if (binRoot != null) { res = new ResImpl(binRoot); final Result oldRes = cache.putIfAbsent(key, res); if (oldRes != null) { res = oldRes; } } } return res; } catch (MalformedURLException mue) { Exceptions.printStackTrace(mue); } catch (URISyntaxException use) { Exceptions.printStackTrace(use); } return null; } private class ResImpl implements BinaryForSourceQuery.Result { private final URL binDir; private ResImpl( @NonNull final URL binDir) { this.binDir = binDir; } @Override @NonNull public URL[] getRoots() { return new URL[] {binDir}; } @Override public void addChangeListener(ChangeListener l) { //Not needed, do not suppose the source root to be changed in nbproject } @Override public void removeChangeListener(ChangeListener l) { //Not needed, do not suppose the source root to be changed in nbproject } } }
2,344
7,629
<filename>projects/spdlog/fuzz/format_fuzzer.cc<gh_stars>1000+ // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cstddef> #include <fuzzer/FuzzedDataProvider.h> #include "spdlog/spdlog.h" #include "spdlog/sinks/basic_file_sink.h" #include "spdlog/pattern_formatter.h" std::string my_formatter_txt = "custom-flag"; class my_formatter_flag : public spdlog::custom_flag_formatter { public: void format(const spdlog::details::log_msg &, const std::tm &, spdlog::memory_buf_t &dest) override { dest.append(my_formatter_txt.data(), my_formatter_txt.data() + my_formatter_txt.size()); } std::unique_ptr<custom_flag_formatter> clone() const override { return spdlog::details::make_unique<my_formatter_flag>(); } }; extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { if (size == 0) { return 0; } static std::shared_ptr<spdlog::logger> my_logger; if (!my_logger.get()) { my_logger = spdlog::basic_logger_mt("basic_logger", "/dev/null"); spdlog::set_default_logger(my_logger); } FuzzedDataProvider stream(data, size); const unsigned long size_arg = stream.ConsumeIntegral<unsigned long>(); const unsigned long int_arg = stream.ConsumeIntegral<unsigned long>(); const char flag = (char)(stream.ConsumeIntegral<char>()); const std::string pattern = stream.ConsumeRandomLengthString(); my_formatter_txt = stream.ConsumeRandomLengthString(); const std::string string_arg = stream.ConsumeRandomLengthString(); const std::string format_string = stream.ConsumeRemainingBytesAsString(); using spdlog::details::make_unique; auto formatter = make_unique<spdlog::pattern_formatter>(); formatter->add_flag<my_formatter_flag>(flag).set_pattern(pattern); spdlog::set_formatter(std::move(formatter)); spdlog::info(format_string.c_str(), size_arg, int_arg, string_arg); return 0; }
840
1,056
<filename>java/javawebstart/src/org/netbeans/modules/javawebstart/J2SERunConfigProviderImpl.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.javawebstart; import java.util.Map; import javax.swing.JComponent; import org.netbeans.api.project.Project; import org.netbeans.modules.java.j2seproject.api.J2SECategoryExtensionProvider; import org.netbeans.modules.java.j2seproject.api.J2SEPropertyEvaluator; import org.netbeans.modules.javawebstart.ui.customizer.JWSCustomizerPanel; import org.netbeans.spi.project.ProjectServiceProvider; import org.netbeans.spi.project.support.ant.PropertyEvaluator; /** * * @author <NAME> * @author <NAME> * @since 1.14 */ @ProjectServiceProvider(service=J2SECategoryExtensionProvider.class, projectType="org-netbeans-modules-java-j2seproject") public class J2SERunConfigProviderImpl implements J2SECategoryExtensionProvider { public J2SERunConfigProviderImpl() {} @Override public ExtensibleCategory getCategory() { return ExtensibleCategory.RUN; } @Override public JComponent createComponent(Project p, J2SECategoryExtensionProvider.ConfigChangeListener listener) { J2SEPropertyEvaluator j2sePropEval = p.getLookup().lookup(J2SEPropertyEvaluator.class); PropertyEvaluator evaluator = j2sePropEval.evaluator(); String enabled = evaluator.getProperty("jnlp.enabled"); // NOI18N JWSCustomizerPanel.runComponent.addListener(listener); if ("true".equals(enabled)) { // NOI18N JWSCustomizerPanel.runComponent.setCheckboxEnabled(true); JWSCustomizerPanel.runComponent.setHintVisible(false); } else { JWSCustomizerPanel.runComponent.setCheckboxEnabled(false); JWSCustomizerPanel.runComponent.setHintVisible(true); } return JWSCustomizerPanel.runComponent; } @Override public void configUpdated(Map<String,String> m) { if ((m.get("$target.run") != null) && (m.get("$target.debug") != null)) { // NOI18N JWSCustomizerPanel.runComponent.setCheckboxSelected(true); } else { JWSCustomizerPanel.runComponent.setCheckboxSelected(false); } } }
1,059
2,151
// Copyright (c) 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBORIGIN_REPORTING_SERVICE_PROXY_PTR_HOLDER_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBORIGIN_REPORTING_SERVICE_PROXY_PTR_HOLDER_H_ #include "third_party/blink/public/platform/interface_provider.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/reporting.mojom-blink.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" namespace blink { class ReportingServiceProxyPtrHolder { public: ReportingServiceProxyPtrHolder() { Platform::Current()->GetInterfaceProvider()->GetInterface( mojo::MakeRequest(&reporting_service_proxy)); } ~ReportingServiceProxyPtrHolder() = default; void QueueInterventionReport(const KURL& url, const String& message, const String& source_file, int line_number, int column_number) { if (reporting_service_proxy) { reporting_service_proxy->QueueInterventionReport( url, message ? message : "", source_file ? source_file : "", line_number, column_number); } } void QueueDeprecationReport(const KURL& url, const String& id, WTF::Time anticipatedRemoval, const String& message, const String& source_file, int line_number, int column_number) { if (reporting_service_proxy) { reporting_service_proxy->QueueDeprecationReport( url, id, anticipatedRemoval, message ? message : "", source_file ? source_file : "", line_number, column_number); } } void QueueCspViolationReport( const KURL& url, const String& group, const SecurityPolicyViolationEventInit& violation_data) { if (reporting_service_proxy) { reporting_service_proxy->QueueCspViolationReport( url, group ? group : "default", violation_data.documentURI() ? violation_data.documentURI() : "", violation_data.referrer() ? violation_data.referrer() : "", violation_data.violatedDirective() ? violation_data.violatedDirective() : "", violation_data.effectiveDirective() ? violation_data.effectiveDirective() : "", violation_data.originalPolicy() ? violation_data.originalPolicy() : "", violation_data.disposition() ? violation_data.disposition() : "", violation_data.blockedURI() ? violation_data.blockedURI() : "", violation_data.lineNumber(), violation_data.columnNumber(), violation_data.sourceFile() ? violation_data.sourceFile() : "", violation_data.statusCode(), violation_data.sample() ? violation_data.sample() : ""); } } private: mojom::blink::ReportingServiceProxyPtr reporting_service_proxy; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WEBORIGIN_REPORTING_SERVICE_PROXY_PTR_HOLDER_H_
1,475
493
<filename>src/main/java/com/mauersu/controller/SetConroller.java package com.mauersu.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import cn.workcenter.common.response.WorkcenterResponseBodyJson; import com.mauersu.service.HashService; import com.mauersu.service.SetService; import com.mauersu.util.Constant; import com.mauersu.util.RedisApplication; @Controller @RequestMapping("/set") public class SetConroller extends RedisApplication implements Constant { @Autowired private SetService setService; @RequestMapping(value="/delSetValue", method=RequestMethod.POST) @ResponseBody public Object delSetValue(HttpServletRequest request, HttpServletResponse response, @RequestParam String serverName, @RequestParam int dbIndex, @RequestParam String key, @RequestParam String dataType, @RequestParam String value) { setService.delSetValue(serverName, dbIndex, key, value); return WorkcenterResponseBodyJson.custom().build(); } @RequestMapping(value="/updateSetValue", method=RequestMethod.POST) @ResponseBody public Object updateSetValue(HttpServletRequest request, HttpServletResponse response, @RequestParam String serverName, @RequestParam int dbIndex, @RequestParam String key, @RequestParam String dataType, @RequestParam String value) { setService.updateSetValue(serverName, dbIndex, key, value); return WorkcenterResponseBodyJson.custom().build(); } }
588
407
<filename>paas/tesla-authproxy/tesla-authproxy-start/src/main/java/com/alibaba/tesla/ApplicationPrivate.java package com.alibaba.tesla; import com.alibaba.tesla.monitor.DatasourceExporterPrivate; import com.alibaba.tesla.monitor.OkhttpExporter; import io.prometheus.client.hotspot.DefaultExports; import io.prometheus.client.spring.boot.EnablePrometheusEndpoint; import io.prometheus.client.spring.boot.EnableSpringBootMetricsCollector; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * <p>Title: Application.java</p> * <p>Description: PandoraBoot启动入口 </p> * <p>Copyright: alibaba (c) 2017</p> * <p>Company: alibaba </p> * * @author <EMAIL> * @version 1.0 * @date 2017年5月3日 */ @EnableTransactionManagement @MapperScan("com.alibaba.tesla.authproxy.model.mapper") @SpringBootApplication(scanBasePackages = {"com.alibaba.tesla"}) @EnablePrometheusEndpoint @EnableSpringBootMetricsCollector @EntityScan("com.alibaba.tesla") public class ApplicationPrivate implements CommandLineRunner { @Autowired private DatasourceExporterPrivate datasourceExporter; @Autowired private OkhttpExporter okhttpExporter; public static void main(String[] args) { try { SpringApplication.run(ApplicationPrivate.class, args); } catch (Exception e) { System.err.println("ApplicationError: " + e.getMessage()); System.exit(1); } } @Override public void run(String... strings) throws Exception { DefaultExports.initialize(); datasourceExporter.register(); okhttpExporter.register(); } }
693
348
<filename>docs/data/leg-t2/068/06804290.json<gh_stars>100-1000 {"nom":"Rustenhart","circ":"4ème circonscription","dpt":"Haut-Rhin","inscrits":654,"abs":400,"votants":254,"blancs":15,"nuls":6,"exp":233,"res":[{"nuance":"REM","nom":"<NAME>","voix":126},{"nuance":"LR","nom":"<NAME>","voix":107}]}
121
2,044
<filename>grpc-spring-boot-starter/src/main/java/org/lognet/springboot/grpc/security/SecurityInterceptor.java package org.lognet.springboot.grpc.security; import io.grpc.Context; import io.grpc.Contexts; import io.grpc.ForwardingServerCall; import io.grpc.ForwardingServerCallListener; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import lombok.extern.slf4j.Slf4j; import org.lognet.springboot.grpc.FailureHandlingSupport; import org.lognet.springboot.grpc.MessageBlockingServerCallListener; import org.lognet.springboot.grpc.autoconfigure.GRpcServerProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.core.Ordered; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.intercept.AbstractSecurityInterceptor; import org.springframework.security.access.intercept.InterceptorStatusToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Optional; @Slf4j public class SecurityInterceptor extends AbstractSecurityInterceptor implements ServerInterceptor, Ordered { private static final Context.Key<InterceptorStatusToken> INTERCEPTOR_STATUS_TOKEN = Context.key("INTERCEPTOR_STATUS_TOKEN"); private final GrpcSecurityMetadataSource securedMethods; private final AuthenticationSchemeSelector schemeSelector; private GRpcServerProperties.SecurityProperties.Auth authCfg; private FailureHandlingSupport failureHandlingSupport; public SecurityInterceptor(GrpcSecurityMetadataSource securedMethods,AuthenticationSchemeSelector schemeSelector) { this.securedMethods = securedMethods; this.schemeSelector = schemeSelector; } @Autowired public void setFailureHandlingSupport(@Lazy FailureHandlingSupport failureHandlingSupport) { this.failureHandlingSupport = failureHandlingSupport; } public void setConfig(GRpcServerProperties.SecurityProperties.Auth authCfg) { this.authCfg = Optional.ofNullable(authCfg).orElseGet(GRpcServerProperties.SecurityProperties.Auth::new); } @Override public int getOrder() { return Optional.ofNullable(authCfg.getInterceptorOrder()).orElse(Ordered.HIGHEST_PRECEDENCE + 1); } @Override public Class<?> getSecureObjectClass() { return MethodDescriptor.class; } @Override public GrpcSecurityMetadataSource obtainSecurityMetadataSource() { return securedMethods; } @Override /** * Execute the same interceptor flow as original FilterSecurityInterceptor/MethodSecurityInterceptor * { * InterceptorStatusToken token = super.beforeInvocation(mi); * Object result; * try { * result = mi.proceed(); * } * finally { * super.finallyInvocation(token); * } * return super.afterInvocation(token, result); * } */ public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall( ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { final CharSequence authorization = Optional.ofNullable(headers.get(Metadata.Key.of("Authorization" + Metadata.BINARY_HEADER_SUFFIX, Metadata.BINARY_BYTE_MARSHALLER))) .map(auth -> (CharSequence) StandardCharsets.UTF_8.decode(ByteBuffer.wrap(auth))) .orElse(headers.get(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER))); try { final Context grpcSecurityContext; try { grpcSecurityContext = setupGRpcSecurityContext(call, authorization); } catch (AccessDeniedException | AuthenticationException e) { return fail(next, call, headers, e); } catch (Exception e) { return fail(next, call, headers, new AuthenticationException("Authentication failure.", e) { }); } return Contexts.interceptCall(grpcSecurityContext, call, headers, authenticationPropagatingHandler(next)); } finally { SecurityContextHolder.getContext().setAuthentication(null); } } private <ReqT, RespT> ServerCallHandler<ReqT, RespT> authenticationPropagatingHandler(ServerCallHandler<ReqT, RespT> next) { return (call, headers) -> new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(next.startCall(afterInvocationPropagator(call), headers)) { @Override public void onMessage(ReqT message) { propagateAuthentication(() -> super.onMessage(message)); } @Override public void onHalfClose() { try { propagateAuthentication(super::onHalfClose); } finally { finallyInvocation(INTERCEPTOR_STATUS_TOKEN.get()); } } @Override public void onCancel() { propagateAuthentication(super::onCancel); } @Override public void onComplete() { propagateAuthentication(super::onComplete); } @Override public void onReady() { propagateAuthentication(super::onReady); } private void propagateAuthentication(Runnable runnable) { try { SecurityContextHolder.getContext().setAuthentication(GrpcSecurity.AUTHENTICATION_CONTEXT_KEY.get()); runnable.run(); } finally { SecurityContextHolder.clearContext(); } } }; } private <RespT, ReqT> ServerCall<RespT, ReqT> afterInvocationPropagator(ServerCall<RespT, ReqT> call) { return new ForwardingServerCall.SimpleForwardingServerCall<RespT, ReqT>(call) { @Override public void sendMessage(ReqT message) { super.sendMessage((ReqT) afterInvocation(INTERCEPTOR_STATUS_TOKEN.get(), message)); } }; } private Context setupGRpcSecurityContext(ServerCall<?, ?> call, CharSequence authorization) { final Authentication authentication = null == authorization ? null : schemeSelector.getAuthScheme(authorization) .orElseThrow(() -> new RuntimeException("Can't get authentication from authorization header")); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); SecurityContextHolder.setContext(context); final InterceptorStatusToken interceptorStatusToken = beforeInvocation(call.getMethodDescriptor()); return Context.current() .withValues(GrpcSecurity.AUTHENTICATION_CONTEXT_KEY, SecurityContextHolder.getContext().getAuthentication(), INTERCEPTOR_STATUS_TOKEN, interceptorStatusToken); } private <RespT, ReqT> ServerCall.Listener<ReqT> fail(ServerCallHandler<ReqT, RespT> next, ServerCall<ReqT, RespT> call, Metadata headers, RuntimeException exception) throws RuntimeException { if (authCfg.isFailFast()) { failureHandlingSupport.closeCall(exception, call, headers); return new ServerCall.Listener<ReqT>() { }; } else { return new MessageBlockingServerCallListener<ReqT>(next.startCall(call, headers)) { @Override public void onMessage(ReqT message) { blockMessage(); failureHandlingSupport.closeCall(exception, call, headers, b -> b.request(message)); } }; } } }
3,265
892
<reponame>westonsteimel/advisory-database-github { "schema_version": "1.2.0", "id": "GHSA-hxw4-2574-h442", "modified": "2022-05-02T03:26:11Z", "published": "2022-05-02T03:26:11Z", "aliases": [ "CVE-2009-1546" ], "details": "Integer overflow in Avifil32.dll in the Windows Media file handling functionality in Microsoft Windows allows remote attackers to execute arbitrary code on a Windows 2000 SP4 system via a crafted AVI file, or cause a denial of service on a Windows XP SP2 or SP3, Server 2003 SP2, Vista Gold, SP1, or SP2, or Server 2008 Gold or SP2 system via a crafted AVI file, aka \"AVI Integer Overflow Vulnerability.\"", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2009-1546" }, { "type": "WEB", "url": "https://docs.microsoft.com/en-us/security-updates/securitybulletins/2009/ms09-038" }, { "type": "WEB", "url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A5930" }, { "type": "WEB", "url": "http://osvdb.org/56909" }, { "type": "WEB", "url": "http://secunia.com/advisories/36206" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/35970" }, { "type": "WEB", "url": "http://www.securitytracker.com/id?1022711" }, { "type": "WEB", "url": "http://www.us-cert.gov/cas/techalerts/TA09-223A.html" }, { "type": "WEB", "url": "http://www.vupen.com/english/advisories/2009/2233" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
790
5,169
{ "name": "HMKit", "version": "1.0.0", "summary": "6th Man Apps helper classes.", "description": "HMKit provides HoopMetrics developers the fundamental building blocks used to enforce the style and feel of the application.", "homepage": "https://github.com/6thManApps/HMKit", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/6thmanapps/HMKit.git", "tag": "1.0.0" }, "social_media_url": "https://twitter.com/6thmanapps", "platforms": { "ios": "7.0" }, "requires_arc": true, "source_files": "Pod/Classes/**/*", "resource_bundles": { "HMKit": [ "Pod/Assets/Fonts/*.otf" ] } }
277
554
/* * MIT License * * Copyright (c) 2020 ManBang Group * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package io.manbang.frontend.thresh_example; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugin.common.StandardMessageCodec; import io.manbang.frontend.thresh.containers.ThreshActivity; import io.manbang.frontend.thresh.runtime.ThreshEngine; import io.manbang.frontend.thresh.runtime.ThreshEngineOptions; import io.manbang.frontend.thresh.runtime.jscore.bundle.BundleOptions; import io.manbang.frontend.thresh.runtime.jscore.bundle.BundleType; import io.manbang.frontend.thresh.runtime.jscore.bundle.ContainerType; import io.manbang.frontend.thresh.runtime.jscore.runtime.JSCallback; import io.manbang.frontend.thresh_example.nativeview.NativeTextView; import io.manbang.frontend.thresh_example.nativeview.NativeViewFactory; /** * 测试demo * <p> * flutter debug模式启动flutter页面会慢,建议切到release模式 * </p> * */ public class ThreshDemoActivity extends ThreshActivity { private ThreshEngine engine; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initThreshEngine(); } private void initThreshEngine(){ long startTime = System.currentTimeMillis(); int loadMode = getIntent().getIntExtra("load_mode", BundleType.ASSETS_FILE.getType()); BundleType bundleType; if (loadMode == BundleType.ASSETS_FILE.getType()){ bundleType = BundleType.ASSETS_FILE; }else if (loadMode == BundleType.LOCAL_FILE.getType()){ bundleType = BundleType.LOCAL_FILE; }else if (loadMode == BundleType.JS_SERVER.getType()){ bundleType = BundleType.JS_SERVER; }else { bundleType = BundleType.ASSETS_FILE; } BundleOptions.Builder bundleBuilder = new BundleOptions.Builder(ContainerType.Thresh); bundleBuilder.withDebugServerIp(getIntent().getStringExtra("debug_local_ip")); bundleBuilder.withDebugServerPort(getIntent().getStringExtra("debug_local_port")); bundleBuilder.withBundleType(bundleType); ThreshEngineOptions.Builder builder = new ThreshEngineOptions.Builder(bundleBuilder.build()); builder.moduleName("test-activity-business-module"); builder.setPageStartTime(startTime); engine = new ThreshEngine(builder.build(), getContextId()); engine.bindThreshMethodCall(new ThreshDemoMethodChannel(getFlutterEngine(),engine)); engine.bindNativeModule(new ThreshDemoBridge(this)); engine.bindBundleLoader(new TestJSBundleLoader(this)); engine.loadScript(new JSCallback() { @Override public void success(@Nullable Object o) { engine.setReady(true); } @Override public void error(int code, @Nullable String reason, @Nullable Object o) { engine.setReady(false); } }); } @Override protected void onPause() { super.onPause(); engine.onPause(); } @Override protected void onResume() { super.onResume(); engine.onResume(); } @Override protected void onDestroy() { super.onDestroy(); engine.onDestroy(); engine = null; } @Override public void onBackPressed() { super.onBackPressed(); engine.onBackPressed(); } @Override public void detachFromFlutterEngine() { } @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { super.configureFlutterEngine(flutterEngine); NativeViewFactory nativeViewFactory = new NativeViewFactory(getActivity(), StandardMessageCodec.INSTANCE, NativeTextView.NATIVE_TEXT_VIEW); flutterEngine.getPlatformViewsController().getRegistry().registerViewFactory(NativeTextView.NATIVE_TEXT_VIEW, nativeViewFactory); } }
1,842
2,151
// 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. #ifndef COMPONENTS_BUBBLE_BUBBLE_MANAGER_MOCKS_H_ #define COMPONENTS_BUBBLE_BUBBLE_MANAGER_MOCKS_H_ #include <memory> #include <utility> #include "base/macros.h" #include "components/bubble/bubble_delegate.h" #include "components/bubble/bubble_reference.h" #include "components/bubble/bubble_ui.h" #include "testing/gmock/include/gmock/gmock.h" class MockBubbleUi : public BubbleUi { public: MockBubbleUi(); ~MockBubbleUi() override; MOCK_METHOD1(Show, void(BubbleReference)); MOCK_METHOD0(Close, void()); MOCK_METHOD0(UpdateAnchorPosition, void()); // To verify destructor call. MOCK_METHOD0(Destroyed, void()); private: DISALLOW_COPY_AND_ASSIGN(MockBubbleUi); }; class MockBubbleDelegate : public BubbleDelegate { public: MockBubbleDelegate(); ~MockBubbleDelegate() override; // Default bubble shows UI and closes when asked to close. static std::unique_ptr<MockBubbleDelegate> Default(); // Stubborn bubble shows UI and doesn't want to close. static std::unique_ptr<MockBubbleDelegate> Stubborn(); MOCK_CONST_METHOD1(ShouldClose, bool(BubbleCloseReason reason)); MOCK_METHOD1(DidClose, void(BubbleCloseReason reason)); // A scoped_ptr can't be returned in MOCK_METHOD. std::unique_ptr<BubbleUi> BuildBubbleUi() override { return std::move(bubble_ui_); } MOCK_METHOD1(UpdateBubbleUi, bool(BubbleUi*)); std::string GetName() const override { return "MockBubble"; } // To verify destructor call. MOCK_METHOD0(Destroyed, void()); // Will be null after |BubbleManager::ShowBubble| is called. MockBubbleUi* bubble_ui() { return bubble_ui_.get(); } MOCK_CONST_METHOD0(OwningFrame, const content::RenderFrameHost*()); private: std::unique_ptr<MockBubbleUi> bubble_ui_; DISALLOW_COPY_AND_ASSIGN(MockBubbleDelegate); }; #endif // COMPONENTS_BUBBLE_BUBBLE_MANAGER_MOCKS_H_
745
410
<gh_stars>100-1000 /* plug_openssl.h - plug-in openssl algorithms */ #ifndef RHASH_PLUG_OPENSSL_H #define RHASH_PLUG_OPENSSL_H #if defined(USE_OPENSSL) || defined(OPENSSL_RUNTIME) #ifdef __cplusplus extern "C" { #endif int rhash_plug_openssl(void); /* load openssl algorithms */ unsigned rhash_get_openssl_supported_hash_mask(void); unsigned rhash_get_openssl_available_hash_mask(void); extern unsigned rhash_openssl_hash_mask; /* mask of hash sums to use */ #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ #else # define rhash_get_openssl_supported_hash_mask() (0) # define rhash_get_openssl_available_hash_mask() (0) #endif /* defined(USE_OPENSSL) || defined(OPENSSL_RUNTIME) */ #endif /* RHASH_PLUG_OPENSSL_H */
285
1,133
<reponame>vincentschut/isce2<gh_stars>1000+ #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2013 California Institute of Technology. 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. # # United States Government Sponsorship acknowledged. This software is subject to # U.S. export control laws and regulations and has been classified as 'EAR99 NLR' # (No [Export] License Required except when exporting to an embargoed country, # end user, or in support of a prohibited end use). By downloading this software, # the user agrees to comply with all applicable U.S. export laws and regulations. # The user has the responsibility to obtain export licenses, or other export # authority as may be required before exporting this software to any 'EAR99' # embargoed foreign country or citizen of those countries. # # Author: <NAME> #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # <NAME>, 2017 # Generalized for full and sub-band interferograms import sys import isce from mroipac.icu.Icu import Icu from iscesys.Component.Component import Component from isceobj.Constants import SPEED_OF_LIGHT import isceobj import os # giangi: taken Piyush code grass.py and adapted def runUnwrap(self , igramSpectrum = "full"): '''Specific connector from an insarApp object to a Snaphu object.''' if igramSpectrum == "full": ifgDirname = self.insar.ifgDirname elif igramSpectrum == "low": if not self.doDispersive: print('Estimating dispersive phase not requested ... skipping sub-band interferogram unwrapping') return ifgDirname = os.path.join(self.insar.ifgDirname, self.insar.lowBandSlcDirname) elif igramSpectrum == "high": if not self.doDispersive: print('Estimating dispersive phase not requested ... skipping sub-band interferogram unwrapping') return ifgDirname = os.path.join(self.insar.ifgDirname, self.insar.highBandSlcDirname) wrapName = os.path.join(ifgDirname , 'filt_' + self.insar.ifgFilename ) if '.flat' in wrapName: unwrapName = wrapName.replace('.flat', '.unw') elif '.int' in wrapName: unwrapName = wrapName.replace('.int', '.unw') else: unwrapName = wrapName + '.unw' img1 = isceobj.createImage() img1.load(wrapName + '.xml') width = img1.getWidth() # Get amp image name originalWrapName = os.path.join(ifgDirname , self.insar.ifgFilename) if '.flat' in originalWrapName: resampAmpImage = originalWrapName.replace('.flat', '.amp') elif '.int' in originalWrapName: resampAmpImage = originalWrapName.replace('.int', '.amp') else: resampAmpImage = originalWrapName + '.amp' ampImage = isceobj.createAmpImage() ampImage.setWidth(width) ampImage.setFilename(resampAmpImage) ampImage.setAccessMode('read') ampImage.createImage() #width = ampImage.getWidth() #intImage intImage = isceobj.createIntImage() intImage.initImage(wrapName, 'read', width) intImage.createImage() #unwImage unwImage = isceobj.Image.createUnwImage() unwImage.setFilename(unwrapName) unwImage.setWidth(width) unwImage.imageType = 'unw' unwImage.bands = 2 unwImage.scheme = 'BIL' unwImage.dataType = 'FLOAT' unwImage.setAccessMode('write') unwImage.createImage() icuObj = Icu(name='insarapp_icu') icuObj.configure() icuObj.filteringFlag = False #icuObj.useAmplitudeFlag = False icuObj.singlePatch = True icuObj.initCorrThreshold = 0.1 icuObj.icu(intImage=intImage, ampImage=ampImage, unwImage = unwImage) #At least one can query for the name used self.insar.connectedComponentsFilename = icuObj.conncompFilename ampImage.finalizeImage() intImage.finalizeImage() unwImage.finalizeImage() unwImage.renderHdr()
1,533
463
<reponame>yangalexandery/rl-teacher # -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2017-03-17 19:07 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('human_feedback_api', '0007_feedback_priority'), ] operations = [ migrations.AddField( model_name='feedback', name='note', field=models.TextField(default=b'', verbose_name=b'note to be displayed along with the query'), ), ]
232
578
<gh_stars>100-1000 // Copyright (c) 2019 <NAME> <EMAIL> // This software is provided 'as-is' under the zlib License, see the LICENSE.txt file. // This notice and the license may not be removed or altered from any source distribution. #ifdef TWO_MODULES module; #include <bgfx/bgfx.h> #include <gfx/Cpp20.h> module TWO(gfx); #else #include <bgfx/bgfx.h> #include <ecs/ECS.hpp> #include <geom/Intersect.h> #include <gfx/Viewport.h> #include <gfx/Camera.h> #include <gfx/Item.h> #include <gfx/Renderer.h> #include <gfx/Froxel.h> #include <gfx/Shot.h> #include <gfx/RenderTarget.h> #endif //#define NO_OCCLUSION_CULLING namespace two { GridECS s_viewer_ecs; GridECS* g_viewer_ecs = &s_viewer_ecs; static uint16_t viewportIndex = 1; Viewport::Viewport(Camera& camera, Scene& scene, const vec4& rect, bool scissor) : m_camera(&camera) , m_scene(&scene) , m_index(viewportIndex++) , m_rect(rect) , m_scissor(scissor) , m_culler(construct<Culler>(*this)) { (Entt&)(*this) = { &s_viewer_ecs, s_viewer_ecs.create() }; } Viewport::~Viewport() {} void Viewport::pass(const Pass& pass) { const FrameBuffer& fbo = *pass.m_fbo; const ushort4 rect = ushort4(m_rect * vec2(fbo.m_size)); bgfx::setViewRect(pass.m_index, rect.x, rect.y, rect.width, rect.height); bgfx::setViewTransform(pass.m_index, value_ptr(m_camera->m_view), value_ptr(m_camera->m_proj)); bgfx::setViewFrameBuffer(pass.m_index, *pass.m_fbo); bgfx::setViewClear(pass.m_index, BGFX_CLEAR_NONE); if(m_scissor) bgfx::setViewScissor(pass.m_index, rect.x, rect.y, rect.width, rect.height); } void Viewport::cull(Render& render) { #ifndef NO_OCCLUSION_CULLING m_culler->render(render); #else UNUSED(render); #endif } void Viewport::render(Render& render) { if(m_rect.height != 0.f) { const vec2 size = m_rect.size * vec2(render.m_fbo->m_size); m_camera->m_aspect = size.x / size.y; } m_camera->update(); if(m_clusters) { const uvec4 rect = uvec4(m_rect * vec2(render.m_fbo->m_size)); m_clusters->m_dirty |= uint8_t(Froxelizer::Dirty::Viewport) | uint8_t(Froxelizer::Dirty::Projection); m_clusters->update(rect, m_camera->m_proj, m_camera->m_near, m_camera->m_far); m_clusters->clusterize_lights(*m_camera, render.m_shot.m_lights); m_clusters->upload(); } for(RenderTask& task : m_tasks) task(render); } void Viewport::set_clustered(GfxSystem& gfx) { if(m_rect.width != 0.f && m_rect.height != 0.f && !m_clusters) { m_clustered = true; m_clusters = make_unique<Froxelizer>(gfx); m_clusters->setup(); } } /*void hmdUpdate() { // Set view and projection matrix for view 0. const bgfx::HMD* hmd = bgfx::getHMD(); if(NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING)) { float view[16]; bx::mtxQuatTranslationHMD(view, hmd->eye[0].rotation, eye); bgfx::setViewTransform(0, view, hmd->eye[0].projection, BGFX_VIEW_STEREO, hmd->eye[1].projection); // Set view 0 default viewport. // // Use HMD's width/height since HMD's internal frame buffer size // might be much larger than window size. bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height); } else }*/ Ray Viewport::ray(const vec2& pos) { // coord in NDC float xNDC = (pos.x / float(m_rect.width)) * 2.0f - 1.0f; float yNDC = ((float(m_rect.height) - pos.y) / float(m_rect.height)) * 2.0f - 1.0f; return m_camera->ray({ xNDC, yNDC }); } vec3 Viewport::raycast(const Plane& plane, const vec2& pos) { Ray ray = this->ray(pos); return plane_segment_intersection(plane, { ray.m_start, ray.m_end }); } }
1,610
662
<gh_stars>100-1000 // // JFImageCollectionViewController.h // JFImagePickerController // // Created by Johnil on 15-7-3. // Copyright (c) 2014年 Johnil. All rights reserved. // #import <UIKit/UIKit.h> @interface JFImageCollectionViewController : UIViewController - (UICollectionView *)collectionView; @end
111
511
/****************************************************************** * * Copyright 2019 Samsung Electronics 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. * ******************************************************************/ // Copyright 2015-2016 Espressif Systems (Shanghai) PTE 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 _SOC_RTC_CNTL_STRUCT_H_ #define _SOC_RTC_CNTL_STRUCT_H_ #ifdef __cplusplus extern "C" { #endif typedef volatile struct { union { struct { uint32_t sw_stall_appcpu_c0 :2; /*{reg_sw_stall_appcpu_c1[5 :0] reg_sw_stall_appcpu_c0[1 :0]} == 0x86 will stall APP CPU */ uint32_t sw_stall_procpu_c0 :2; /*{reg_sw_stall_procpu_c1[5 :0] reg_sw_stall_procpu_c0[1 :0]} == 0x86 will stall PRO CPU */ uint32_t sw_appcpu_rst :1; /*APP CPU SW reset */ uint32_t sw_procpu_rst :1; /*PRO CPU SW reset */ uint32_t bb_i2c_force_pd :1; /*BB_I2C force power down */ uint32_t bb_i2c_force_pu :1; /*BB_I2C force power up */ uint32_t bbpll_i2c_force_pd :1; /*BB_PLL _I2C force power down */ uint32_t bbpll_i2c_force_pu :1; /*BB_PLL_I2C force power up */ uint32_t bbpll_force_pd :1; /*BB_PLL force power down */ uint32_t bbpll_force_pu :1; /*BB_PLL force power up */ uint32_t xtl_force_pd :1; /*crystall force power down */ uint32_t xtl_force_pu :1; /*crystall force power up */ uint32_t bias_sleep_folw_8m :1; /*BIAS_SLEEP follow CK8M */ uint32_t bias_force_sleep :1; /*BIAS_SLEEP force sleep */ uint32_t bias_force_nosleep :1; /*BIAS_SLEEP force no sleep */ uint32_t bias_i2c_folw_8m :1; /*BIAS_I2C follow CK8M */ uint32_t bias_i2c_force_pd :1; /*BIAS_I2C force power down */ uint32_t bias_i2c_force_pu :1; /*BIAS_I2C force power up */ uint32_t bias_core_folw_8m :1; /*BIAS_CORE follow CK8M */ uint32_t bias_core_force_pd :1; /*BIAS_CORE force power down */ uint32_t bias_core_force_pu :1; /*BIAS_CORE force power up */ uint32_t xtl_force_iso :1; uint32_t pll_force_iso :1; uint32_t analog_force_iso :1; uint32_t xtl_force_noiso :1; uint32_t pll_force_noiso :1; uint32_t analog_force_noiso :1; uint32_t dg_wrap_force_rst :1; /*digital wrap force reset in deep sleep */ uint32_t dg_wrap_force_norst :1; /*digital core force no reset in deep sleep */ uint32_t sw_sys_rst :1; /*SW system reset */ }; uint32_t val; } options0; uint32_t slp_timer0; /*RTC sleep timer low 32 bits */ union { struct { uint32_t slp_val_hi :16; /*RTC sleep timer high 16 bits */ uint32_t main_timer_alarm_en :1; /*timer alarm enable bit */ uint32_t reserved17 :15; }; uint32_t val; } slp_timer1; union { struct { uint32_t reserved0 :30; uint32_t valid :1; /*To indicate the register is updated */ uint32_t update :1; /*Set 1 : to update register with RTC timer */ }; uint32_t val; } time_update; uint32_t time0; /*RTC timer low 32 bits */ union { struct { uint32_t time_hi :16; /*RTC timer high 16 bits */ uint32_t reserved16 :16; }; uint32_t val; } time1; union { struct { uint32_t reserved0 :20; uint32_t touch_wakeup_force_en :1; /*touch controller force wake up */ uint32_t ulp_cp_wakeup_force_en :1; /*ULP-coprocessor force wake up */ uint32_t apb2rtc_bridge_sel :1; /*1 : APB to RTC using bridge 0 : APB to RTC using sync */ uint32_t touch_slp_timer_en :1; /*touch timer enable bit */ uint32_t ulp_cp_slp_timer_en :1; /*ULP-coprocessor timer enable bit */ uint32_t reserved25 :3; uint32_t sdio_active_ind :1; /*SDIO active indication */ uint32_t slp_wakeup :1; /*sleep wakeup bit */ uint32_t slp_reject :1; /*sleep reject bit */ uint32_t sleep_en :1; /*sleep enable bit */ }; uint32_t val; } state0; union { struct { uint32_t cpu_stall_en :1; /*CPU stall enable bit */ uint32_t cpu_stall_wait :5; /*CPU stall wait cycles in fast_clk_rtc */ uint32_t ck8m_wait :8; /*CK8M wait cycles in slow_clk_rtc */ uint32_t xtl_buf_wait :10; /*XTAL wait cycles in slow_clk_rtc */ uint32_t pll_buf_wait :8; /*PLL wait cycles in slow_clk_rtc */ }; uint32_t val; } timer1; union { struct { uint32_t reserved0 :15; uint32_t ulpcp_touch_start_wait :9; /*wait cycles in slow_clk_rtc before ULP-coprocessor / touch controller start to work */ uint32_t min_time_ck8m_off :8; /*minimal cycles in slow_clk_rtc for CK8M in power down state */ }; uint32_t val; } timer2; union { struct { uint32_t wifi_wait_timer :9; uint32_t wifi_powerup_timer :7; uint32_t rom_ram_wait_timer :9; uint32_t rom_ram_powerup_timer :7; }; uint32_t val; } timer3; union { struct { uint32_t rtc_wait_timer :9; uint32_t rtc_powerup_timer :7; uint32_t dg_wrap_wait_timer :9; uint32_t dg_wrap_powerup_timer :7; }; uint32_t val; } timer4; union { struct { uint32_t ulp_cp_subtimer_prediv :8; uint32_t min_slp_val :8; /*minimal sleep cycles in slow_clk_rtc */ uint32_t rtcmem_wait_timer :9; uint32_t rtcmem_powerup_timer :7; }; uint32_t val; } timer5; union { struct { uint32_t reserved0 :23; uint32_t plla_force_pd :1; /*PLLA force power down */ uint32_t plla_force_pu :1; /*PLLA force power up */ uint32_t bbpll_cal_slp_start :1; /*start BBPLL calibration during sleep */ uint32_t pvtmon_pu :1; /*1 : PVTMON power up otherwise power down */ uint32_t txrf_i2c_pu :1; /*1 : TXRF_I2C power up otherwise power down */ uint32_t rfrx_pbus_pu :1; /*1 : RFRX_PBUS power up otherwise power down */ uint32_t reserved29 :1; uint32_t ckgen_i2c_pu :1; /*1 : CKGEN_I2C power up otherwise power down */ uint32_t pll_i2c_pu :1; /*1 : PLL_I2C power up otherwise power down */ }; uint32_t val; } ana_conf; union { struct { uint32_t reset_cause_procpu :6; /*reset cause of PRO CPU */ uint32_t reset_cause_appcpu :6; /*reset cause of APP CPU */ uint32_t appcpu_stat_vector_sel :1; /*APP CPU state vector sel */ uint32_t procpu_stat_vector_sel :1; /*PRO CPU state vector sel */ uint32_t reserved14 :18; }; uint32_t val; } reset_state; union { struct { uint32_t wakeup_cause :11; /*wakeup cause */ uint32_t rtc_wakeup_ena :11; /*wakeup enable bitmap */ uint32_t gpio_wakeup_filter :1; /*enable filter for gpio wakeup event */ uint32_t reserved23 :9; }; uint32_t val; } wakeup_state; union { struct { uint32_t slp_wakeup :1; /*enable sleep wakeup interrupt */ uint32_t slp_reject :1; /*enable sleep reject interrupt */ uint32_t sdio_idle :1; /*enable SDIO idle interrupt */ uint32_t rtc_wdt :1; /*enable RTC WDT interrupt */ uint32_t rtc_time_valid :1; /*enable RTC time valid interrupt */ uint32_t rtc_ulp_cp :1; /*enable ULP-coprocessor interrupt */ uint32_t rtc_touch :1; /*enable touch interrupt */ uint32_t rtc_brown_out :1; /*enable brown out interrupt */ uint32_t rtc_main_timer :1; /*enable RTC main timer interrupt */ uint32_t reserved9 :23; }; uint32_t val; } int_ena; union { struct { uint32_t slp_wakeup :1; /*sleep wakeup interrupt raw */ uint32_t slp_reject :1; /*sleep reject interrupt raw */ uint32_t sdio_idle :1; /*SDIO idle interrupt raw */ uint32_t rtc_wdt :1; /*RTC WDT interrupt raw */ uint32_t rtc_time_valid :1; /*RTC time valid interrupt raw */ uint32_t rtc_ulp_cp :1; /*ULP-coprocessor interrupt raw */ uint32_t rtc_touch :1; /*touch interrupt raw */ uint32_t rtc_brown_out :1; /*brown out interrupt raw */ uint32_t rtc_main_timer :1; /*RTC main timer interrupt raw */ uint32_t reserved9 :23; }; uint32_t val; } int_raw; union { struct { uint32_t slp_wakeup :1; /*sleep wakeup interrupt state */ uint32_t slp_reject :1; /*sleep reject interrupt state */ uint32_t sdio_idle :1; /*SDIO idle interrupt state */ uint32_t rtc_wdt :1; /*RTC WDT interrupt state */ uint32_t rtc_time_valid :1; /*RTC time valid interrupt state */ uint32_t rtc_sar :1; /*ULP-coprocessor interrupt state */ uint32_t rtc_touch :1; /*touch interrupt state */ uint32_t rtc_brown_out :1; /*brown out interrupt state */ uint32_t rtc_main_timer :1; /*RTC main timer interrupt state */ uint32_t reserved9 :23; }; uint32_t val; } int_st; union { struct { uint32_t slp_wakeup :1; /*Clear sleep wakeup interrupt state */ uint32_t slp_reject :1; /*Clear sleep reject interrupt state */ uint32_t sdio_idle :1; /*Clear SDIO idle interrupt state */ uint32_t rtc_wdt :1; /*Clear RTC WDT interrupt state */ uint32_t rtc_time_valid :1; /*Clear RTC time valid interrupt state */ uint32_t rtc_sar :1; /*Clear ULP-coprocessor interrupt state */ uint32_t rtc_touch :1; /*Clear touch interrupt state */ uint32_t rtc_brown_out :1; /*Clear brown out interrupt state */ uint32_t rtc_main_timer :1; /*Clear RTC main timer interrupt state */ uint32_t reserved9 :23; }; uint32_t val; } int_clr; uint32_t rtc_store0; /*32-bit general purpose retention register */ uint32_t rtc_store1; /*32-bit general purpose retention register */ uint32_t rtc_store2; /*32-bit general purpose retention register */ uint32_t rtc_store3; /*32-bit general purpose retention register */ union { struct { uint32_t reserved0 :30; uint32_t ctr_lv :1; /*0 : power down XTAL at high level 1 : power down XTAL at low level */ uint32_t ctr_en :1; /*enable control XTAL by external pads */ }; uint32_t val; } ext_xtl_conf; union { struct { uint32_t reserved0 :30; uint32_t wakeup0_lv :1; /*0 : external wakeup at low level 1 : external wakeup at high level */ uint32_t wakeup1_lv :1; /*0 : external wakeup at low level 1 : external wakeup at high level */ }; uint32_t val; } ext_wakeup_conf; union { struct { uint32_t reserved0 :24; uint32_t gpio_reject_en :1; /*enable GPIO reject */ uint32_t sdio_reject_en :1; /*enable SDIO reject */ uint32_t light_slp_reject_en :1; /*enable reject for light sleep */ uint32_t deep_slp_reject_en :1; /*enable reject for deep sleep */ uint32_t reject_cause :4; /*sleep reject cause */ }; uint32_t val; } slp_reject_conf; union { struct { uint32_t reserved0 :29; uint32_t cpusel_conf :1; /*CPU sel option */ uint32_t cpuperiod_sel :2; /*CPU period sel */ }; uint32_t val; } cpu_period_conf; union { struct { uint32_t reserved0 :22; uint32_t sdio_act_dnum :10; }; uint32_t val; } sdio_act_conf; union { struct { uint32_t reserved0 :4; uint32_t ck8m_div :2; /*CK8M_D256_OUT divider. 00 : div128 01 : div256 10 : div512 11 : div1024. */ uint32_t enb_ck8m :1; /*disable CK8M and CK8M_D256_OUT */ uint32_t enb_ck8m_div :1; /*1 : CK8M_D256_OUT is actually CK8M 0 : CK8M_D256_OUT is CK8M divided by 256 */ uint32_t dig_xtal32k_en :1; /*enable CK_XTAL_32K for digital core (no relationship with RTC core) */ uint32_t dig_clk8m_d256_en :1; /*enable CK8M_D256_OUT for digital core (no relationship with RTC core) */ uint32_t dig_clk8m_en :1; /*enable CK8M for digital core (no relationship with RTC core) */ uint32_t ck8m_dfreq_force :1; uint32_t ck8m_div_sel :3; /*divider = reg_ck8m_div_sel + 1 */ uint32_t xtal_force_nogating :1; /*XTAL force no gating during sleep */ uint32_t ck8m_force_nogating :1; /*CK8M force no gating during sleep */ uint32_t ck8m_dfreq :8; /*CK8M_DFREQ */ uint32_t ck8m_force_pd :1; /*CK8M force power down */ uint32_t ck8m_force_pu :1; /*CK8M force power up */ uint32_t soc_clk_sel :2; /*SOC clock sel. 0 : XTAL 1 : PLL 2 : CK8M 3 : APLL */ uint32_t fast_clk_rtc_sel :1; /*fast_clk_rtc sel. 0 : XTAL div 4 1 : CK8M */ uint32_t ana_clk_rtc_sel :2; /*slow_clk_rtc sel. 0 : SLOW_CK 1 : CK_XTAL_32K 2 : CK8M_D256_OUT */ }; uint32_t val; } clk_conf; union { struct { uint32_t reserved0 :21; uint32_t sdio_pd_en :1; /*power down SDIO_REG in sleep. Only active when reg_sdio_force = 0 */ uint32_t sdio_force :1; /*1 : use SW option to control SDIO_REG 0 : use state machine */ uint32_t sdio_tieh :1; /*SW option for SDIO_TIEH. Only active when reg_sdio_force = 1 */ uint32_t reg1p8_ready :1; /*read only register for REG1P8_READY */ uint32_t drefl_sdio :2; /*SW option for DREFL_SDIO. Only active when reg_sdio_force = 1 */ uint32_t drefm_sdio :2; /*SW option for DREFM_SDIO. Only active when reg_sdio_force = 1 */ uint32_t drefh_sdio :2; /*SW option for DREFH_SDIO. Only active when reg_sdio_force = 1 */ uint32_t xpd_sdio :1; /*SW option for XPD_SDIO_REG. Only active when reg_sdio_force = 1 */ }; uint32_t val; } sdio_conf; union { struct { uint32_t reserved0 :24; uint32_t dbg_atten :2; /*DBG_ATTEN */ uint32_t enb_sck_xtal :1; /*ENB_SCK_XTAL */ uint32_t inc_heartbeat_refresh :1; /*INC_HEARTBEAT_REFRESH */ uint32_t dec_heartbeat_period :1; /*DEC_HEARTBEAT_PERIOD */ uint32_t inc_heartbeat_period :1; /*INC_HEARTBEAT_PERIOD */ uint32_t dec_heartbeat_width :1; /*DEC_HEARTBEAT_WIDTH */ uint32_t rst_bias_i2c :1; /*RST_BIAS_I2C */ }; uint32_t val; } bias_conf; union { struct { uint32_t reserved0 :7; uint32_t sck_dcap_force :1; /*N/A */ uint32_t dig_dbias_slp :3; /*DIG_REG_DBIAS during sleep */ uint32_t dig_dbias_wak :3; /*DIG_REG_DBIAS during wakeup */ uint32_t sck_dcap :8; /*SCK_DCAP */ uint32_t rtc_dbias_slp :3; /*RTC_DBIAS during sleep */ uint32_t rtc_dbias_wak :3; /*RTC_DBIAS during wakeup */ uint32_t rtc_dboost_force_pd :1; /*RTC_DBOOST force power down */ uint32_t rtc_dboost_force_pu :1; /*RTC_DBOOST force power up */ uint32_t rtc_force_pd :1; /*RTC_REG force power down (for RTC_REG power down means decrease the voltage to 0.8v or lower ) */ uint32_t rtc_force_pu :1; /*RTC_REG force power up */ }; uint32_t val; } rtc; union { struct { uint32_t fastmem_force_noiso :1; /*Fast RTC memory force no ISO */ uint32_t fastmem_force_iso :1; /*Fast RTC memory force ISO */ uint32_t slowmem_force_noiso :1; /*RTC memory force no ISO */ uint32_t slowmem_force_iso :1; /*RTC memory force ISO */ uint32_t rtc_force_iso :1; /*rtc_peri force ISO */ uint32_t force_noiso :1; /*rtc_peri force no ISO */ uint32_t fastmem_folw_cpu :1; /*1 : Fast RTC memory PD following CPU 0 : fast RTC memory PD following RTC state machine */ uint32_t fastmem_force_lpd :1; /*Fast RTC memory force PD */ uint32_t fastmem_force_lpu :1; /*Fast RTC memory force no PD */ uint32_t slowmem_folw_cpu :1; /*1 : RTC memory PD following CPU 0 : RTC memory PD following RTC state machine */ uint32_t slowmem_force_lpd :1; /*RTC memory force PD */ uint32_t slowmem_force_lpu :1; /*RTC memory force no PD */ uint32_t fastmem_force_pd :1; /*Fast RTC memory force power down */ uint32_t fastmem_force_pu :1; /*Fast RTC memory force power up */ uint32_t fastmem_pd_en :1; /*enable power down fast RTC memory in sleep */ uint32_t slowmem_force_pd :1; /*RTC memory force power down */ uint32_t slowmem_force_pu :1; /*RTC memory force power up */ uint32_t slowmem_pd_en :1; /*enable power down RTC memory in sleep */ uint32_t pwc_force_pd :1; /*rtc_peri force power down */ uint32_t pwc_force_pu :1; /*rtc_peri force power up */ uint32_t pd_en :1; /*enable power down rtc_peri in sleep */ uint32_t reserved21 :11; }; uint32_t val; } rtc_pwc; union { struct { uint32_t reserved0 :3; uint32_t lslp_mem_force_pd :1; /*memories in digital core force PD in sleep */ uint32_t lslp_mem_force_pu :1; /*memories in digital core force no PD in sleep */ uint32_t rom0_force_pd :1; /*ROM force power down */ uint32_t rom0_force_pu :1; /*ROM force power up */ uint32_t inter_ram0_force_pd :1; /*internal SRAM 0 force power down */ uint32_t inter_ram0_force_pu :1; /*internal SRAM 0 force power up */ uint32_t inter_ram1_force_pd :1; /*internal SRAM 1 force power down */ uint32_t inter_ram1_force_pu :1; /*internal SRAM 1 force power up */ uint32_t inter_ram2_force_pd :1; /*internal SRAM 2 force power down */ uint32_t inter_ram2_force_pu :1; /*internal SRAM 2 force power up */ uint32_t inter_ram3_force_pd :1; /*internal SRAM 3 force power down */ uint32_t inter_ram3_force_pu :1; /*internal SRAM 3 force power up */ uint32_t inter_ram4_force_pd :1; /*internal SRAM 4 force power down */ uint32_t inter_ram4_force_pu :1; /*internal SRAM 4 force power up */ uint32_t wifi_force_pd :1; /*wifi force power down */ uint32_t wifi_force_pu :1; /*wifi force power up */ uint32_t dg_wrap_force_pd :1; /*digital core force power down */ uint32_t dg_wrap_force_pu :1; /*digital core force power up */ uint32_t reserved21 :3; uint32_t rom0_pd_en :1; /*enable power down ROM in sleep */ uint32_t inter_ram0_pd_en :1; /*enable power down internal SRAM 0 in sleep */ uint32_t inter_ram1_pd_en :1; /*enable power down internal SRAM 1 in sleep */ uint32_t inter_ram2_pd_en :1; /*enable power down internal SRAM 2 in sleep */ uint32_t inter_ram3_pd_en :1; /*enable power down internal SRAM 3 in sleep */ uint32_t inter_ram4_pd_en :1; /*enable power down internal SRAM 4 in sleep */ uint32_t wifi_pd_en :1; /*enable power down wifi in sleep */ uint32_t dg_wrap_pd_en :1; /*enable power down digital core in sleep */ }; uint32_t val; } dig_pwc; union { struct { uint32_t reserved0 :7; uint32_t dig_iso_force_off :1; uint32_t dig_iso_force_on :1; uint32_t dg_pad_autohold :1; /*read only register to indicate digital pad auto-hold status */ uint32_t clr_dg_pad_autohold :1; /*wtite only register to clear digital pad auto-hold */ uint32_t dg_pad_autohold_en :1; /*digital pad enable auto-hold */ uint32_t dg_pad_force_noiso :1; /*digital pad force no ISO */ uint32_t dg_pad_force_iso :1; /*digital pad force ISO */ uint32_t dg_pad_force_unhold :1; /*digital pad force un-hold */ uint32_t dg_pad_force_hold :1; /*digital pad force hold */ uint32_t rom0_force_iso :1; /*ROM force ISO */ uint32_t rom0_force_noiso :1; /*ROM force no ISO */ uint32_t inter_ram0_force_iso :1; /*internal SRAM 0 force ISO */ uint32_t inter_ram0_force_noiso :1; /*internal SRAM 0 force no ISO */ uint32_t inter_ram1_force_iso :1; /*internal SRAM 1 force ISO */ uint32_t inter_ram1_force_noiso :1; /*internal SRAM 1 force no ISO */ uint32_t inter_ram2_force_iso :1; /*internal SRAM 2 force ISO */ uint32_t inter_ram2_force_noiso :1; /*internal SRAM 2 force no ISO */ uint32_t inter_ram3_force_iso :1; /*internal SRAM 3 force ISO */ uint32_t inter_ram3_force_noiso :1; /*internal SRAM 3 force no ISO */ uint32_t inter_ram4_force_iso :1; /*internal SRAM 4 force ISO */ uint32_t inter_ram4_force_noiso :1; /*internal SRAM 4 force no ISO */ uint32_t wifi_force_iso :1; /*wifi force ISO */ uint32_t wifi_force_noiso :1; /*wifi force no ISO */ uint32_t dg_wrap_force_iso :1; /*digital core force ISO */ uint32_t dg_wrap_force_noiso :1; /*digital core force no ISO */ }; uint32_t val; } dig_iso; union { struct { uint32_t reserved0 :7; uint32_t pause_in_slp :1; /*pause WDT in sleep */ uint32_t appcpu_reset_en :1; /*enable WDT reset APP CPU */ uint32_t procpu_reset_en :1; /*enable WDT reset PRO CPU */ uint32_t flashboot_mod_en :1; /*enable WDT in flash boot */ uint32_t sys_reset_length :3; /*system reset counter length */ uint32_t cpu_reset_length :3; /*CPU reset counter length */ uint32_t level_int_en :1; /*N/A */ uint32_t edge_int_en :1; /*N/A */ uint32_t stg3 :3; /*1 : interrupt stage en 2 : CPU reset stage en 3 : system reset stage en 4 : RTC reset stage en */ uint32_t stg2 :3; /*1 : interrupt stage en 2 : CPU reset stage en 3 : system reset stage en 4 : RTC reset stage en */ uint32_t stg1 :3; /*1 : interrupt stage en 2 : CPU reset stage en 3 : system reset stage en 4 : RTC reset stage en */ uint32_t stg0 :3; /*1 : interrupt stage en 2 : CPU reset stage en 3 : system reset stage en 4 : RTC reset stage en */ uint32_t en :1; /*enable RTC WDT */ }; uint32_t val; } wdt_config0; uint32_t wdt_config1; uint32_t wdt_config2; uint32_t wdt_config3; uint32_t wdt_config4; union { struct { uint32_t reserved0 :31; uint32_t feed :1; }; uint32_t val; } wdt_feed; uint32_t wdt_wprotect; union { struct { uint32_t reserved0 :29; uint32_t ent_rtc :1; /*ENT_RTC */ uint32_t dtest_rtc :2; /*DTEST_RTC */ }; uint32_t val; } test_mux; union { struct { uint32_t reserved0 :20; uint32_t appcpu_c1 :6; /*{reg_sw_stall_appcpu_c1[5 :0] reg_sw_stall_appcpu_c0[1 :0]} == 0x86 will stall APP CPU */ uint32_t procpu_c1 :6; /*{reg_sw_stall_procpu_c1[5 :0] reg_sw_stall_procpu_c0[1 :0]} == 0x86 will stall PRO CPU */ }; uint32_t val; } sw_cpu_stall; uint32_t store4; /*32-bit general purpose retention register */ uint32_t store5; /*32-bit general purpose retention register */ uint32_t store6; /*32-bit general purpose retention register */ uint32_t store7; /*32-bit general purpose retention register */ uint32_t diag0; uint32_t diag1; union { struct { uint32_t adc1_hold_force :1; uint32_t adc2_hold_force :1; uint32_t pdac1_hold_force :1; uint32_t pdac2_hold_force :1; uint32_t sense1_hold_force :1; uint32_t sense2_hold_force :1; uint32_t sense3_hold_force :1; uint32_t sense4_hold_force :1; uint32_t touch_pad0_hold_force :1; uint32_t touch_pad1_hold_force :1; uint32_t touch_pad2_hold_force :1; uint32_t touch_pad3_hold_force :1; uint32_t touch_pad4_hold_force :1; uint32_t touch_pad5_hold_force :1; uint32_t touch_pad6_hold_force :1; uint32_t touch_pad7_hold_force :1; uint32_t x32p_hold_force :1; uint32_t x32n_hold_force :1; uint32_t reserved18 :14; }; uint32_t val; } hold_force; union { struct { uint32_t ext_wakeup1_sel :18; /*Bitmap to select RTC pads for ext wakeup1 */ uint32_t ext_wakeup1_status_clr :1; /*clear ext wakeup1 status */ uint32_t reserved19 :13; }; uint32_t val; } ext_wakeup1; union { struct { uint32_t ext_wakeup1_status :18; /*ext wakeup1 status */ uint32_t reserved18 :14; }; uint32_t val; } ext_wakeup1_status; union { struct { uint32_t reserved0 :14; uint32_t close_flash_ena :1; /*enable close flash when brown out happens */ uint32_t pd_rf_ena :1; /*enable power down RF when brown out happens */ uint32_t rst_wait :10; /*brown out reset wait cycles */ uint32_t rst_ena :1; /*enable brown out reset */ uint32_t thres :3; /*brown out threshold */ uint32_t ena :1; /*enable brown out */ uint32_t det :1; /*brown out detect */ }; uint32_t val; } brown_out; uint32_t reserved_39; uint32_t reserved_3d; uint32_t reserved_41; uint32_t reserved_45; uint32_t reserved_49; uint32_t reserved_4d; union { struct { uint32_t date :28; uint32_t reserved28 :4; }; uint32_t val; } date; } rtc_cntl_dev_t; extern rtc_cntl_dev_t RTCCNTL; #ifdef __cplusplus } #endif #endif /* _SOC_RTC_CNTL_STRUCT_H_ */
10,994
348
<reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000 {"nom":"Villar-Loubière","dpt":"Hautes-Alpes","inscrits":50,"abs":11,"votants":39,"blancs":4,"nuls":2,"exp":33,"res":[{"panneau":"1","voix":21},{"panneau":"2","voix":12}]}
100
315
#include <bits/stdc++.h> using namespace std; using LL = long long; int main() { cout << "Total Number of Elements : "; int n; cin >> n; int arr[n]; cout << "Enter the numbers one by one : " << endl; for (int i = 0; i < n; i++) { cin >> arr[i]; } int permutations = 0; cout << "The different permutations are : " << endl; do { permutations++; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; } while (next_permutation(arr, arr + n)); cout << "Total Number of Permutations : " << permutations << endl; }
239
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.core; import java.awt.GraphicsEnvironment; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.CLIHandler; import org.netbeans.TopSecurityManager; import org.netbeans.core.startup.CLIOptions; import org.netbeans.core.startup.Main; import org.netbeans.core.startup.layers.SessionManager; import org.openide.util.Exceptions; import org.openide.util.Lookup; import org.openide.util.Mutex; import org.openide.util.RequestProcessor; import org.openide.util.Task; /** * * @author <NAME> <<EMAIL>> */ final class NbLifeExit implements Runnable { private static final RequestProcessor RP = new RequestProcessor("Nb Exit"); // NOI18N private final int type; private final int status; private final Future<Boolean> waitFor; private final CountDownLatch onExit; NbLifeExit(int type, int status, CountDownLatch onExit) { this(type, status, null, onExit); } private NbLifeExit(int type, int status, Future<Boolean> waitFor, CountDownLatch onExit) { this.type = type; this.status = status; this.waitFor = waitFor; this.onExit = onExit; NbLifecycleManager.LOG.log( Level.FINE, "NbLifeExit({0}, {1}, {2}, {3}) = {4}", new Object[]{ type, status, waitFor, onExit, this } ); } @Override public void run() { NbLifecycleManager.LOG.log(Level.FINE, "{0}.run()", this); switch (type) { case 0: doExit(status); break; case 1: doStopInfra(status); break; case 2: int s = 3; try { if (waitFor != null && waitFor.get()) { s = 4; } } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } catch (ExecutionException ex) { Exceptions.printStackTrace(ex); } Mutex.EVENT.readAccess(new NbLifeExit(s, status, null, onExit)); break; case 3: case 4: doApproved(type == 4, status); break; case 5: try { final boolean doExit = !Boolean.getBoolean("netbeans.close.no.exit"); // NOI18N NbLifecycleManager.LOG.log(Level.FINE, "Calling exit: {0}", doExit); // NOI18N if (doExit) { TopSecurityManager.exit(status); } } finally { NbLifecycleManager.LOG.log(Level.FINE, "After exit!"); // NOI18N onExit.countDown(); } break; default: throw new IllegalStateException("Type: " + type); // NOI18N } } private void doExit(int status) { // save all open files Future<Boolean> res; boolean noDialog = GraphicsEnvironment.isHeadless() || System.getProperty("netbeans.close") != null; // NOI18N if (noDialog || ExitDialog.showDialog()) { res = Main.getModuleSystem().shutDownAsync(new NbLifeExit(1, status, null, onExit)); } else { res = null; } RP.post(new NbLifeExit(2, status, res, onExit)); } private void doStopInfra(int status) { CLIHandler.stopServer(); final WindowSystem windowSystem = Lookup.getDefault().lookup(WindowSystem.class); boolean gui = CLIOptions.isGui(); if (windowSystem != null && gui) { windowSystem.hide(); windowSystem.save(); } if (Boolean.getBoolean("netbeans.close.when.invisible")) { // NOI18N // hook to permit perf testing of time to *apparently* shut down try { TopSecurityManager.exit(status); } finally { onExit.countDown(); } } } private void doApproved(boolean isApproved, int status) throws ThreadDeath { if (isApproved) { try { try { NbLoaderPool.store(); } catch (IOException ioe) { Logger.getLogger(NbLifecycleManager.class.getName()).log(Level.WARNING, null, ioe); } //#46940 -saving just once.. // // save window system, [PENDING] remove this after the winsys will // // persist its state automaticaly // if (windowSystem != null) { // windowSystem.save(); // } SessionManager.getDefault().close(); } catch (ThreadDeath td) { throw td; } catch (Throwable t) { // Do not let problems here prevent system shutdown. The module // system is down; the IDE cannot be used further. Exceptions.printStackTrace(t); } // #37231 Someone (e.g. Jemmy) can install its own EventQueue and then // exit is dispatched through that proprietary queue and it // can be refused by security check. So, we need to replan // to RequestProcessor to avoid security problems. Task exitTask = new Task(new NbLifeExit(5, status, null, onExit)); RP.post(exitTask); } else { // end of exit onExit.countDown(); } } } // end of ExitActions
3,139
8,664
<reponame>Taritsyn/ChakraCore //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "RuntimeLibraryPch.h" using namespace Js; FunctionInfo JavascriptAsyncFunction::functionInfo( FORCE_NO_WRITE_BARRIER_TAG(JavascriptAsyncFunction::EntryAsyncFunctionImplementation), (FunctionInfo::Attributes)(FunctionInfo::DoNotProfile | FunctionInfo::ErrorOnNew)); JavascriptAsyncFunction::JavascriptAsyncFunction( DynamicType* type, GeneratorVirtualScriptFunction* scriptFunction) : JavascriptGeneratorFunction(type, &functionInfo, scriptFunction) { DebugOnly(VerifyEntryPoint()); } JavascriptAsyncFunction* JavascriptAsyncFunction::New( ScriptContext* scriptContext, GeneratorVirtualScriptFunction* scriptFunction) { return scriptContext->GetLibrary()->CreateAsyncFunction( functionInfo.GetOriginalEntryPoint(), scriptFunction); } template<> bool Js::VarIsImpl<JavascriptAsyncFunction>(RecyclableObject* obj) { return VarIs<JavascriptFunction>(obj) && ( VirtualTableInfo<JavascriptAsyncFunction>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<JavascriptAsyncFunction>>::HasVirtualTable(obj) ); } Var JavascriptAsyncFunction::EntryAsyncFunctionImplementation( RecyclableObject* function, CallInfo callInfo, ...) { auto* scriptContext = function->GetScriptContext(); PROBE_STACK(scriptContext, Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); auto* library = scriptContext->GetLibrary(); auto* asyncFn = VarTo<JavascriptAsyncFunction>(function); auto* scriptFn = asyncFn->GetGeneratorVirtualScriptFunction(); auto* generator = library->CreateGenerator(args, scriptFn, library->GetNull()); return BeginAsyncFunctionExecution(generator); } JavascriptPromise* JavascriptAsyncFunction::BeginAsyncFunctionExecution(JavascriptGenerator* generator) { auto* library = generator->GetLibrary(); auto* scriptContext = generator->GetScriptContext(); auto* promise = library->CreatePromise(); auto* stepFn = library->CreateAsyncSpawnStepFunction( EntryAsyncSpawnStepNextFunction, generator, library->GetUndefined()); JavascriptExceptionObject* exception = nullptr; JavascriptPromiseResolveOrRejectFunction* resolve; JavascriptPromiseResolveOrRejectFunction* reject; JavascriptPromise::InitializePromise(promise, &resolve, &reject, scriptContext); try { AsyncSpawnStep(stepFn, generator, resolve, reject); } catch (const JavascriptException& err) { exception = err.GetAndClear(); } if (exception != nullptr) JavascriptPromise::TryRejectWithExceptionObject(exception, reject, scriptContext); return promise; } Var JavascriptAsyncFunction::EntryAsyncSpawnStepNextFunction( RecyclableObject* function, CallInfo callInfo, ...) { auto* scriptContext = function->GetScriptContext(); PROBE_STACK(scriptContext, Js::Constants::MinStackDefault); auto* stepFn = VarTo<JavascriptAsyncSpawnStepFunction>(function); return stepFn->generator->CallGenerator(stepFn->argument, ResumeYieldKind::Normal); } Var JavascriptAsyncFunction::EntryAsyncSpawnStepThrowFunction( RecyclableObject* function, CallInfo callInfo, ...) { auto* scriptContext = function->GetScriptContext(); PROBE_STACK(scriptContext, Js::Constants::MinStackDefault); auto* stepFn = VarTo<JavascriptAsyncSpawnStepFunction>(function); return stepFn->generator->CallGenerator(stepFn->argument, ResumeYieldKind::Throw); } Var JavascriptAsyncFunction::EntryAsyncSpawnCallStepFunction( RecyclableObject* function, CallInfo callInfo, ...) { auto* scriptContext = function->GetScriptContext(); PROBE_STACK(scriptContext, Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); auto* library = scriptContext->GetLibrary(); Var undefinedVar = library->GetUndefined(); Var resolvedValue = args.Info.Count > 1 ? args[1] : undefinedVar; auto* stepFn = VarTo<JavascriptAsyncSpawnStepFunction>(function); JavascriptMethod method = stepFn->isReject ? EntryAsyncSpawnStepThrowFunction : EntryAsyncSpawnStepNextFunction; auto* nextStepFn = library->CreateAsyncSpawnStepFunction( method, stepFn->generator, resolvedValue); AsyncSpawnStep(nextStepFn, stepFn->generator, stepFn->resolve, stepFn->reject); return undefinedVar; } void JavascriptAsyncFunction::AsyncSpawnStep( JavascriptAsyncSpawnStepFunction* stepFunction, JavascriptGenerator* generator, Var resolve, Var reject) { ScriptContext* scriptContext = generator->GetScriptContext(); BEGIN_SAFE_REENTRANT_REGION(scriptContext->GetThreadContext()) JavascriptLibrary* library = scriptContext->GetLibrary(); Var undefinedVar = library->GetUndefined(); JavascriptExceptionObject* exception = nullptr; RecyclableObject* result = nullptr; try { Var resultVar = CALL_FUNCTION( scriptContext->GetThreadContext(), stepFunction, CallInfo(CallFlags_Value, 1), undefinedVar); result = VarTo<RecyclableObject>(resultVar); } catch (const JavascriptException& err) { exception = err.GetAndClear(); } if (exception != nullptr) { // If the generator threw an exception, reject the promise JavascriptPromise::TryRejectWithExceptionObject(exception, reject, scriptContext); return; } Assert(result != nullptr); Var value = JavascriptOperators::GetProperty(result, PropertyIds::value, scriptContext); // If the generator is done, resolve the promise if (generator->IsCompleted()) { if (!JavascriptConversion::IsCallable(resolve)) JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedFunction); CALL_FUNCTION( scriptContext->GetThreadContext(), VarTo<RecyclableObject>(resolve), CallInfo(CallFlags_Value, 2), undefinedVar, value); return; } else { Assert(JavascriptOperators::GetTypeId(result) == TypeIds_AwaitObject); } // Chain off the yielded promise and step again auto* successFunction = library->CreateAsyncSpawnStepFunction( EntryAsyncSpawnCallStepFunction, generator, undefinedVar, resolve, reject); auto* failFunction = library->CreateAsyncSpawnStepFunction( EntryAsyncSpawnCallStepFunction, generator, undefinedVar, resolve, reject, true); auto* promise = JavascriptPromise::InternalPromiseResolve(value, scriptContext); auto* unused = JavascriptPromise::UnusedPromiseCapability(scriptContext); JavascriptPromise::PerformPromiseThen( promise, unused, successFunction, failFunction, scriptContext); END_SAFE_REENTRANT_REGION } template<> bool Js::VarIsImpl<JavascriptAsyncSpawnStepFunction>(RecyclableObject* obj) { return VarIs<JavascriptFunction>(obj) && ( VirtualTableInfo<JavascriptAsyncSpawnStepFunction>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<JavascriptAsyncSpawnStepFunction>>::HasVirtualTable(obj) ); } #if ENABLE_TTD TTD::NSSnapObjects::SnapObjectType JavascriptAsyncFunction::GetSnapTag_TTD() const { return TTD::NSSnapObjects::SnapObjectType::SnapAsyncFunction; } void JavascriptAsyncFunction::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc) { TTD::NSSnapObjects::SnapGeneratorFunctionInfo* fi = nullptr; uint32 depCount = 0; TTD_PTR_ID* depArray = nullptr; this->CreateSnapObjectInfo(alloc, &fi, &depArray, &depCount); if (depCount == 0) { TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapGeneratorFunctionInfo*, TTD::NSSnapObjects::SnapObjectType::SnapAsyncFunction>(objData, fi); } else { TTDAssert(depArray != nullptr, "depArray should be non-null if depCount is > 0"); TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapGeneratorFunctionInfo*, TTD::NSSnapObjects::SnapObjectType::SnapAsyncFunction>(objData, fi, alloc, depCount, depArray); } } void JavascriptAsyncSpawnStepFunction::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor) { if (this->generator != nullptr) { extractor->MarkVisitVar(this->generator); } if (this->reject != nullptr) { extractor->MarkVisitVar(this->reject); } if (this->resolve != nullptr) { extractor->MarkVisitVar(this->resolve); } if (this->argument != nullptr) { extractor->MarkVisitVar(this->argument); } } TTD::NSSnapObjects::SnapObjectType JavascriptAsyncSpawnStepFunction::GetSnapTag_TTD() const { return TTD::NSSnapObjects::SnapObjectType::JavascriptAsyncSpawnStepFunction; } void JavascriptAsyncSpawnStepFunction::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc) { TTD::NSSnapObjects::SnapJavascriptAsyncSpawnStepFunctionInfo* info = alloc.SlabAllocateStruct<TTD::NSSnapObjects::SnapJavascriptAsyncSpawnStepFunctionInfo>(); info->generator = TTD_CONVERT_VAR_TO_PTR_ID(this->generator); info->reject = this->reject; info->resolve = this->resolve; info->argument = this->argument; info->isReject = this->isReject; info->entryPoint = 0; JavascriptMethod entryPoint = this->GetFunctionInfo()->GetOriginalEntryPoint(); if (entryPoint == JavascriptAsyncFunction::EntryAsyncSpawnStepNextFunction) { info->entryPoint = 1; } else if (entryPoint == JavascriptAsyncFunction::EntryAsyncSpawnStepThrowFunction) { info->entryPoint = 2; } else if (entryPoint == JavascriptAsyncFunction::EntryAsyncSpawnCallStepFunction) { info->entryPoint = 3; } else { TTDAssert(false, "Unexpected entrypoint found JavascriptAsyncSpawnStepArgumentExecutorFunction"); } const uint32 maxDeps = 4; uint32 depCount = 0; TTD_PTR_ID* depArray = alloc.SlabReserveArraySpace<TTD_PTR_ID>(maxDeps); if (this->reject != nullptr && TTD::JsSupport::IsVarComplexKind(this->reject)) { depArray[depCount] = TTD_CONVERT_VAR_TO_PTR_ID(this->reject); depCount++; } if (this->resolve != nullptr && TTD::JsSupport::IsVarComplexKind(this->resolve)) { depArray[depCount] = TTD_CONVERT_VAR_TO_PTR_ID(this->resolve); depCount++; } if (this->argument != nullptr && TTD::JsSupport::IsVarComplexKind(this->argument)) { depArray[depCount] = TTD_CONVERT_VAR_TO_PTR_ID(this->argument); depCount++; } if (this->generator != nullptr) { depArray[depCount] = TTD_CONVERT_VAR_TO_PTR_ID(this->generator); depCount++; } if (depCount > 0) { alloc.SlabCommitArraySpace<TTD_PTR_ID>(depCount, maxDeps); } else { alloc.SlabAbortArraySpace<TTD_PTR_ID>(maxDeps); } if (depCount == 0) { TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapJavascriptAsyncSpawnStepFunctionInfo*, TTD::NSSnapObjects::SnapObjectType::JavascriptAsyncSpawnStepFunction>(objData, info); } else { TTDAssert(depArray != nullptr, "depArray should be non-null if depCount is > 0"); TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapJavascriptAsyncSpawnStepFunctionInfo*, TTD::NSSnapObjects::SnapObjectType::JavascriptAsyncSpawnStepFunction>(objData, info, alloc, depCount, depArray); } } #endif
4,363