repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
olivierlemasle/cloudstack
framework/quota/src/main/java/org/apache/cloudstack/quota/dao/QuotaEmailTemplatesDaoImpl.java
<reponame>olivierlemasle/cloudstack<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.cloudstack.quota.dao; import java.util.List; import org.apache.cloudstack.quota.vo.QuotaEmailTemplatesVO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.TransactionCallback; import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.db.TransactionStatus; import com.google.common.base.Strings; @Component public class QuotaEmailTemplatesDaoImpl extends GenericDaoBase<QuotaEmailTemplatesVO, Long> implements QuotaEmailTemplatesDao { private static final Logger s_logger = Logger.getLogger(QuotaEmailTemplatesDaoImpl.class); protected SearchBuilder<QuotaEmailTemplatesVO> QuotaEmailTemplateSearch; public QuotaEmailTemplatesDaoImpl() { super(); QuotaEmailTemplateSearch = createSearchBuilder(); QuotaEmailTemplateSearch.and("template_name", QuotaEmailTemplateSearch.entity().getTemplateName(), SearchCriteria.Op.EQ); QuotaEmailTemplateSearch.done(); } @Override public List<QuotaEmailTemplatesVO> listAllQuotaEmailTemplates(final String templateName) { return Transaction.execute(TransactionLegacy.USAGE_DB, new TransactionCallback<List<QuotaEmailTemplatesVO>>() { @Override public List<QuotaEmailTemplatesVO> doInTransaction(final TransactionStatus status) { SearchCriteria<QuotaEmailTemplatesVO> sc = QuotaEmailTemplateSearch.create(); if (!Strings.isNullOrEmpty(templateName)) { sc.setParameters("template_name", templateName); } return listBy(sc); } }); } @Override public boolean updateQuotaEmailTemplate(final QuotaEmailTemplatesVO template) { return Transaction.execute(TransactionLegacy.USAGE_DB, new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(final TransactionStatus status) { return update(template.getId(), template); } }); } }
CDAGaming/TC_Research
src/main/java/thaumcraft/common/lib/research/theorycraft/CardCelestial.java
<filename>src/main/java/thaumcraft/common/lib/research/theorycraft/CardCelestial.java package thaumcraft.common.lib.research.theorycraft; import net.minecraft.nbt.*; import net.minecraft.entity.player.*; import thaumcraft.api.research.theorycraft.*; import net.minecraft.util.math.*; import java.util.*; import net.minecraft.util.text.*; import net.minecraft.item.*; import thaumcraft.api.items.*; import thaumcraft.api.*; import thaumcraft.api.capabilities.*; public class CardCelestial extends TheorycraftCard { int md1; int md2; String cat; public CardCelestial() { this.cat = "BASICS"; } @Override public NBTTagCompound serialize() { final NBTTagCompound nbt = super.serialize(); nbt.func_74768_a("md1", this.md1); nbt.func_74768_a("md2", this.md2); nbt.func_74778_a("cat", this.cat); return nbt; } @Override public void deserialize(final NBTTagCompound nbt) { super.deserialize(nbt); this.md1 = nbt.func_74762_e("md1"); this.md2 = nbt.func_74762_e("md2"); this.cat = nbt.func_74779_i("cat"); } @Override public String getResearchCategory() { return this.cat; } @Override public boolean initialize(final EntityPlayer player, final ResearchTableData data) { if (data.categoryTotals.isEmpty() || !ThaumcraftCapabilities.knowsResearch(player, "CELESTIALSCANNING")) { return false; } final Random r = new Random(this.getSeed()); this.md1 = MathHelper.func_76136_a(r, 0, 12); this.md2 = MathHelper.func_76136_a(r, 0, 12); int hVal = 0; String hKey = ""; for (final String category : data.categoryTotals.keySet()) { final int q = data.getTotal(category); if (q > hVal) { hVal = q; hKey = category; } } this.cat = hKey; return this.cat != null; } @Override public int getInspirationCost() { return 1; } @Override public String getLocalizedName() { return new TextComponentTranslation("card.celestial.name", new Object[0]).func_150254_d(); } @Override public String getLocalizedText() { return new TextComponentTranslation("card.celestial.text", new Object[] { TextFormatting.BOLD + new TextComponentTranslation("tc.research_category." + this.cat, new Object[0]).func_150254_d() + TextFormatting.RESET }).func_150260_c(); } @Override public ItemStack[] getRequiredItems() { return new ItemStack[] { new ItemStack(ItemsTC.celestialNotes, 1, this.md1), new ItemStack(ItemsTC.celestialNotes, 1, this.md2) }; } @Override public boolean[] getRequiredItemsConsumed() { return new boolean[] { true, true }; } @Override public boolean activate(final EntityPlayer player, final ResearchTableData data) { data.addTotal(this.getResearchCategory(), MathHelper.func_76136_a(player.func_70681_au(), 25, 50)); final boolean sun = this.md1 == 0 || this.md2 == 0; final boolean moon = this.md1 > 4 || this.md2 > 4; final boolean stars = (this.md1 > 0 && this.md1 < 5) || (this.md2 > 0 && this.md2 < 5); if (stars) { final int amt = MathHelper.func_76136_a(player.func_70681_au(), 0, 5); data.addTotal("ELDRITCH", amt * 2); ThaumcraftApi.internalMethods.addWarpToPlayer(player, amt, IPlayerWarp.EnumWarpType.TEMPORARY); } if (sun) { ++data.penaltyStart; } if (moon) { ++data.bonusDraws; } return true; } }
momokapapa/hanakapapa
libraries/utilities/include/enumivo/utilities/exception_macros.hpp
<reponame>momokapapa/hanakapapa /** * @file * @copyright defined in enumivo/LICENSE.txt */ #define ENU_ASSERT( expr, exc_type, FORMAT, ... ) \ FC_MULTILINE_MACRO_BEGIN \ if( !(expr) ) \ FC_THROW_EXCEPTION( exc_type, FORMAT, __VA_ARGS__ ); \ FC_MULTILINE_MACRO_END #define ENU_THROW( exc_type, FORMAT, ... ) \ throw exc_type( FC_LOG_MESSAGE( error, FORMAT, __VA_ARGS__ ) ); /** * Macro inspired from FC_RETHROW_EXCEPTIONS * The main difference here is that if the exception caught isn't of type "enumivo::chain::chain_exception" * This macro will rethrow the exception as the specified "exception_type" */ #define ENU_RETHROW_EXCEPTIONS(exception_type, FORMAT, ... ) \ catch (enumivo::chain::chain_exception& e) { \ FC_RETHROW_EXCEPTION( e, warn, FORMAT, __VA_ARGS__ ); \ } catch (fc::exception& e) { \ exception_type new_exception(FC_LOG_MESSAGE( warn, FORMAT, __VA_ARGS__ )); \ for (const auto& log: e.get_log()) { \ new_exception.append_log(log); \ } \ throw new_exception; \ } catch( const std::exception& e ) { \ exception_type fce(FC_LOG_MESSAGE( warn, FORMAT" (${what})" ,__VA_ARGS__("what",e.what()))); \ throw fce;\ } catch( ... ) { \ throw fc::unhandled_exception( \ FC_LOG_MESSAGE( warn, FORMAT,__VA_ARGS__), \ std::current_exception() ); \ } /** * Macro inspired from FC_CAPTURE_AND_RETHROW * The main difference here is that if the exception caught isn't of type "enumivo::chain::chain_exception" * This macro will rethrow the exception as the specified "exception_type" */ #define ENU_CAPTURE_AND_RETHROW( exception_type, ... ) \ catch (enumivo::chain::chain_exception& e) { \ FC_RETHROW_EXCEPTION( e, warn, "", FC_FORMAT_ARG_PARAMS(__VA_ARGS__) ); \ } catch (fc::exception& e) { \ exception_type new_exception(e.get_log()); \ throw new_exception; \ } catch( const std::exception& e ) { \ exception_type fce( \ FC_LOG_MESSAGE( warn, "${what}: ",FC_FORMAT_ARG_PARAMS(__VA_ARGS__)("what",e.what())), \ fc::std_exception_code,\ BOOST_CORE_TYPEID(decltype(e)).name(), \ e.what() ) ; throw fce;\ } catch( ... ) { \ throw fc::unhandled_exception( \ FC_LOG_MESSAGE( warn, "",FC_FORMAT_ARG_PARAMS(__VA_ARGS__)), \ std::current_exception() ); \ } #define ENU_DECLARE_OP_BASE_EXCEPTIONS( op_name ) \ FC_DECLARE_DERIVED_EXCEPTION( \ op_name ## _validate_exception, \ enumivo::chain::message_validate_exception, \ 3040000 + 100 * operation::tag< op_name ## _operation >::value, \ #op_name "_operation validation exception" \ ) \ FC_DECLARE_DERIVED_EXCEPTION( \ op_name ## _evaluate_exception, \ enumivo::chain::message_evaluate_exception, \ 3050000 + 100 * operation::tag< op_name ## _operation >::value, \ #op_name "_operation evaluation exception" \ ) #define ENU_DECLARE_OP_VALIDATE_EXCEPTION( exc_name, op_name, seqnum, msg ) \ FC_DECLARE_DERIVED_EXCEPTION( \ op_name ## _ ## exc_name, \ enumivo::chain::op_name ## _validate_exception, \ 3040000 + 100 * operation::tag< op_name ## _operation >::value \ + seqnum, \ msg \ ) #define ENU_DECLARE_OP_EVALUATE_EXCEPTION( exc_name, op_name, seqnum, msg ) \ FC_DECLARE_DERIVED_EXCEPTION( \ op_name ## _ ## exc_name, \ enumivo::chain::op_name ## _evaluate_exception, \ 3050000 + 100 * operation::tag< op_name ## _operation >::value \ + seqnum, \ msg \ ) #define ENU_RECODE_EXC( cause_type, effect_type ) \ catch( const cause_type& e ) \ { throw( effect_type( e.what(), e.get_log() ) ); }
talsewell/cerberus
tests/csmith/small_arrays/csmith_30.c
<filename>tests/csmith/small_arrays/csmith_30.c // Options: --no-pointers --no-structs --no-unions --argc --no-bitfields --checksum --comma-operators --compound-assignment --concise --consts --divs --embedded-assigns --pre-incr-operator --pre-decr-operator --post-incr-operator --post-decr-operator --unary-plus-operator --jumps --longlong --int8 --uint8 --no-float --main --math64 --muls --safe-math --no-packed-struct --no-paranoid --no-volatiles --no-volatile-pointers --const-pointers --no-builtins --max-array-dim 1 --max-array-len-per-dim 4 --max-block-depth 1 --max-block-size 10 --max-expr-complexity 4 --max-funcs 10 --max-pointer-depth 2 --max-struct-fields 2 --max-union-fields 2 -o csmith_30.c #include "csmith.h" static long __undefined; static int32_t g_2 = (-2L); static int64_t g_67 = 0x78C6AEE34D1CD050LL; static uint32_t g_68[3] = {0x86007675L,0x86007675L,0x86007675L}; static uint8_t g_153 = 0xA2L; static uint64_t g_154 = 3UL; static uint32_t g_155 = 0UL; static int16_t g_165 = 1L; static uint8_t g_166 = 0x69L; static int64_t g_175 = 0x3271FE85D9B24318LL; static uint32_t g_177 = 0xB8CF327FL; static uint64_t g_195 = 0xD28D446D23EE2624LL; static uint32_t g_216 = 0UL; static uint32_t g_217 = 0UL; static uint16_t g_226 = 0xC2E7L; static uint8_t g_242 = 0xB4L; static int32_t g_244 = 1L; static uint32_t g_245[3] = {18446744073709551615UL,18446744073709551615UL,18446744073709551615UL}; static int32_t g_255 = 0x956EE47DL; static int64_t g_256 = 0L; static int32_t g_258 = 1L; static uint32_t g_259[2] = {4UL,4UL}; static int16_t g_342 = 0xB004L; static uint8_t g_376 = 0x56L; static int64_t g_412 = (-7L); static uint32_t g_430 = 4294967295UL; static uint64_t g_460[4] = {18446744073709551615UL,18446744073709551615UL,18446744073709551615UL,18446744073709551615UL}; static uint32_t g_469[2] = {0xD1A09568L,0xD1A09568L}; static int16_t g_487 = (-4L); static uint32_t g_494 = 18446744073709551614UL; static int64_t g_497[1] = {2L}; static uint32_t g_498 = 0x017BAB5EL; static uint32_t g_501 = 0x0989A894L; static int32_t g_519 = 0x27BCB12AL; static int32_t g_520 = 0x19A99B7AL; static int32_t g_521 = 0xE645D047L; static int64_t g_522 = 0xDA40333B9CF4F018LL; static int16_t g_523 = 0x1614L; static uint64_t g_526[1] = {1UL}; static uint16_t g_530 = 7UL; static const uint32_t g_547 = 18446744073709551615UL; static uint16_t g_594 = 0xFF94L; static uint16_t g_645 = 65535UL; static uint64_t g_650 = 0x4DC842FB3E711866LL; static int64_t g_702 = 0x1825AB7781D03DF5LL; static int16_t g_732 = 8L; static uint32_t g_796 = 0x1B8EA729L; static int8_t g_802 = 0L; static int8_t g_803 = 0x55L; static uint64_t g_804 = 0UL; static int8_t g_950 = 0x3CL; static int32_t g_953 = 0x88E3369BL; static int64_t g_957[3] = {0xD0365E0072052BDBLL,0xD0365E0072052BDBLL,0xD0365E0072052BDBLL}; static uint16_t g_958 = 0UL; static uint32_t g_1001 = 18446744073709551615UL; static uint32_t g_1031[4] = {1UL,1UL,1UL,1UL}; static uint16_t func_1(void); static uint8_t func_9(const uint64_t p_10, uint8_t p_11, const uint32_t p_12, uint64_t p_13); static const int16_t func_16(uint32_t p_17, uint16_t p_18); static int32_t func_21(int16_t p_22, int32_t p_23); static int16_t func_30(int16_t p_31, int32_t p_32, uint8_t p_33, int32_t p_34, uint32_t p_35); static int16_t func_40(int8_t p_41, int8_t p_42, uint64_t p_43, uint32_t p_44); static uint16_t func_62(uint32_t p_63, uint32_t p_64, uint32_t p_65, int8_t p_66); static int32_t func_71(uint64_t p_72, uint32_t p_73, int16_t p_74, uint16_t p_75); static uint64_t func_92(int8_t p_93, int32_t p_94, int32_t p_95); static const int32_t func_100(int32_t p_101); static uint16_t func_1(void) { uint32_t l_20 = 0xB6968939L; int32_t l_1024[1]; int i; for (i = 0; i < 1; i++) l_1024[i] = 0L; for (g_2 = 0; (g_2 < (-30)); g_2 = safe_sub_func_int32_t_s_s(g_2, 6)) { int8_t l_861 = 0xBFL; uint32_t l_1023 = 0xD1A58BD0L; int32_t l_1027 = (-7L); int32_t l_1028 = 0L; int32_t l_1029 = (-9L); int32_t l_1030 = (-1L); l_1024[0] = ((l_1023 ^= (safe_sub_func_uint64_t_u_u(0x91F782A1836CCB03LL, (safe_add_func_uint8_t_u_u(func_9((func_16(((((g_2 < (safe_unary_minus_func_uint16_t_u(0x4057L))) , g_2) > 0xBCL) > l_20), g_2) > 0L), l_20, l_20, l_861), 0x8EL))))) | g_950); g_244 ^= (((6L & (((g_460[1] != ((safe_mul_func_uint16_t_u_u(((l_1024[0] = ((g_165 == g_497[0]) & 0x60L)) < g_804), l_1023)) , 0UL)) & l_1023) > g_526[0])) > l_1023) <= g_469[0]); if (l_861) continue; --g_1031[2]; return g_460[3]; } for (g_226 = 0; (g_226 >= 59); g_226 = safe_add_func_int32_t_s_s(g_226, 1)) { int8_t l_1040 = (-3L); int32_t l_1043 = 0xCBA41028L; int32_t l_1044 = 0x1D43D414L; l_1044 ^= (safe_mod_func_uint32_t_u_u(((g_1031[0] = (safe_rshift_func_uint16_t_u_s((l_1040 ^= l_20), 6))) ^ ((safe_sub_func_int64_t_s_s(g_255, (g_732 ^ g_958))) >= g_226)), l_1043)); return l_1044; } l_1024[0] = (safe_mod_func_int16_t_s_s(l_20, (safe_lshift_func_int8_t_s_u((safe_sub_func_uint32_t_u_u((((g_259[0] != (safe_mod_func_int16_t_s_s((l_1024[0] , g_957[0]), g_957[0]))) | 255UL) >= l_1024[0]), g_1001)), 2)))); for (g_195 = (-26); (g_195 >= 43); g_195 = safe_add_func_uint16_t_u_u(g_195, 2)) { g_244 = (safe_unary_minus_func_int16_t_s(l_1024[0])); return g_526[0]; } return l_1024[0]; } static uint8_t func_9(const uint64_t p_10, uint8_t p_11, const uint32_t p_12, uint64_t p_13) { int8_t l_864 = 0L; uint64_t l_870 = 0UL; uint64_t l_871 = 18446744073709551611UL; int32_t l_872 = 0x1F3E3C48L; int32_t l_873 = 1L; uint64_t l_881 = 6UL; int32_t l_895[4] = {0L,0L,0L,0L}; int32_t l_897[2]; uint32_t l_946 = 0UL; int8_t l_949 = 0xD2L; int32_t l_955 = 0x79CDDBCAL; int16_t l_965 = 0xED2CL; int16_t l_1012 = (-1L); int i; for (i = 0; i < 2; i++) l_897[i] = 1L; lbl_948: if ((l_873 = (l_872 = (g_520 &= ((safe_mod_func_uint8_t_u_u((l_864 ^ ((((safe_add_func_int32_t_s_s((safe_add_func_int8_t_s_s((l_870 = (((safe_unary_minus_func_uint8_t_u(g_497[0])) || 4294967295UL) , 0L)), 0x22L)), g_217)) != l_864) != 1L) <= l_864)), l_871)) & p_11))))) { int32_t l_876 = 0x8C4ADD30L; int32_t l_877 = 0x0A5EFBDDL; l_877 ^= ((safe_lshift_func_uint16_t_u_s(g_153, 11)) <= (p_13 = l_876)); g_244 = g_469[0]; return l_876; } else { int32_t l_878[2]; int i; for (i = 0; i < 2; i++) l_878[i] = 0xDF67A0C9L; l_878[1] = g_487; l_873 = g_526[0]; l_873 |= (safe_mul_func_int16_t_s_s((((l_878[1] , p_13) & (((l_872 = ((l_881 <= p_11) & l_864)) != p_11) && p_12)) > g_245[0]), l_878[1])); } for (g_796 = 0; (g_796 > 42); ++g_796) { const uint8_t l_896 = 4UL; int32_t l_898 = (-1L); int64_t l_907 = 0xFDE32081513785D8LL; uint64_t l_908 = 18446744073709551615UL; l_897[1] ^= (safe_mul_func_uint8_t_u_u((safe_lshift_func_uint16_t_u_u((((safe_mul_func_uint16_t_u_u((safe_lshift_func_uint8_t_u_s((((l_870 | ((+(((g_226 |= (((g_376 > ((((safe_mul_func_int16_t_s_s((l_895[3] , p_13), 3L)) ^ 0x24C946D3L) <= g_501) != g_732)) && p_13) <= l_896)) <= (-7L)) == 1UL)) == l_872)) < l_896) <= g_526[0]), 4)), l_872)) ^ 0xA5L) <= l_864), l_881)), l_873)); l_897[1] = p_13; l_898 = p_12; l_897[1] = (((safe_mul_func_int8_t_s_s((g_68[0] , g_530), (((safe_mod_func_int64_t_s_s((((l_895[3] = (safe_div_func_uint64_t_u_u((safe_lshift_func_uint16_t_u_s(g_175, l_895[0])), g_487))) < l_907) , 0xEDE1F16ACA95351CLL), g_501)) | l_907) , l_896))) != l_871) , g_430); --l_908; l_895[3] = (safe_mul_func_int8_t_s_s(g_547, ((safe_lshift_func_int16_t_s_s((safe_rshift_func_int8_t_s_s(l_896, 7)), 4)) & g_487))); return l_907; } for (g_155 = 0; (g_155 < 35); g_155 = safe_add_func_uint8_t_u_u(g_155, 8)) { uint16_t l_923 = 0UL; uint8_t l_924 = 250UL; int8_t l_930 = 0L; g_520 = g_526[0]; l_924 = (safe_mul_func_int16_t_s_s(((((((safe_mod_func_int32_t_s_s((-9L), ((g_153 = 0x03L) , g_804))) , p_11) == p_10) < 0xB88AB512L) >= g_245[0]) == p_13), l_923)); g_519 = ((l_897[1] = (l_930 = (g_498 , (safe_unary_minus_func_uint32_t_u((safe_rshift_func_uint16_t_u_u(((safe_mod_func_int16_t_s_s(((0x9B02FB528D72A514LL || l_923) ^ (-3L)), l_923)) & 1UL), 15))))))) > l_923); } l_895[3] = ((safe_div_func_int16_t_s_s((((safe_mul_func_uint8_t_u_u((+((((safe_sub_func_int32_t_s_s(((0xD0E4FFD1L > ((safe_lshift_func_uint16_t_u_s(((g_523 >= ((9UL & g_258) , 0x19L)) >= 0xC8E7D989B0D8A868LL), g_460[0])) ^ g_522)) > l_872), 0xAB2B2F68L)) || 0x651BFC77L) ^ p_12) || 0x31052512L)), p_12)) & p_12) == g_245[0]), 0x097BL)) ^ 246UL); lbl_966: l_873 = 2L; for (l_873 = 0; (l_873 <= 14); l_873 = safe_add_func_int64_t_s_s(l_873, 9)) { int32_t l_942 = (-6L); int32_t l_947 = 0x51256B60L; int32_t l_951 = 1L; int32_t l_952 = 0x7E6D4CA8L; int32_t l_954[1]; int8_t l_956 = 0xD3L; int i; for (i = 0; i < 1; i++) l_954[i] = 0x7722FE50L; l_942 = g_165; l_895[0] = ((g_732 |= (g_342 = l_897[1])) <= ((safe_rshift_func_int16_t_s_s(l_942, 4)) , (safe_unary_minus_func_uint16_t_u(((((((0x5352L >= 0x6C55L) , l_946) != g_245[2]) , 0xF3L) && l_873) , l_942))))); l_947 = p_11; if (p_12) continue; if (p_12) break; if (g_487) goto lbl_948; --g_958; g_519 ^= ((g_650 = g_469[0]) || (safe_mul_func_uint8_t_u_u((g_242 &= (((safe_sub_func_uint32_t_u_u((((l_871 , l_965) , g_175) >= p_11), l_895[3])) | l_872) != p_11)), g_702))); } if (p_10) { uint32_t l_969 = 2UL; int32_t l_981 = 6L; if (p_10) goto lbl_966; if (l_946) goto lbl_972; lbl_972: g_520 |= (safe_div_func_int16_t_s_s(((((l_969 >= (((safe_lshift_func_int8_t_s_s((0L | g_175), 3)) == 0x234E2E50L) , p_13)) , l_897[1]) | 0xCF6FDCA15E5B4558LL) , p_13), 65535UL)); g_520 &= ((((safe_sub_func_uint16_t_u_u(((l_981 = ((l_873 |= ((safe_lshift_func_int8_t_s_s((safe_mul_func_uint16_t_u_u(((safe_mul_func_uint8_t_u_u(0x37L, (l_897[1] | (l_969 && l_895[3])))) >= 3UL), 65529UL)), l_969)) >= g_177)) ^ p_12)) | l_881), g_430)) && 0x9D2D267422E1D874LL) , l_969) <= p_13); g_520 = (safe_sub_func_uint8_t_u_u((l_981 |= l_949), g_526[0])); l_981 = ((l_969 , 4294967295UL) <= (safe_mod_func_uint32_t_u_u((((safe_sub_func_uint16_t_u_u((safe_sub_func_uint32_t_u_u(((g_177 == 0x44L) & 0x5CAE4B2DL), 0x77A2D395L)), g_732)) , g_244) && 0xFBF52A11FE49B186LL), l_895[1]))); return g_522; } else { int64_t l_992 = 0xAE450B28B0A5DC65LL; g_520 = (p_10 , (safe_rshift_func_int8_t_s_u(g_68[2], ((l_992 && l_895[3]) , p_10)))); g_519 = (((safe_mul_func_uint16_t_u_u((((((safe_mul_func_int8_t_s_s((((safe_sub_func_uint32_t_u_u(p_11, p_12)) , (safe_mul_func_int8_t_s_s(((p_11 ^ 0x18L) | l_871), 0xE6L))) ^ p_12), 0xE0L)) | g_650) != (-1L)) , l_895[3]) < l_992), 65535UL)) && 1L) && p_10); --g_1001; g_244 = ((g_702 , (((l_992 <= (((safe_rshift_func_int8_t_s_u(((safe_add_func_uint32_t_u_u(((safe_div_func_uint8_t_u_u((safe_mul_func_int16_t_s_s(((l_897[1] , l_1012) ^ 1UL), 0x8849L)), p_12)) >= 0x7842A114L), 0xF9591544L)) == g_195), 4)) ^ l_872) && g_469[0])) , 0x9EFDE755L) == g_526[0])) != l_872); l_873 = ((((safe_div_func_int32_t_s_s(0x7721B04BL, g_216)) > g_460[1]) & g_259[0]) ^ 4294967295UL); } for (g_256 = 0; (g_256 <= 5); g_256 = safe_add_func_int64_t_s_s(g_256, 3)) { uint64_t l_1018 = 6UL; l_955 = g_802; l_1018 ^= (!(((p_10 ^ p_13) || (g_547 != p_10)) , l_897[1])); g_519 ^= (safe_add_func_uint16_t_u_u(0xB18BL, ((safe_sub_func_int16_t_s_s((g_259[1] <= (-1L)), 0xF1ACL)) && 0x8683B5C5L))); } return p_11; } static const int16_t func_16(uint32_t p_17, uint16_t p_18) { uint8_t l_807[3]; int32_t l_808 = (-8L); uint64_t l_827 = 18446744073709551608UL; int32_t l_837[1]; int i; for (i = 0; i < 3; i++) l_807[i] = 1UL; for (i = 0; i < 1; i++) l_837[i] = 0x13D92FC4L; l_807[1] = func_21((safe_mul_func_int8_t_s_s(0L, (!((safe_add_func_int64_t_s_s(p_17, g_2)) & g_2)))), p_17); l_808 = g_523; for (g_522 = (-2); (g_522 == 17); ++g_522) { uint32_t l_811 = 0xE99A4875L; int32_t l_812 = (-1L); l_811 = l_807[1]; l_812 = g_460[1]; return g_259[1]; } for (g_216 = (-14); (g_216 < 44); g_216 = safe_add_func_uint32_t_u_u(g_216, 6)) { int64_t l_817 = 0xFDEA44BDE8EF1B5ALL; int32_t l_826 = 0x35704607L; const uint32_t l_828 = 0xE7936054L; l_808 &= (safe_add_func_int64_t_s_s((l_817 ^= 0x3D08544918D01A2FLL), ((safe_lshift_func_int16_t_s_u((safe_rshift_func_uint8_t_u_u((((p_17 = (((safe_div_func_int16_t_s_s((((g_497[0] ^= (((g_519 &= (((255UL | (safe_add_func_int32_t_s_s((p_18 && p_18), 1UL))) & l_826) < l_826)) , l_826) > l_826)) < g_256) , p_17), l_826)) & 1L) < g_804)) , l_826) == p_18), l_826)), l_827)) | p_18))); return l_828; } l_808 = ((safe_mul_func_uint8_t_u_u(p_18, p_17)) != ((g_195++) || (safe_add_func_uint16_t_u_u(((safe_lshift_func_uint16_t_u_s((l_837[0] , g_244), p_17)) == l_837[0]), l_808)))); if (p_18) { int32_t l_838[1]; uint8_t l_855 = 0xCDL; int i; for (i = 0; i < 1; i++) l_838[i] = 0x2115D6B1L; l_838[0] = l_838[0]; l_837[0] = (safe_add_func_int8_t_s_s((safe_unary_minus_func_uint8_t_u((!(l_838[0] && (safe_mod_func_uint32_t_u_u(((l_838[0] = (safe_mul_func_int16_t_s_s((0xDEL >= p_17), g_732))) , p_18), g_259[1])))))), 0x2FL)); l_838[0] = l_808; g_520 = (0xBE78E112L < p_17); l_837[0] |= 0x2B4D4061L; g_520 = (safe_add_func_int16_t_s_s((safe_rshift_func_uint8_t_u_s((((safe_rshift_func_int8_t_s_s(((((g_519 = g_245[0]) < l_807[1]) | 0L) > 0xDBL), p_18)) == p_18) <= g_195), p_18)), 0x307DL)); l_838[0] = g_804; l_838[0] = (safe_mod_func_uint8_t_u_u(((g_259[1] &= l_855) || (safe_unary_minus_func_uint64_t_u(((((g_732 ^= (safe_add_func_uint64_t_u_u((l_855 , ((safe_div_func_uint32_t_u_u(l_807[1], p_17)) <= 1L)), g_226))) == l_838[0]) , p_18) | 0xC9ECL)))), g_226)); } else { g_519 = g_802; g_520 = 0x206E2F20L; } return l_807[1]; } static int32_t func_21(int16_t p_22, int32_t p_23) { uint8_t l_29 = 255UL; int32_t l_742 = (-1L); int32_t l_793 = 0x5F00BF07L; int32_t l_794[1]; int64_t l_795 = 1L; int i; for (i = 0; i < 1; i++) l_794[i] = 0x51737B28L; g_732 &= (l_29 ^ (g_2 != func_30(p_22, p_23, l_29, p_22, p_22))); g_244 = ((safe_sub_func_int8_t_s_s(((-1L) >= (safe_add_func_uint16_t_u_u((safe_add_func_int16_t_s_s(g_497[0], (((safe_add_func_int8_t_s_s(((~(((l_742 |= g_244) && l_742) ^ g_217)) >= 0x98C10640L), p_23)) | 0xB3BCL) & l_29))), g_258))), 0x09L)) >= (-1L)); g_519 = (safe_lshift_func_uint8_t_u_s((safe_mul_func_uint16_t_u_u((g_645 = ((safe_div_func_uint16_t_u_u((safe_mod_func_uint32_t_u_u((safe_add_func_uint32_t_u_u(((safe_sub_func_uint64_t_u_u((safe_div_func_uint64_t_u_u(((safe_sub_func_uint16_t_u_u(g_469[0], (((g_702 <= (safe_div_func_uint32_t_u_u(((safe_lshift_func_uint16_t_u_s((g_469[0] >= l_742), 4)) < p_22), p_22))) & l_742) != g_195))) , g_255), l_29)), 2UL)) == 0x61BEL), 0xD3379641L)), g_497[0])), 65530UL)) == g_2)), l_29)), l_29)); if ((safe_mod_func_int8_t_s_s((((safe_rshift_func_uint16_t_u_s((((safe_lshift_func_int16_t_s_s(g_487, 6)) > (safe_mod_func_int64_t_s_s(((l_29 & (safe_lshift_func_int8_t_s_s(((safe_mul_func_uint8_t_u_u((g_376 = (safe_add_func_uint8_t_u_u(7UL, 0xA4L))), g_226)) , g_522), 0))) && g_165), 1UL))) || 0xC5081803727745DFLL), 14)) && l_742) <= p_23), l_29))) { int8_t l_784 = 8L; uint16_t l_785[1]; int8_t l_786 = 9L; int32_t l_787 = (-2L); uint32_t l_792 = 0xA83D2183L; int i; for (i = 0; i < 1; i++) l_785[i] = 0x8E31L; l_786 &= (p_23 = ((((-1L) > (+((safe_sub_func_uint16_t_u_u(((((safe_lshift_func_uint16_t_u_s(l_784, ((l_784 & l_742) || 0UL))) || 252UL) <= 0xD98F4494B680EE6FLL) || g_526[0]), p_23)) & l_784))) >= g_650) && l_785[0])); p_23 ^= (l_787 = (g_154 != 0x6AL)); l_742 |= (((((((((safe_add_func_int8_t_s_s((safe_rshift_func_int8_t_s_s(0x19L, l_786)), ((p_22 < 0x8CBF1A2AL) ^ l_792))) ^ 18446744073709551610UL) == l_792) > 0x6241L) >= p_23) | l_784) < p_23) <= g_2) >= 7UL); g_244 |= p_22; } else { return l_742; } --g_796; for (g_342 = 0; (g_342 == 9); ++g_342) { int32_t l_801 = (-7L); g_804--; if (g_155) break; g_519 &= 3L; } for (g_519 = 1; (g_519 >= 0); g_519 -= 1) { int i; return g_469[g_519]; } return g_177; } static int16_t func_30(int16_t p_31, int32_t p_32, uint8_t p_33, int32_t p_34, uint32_t p_35) { uint32_t l_36 = 0x1C5860BCL; uint32_t l_45 = 0xEB945924L; int8_t l_712[4]; int32_t l_717 = 0x73BD7D42L; uint8_t l_728 = 1UL; int i; for (i = 0; i < 4; i++) l_712[i] = 0x5FL; l_36 = 0xB7BE2D3DL; for (p_33 = 0; (p_33 <= 31); ++p_33) { uint32_t l_39 = 0UL; uint32_t l_729[1]; uint16_t l_730[4]; int32_t l_731[4]; int i; for (i = 0; i < 1; i++) l_729[i] = 0UL; for (i = 0; i < 4; i++) l_730[i] = 0x2C9EL; for (i = 0; i < 4; i++) l_731[i] = 0xA998318DL; p_32 = ((l_39 |= g_2) && (((g_2 , (g_487 |= (p_31 = func_40(g_2, l_45, p_34, p_32)))) < l_712[1]) > g_497[0])); l_717 = (safe_mod_func_int32_t_s_s((safe_mod_func_uint8_t_u_u(l_712[0], g_521)), l_45)); g_244 = ((l_731[2] = (g_530 = (safe_sub_func_int8_t_s_s((safe_sub_func_int16_t_s_s((safe_div_func_uint32_t_u_u((l_36 && ((((safe_div_func_int8_t_s_s((g_255 , (((safe_mod_func_int64_t_s_s((l_717 |= l_728), l_39)) < l_39) != l_729[0])), g_650)) ^ 0x8ADDL) < p_33) ^ p_33)), l_730[3])), 0L)), g_547)))) | p_35); } return p_35; } static int16_t func_40(int8_t p_41, int8_t p_42, uint64_t p_43, uint32_t p_44) { int64_t l_48 = (-1L); int32_t l_488 = 0x11363FC4L; int32_t l_490 = 0L; int32_t l_524 = 0xAF41B11BL; int32_t l_525 = 0x391D0DBAL; int8_t l_529[3]; uint32_t l_539 = 4294967286UL; int64_t l_540 = (-2L); int32_t l_642 = 0L; int32_t l_643 = (-1L); int32_t l_644 = 0xEC0E2BE6L; uint8_t l_667 = 1UL; uint16_t l_679[4] = {0x55F3L,0x55F3L,0x55F3L,0x55F3L}; int i; for (i = 0; i < 3; i++) l_529[i] = 0x0BL; l_48 ^= (safe_sub_func_int8_t_s_s(0L, p_43)); for (p_44 = 0; (p_44 <= 58); p_44 = safe_add_func_int8_t_s_s(p_44, 8)) { int16_t l_473 = 1L; uint16_t l_482 = 0xD06FL; int32_t l_486 = 0x002A6962L; int32_t l_489 = 0x775714E6L; int32_t l_491 = 0xB15A7122L; int32_t l_492 = (-2L); int32_t l_493 = 0x158996B3L; l_473 &= ((safe_div_func_int32_t_s_s(((safe_add_func_int8_t_s_s((safe_sub_func_uint8_t_u_u((safe_unary_minus_func_int64_t_s(p_42)), ((safe_lshift_func_uint8_t_u_s((p_41 > (safe_lshift_func_int8_t_s_s(((func_62(g_2, g_2, p_41, p_42) > l_48) | 0x297F213C8FBD4BF0LL), g_256))), 1)) < g_2))), g_68[2])) ^ 2L), p_42)) != g_2); g_244 = (((safe_div_func_uint8_t_u_u((safe_add_func_int16_t_s_s((l_48 | ((safe_sub_func_uint16_t_u_u((l_473 , (safe_mul_func_int8_t_s_s(((p_44 == l_48) , 0L), 0xC1L))), g_155)) >= p_42)), p_43)), l_48)) <= l_482) | 1UL); if (g_68[1]) continue; g_244 = (safe_div_func_int8_t_s_s((safe_unary_minus_func_int64_t_s(g_216)), 1UL)); g_244 = l_473; g_494++; ++g_498; ++g_501; } lbl_691: for (g_501 = (-1); (g_501 >= 58); g_501 = safe_add_func_uint64_t_u_u(g_501, 5)) { int16_t l_516 = 0x5E45L; int32_t l_517 = 0x2F461F9DL; int32_t l_518[4] = {0x89C036F8L,0x89C036F8L,0x89C036F8L,0x89C036F8L}; int i; l_490 = ((((((0L && (safe_rshift_func_int16_t_s_s((3L || ((safe_add_func_int16_t_s_s((safe_mul_func_uint8_t_u_u((safe_div_func_uint16_t_u_u((safe_sub_func_int16_t_s_s(0x72D8L, p_42)), g_430)), g_255)), l_490)) < (-5L))), 11))) ^ 0UL) < g_155) , l_516) || l_490) , g_177); g_526[0]--; g_530++; l_518[3] &= g_68[0]; } if ((safe_div_func_uint64_t_u_u((l_525 , (g_526[0] = (((p_41 < (safe_lshift_func_int16_t_s_u((((safe_div_func_uint8_t_u_u((g_216 ^ l_488), l_525)) > l_539) && l_539), 10))) ^ p_44) <= l_540))), g_494))) { int32_t l_558 = 0x01B3E128L; int32_t l_559[2]; const uint16_t l_569 = 0xBD2FL; uint8_t l_595[1]; int i; for (i = 0; i < 2; i++) l_559[i] = 0x633AAC75L; for (i = 0; i < 1; i++) l_595[i] = 247UL; g_244 = (((((safe_mod_func_int64_t_s_s(((l_490 = ((safe_mod_func_int64_t_s_s((safe_sub_func_uint16_t_u_u(((g_547 || (safe_rshift_func_int8_t_s_u((safe_mod_func_uint32_t_u_u((((safe_rshift_func_uint16_t_u_s((g_530 = 1UL), ((l_559[1] &= (((((safe_div_func_uint8_t_u_u((safe_sub_func_int32_t_s_s(((g_526[0] = ((-1L) ^ l_558)) | g_255), l_558)), g_242)) ^ l_558) && g_522) || g_153) , (-3L))) , 0x5A87L))) & 6UL) && l_48), p_41)), 1))) >= l_558), (-9L))), l_558)) != (-1L))) >= p_43), p_41)) == g_256) , g_217) || 0x48L) , 0xA302CC0FL); l_559[1] = ((safe_add_func_int32_t_s_s(0x3484D1A5L, (((g_376 | ((safe_mod_func_uint32_t_u_u(g_154, l_539)) , 8UL)) >= l_490) <= l_540))) ^ 0x1D19L); g_244 ^= 0x2FF4E7C8L; l_524 = ((((safe_sub_func_uint64_t_u_u(p_41, (l_488 |= (p_43 = ((+(g_226 = p_44)) != (((safe_div_func_int64_t_s_s(l_569, g_526[0])) , 0x4DL) != p_41)))))) == 0x4CA4F0B8C3216053LL) , l_525) , p_43); g_244 = (safe_rshift_func_uint16_t_u_s((((~1UL) > ((safe_rshift_func_int8_t_s_s((((((safe_add_func_uint16_t_u_u(p_42, (safe_unary_minus_func_int64_t_s((((((18446744073709551609UL == 18446744073709551613UL) || g_165) && 65535UL) || 0x960AB7BAL) >= g_165))))) < l_559[0]) ^ 0xC3ADL) == 1UL) , p_43), g_256)) , 1UL)) | l_539), 9)); l_559[1] = g_226; g_244 = (safe_div_func_uint32_t_u_u((p_44 != (safe_add_func_uint16_t_u_u(((safe_mod_func_int16_t_s_s((safe_mod_func_uint64_t_u_u((l_559[1] >= (safe_mul_func_int16_t_s_s(((safe_unary_minus_func_uint64_t_u((((~(((safe_rshift_func_uint16_t_u_u(((p_42 &= (safe_rshift_func_int8_t_s_u((g_154 < p_43), g_166))) , g_376), p_44)) == l_540) && 65531UL)) , l_525) >= g_526[0]))) < g_155), g_497[0]))), g_245[2])), g_460[0])) > l_569), (-9L)))), l_539)); l_524 ^= ((p_44 && g_68[0]) & (((-10L) | p_44) && 4L)); l_525 = ((l_569 || ((g_594 &= (((g_342 ^= (((0xC856L & (g_195 , g_67)) ^ p_42) || 0x03A0L)) == 2UL) < (-1L))) == p_43)) | l_595[0]); } else { int16_t l_600 = 0x64FEL; int32_t l_606 = 0x9FF2AFA1L; int32_t l_607[4]; int32_t l_608 = 9L; uint64_t l_641 = 0x778EB83A8703EAB7LL; int i; for (i = 0; i < 4; i++) l_607[i] = 1L; l_608 = (safe_rshift_func_int8_t_s_u(((safe_sub_func_uint32_t_u_u(l_600, (safe_div_func_int8_t_s_s((l_600 > (safe_lshift_func_uint16_t_u_s((((((l_607[1] ^= (l_606 = (safe_unary_minus_func_uint32_t_u(g_547)))) ^ 4L) | 0xAA74L) , 18446744073709551615UL) == 4UL), l_525))), g_460[2])))) <= 0xFBEC49CCF5684AA2LL), g_519)); l_524 = (safe_rshift_func_uint8_t_u_s(0xD2L, (((safe_mod_func_uint16_t_u_u((++g_226), (safe_mod_func_int8_t_s_s((safe_lshift_func_uint16_t_u_s((safe_unary_minus_func_int8_t_s((l_606 &= ((safe_div_func_uint8_t_u_u((((!((((g_519 = ((safe_unary_minus_func_int32_t_s((safe_rshift_func_uint16_t_u_u(((safe_mul_func_uint16_t_u_u(((((safe_add_func_uint8_t_u_u((l_488 &= 0x2AL), ((safe_div_func_uint8_t_u_u((safe_rshift_func_int16_t_s_u((l_608 | l_539), 6)), 1UL)) >= g_175))) && l_539) > 0xBF25L) >= l_529[0]), 0x8C73L)) > 1L), l_607[1])))) != p_42)) && l_525) < 0xD8CBL) >= l_540)) != l_539) == 4UL), l_608)) , p_43)))), 4)), g_256)))) != p_41) | (-8L)))); l_607[2] = (+(safe_div_func_uint32_t_u_u((safe_mul_func_uint16_t_u_u(g_68[1], ((l_641 = (((l_606 ^= g_521) < (p_43 = (safe_lshift_func_int16_t_s_u(0x83A2L, 11)))) , l_540)) , l_529[1]))), p_41))); g_645--; if (l_525) goto lbl_653; l_643 |= (g_244 ^= ((safe_sub_func_int8_t_s_s(g_460[1], 0x7FL)) ^ (((-3L) ^ p_44) || g_175))); lbl_653: g_650++; l_524 ^= ((safe_sub_func_int64_t_s_s((safe_sub_func_uint8_t_u_u(0x91L, (((safe_div_func_int32_t_s_s(0xE0DE5307L, (l_606 = (l_644 ^= ((safe_mul_func_int16_t_s_s(l_48, g_469[0])) <= 0xAD6FL))))) || (-1L)) | g_521))), p_41)) | g_498); } l_490 = (((l_524 , ((~g_2) ^ ((safe_unary_minus_func_int8_t_s((g_226 != 1UL))) >= l_488))) > g_259[1]) <= p_41); for (l_644 = 4; (l_644 == (-1)); --l_644) { uint16_t l_668 = 0x8555L; int32_t l_669 = 0xD4B5F37CL; uint32_t l_672 = 0x43878AC9L; g_519 = (!(p_41 <= g_154)); l_669 = (l_488 = (l_667 , ((((((g_526[0] , g_650) == p_43) >= g_245[0]) ^ g_256) && p_43) && l_668))); l_672 = (safe_lshift_func_int8_t_s_u((-9L), 1)); } l_642 = ((g_497[0] , (g_153 = (safe_sub_func_uint8_t_u_u((l_539 , 0x8BL), l_488)))) , g_165); if (g_258) { int16_t l_675[2]; int32_t l_676 = 0L; int32_t l_677 = 9L; int32_t l_678 = 0L; int i; for (i = 0; i < 2; i++) l_675[i] = (-4L); l_679[0]--; g_520 = (-1L); g_519 = ((g_523 = (((((safe_sub_func_int8_t_s_s((((l_677 &= g_195) != (g_430 ^ p_44)) > (-1L)), (-4L))) >= g_497[0]) <= 255UL) > l_678) == 6L)) , 0x16FFFE09L); return p_43; } else { uint32_t l_684 = 1UL; l_684--; l_644 |= (((safe_rshift_func_int8_t_s_u(((g_153 &= l_684) == (((p_43 = l_684) <= (-7L)) & g_520)), g_245[0])) , p_44) , g_2); l_524 = 7L; g_519 = 0x9ED488A8L; } for (l_539 = (-30); (l_539 > 32); l_539 = safe_add_func_int8_t_s_s(l_539, 9)) { int32_t l_694 = (-9L); int32_t l_697 = 0L; if (l_524) goto lbl_691; g_244 = (((l_525 = ((g_154 , ((0UL | (g_501 | 0x70L)) | g_245[0])) == p_43)) , p_42) , g_497[0]); l_643 = (((safe_add_func_uint16_t_u_u((g_594 = l_694), (l_697 ^= (safe_mod_func_uint16_t_u_u(p_42, l_643))))) != l_529[1]) , p_42); g_244 = (l_643 = 0x11C1167AL); g_520 = g_67; if (l_529[0]) continue; l_524 = ((safe_mod_func_int32_t_s_s((safe_sub_func_int64_t_s_s(((18446744073709551606UL == (g_702 = ((p_42 |= g_702) , (((((safe_sub_func_int64_t_s_s((0x2682L <= 0xD07BL), l_694)) , 0x16L) , g_245[0]) <= 0L) | 0L)))) , 1L), g_342)), p_44)) > l_697); l_644 = p_44; g_519 = ((safe_mod_func_uint16_t_u_u(0UL, g_258)) >= ((l_488 = g_523) <= 9L)); } l_643 = (((+g_175) & (safe_add_func_uint16_t_u_u(((safe_mul_func_uint8_t_u_u((l_540 > l_679[2]), 0x37L)) , g_460[1]), p_43))) && g_175); return p_41; } static uint16_t func_62(uint32_t p_63, uint32_t p_64, uint32_t p_65, int8_t p_66) { uint64_t l_76 = 18446744073709551613UL; int32_t l_438 = 1L; int32_t l_447 = (-10L); const int64_t l_454[3] = {(-1L),(-1L),(-1L)}; int32_t l_459 = (-10L); int i; g_67 = 0xDDD0C6A3L; for (p_65 = 0; (p_65 <= 2); p_65 += 1) { int32_t l_439 = 0xCCF848ACL; uint16_t l_446 = 0x05E4L; int i; l_438 = (safe_mul_func_int8_t_s_s((g_68[p_65] == g_68[p_65]), ((func_71((l_76 = g_67), g_67, g_68[p_65], p_66) == 0x46A87F33L) >= 0L))); g_244 ^= p_65; if (g_216) break; l_439 &= g_68[p_65]; g_244 &= g_259[0]; l_447 = (((((safe_lshift_func_uint16_t_u_u((l_438 = ((!(p_63 || (!((safe_rshift_func_int8_t_s_s((l_446 ^ g_68[1]), 4)) , p_66)))) && 1L)), g_258)) == p_65) == p_65) != l_446) >= p_64); if (l_446) continue; g_244 ^= (l_447 &= (safe_lshift_func_uint16_t_u_u((((safe_mul_func_uint16_t_u_u(0x94DFL, ((safe_lshift_func_uint16_t_u_u((g_165 && 1UL), 11)) && l_454[2]))) ^ (-1L)) && (-5L)), p_63))); if (p_66) continue; } for (p_64 = 0; (p_64 != 29); p_64++) { int8_t l_457 = 0x63L; int32_t l_458 = 0x263AD6D1L; l_458 = l_457; g_460[1]++; return g_2; } l_459 |= (((safe_rshift_func_int16_t_s_s(0x74BCL, 4)) <= ((0xF9FEL || (((((((safe_div_func_uint32_t_u_u(g_195, 0x4A245415L)) == l_454[2]) ^ l_447) >= l_454[2]) || p_64) && 0xF9L) & l_447)) < 0x604427A126096A5CLL)) > l_454[0]); for (g_226 = (-8); (g_226 <= 13); ++g_226) { uint64_t l_472 = 8UL; --g_469[0]; l_472 = p_63; g_244 = 0xBB784283L; if (g_245[2]) continue; return p_65; } return p_66; } static int32_t func_71(uint64_t p_72, uint32_t p_73, int16_t p_74, uint16_t p_75) { uint8_t l_77[4] = {252UL,252UL,252UL,252UL}; uint8_t l_377 = 255UL; int32_t l_385 = 0x12A3E49AL; int32_t l_392 = 0x2CCC2C28L; int i; lbl_422: for (p_75 = 0; (p_75 <= 3); p_75 += 1) { int32_t l_98 = 0x7D1D410AL; int32_t l_99 = 7L; uint16_t l_378[2]; int32_t l_379 = 0xC901CCD8L; int i; for (i = 0; i < 2; i++) l_378[i] = 65533UL; l_379 |= ((0xF2B9ACCEL >= (((((safe_lshift_func_int16_t_s_u((safe_lshift_func_int8_t_s_u((((safe_mul_func_uint8_t_u_u(((safe_sub_func_uint8_t_u_u(((safe_mul_func_uint8_t_u_u((safe_sub_func_uint8_t_u_u((safe_mul_func_uint8_t_u_u(((g_2 , func_92(((l_99 &= (safe_rshift_func_uint16_t_u_s(g_68[1], l_98))) , g_2), l_77[0], p_72)) >= l_377), l_98)), g_67)), p_72)) , l_99), l_98)) , g_226), 247UL)) ^ (-1L)) , 3L), g_256)), 9)) > 0x914E0829E44B4A44LL) | l_77[3]) , l_378[1]) | p_75)) >= l_378[1]); if (p_73) break; g_244 = (((safe_rshift_func_int16_t_s_u((0L & (l_378[1] || (~(((safe_mod_func_int32_t_s_s((((((0x07C5L || (-1L)) != 0xC374L) < l_377) <= l_377) || 0xCBC4L), l_377)) != 0x834F8327AEA69420LL) | g_244)))), l_77[0])) == g_154) , l_385); if (p_75) break; l_392 ^= (((safe_lshift_func_uint8_t_u_s((safe_div_func_uint16_t_u_u(g_67, (p_73 || (safe_add_func_int16_t_s_s((g_155 | l_77[2]), p_72))))), 5)) , l_378[1]) | 0x36119D7EF94F6C1ALL); g_244 |= (l_77[1] , ((safe_sub_func_uint64_t_u_u(((!p_74) >= ((p_72 ^= ((g_245[0] |= (safe_rshift_func_int16_t_s_s(((g_154 = ((safe_add_func_int8_t_s_s((safe_rshift_func_uint8_t_u_u(0x68L, 1)), l_77[1])) | 7L)) , (-1L)), 2))) , 1UL)) , p_74)), g_166)) <= 18446744073709551615UL)); l_98 |= (safe_add_func_uint16_t_u_u((safe_rshift_func_uint8_t_u_s((safe_lshift_func_int8_t_s_u((safe_mul_func_uint16_t_u_u(6UL, ((((safe_mod_func_int8_t_s_s((l_392 = p_74), l_377)) , l_385) > g_412) || g_155))), p_73)), p_73)), 0L)); } if (((p_72 |= ((((+(safe_add_func_uint64_t_u_u((safe_mod_func_int64_t_s_s((safe_mod_func_int8_t_s_s((safe_mod_func_uint32_t_u_u((l_392 = ((g_245[0] != (-1L)) & ((l_77[3] , g_245[0]) > p_75))), l_385)), 0x13L)), g_2)), g_259[0]))) & l_77[1]) > g_245[2]) >= g_165)) && p_73)) { lbl_427: if (p_73) goto lbl_422; return p_75; } else { uint32_t l_425 = 4294967290UL; int32_t l_426 = 0L; int32_t l_429[1]; int32_t l_433 = 0x70B0799FL; int i; for (i = 0; i < 1; i++) l_429[i] = (-8L); l_425 = (safe_rshift_func_int16_t_s_u((p_74 < g_412), 15)); lbl_428: l_426 = l_425; if (l_392) goto lbl_427; if (l_392) goto lbl_428; g_430--; l_392 = 0x0A5AA052L; l_433 = g_68[0]; g_244 |= (safe_rshift_func_int16_t_s_u(((((p_75 = ((safe_mul_func_int8_t_s_s((g_245[0] && l_77[0]), 0L)) >= 0xB8L)) ^ p_72) , g_226) || p_74), g_226)); return g_255; } } static uint64_t func_92(int8_t p_93, int32_t p_94, int32_t p_95) { uint64_t l_102[1]; int32_t l_357[3]; int32_t l_364[1]; int8_t l_368 = 1L; int i; for (i = 0; i < 1; i++) l_102[i] = 0xE3B6EA11B98B5DB2LL; for (i = 0; i < 3; i++) l_357[i] = (-6L); for (i = 0; i < 1; i++) l_364[i] = 8L; p_94 ^= func_100(l_102[0]); p_94 = ((safe_mod_func_int32_t_s_s(((((g_242 <= g_259[0]) , l_102[0]) < l_102[0]) && 1UL), 0xF77E456CL)) | l_102[0]); l_357[0] ^= (((((-1L) <= 0x8BBF57C4L) > (safe_mul_func_int8_t_s_s(((safe_lshift_func_int8_t_s_s(((safe_rshift_func_int8_t_s_s(((safe_lshift_func_uint16_t_u_u((0xD7L >= 1L), 9)) >= (-7L)), l_102[0])) || 8UL), g_226)) | p_94), 1L))) , l_102[0]) == g_256); p_94 ^= l_102[0]; g_244 &= 1L; g_244 = g_244; g_244 = (((((safe_rshift_func_int8_t_s_s(((--g_259[0]) > (safe_add_func_uint64_t_u_u((l_357[0] = g_175), 0x73CFD7DF8042BDC2LL))), 1)) != ((g_175 >= l_364[0]) || 1L)) <= 1UL) & g_255) & p_95); l_357[0] |= (safe_mul_func_int8_t_s_s((!l_368), (((safe_add_func_uint16_t_u_u(65535UL, ((g_376 = (p_93 = (safe_lshift_func_uint16_t_u_s((safe_div_func_uint8_t_u_u((safe_unary_minus_func_uint32_t_u(((((-5L) && 0x8C44A252L) | 18446744073709551614UL) < p_93))), l_102[0])), 7)))) & 0xA2L))) ^ p_94) > g_226))); return p_94; } static const int32_t func_100(int32_t p_101) { const int16_t l_105 = (-1L); uint64_t l_108 = 0UL; int32_t l_125 = 0xB7884FD3L; int16_t l_126 = (-7L); int32_t l_129 = 0x49D34E1BL; int32_t l_163 = 1L; uint64_t l_189 = 0x140D65803A083379LL; int32_t l_243[3]; int8_t l_257 = 0x76L; int16_t l_280 = 1L; int64_t l_282 = (-6L); uint64_t l_340[4] = {0x3FF47733F460C0EELL,0x3FF47733F460C0EELL,0x3FF47733F460C0EELL,0x3FF47733F460C0EELL}; int16_t l_341[3]; int i; for (i = 0; i < 3; i++) l_243[i] = 0xE0E4DEADL; for (i = 0; i < 3; i++) l_341[i] = 0L; lbl_176: if ((safe_mod_func_uint32_t_u_u((l_105 && ((safe_rshift_func_int8_t_s_s((0x0CFC2012L == 4294967295UL), l_105)) == l_108)), (-8L)))) { int16_t l_127 = 1L; int32_t l_128[1]; int i; for (i = 0; i < 1; i++) l_128[i] = 0x066BE38AL; l_129 &= (safe_add_func_uint16_t_u_u(((safe_sub_func_int64_t_s_s((((safe_lshift_func_int8_t_s_s(((l_128[0] = (p_101 | (safe_rshift_func_uint8_t_u_u((((safe_div_func_uint64_t_u_u(0xF62D42CB0EA5CD88LL, (~(safe_div_func_int16_t_s_s(((~(safe_mod_func_uint32_t_u_u(((((l_125 = (((l_108 < 0L) && p_101) && 0xACB962FAL)) ^ 0xF3B3E57EL) , p_101) | l_126), p_101))) , 0x2974L), 0x85FCL))))) && l_127) || l_127), 3)))) > 1L), p_101)) , p_101) >= l_127), g_68[1])) <= 0x96F13771C77DD35ALL), 3L)); } else { l_129 = (safe_sub_func_uint16_t_u_u((+(0x9D5A4BDFL || ((safe_sub_func_int32_t_s_s((p_101 >= 0x8DL), 0xB1B77089L)) && g_67))), 0xE8C0L)); return g_2; } for (l_126 = 0; (l_126 <= (-13)); l_126 = safe_sub_func_uint8_t_u_u(l_126, 8)) { uint64_t l_143[1]; int32_t l_150 = 0xC227FEFFL; int64_t l_151 = (-4L); int8_t l_152 = 0x60L; int32_t l_164 = 7L; int i; for (i = 0; i < 1; i++) l_143[i] = 18446744073709551609UL; l_125 = ((safe_rshift_func_uint8_t_u_u((safe_sub_func_uint64_t_u_u(p_101, ((safe_mod_func_int8_t_s_s(0xD9L, l_143[0])) , 0xC195823B322AC55BLL))), 5)) , g_2); g_155 |= ((g_154 = (safe_add_func_int8_t_s_s((((g_153 = ((safe_div_func_uint64_t_u_u(((l_129 = (((safe_mul_func_uint16_t_u_u((l_150 ^= l_143[0]), g_67)) <= ((p_101 < l_151) , g_68[2])) ^ l_151)) < l_143[0]), l_152)) > 3L)) & g_67) < g_68[0]), p_101))) , p_101); l_164 &= (((((safe_lshift_func_int16_t_s_u((g_153 && ((((((((l_129 , (safe_add_func_uint16_t_u_u((!(l_163 ^= (safe_div_func_uint16_t_u_u(g_153, p_101)))), 0UL))) <= 0x3AFFD86C0845370BLL) ^ g_155) >= p_101) && l_108) ^ g_68[1]) , p_101) || l_163)), 4)) || p_101) , 4294967295UL) && l_150) | l_143[0]); g_166++; g_175 = (p_101 , (safe_mod_func_uint16_t_u_u((safe_mul_func_uint16_t_u_u(p_101, (safe_add_func_int16_t_s_s(0x7850L, l_143[0])))), p_101))); if (l_152) goto lbl_176; g_177++; l_189 = (((safe_div_func_uint32_t_u_u((p_101 ^ ((((((((safe_mul_func_int8_t_s_s(((safe_mul_func_uint16_t_u_u(l_152, (safe_sub_func_int64_t_s_s(((safe_unary_minus_func_uint16_t_u(65535UL)) && 0xA3L), (-1L))))) | g_67), 4L)) ^ p_101) | p_101) >= 0x97C6L) , l_143[0]) ^ 0x4A855424L) || g_155) && p_101)), p_101)) | g_165) < p_101); } for (l_125 = 20; (l_125 <= (-1)); l_125 = safe_sub_func_int8_t_s_s(l_125, 4)) { uint32_t l_194 = 0UL; int32_t l_198[4] = {0x5FB264BAL,0x5FB264BAL,0x5FB264BAL,0x5FB264BAL}; int i; l_198[3] ^= (g_154 ^ (safe_sub_func_int16_t_s_s(l_194, ((g_195--) <= 0x8505D4F8719566CBLL)))); } l_125 = ((safe_mul_func_int8_t_s_s((-1L), (((((safe_rshift_func_int8_t_s_u(g_153, (safe_rshift_func_int16_t_s_s(l_129, p_101)))) , 1L) < g_2) && p_101) , 0x22L))) <= 0L); if (g_166) { int64_t l_210[4] = {0xC37AD79404BF6FAELL,0xC37AD79404BF6FAELL,0xC37AD79404BF6FAELL,0xC37AD79404BF6FAELL}; int i; g_217 = ((safe_unary_minus_func_int16_t_s(((safe_lshift_func_int16_t_s_u(((p_101 >= ((((safe_sub_func_uint32_t_u_u(((l_210[2] , (g_216 |= (((safe_unary_minus_func_uint32_t_u((((safe_lshift_func_uint8_t_u_u((safe_sub_func_int32_t_s_s(g_165, p_101)), p_101)) == l_210[2]) == l_210[2]))) ^ l_163) >= p_101))) || 0x8EEED4ECL), 0x99CEFAC0L)) <= p_101) , l_108) , g_154)) || l_210[2]), l_129)) | p_101))) && l_105); return p_101; } else { int8_t l_225 = 0x78L; int32_t l_234 = 0x403320DEL; g_226 = ((safe_div_func_uint16_t_u_u(0x37C7L, l_105)) >= ((safe_rshift_func_uint16_t_u_s(((safe_unary_minus_func_uint64_t_u((safe_add_func_uint64_t_u_u((l_225 & l_225), g_153)))) | l_126), g_217)) != g_217)); l_125 |= (l_129 = (safe_sub_func_int64_t_s_s((safe_sub_func_uint16_t_u_u((!l_225), g_67)), ((safe_mod_func_uint64_t_u_u((l_234 = 0xE751A909BF4FE08CLL), 5UL)) , g_2)))); l_125 |= (safe_lshift_func_int16_t_s_u((g_153 , g_217), 3)); } if (l_189) { return g_2; } else { int32_t l_237 = 1L; int32_t l_238 = 0xE08C4F1EL; int32_t l_241[2]; int i; for (i = 0; i < 2; i++) l_241[i] = 0x7F8D447FL; g_242 &= (((((l_238 = l_237) | (safe_sub_func_uint32_t_u_u((p_101 || (l_129 = ((l_241[1] = (((g_216 <= g_226) >= l_237) , g_2)) != (-2L)))), p_101))) || 0xE05FA8EDL) > g_177) || g_216); g_245[0]++; g_255 = (g_244 &= (safe_rshift_func_uint8_t_u_u((+(safe_rshift_func_uint16_t_u_u((18446744073709551608UL >= (safe_sub_func_uint16_t_u_u(l_129, p_101))), 9))), g_195))); g_259[0]++; } if (p_101) { uint32_t l_279 = 9UL; uint64_t l_281 = 8UL; int32_t l_284 = 0x160EC466L; l_125 = (l_243[0] = l_163); if (l_129) goto lbl_283; l_280 ^= ((safe_sub_func_int8_t_s_s((+(safe_rshift_func_int8_t_s_u((0xD120FEEDL == p_101), (safe_lshift_func_uint8_t_u_s(((safe_mul_func_int8_t_s_s(((safe_div_func_int8_t_s_s((safe_mod_func_int8_t_s_s((((safe_sub_func_uint64_t_u_u(((l_279 = ((safe_mod_func_uint32_t_u_u(p_101, p_101)) , p_101)) , 0xD4508A83B6B2B969LL), (-3L))) ^ g_258) == g_166), g_154)), l_189)) > g_177), l_243[0])) , l_108), 0))))), g_68[0])) | l_125); l_243[0] = (p_101 > g_256); lbl_283: l_282 &= (((l_281 = (l_243[0] = l_279)) , p_101) || p_101); l_284 |= p_101; } else { int32_t l_285 = 0xCF389D0FL; l_285 = l_125; g_244 = (((safe_sub_func_uint16_t_u_u(((g_259[1] && (safe_mod_func_int8_t_s_s(((safe_sub_func_int8_t_s_s(((((safe_lshift_func_uint16_t_u_s((((g_68[1] != 0L) != l_163) == p_101), p_101)) == g_255) <= 1UL) >= 7L), p_101)) <= 0UL), g_245[2]))) || 1UL), p_101)) & l_280) >= 1L); return p_101; } g_244 ^= (safe_div_func_uint64_t_u_u((((((safe_add_func_uint64_t_u_u(((l_243[0] = (+(safe_mul_func_int8_t_s_s((-3L), (g_216 , (safe_mul_func_int16_t_s_s((safe_div_func_uint64_t_u_u(((safe_mul_func_uint8_t_u_u(((l_129 ^= ((((+1UL) || 0xCDE32BABL) < l_108) == l_243[1])) | g_256), g_216)) >= 0xD686L), 1L)), 0xEB10L))))))) , l_280), g_154)) & 0x9DL) >= l_257) <= 253UL) < p_101), p_101)); g_342 &= (safe_mod_func_int32_t_s_s((((safe_lshift_func_uint8_t_u_s((safe_lshift_func_int16_t_s_u(((((((safe_rshift_func_uint8_t_u_s((((safe_mul_func_int8_t_s_s(((65535UL > (safe_rshift_func_int16_t_s_s((((((~(((safe_lshift_func_int16_t_s_s(((((safe_mod_func_uint64_t_u_u((g_244 != ((safe_div_func_int8_t_s_s(((safe_div_func_int16_t_s_s((((safe_mul_func_uint16_t_u_u((((safe_mul_func_uint8_t_u_u(((l_129 ^= (safe_div_func_uint32_t_u_u((safe_rshift_func_uint8_t_u_u((+(safe_rshift_func_int16_t_s_u(p_101, 8))), g_259[0])), p_101))) >= p_101), g_165)) , 0x4E06L) | 0x684EL), (-5L))) , 0xCC2CE9A7L) & (-1L)), 2UL)) >= 0L), p_101)) && g_258)), p_101)) ^ g_165) > p_101) < p_101), g_258)) ^ 0xBC0FL) , l_340[2])) <= g_177) <= g_259[0]) , 0xC7F7L) == g_177), g_245[0]))) & g_166), g_155)) < l_243[2]) , 0xCBL), g_67)) ^ l_243[0]) ^ 6L) <= (-1L)) < p_101) || p_101), p_101)), 6)) > g_68[0]) && l_341[1]), g_226)); g_244 ^= (p_101 , ((safe_mod_func_uint64_t_u_u(g_2, ((safe_rshift_func_uint8_t_u_u(((((l_129 &= l_243[0]) <= l_340[3]) ^ 0x17D3968EL) || 0x701E65F4L), p_101)) || 7UL))) < g_155)); return g_256; } int main (int argc, char* argv[]) { int i; int print_hash_value = 0; if (argc == 2 && strcmp(argv[1], "1") == 0) print_hash_value = 1; platform_main_begin(); crc32_gentab(); func_1(); transparent_crc(g_2, "g_2", print_hash_value); transparent_crc(g_67, "g_67", print_hash_value); for (i = 0; i < 3; i++) { transparent_crc(g_68[i], "g_68[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_153, "g_153", print_hash_value); transparent_crc(g_154, "g_154", print_hash_value); transparent_crc(g_155, "g_155", print_hash_value); transparent_crc(g_165, "g_165", print_hash_value); transparent_crc(g_166, "g_166", print_hash_value); transparent_crc(g_175, "g_175", print_hash_value); transparent_crc(g_177, "g_177", print_hash_value); transparent_crc(g_195, "g_195", print_hash_value); transparent_crc(g_216, "g_216", print_hash_value); transparent_crc(g_217, "g_217", print_hash_value); transparent_crc(g_226, "g_226", print_hash_value); transparent_crc(g_242, "g_242", print_hash_value); transparent_crc(g_244, "g_244", print_hash_value); for (i = 0; i < 3; i++) { transparent_crc(g_245[i], "g_245[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_255, "g_255", print_hash_value); transparent_crc(g_256, "g_256", print_hash_value); transparent_crc(g_258, "g_258", print_hash_value); for (i = 0; i < 2; i++) { transparent_crc(g_259[i], "g_259[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_342, "g_342", print_hash_value); transparent_crc(g_376, "g_376", print_hash_value); transparent_crc(g_412, "g_412", print_hash_value); transparent_crc(g_430, "g_430", print_hash_value); for (i = 0; i < 4; i++) { transparent_crc(g_460[i], "g_460[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } for (i = 0; i < 2; i++) { transparent_crc(g_469[i], "g_469[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_487, "g_487", print_hash_value); transparent_crc(g_494, "g_494", print_hash_value); for (i = 0; i < 1; i++) { transparent_crc(g_497[i], "g_497[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_498, "g_498", print_hash_value); transparent_crc(g_501, "g_501", print_hash_value); transparent_crc(g_519, "g_519", print_hash_value); transparent_crc(g_520, "g_520", print_hash_value); transparent_crc(g_521, "g_521", print_hash_value); transparent_crc(g_522, "g_522", print_hash_value); transparent_crc(g_523, "g_523", print_hash_value); for (i = 0; i < 1; i++) { transparent_crc(g_526[i], "g_526[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_530, "g_530", print_hash_value); transparent_crc(g_547, "g_547", print_hash_value); transparent_crc(g_594, "g_594", print_hash_value); transparent_crc(g_645, "g_645", print_hash_value); transparent_crc(g_650, "g_650", print_hash_value); transparent_crc(g_702, "g_702", print_hash_value); transparent_crc(g_732, "g_732", print_hash_value); transparent_crc(g_796, "g_796", print_hash_value); transparent_crc(g_802, "g_802", print_hash_value); transparent_crc(g_803, "g_803", print_hash_value); transparent_crc(g_804, "g_804", print_hash_value); transparent_crc(g_950, "g_950", print_hash_value); transparent_crc(g_953, "g_953", print_hash_value); for (i = 0; i < 3; i++) { transparent_crc(g_957[i], "g_957[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_958, "g_958", print_hash_value); transparent_crc(g_1001, "g_1001", print_hash_value); for (i = 0; i < 4; i++) { transparent_crc(g_1031[i], "g_1031[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } platform_main_end(crc32_context ^ 0xFFFFFFFFUL, print_hash_value); return 0; }
IHTSDO/snow-owl
dependencies/org.eclipse.emf.cdo.net4j/src/org/eclipse/emf/cdo/internal/net4j/protocol/GetRemoteSessionsRequest.java
/* * Copyright (c) 2004 - 2012 <NAME> (Berlin, Germany) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * <NAME> - initial API and implementation */ package org.eclipse.emf.cdo.internal.net4j.protocol; import org.eclipse.emf.cdo.common.protocol.CDODataInput; import org.eclipse.emf.cdo.common.protocol.CDODataOutput; import org.eclipse.emf.cdo.common.protocol.CDOProtocolConstants; import org.eclipse.emf.cdo.internal.net4j.bundle.OM; import org.eclipse.emf.cdo.session.remote.CDORemoteSession; import org.eclipse.net4j.util.om.trace.ContextTracer; import org.eclipse.emf.spi.cdo.InternalCDORemoteSessionManager; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * @author <NAME> */ public class GetRemoteSessionsRequest extends CDOClientRequest<List<CDORemoteSession>> { private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_PROTOCOL, GetRemoteSessionsRequest.class); private boolean subscribe; public GetRemoteSessionsRequest(CDOClientProtocol protocol, boolean subscribe) { super(protocol, CDOProtocolConstants.SIGNAL_GET_REMOTE_SESSIONS); this.subscribe = subscribe; } @Override protected void requesting(CDODataOutput out) throws IOException { if (TRACER.isEnabled()) { TRACER.format("Writing subscribe: {0}", subscribe); //$NON-NLS-1$ } out.writeBoolean(subscribe); } @Override protected List<CDORemoteSession> confirming(CDODataInput in) throws IOException { List<CDORemoteSession> result = new ArrayList<CDORemoteSession>(); for (;;) { int sessionID = in.readInt(); if (sessionID == CDOProtocolConstants.NO_MORE_REMOTE_SESSIONS) { break; } String userID = in.readString(); boolean subscribed = in.readBoolean(); InternalCDORemoteSessionManager manager = getSession().getRemoteSessionManager(); CDORemoteSession remoteSession = manager.createRemoteSession(sessionID, userID, subscribed); result.add(remoteSession); } return result; } }
FANsZL/hive
ql/src/test/org/apache/hadoop/hive/ql/exec/util/rowobjects/RowTestObjectsMultiSet.java
<filename>ql/src/test/org/apache/hadoop/hive/ql/exec/util/rowobjects/RowTestObjectsMultiSet.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.exec.util.rowobjects; import java.util.Iterator; import java.util.SortedMap; import java.util.TreeMap; import java.util.Map.Entry; import org.apache.hadoop.hive.ql.exec.util.rowobjects.RowTestObjects; public class RowTestObjectsMultiSet { public enum RowFlag { NONE (0), REGULAR (0x01), LEFT_OUTER (0x02), FULL_OUTER (0x04); public final long value; RowFlag(long value) { this.value = value; } } private static class Value { // Mutable. public int count; public long rowFlags; public final int initialKeyCount; public final int initialValueCount; public final RowFlag initialRowFlag; public Value(int count, RowFlag rowFlag, int totalKeyCount, int totalValueCount) { this.count = count; this.rowFlags = rowFlag.value; initialKeyCount = totalKeyCount; initialValueCount = totalValueCount; initialRowFlag = rowFlag; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("count "); sb.append(count); return sb.toString(); } } private SortedMap<RowTestObjects, Value> sortedMap; private int totalKeyCount; private int totalValueCount; public RowTestObjectsMultiSet() { sortedMap = new TreeMap<RowTestObjects, Value>(); totalKeyCount = 0; totalValueCount = 0; } public int getTotalKeyCount() { return totalKeyCount; } public int getTotalValueCount() { return totalValueCount; } public void add(RowTestObjects testRow, RowFlag rowFlag) { if (sortedMap.containsKey(testRow)) { Value value = sortedMap.get(testRow); value.count++; value.rowFlags |= rowFlag.value; totalValueCount++; } else { sortedMap.put(testRow, new Value(1, rowFlag, ++totalKeyCount, ++totalValueCount)); } } public void add(RowTestObjects testRow, int count) { if (sortedMap.containsKey(testRow)) { throw new RuntimeException(); } sortedMap.put(testRow, new Value(count, RowFlag.NONE, ++totalKeyCount, ++totalValueCount)); } public String displayRowFlags(long rowFlags) { StringBuilder sb = new StringBuilder(); sb.append("{"); for (RowFlag rowFlag : RowFlag.values()) { if ((rowFlags & rowFlag.value) != 0) { if (sb.length() > 1) { sb.append(", "); } sb.append(rowFlag.name()); } } sb.append("}"); return sb.toString(); } public boolean verify(RowTestObjectsMultiSet other, String left, String right) { final int thisSize = this.sortedMap.size(); final int otherSize = other.sortedMap.size(); if (thisSize != otherSize) { System.out.println("*BENCHMARK* " + left + " count " + thisSize + " doesn't match " + right + " " + otherSize); return false; } Iterator<Entry<RowTestObjects, Value>> thisIterator = this.sortedMap.entrySet().iterator(); Iterator<Entry<RowTestObjects, Value>> otherIterator = other.sortedMap.entrySet().iterator(); for (int i = 0; i < thisSize; i++) { Entry<RowTestObjects, Value> thisEntry = thisIterator.next(); Entry<RowTestObjects, Value> otherEntry = otherIterator.next(); if (!thisEntry.getKey().equals(otherEntry.getKey())) { System.out.println("*BENCHMARK* " + left + " row " + thisEntry.getKey().toString() + " (rowFlags " + displayRowFlags(thisEntry.getValue().rowFlags) + " count " + thisEntry.getValue().count + ")" + " but found " + right + " row " + otherEntry.getKey().toString() + " (initialKeyCount " + + otherEntry.getValue().initialKeyCount + " initialValueCount " + otherEntry.getValue().initialValueCount + ")"); return false; } // Check multi-set count. if (thisEntry.getValue().count != otherEntry.getValue().count) { System.out.println("*BENCHMARK* " + left + " row " + thisEntry.getKey().toString() + " count " + thisEntry.getValue().count + " (rowFlags " + displayRowFlags(thisEntry.getValue().rowFlags) + ")" + " doesn't match " + right + " row count " + otherEntry.getValue().count + " (initialKeyCount " + + otherEntry.getValue().initialKeyCount + " initialValueCount " + otherEntry.getValue().initialValueCount + ")"); return false; } } if (thisSize != otherSize) { return false; } return true; } public RowTestObjectsMultiSet subtract(RowTestObjectsMultiSet other) { RowTestObjectsMultiSet result = new RowTestObjectsMultiSet(); Iterator<Entry<RowTestObjects, Value>> thisIterator = this.sortedMap.entrySet().iterator(); while (thisIterator.hasNext()) { Entry<RowTestObjects, Value> thisEntry = thisIterator.next(); if (other.sortedMap.containsKey(thisEntry.getKey())) { Value thisValue = thisEntry.getValue(); Value otherValue = other.sortedMap.get(thisEntry.getKey()); if (thisValue.count == otherValue.count) { continue; } } result.add(thisEntry.getKey(), thisEntry.getValue().count); } return result; } public void displayDifferences(RowTestObjectsMultiSet other, String left, String right) { RowTestObjectsMultiSet leftOnly = this.subtract(other); Iterator<Entry<RowTestObjects, Value>> leftOnlyIterator = leftOnly.sortedMap.entrySet().iterator(); while (leftOnlyIterator.hasNext()) { Entry<RowTestObjects, Value> leftOnlyEntry = leftOnlyIterator.next(); System.out.println( "*BENCHMARK* " + left + " only row " + leftOnlyEntry.getKey().toString() + " count " + leftOnlyEntry.getValue().count + " (initialRowFlag " + leftOnlyEntry.getValue().initialRowFlag.name() + ")"); } RowTestObjectsMultiSet rightOnly = other.subtract(this); Iterator<Entry<RowTestObjects, Value>> rightOnlyIterator = rightOnly.sortedMap.entrySet().iterator(); while (rightOnlyIterator.hasNext()) { Entry<RowTestObjects, Value> rightOnlyEntry = rightOnlyIterator.next(); System.out.println( "*BENCHMARK* " + right + " only row " + rightOnlyEntry.getKey().toString() + " count " + rightOnlyEntry.getValue().count + " (initialRowFlag " + rightOnlyEntry.getValue().initialRowFlag.name() + ")"); } } @Override public String toString() { return sortedMap.toString(); } }
Astroray073/Feth
app/src/main/java/com/kyigames/feth/utils/ResourceUtils.java
package com.kyigames.feth.utils; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import com.kyigames.feth.R; import java.util.List; import java.util.StringJoiner; public class ResourceUtils { private static final String m_drawable = "drawable"; private static Resources m_resources; private static PackageInfo m_packageInfo; public static void initialize(Context context) throws PackageManager.NameNotFoundException { m_resources = context.getResources(); m_packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); } public static String getPackageName() { return m_packageInfo.packageName; } public static int getVersionCode() { return m_packageInfo.versionCode; } public static int getIconRes(String name) { return m_resources.getIdentifier(name, m_drawable, getPackageName()); } public static String getListItemText(List<String> list) { return getListItemText(list, ", "); } public static String getListItemText(List<String> list, String delimiter) { if (list == null || list.size() == 0) { return m_resources.getString(R.string.none); } StringJoiner joiner = new StringJoiner(delimiter); for (String item : list) { joiner.add(item); } return joiner.toString(); } }
AmdPathirana/autoaid-front
src/components/Atoms/SelectedSevicesSVAD.js
import React from 'react' export default function SelectedSevicesSVAD(props) { return ( <div> <div className="text-black font-primary font-medium text-2xl flex flex-row justify-center"> {props.heading1} </div> <div className="text-gray-500 font-primary fo text-center mt-6 mb-6"> {props.description} </div> <div className="border-b-2 "></div> </div> ) }
JakMobius/zeta_path_tracer
src/collections/materials/utils_header.h
#ifndef MATERIALS_UTILS_HEADER_H #define MATERIALS_UTILS_HEADER_H #include "material/material.h" #include "hits/hit_record.h" #include "color/texture.h" #include "../textures/Textures.h" #endif // MATERIALS_UTILS_HEADER_H
BlueRidgeLabs/patterns
app/controllers/budgets_controller.rb
<gh_stars>1-10 # frozen_string_literal: true class BudgetsController < ApplicationController before_action :admin_needed before_action :set_budget, only: %i[show edit update destroy] before_action :check_transaction_type, only: :create_transaction # GET /budgets # GET /budgets.json def index @budgets = Budget.all begin @current_giftrocket_budget = DigitalGift.current_budget.to_s rescue JSON::ParserError @current_giftrocket_budget = 'Unknown' end respond_to do |format| format.html format.csv do send_data TransactionLog.all_csv, filename: 'transactions-all.csv' end end end # GET /budgets/1 # GET /budgets/1.json def show @transaction_log = TransactionLog.new @transactions = @budget.transactions.paginate(page: params[:page]) respond_to do |format| format.html format.csv do output = CSV.generate do |csv| csv << TransactionLog.csv_headers @transactions.each { |t| csv << t.to_csv_row } end send_data output, filename: "transactions-#{@budget.name}.csv" end end end # GET /budgets/new def new @budget = Budget.new end def create_transaction case transaction_log_params[:transaction_type] when 'Topup' from_type = 'User' from_id = current_user.id recipient_id = current_user.budget.id when 'Transfer' from_type = 'Budget' recipient_id = transaction_log_params[:recipient_id] from_id = transaction_log_params[:from_id].presence || current_user.budget.id end @transaction_log = TransactionLog.new(amount: transaction_log_params[:amount], transaction_type: transaction_log_params[:transaction_type], # all recipients here are budgets. No Digital Gifts recipient_type: 'Budget', recipient_id: recipient_id, from_id: from_id, from_type: from_type, user_id: current_user.id) respond_to do |format| if @transaction_log.save flash[:success] = 'Transaction Created' format.json { render json: @transaction_log } else flash[:error] = "Transaction failed: #{@transaction_log.errors.full_messages.join(' ')}" format.json { render json: @transaction_log.errors, status: :unprocessable_entity } end format.js {} end end # GET /budgets/1/edit def edit; end # POST /budgets # POST /budgets.json def create @budget = Budget.new(budget_params) respond_to do |format| if @budget.save format.html { redirect_to @budget, notice: 'Budget was successfully created.' } format.json { render :show, status: :created, location: @budget } else format.html { render :new } format.json { render json: @budget.errors, status: :unprocessable_entity } end end end # PATCH/PUT /budgets/1 # PATCH/PUT /budgets/1.json def update respond_to do |format| if @budget.update(budget_params) format.html { redirect_to @budget, notice: 'Budget was successfully updated.' } format.json { render :show, status: :ok, location: @budget } else format.html { render :edit } format.json { render json: @budget.errors, status: :unprocessable_entity } end end end # DELETE /budgets/1 # DELETE /budgets/1.json def destroy @budget.destroy respond_to do |format| format.html { redirect_to budgets_url, notice: 'Budget was successfully destroyed.' } format.json { head :no_content } end end private def check_transaction_type @transaction_type = transaction_log_params[:transaction_type] %w[Transfer Topup].include? @transaction_typez end def transaction_log_params params.permit(:transaction_type, :recipient_id, :from_id, :amount) end # Use callbacks to share common setup or constraints between actions. def set_budget @budget = Budget.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def budget_params params.fetch(:budget, {}) end end
laggingreflex/sicksync
test/local/fs-helper.mspec.js
import _ from 'lodash'; import { expect } from 'chai'; import proxyquire from 'proxyquire'; import chokidarStub from '../stubs/chokidar'; import fsStub from '../stubs/fs'; const { FSHelper } = proxyquire('../../src/local/fs-helper', { chokidar: chokidarStub, fs: fsStub, }); const config = { sourceLocation: 'my/home/', destinationLocation: 'my/remote/box/', excludes: ['.git/**'], }; describe('local fs-helper', function() { let fsHelper = null; beforeEach(function() { fsHelper = new FSHelper(config); }); afterEach(function() { fsStub.resetAll(); chokidarStub.resetAll(); }); describe('#watch', function() { it('should watch the source directory', function() { fsHelper.watch(); expect(chokidarStub.watch.lastCall.args[0]).to.equal(config.sourceLocation); }); it('should pass a list of ignored files to the watcher', function() { fsHelper.watch(); expect(chokidarStub.watch.lastCall.args[1].ignored).to.eql(config.excludes); }); it('should persist the watch', function() { fsHelper.watch(); expect(chokidarStub.watch.lastCall.args[1].persistent).to.be.true; }); it('should pass in a flag for symlinks', function() { fsHelper.watch(); expect(chokidarStub.watch.lastCall.args[1].followSymlinks).to.equal(config.followSymlinks); }); it('should pass in an empty array of ignores if none are there', function() { const noExcludesConfig = _.clone(config); delete noExcludesConfig.excludes; fsHelper = new FSHelper(noExcludesConfig); expect(chokidarStub.watch.lastCall.args[1].ignored).to.eql([]); }); describe('#on', function() { beforeEach(function() { fsHelper.watch(); }); it('should register an `all` callback', function() { expect(chokidarStub._api.on.lastCall.args[0]).to.equal('all'); }); it('should pass in a function for the `all` callback', function() { expect(chokidarStub._api.on.lastCall.args[1]).to.be.a('function'); }); }); describe('fs events', function() { const localPath = 'file/path'; beforeEach(function() { fsHelper.watch(); }); it('should pass along the file contents', function(done) { fsHelper.once('file-change', function(data) { expect(data.contents).to.be.a('string'); expect(data.sourcepath).to.equal(config.sourceLocation + localPath); done(); }); chokidarStub.triggerFsEvent('add', config.sourceLocation + localPath); }); it('should not pass along the file contents if the event isn\'t add or change', function(done) { fsHelper.once('file-change', function(data) { expect(data.contents).to.be.null; done(); }); chokidarStub.triggerFsEvent('unlink', config.sourceLocation + localPath); }); it('should not emit events for files that are ignored', function() { fsHelper.once('file-change', function() { expect.fail('File changes shouldn\'t happen when ignored.'); }); chokidarStub.triggerFsEvent('unlink', '.git/some/file'); }); it('should not emit events when the watch is paused', function() { fsHelper.once('file-change', function() { expect.fail('File changes shouldn\'t happen when paused.'); }); fsHelper.pauseWatch(); chokidarStub.triggerFsEvent('unlink', config.sourceLocation + localPath); }); it('should emit events when unpaused', function(done) { fsHelper.once('file-change', function(data) { expect(data.sourcepath).to.contain(localPath); done(); }); fsHelper.pauseWatch(); fsHelper.watch(); chokidarStub.triggerFsEvent('unlink', config.sourceLocation + localPath); }); }); }); });
nomad-coe/electronic-parsers
tests/test_dmol3parser.py
<filename>tests/test_dmol3parser.py<gh_stars>0 # # Copyright The NOMAD Authors. # # This file is part of NOMAD. See https://nomad-lab.eu for further info. # # 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 pytest from nomad.datamodel import EntryArchive from electronicparsers.dmol3 import Dmol3Parser def approx(value, abs=0, rel=1e-6): return pytest.approx(value, abs=abs, rel=rel) @pytest.fixture(scope='module') def parser(): return Dmol3Parser() def test_optimization(parser): archive = EntryArchive() parser.parse('tests/data/dmol3/h2o.outmol', archive, None) sec_run = archive.run[0] assert sec_run.program.version == '3.0' assert sec_run.time_run.date_start > 0. sec_method = archive.run[0].method[0] assert sec_method.x_dmol3_calculation_type == 'optimize_frequency' assert sec_method.x_dmol3_rcut == approx(6.0) assert sec_method.x_dmol3_scf_iterations == 150 assert sec_method.x_dmol3_occupation_name == 'Fermi' assert sec_method.x_dmol3_diis_number == 10 assert sec_method.x_dmol3_diis_name == 'pulay' assert sec_method.x_dmol3_opt_energy_convergence == approx(1.0e-05) sec_system = archive.run[0].system assert len(sec_system) == 11 assert sec_system[0].atoms.labels[2] == 'H' assert sec_system[2].atoms.positions[1][2].magnitude == approx(-8.84266338e-10,) sec_calc = sec_run.calculation assert sec_calc[7].energy.total.value.magnitude == approx(-3.33238073e-16) assert sec_calc[2].energy.x_dmol3_binding.value.magnitude == approx(-1.66336861e-18) assert len(sec_calc[5].scf_iteration) == 7 assert sec_calc[1].scf_iteration[2].energy.total.value.magnitude == approx(-3.33238086e-16) assert sec_calc[5].scf_iteration[5].energy.x_dmol3_binding.value.magnitude == approx(-1.66332632e-18) assert sec_calc[0].eigenvalues[0].energies[0][0][4].magnitude == approx(-1.08436443e-18) assert sec_calc[0].eigenvalues[0].occupations[0][0][2] == approx(2.0) assert sec_calc[1].charges[0].value[0].magnitude == approx(-4.82255167e-20) assert sec_calc[1].charges[1].value[2].magnitude == approx(3.89328922e-20) assert sec_calc[1].multipoles[0].dipole.total == approx(1.9470) assert sec_calc[10].vibrational_frequencies[0].value[2].magnitude == approx(-1050.0) assert sec_calc[10].vibrational_frequencies[0].x_dmol3_normal_modes[5][2][0] == approx(-0.1073) assert sec_calc[10].x_dmol3_h_rot.magnitude == approx(0.889) assert sec_calc[10].x_dmol3_c_vib.magnitude == approx(5.816) sec_workflow = archive.workflow assert sec_workflow[0].geometry_optimization.convergence_tolerance_energy_difference.magnitude == approx(4.35974472e-23) assert sec_workflow[0].geometry_optimization.convergence_tolerance_force_maximum.magnitude == approx(8.2387235e-12) assert sec_workflow[0].geometry_optimization.convergence_tolerance_displacement_maximum.magnitude == approx(1.58753163e-13) assert sec_workflow[1].thermodynamics.temperature[22].magnitude == approx(550.00) assert sec_workflow[1].thermodynamics.entropy[32].magnitude == approx(5.15393944e-22) assert sec_workflow[1].thermodynamics.heat_capacity_c_p[40].magnitude == approx(1.08988499e-22) # TODO uncomment this after merging workflow changes # assert sec_workflow[1].thermodynamics.enthalpy[7].magnitude == approx(1.1136461e-19) assert sec_workflow[1].thermodynamics.gibbs_free_energy[20].magnitude == approx(-9.34881901e-20)
dotzero/habrahabr-api-python
examples/company.py
<filename>examples/company.py #!/usr/bin/env python # -*- coding: utf-8 -*- import logging import habrahabr logging.basicConfig( level=logging.INFO, format='%(levelname)-8s %(asctime)s - %(message)s' ) auth = habrahabr.Auth(client="000000.00000000", token="<PASSWORD>") api = habrahabr.Api(auth) try: posts = api.company.posts('tm') info = api.company.info('tm') companies = api.company.list() except habrahabr.ApiHandlerError as e: logging.error(e)
jtejido/golucene
core/search/similarities/bm25.go
<gh_stars>0 package similarities import ( "fmt" "github.com/jtejido/golucene/core/codec/spi" "github.com/jtejido/golucene/core/index" "github.com/jtejido/golucene/core/search" "github.com/jtejido/golucene/core/util" "math" ) var _ Similarity = (*BM25Similarity)(nil) const ( DEFAULT_K1 float32 = 1.2 DEFAULT_B float32 = .75 ) /** * BM25 is a class for ranking documents against a query. * * The implementation is based on the paper by <NAME>, <NAME>, <NAME>, * <NAME> & <NAME> (November 1994). * @see http://trec.nist.gov/pubs/trec3/t3_proceedings.html. * * Some modifications have been made to allow for non-negative scoring as suggested here. * @see https://doc.rero.ch/record/16754/files/Dolamic_Ljiljana_-_When_Stopword_Lists_Make_the_Difference_20091218.pdf */ type BM25Similarity struct { baseBM25Similarity } func NewBM25Similarity(k1, b float32, discountOverlaps bool) *BM25Similarity { ans := new(BM25Similarity) ans.k1 = k1 ans.b = b ans.discountOverlaps = discountOverlaps ans.spi = ans once.Do(func() { norm_table = ans.buildNormTable() }) return ans } func NewDefaultBM25Similarity() *BM25Similarity { return NewBM25Similarity(DEFAULT_K1, DEFAULT_B, true) } func (bm25 *BM25Similarity) idf(docFreq, numDocs int64) float32 { return float32(math.Log(1. + (float64(numDocs)-float64(docFreq)+0.5)/(float64(docFreq)+0.5))) } func (bm25 *BM25Similarity) score(freq, norm float32) float32 { num := freq * (bm25.k1 + 1) denom := freq + bm25.k1*(1-bm25.b+bm25.b*norm) return num / denom } func (bm25 *BM25Similarity) String() string { return fmt.Sprintf("BM25(k1=%v, b=%v)", bm25.k1, bm25.b) } type bm25SimilaritySPI interface { idf(docFreq, numDocs int64) float32 score(freq, norm float32) float32 String() string } type baseBM25Similarity struct { similarityImpl spi bm25SimilaritySPI k1, b float32 discountOverlaps bool } func (bbm25 *baseBM25Similarity) buildNormTable() []float32 { table := make([]float32, 256) for i, _ := range table { f := util.Byte315ToFloat(byte(i)) table[i] = 1.0 / (f * f) } return table } func (bbm25 *baseBM25Similarity) idf(docFreq, numDocs int64) float32 { return bbm25.spi.idf(docFreq, numDocs) } func (bbm25 *baseBM25Similarity) sloppyFreq(distance int) float32 { return 1.0 / (float32(distance) + 1) } func (bbm25 *baseBM25Similarity) scorePayload(doc, start, end int, payload *util.BytesRef) float32 { return 1 } func (bbm25 *baseBM25Similarity) avgFieldLength(collectionStats search.CollectionStatistics) float32 { sumTotalTermFreq := collectionStats.SumTotalTermFreq() if sumTotalTermFreq <= 0 { return 1. } return (float32(sumTotalTermFreq) / float32(collectionStats.MaxDoc())) } func (bbm25 *baseBM25Similarity) encodeNormValue(boost float32, fieldLength int) byte { return byte(util.FloatToByte315(boost / float32(math.Sqrt(float64(fieldLength))))) } func (bbm25 *baseBM25Similarity) decodeNormValue(b byte) float32 { return norm_table[b&0xFF] } func (bbm25 *baseBM25Similarity) idfExplainTerm(collectionStats search.CollectionStatistics, termStats search.TermStatistics) search.Explanation { df, max := termStats.DocFreq, collectionStats.MaxDoc() idf := bbm25.idf(df, max) return search.NewExplanation(idf, fmt.Sprintf("idf(docFreq=%v, maxDocs=%v)", df, max)) } func (bbm25 *baseBM25Similarity) idfExplainPhrase(collectionStats search.CollectionStatistics, termStats []search.TermStatistics) search.Explanation { details := make([]search.Explanation, len(termStats)) var idf float32 = 0 for i, stat := range termStats { details[i] = bbm25.idfExplainTerm(collectionStats, stat) idf += details[i].(*search.ExplanationImpl).Value() } ans := search.NewExplanation(idf, fmt.Sprintf("idf(), sum of:")) ans.SetDetails(details) return ans } func (bbm25 *baseBM25Similarity) ComputeNorm(state *index.FieldInvertState) int64 { var numTerms int if bbm25.discountOverlaps { numTerms = state.Length() - state.NumOverlap() } else { numTerms = state.Length() } return int64(bbm25.encodeNormValue(state.Boost(), numTerms)) } func (bbm25 *baseBM25Similarity) ComputeWeight(queryBoost float32, collectionStats search.CollectionStatistics, termStats ...search.TermStatistics) search.SimWeight { var idf search.Explanation if len(termStats) == 1 { idf = bbm25.idfExplainTerm(collectionStats, termStats[0]) } else { idf = bbm25.idfExplainPhrase(collectionStats, termStats) } avgdl := bbm25.avgFieldLength(collectionStats) cache := make([]float32, 256) for i, _ := range cache { cache[i] = bbm25.decodeNormValue(byte(i)) / avgdl } return newBM25Stats(collectionStats.Field(), idf, queryBoost, avgdl, cache) } func (bbm25 *baseBM25Similarity) score(freq, norm float32) float32 { return bbm25.spi.score(freq, norm) } func (bbm25 *baseBM25Similarity) explainScore(doc int, freq search.Explanation, stats *bm25Stats, norms spi.NumericDocValues) search.Explanation { var tfNormExpl search.ExplanationSPI // explain query weight boostExpl := search.NewExplanation(stats.queryBoost*stats.topLevelBoost, "boost") if norms != nil { tfNormExpl = search.NewExplanation((freq.Value()*(bbm25.k1+1))/(freq.Value()+bbm25.k1), "tfNorm, computed from:") tfNormExpl.AddDetail(freq) tfNormExpl.AddDetail(search.NewExplanation(bbm25.k1, "parameter k1")) tfNormExpl.AddDetail(search.NewExplanation(0, "parameter b (norms omitted for field)")) } else { doclen := bbm25.decodeNormValue(byte(norms(doc))) tfNormExpl = search.NewExplanation((freq.Value()*(bbm25.k1+1))/(freq.Value()+bbm25.k1*(1-bbm25.b+bbm25.b*doclen/stats.avgdl)), "tfNorm, computed from:") tfNormExpl.AddDetail(search.NewExplanation(bbm25.b, "parameter b")) tfNormExpl.AddDetail(search.NewExplanation(stats.avgdl, "avgFieldLength")) tfNormExpl.AddDetail(search.NewExplanation(doclen, "fieldLength")) } // combine them ans := search.NewExplanation(boostExpl.Value()*stats.idf.Value()*tfNormExpl.Value(), fmt.Sprintf("score(doc=%v,freq=%v), product of:", doc, freq)) if boostExpl.Value() != 1 { ans.AddDetail(boostExpl) } ans.AddDetail(stats.idf) ans.AddDetail(tfNormExpl) return ans } func (bbm25 *baseBM25Similarity) SimScorer(stats search.SimWeight, ctx *index.AtomicReaderContext) (ss search.SimScorer, err error) { bm25Stats := stats.(*bm25Stats) ndv, err := ctx.Reader().(index.AtomicReader).NormValues(bm25Stats.field) if err != nil { return nil, err } return newBM25SimScorer(bbm25, bm25Stats, ndv), nil } func (bbm25 *baseBM25Similarity) String() string { return bbm25.spi.String() } type bm25Stats struct { /** The idf and its explanation */ idf search.Explanation /** The average document length. */ avgdl float32 /** query's inner boost */ queryBoost float32 /** query's outer boost (only for explain) */ topLevelBoost float32 /** weight (idf * boost) */ weight float32 /** field name, for pulling norms */ field string /** precomputed norm[256] with k1 * ((1 - b) + b * dl / avgdl) */ cache []float32 } type bm25SimScorer struct { owner *baseBM25Similarity stats *bm25Stats weightValue float32 norms spi.NumericDocValues cache []float32 } func newBM25SimScorer(owner *baseBM25Similarity, stats *bm25Stats, norms spi.NumericDocValues) *bm25SimScorer { return &bm25SimScorer{owner, stats, stats.weight, norms, stats.cache} } func (ss *bm25SimScorer) Score(doc int, freq float32) float32 { var norm float32 if ss.norms == nil { norm = ss.owner.k1 } else { norm = ss.cache[byte(ss.norms(doc))&0xFF] } return ss.weightValue * ss.owner.score(freq, norm) } func (ss *bm25SimScorer) Explain(doc int, freq search.Explanation) search.Explanation { return ss.owner.explainScore(doc, freq, ss.stats, ss.norms) } func (ss *bm25SimScorer) ComputeSlopFactor(distance int) float32 { return ss.owner.sloppyFreq(distance) } func (ss *bm25SimScorer) ComputePayloadFactor(doc, start, end int, payload *util.BytesRef) float32 { return ss.owner.scorePayload(doc, start, end, payload) } func newBM25Stats(field string, idf search.Explanation, queryBoost, avgdl float32, cache []float32) *bm25Stats { return &bm25Stats{ field: field, idf: idf, queryBoost: queryBoost, avgdl: avgdl, cache: cache, } } func (stats *bm25Stats) ValueForNormalization() float32 { queryWeight := stats.idf.(*search.ExplanationImpl).Value() * stats.queryBoost return queryWeight * queryWeight } func (stats *bm25Stats) Normalize(queryNorm float32, topLevelBoost float32) { stats.topLevelBoost = topLevelBoost stats.weight = stats.idf.(*search.ExplanationImpl).Value() * stats.queryBoost * topLevelBoost }
zhaozengj/ICRA2020-JLU-TARS_GO-Navigation
roborts_detection/armor_detection/proto/armor_detection.pb.cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: armor_detection.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "armor_detection.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace roborts_detection { namespace { const ::google::protobuf::Descriptor* CameraGimbalTransform_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* CameraGimbalTransform_reflection_ = NULL; const ::google::protobuf::Descriptor* ProjectileModelInfo_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* ProjectileModelInfo_reflection_ = NULL; const ::google::protobuf::Descriptor* ArmorDetectionAlgorithms_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* ArmorDetectionAlgorithms_reflection_ = NULL; } // namespace void protobuf_AssignDesc_armor_5fdetection_2eproto() { protobuf_AddDesc_armor_5fdetection_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "armor_detection.proto"); GOOGLE_CHECK(file != NULL); CameraGimbalTransform_descriptor_ = file->message_type(0); static const int CameraGimbalTransform_offsets_[5] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CameraGimbalTransform, offset_x_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CameraGimbalTransform, offset_y_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CameraGimbalTransform, offset_z_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CameraGimbalTransform, offset_pitch_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CameraGimbalTransform, offset_yaw_), }; CameraGimbalTransform_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( CameraGimbalTransform_descriptor_, CameraGimbalTransform::default_instance_, CameraGimbalTransform_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CameraGimbalTransform, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CameraGimbalTransform, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(CameraGimbalTransform)); ProjectileModelInfo_descriptor_ = file->message_type(1); static const int ProjectileModelInfo_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProjectileModelInfo, init_v_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProjectileModelInfo, init_k_), }; ProjectileModelInfo_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( ProjectileModelInfo_descriptor_, ProjectileModelInfo::default_instance_, ProjectileModelInfo_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProjectileModelInfo, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ProjectileModelInfo, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(ProjectileModelInfo)); ArmorDetectionAlgorithms_descriptor_ = file->message_type(2); static const int ArmorDetectionAlgorithms_offsets_[6] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ArmorDetectionAlgorithms, name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ArmorDetectionAlgorithms, selected_algorithm_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ArmorDetectionAlgorithms, undetected_armor_delay_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ArmorDetectionAlgorithms, camera_name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ArmorDetectionAlgorithms, camera_gimbal_transform_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ArmorDetectionAlgorithms, projectile_model_info_), }; ArmorDetectionAlgorithms_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( ArmorDetectionAlgorithms_descriptor_, ArmorDetectionAlgorithms::default_instance_, ArmorDetectionAlgorithms_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ArmorDetectionAlgorithms, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ArmorDetectionAlgorithms, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(ArmorDetectionAlgorithms)); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_armor_5fdetection_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( CameraGimbalTransform_descriptor_, &CameraGimbalTransform::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( ProjectileModelInfo_descriptor_, &ProjectileModelInfo::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( ArmorDetectionAlgorithms_descriptor_, &ArmorDetectionAlgorithms::default_instance()); } } // namespace void protobuf_ShutdownFile_armor_5fdetection_2eproto() { delete CameraGimbalTransform::default_instance_; delete CameraGimbalTransform_reflection_; delete ProjectileModelInfo::default_instance_; delete ProjectileModelInfo_reflection_; delete ArmorDetectionAlgorithms::default_instance_; delete ArmorDetectionAlgorithms_reflection_; } void protobuf_AddDesc_armor_5fdetection_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\025armor_detection.proto\022\021roborts_detecti" "on\"w\n\025CameraGimbalTransform\022\020\n\010offset_x\030" "\001 \002(\002\022\020\n\010offset_y\030\002 \002(\002\022\020\n\010offset_z\030\003 \002(" "\002\022\024\n\014offset_pitch\030\004 \002(\002\022\022\n\noffset_yaw\030\005 " "\002(\002\"5\n\023ProjectileModelInfo\022\016\n\006init_v\030\001 \001" "(\002\022\016\n\006init_k\030\002 \001(\002\"\213\002\n\030ArmorDetectionAlg" "orithms\022\014\n\004name\030\001 \003(\t\022\032\n\022selected_algori" "thm\030\002 \001(\t\022\036\n\026undetected_armor_delay\030\003 \001(" "\r\022\023\n\013camera_name\030\004 \001(\t\022I\n\027camera_gimbal_" "transform\030\005 \002(\0132(.roborts_detection.Came" "raGimbalTransform\022E\n\025projectile_model_in" "fo\030\006 \001(\0132&.roborts_detection.ProjectileM" "odelInfo", 488); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "armor_detection.proto", &protobuf_RegisterTypes); CameraGimbalTransform::default_instance_ = new CameraGimbalTransform(); ProjectileModelInfo::default_instance_ = new ProjectileModelInfo(); ArmorDetectionAlgorithms::default_instance_ = new ArmorDetectionAlgorithms(); CameraGimbalTransform::default_instance_->InitAsDefaultInstance(); ProjectileModelInfo::default_instance_->InitAsDefaultInstance(); ArmorDetectionAlgorithms::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_armor_5fdetection_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_armor_5fdetection_2eproto { StaticDescriptorInitializer_armor_5fdetection_2eproto() { protobuf_AddDesc_armor_5fdetection_2eproto(); } } static_descriptor_initializer_armor_5fdetection_2eproto_; // =================================================================== #ifndef _MSC_VER const int CameraGimbalTransform::kOffsetXFieldNumber; const int CameraGimbalTransform::kOffsetYFieldNumber; const int CameraGimbalTransform::kOffsetZFieldNumber; const int CameraGimbalTransform::kOffsetPitchFieldNumber; const int CameraGimbalTransform::kOffsetYawFieldNumber; #endif // !_MSC_VER CameraGimbalTransform::CameraGimbalTransform() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:roborts_detection.CameraGimbalTransform) } void CameraGimbalTransform::InitAsDefaultInstance() { } CameraGimbalTransform::CameraGimbalTransform(const CameraGimbalTransform& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:roborts_detection.CameraGimbalTransform) } void CameraGimbalTransform::SharedCtor() { _cached_size_ = 0; offset_x_ = 0; offset_y_ = 0; offset_z_ = 0; offset_pitch_ = 0; offset_yaw_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } CameraGimbalTransform::~CameraGimbalTransform() { // @@protoc_insertion_point(destructor:roborts_detection.CameraGimbalTransform) SharedDtor(); } void CameraGimbalTransform::SharedDtor() { if (this != default_instance_) { } } void CameraGimbalTransform::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* CameraGimbalTransform::descriptor() { protobuf_AssignDescriptorsOnce(); return CameraGimbalTransform_descriptor_; } const CameraGimbalTransform& CameraGimbalTransform::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_armor_5fdetection_2eproto(); return *default_instance_; } CameraGimbalTransform* CameraGimbalTransform::default_instance_ = NULL; CameraGimbalTransform* CameraGimbalTransform::New() const { return new CameraGimbalTransform; } void CameraGimbalTransform::Clear() { #define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>( \ &reinterpret_cast<CameraGimbalTransform*>(16)->f) - \ reinterpret_cast<char*>(16)) #define ZR_(first, last) do { \ size_t f = OFFSET_OF_FIELD_(first); \ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ ::memset(&first, 0, n); \ } while (0) if (_has_bits_[0 / 32] & 31) { ZR_(offset_x_, offset_yaw_); } #undef OFFSET_OF_FIELD_ #undef ZR_ ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool CameraGimbalTransform::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:roborts_detection.CameraGimbalTransform) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required float offset_x = 1; case 1: { if (tag == 13) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &offset_x_))); set_has_offset_x(); } else { goto handle_unusual; } if (input->ExpectTag(21)) goto parse_offset_y; break; } // required float offset_y = 2; case 2: { if (tag == 21) { parse_offset_y: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &offset_y_))); set_has_offset_y(); } else { goto handle_unusual; } if (input->ExpectTag(29)) goto parse_offset_z; break; } // required float offset_z = 3; case 3: { if (tag == 29) { parse_offset_z: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &offset_z_))); set_has_offset_z(); } else { goto handle_unusual; } if (input->ExpectTag(37)) goto parse_offset_pitch; break; } // required float offset_pitch = 4; case 4: { if (tag == 37) { parse_offset_pitch: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &offset_pitch_))); set_has_offset_pitch(); } else { goto handle_unusual; } if (input->ExpectTag(45)) goto parse_offset_yaw; break; } // required float offset_yaw = 5; case 5: { if (tag == 45) { parse_offset_yaw: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &offset_yaw_))); set_has_offset_yaw(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:roborts_detection.CameraGimbalTransform) return true; failure: // @@protoc_insertion_point(parse_failure:roborts_detection.CameraGimbalTransform) return false; #undef DO_ } void CameraGimbalTransform::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:roborts_detection.CameraGimbalTransform) // required float offset_x = 1; if (has_offset_x()) { ::google::protobuf::internal::WireFormatLite::WriteFloat(1, this->offset_x(), output); } // required float offset_y = 2; if (has_offset_y()) { ::google::protobuf::internal::WireFormatLite::WriteFloat(2, this->offset_y(), output); } // required float offset_z = 3; if (has_offset_z()) { ::google::protobuf::internal::WireFormatLite::WriteFloat(3, this->offset_z(), output); } // required float offset_pitch = 4; if (has_offset_pitch()) { ::google::protobuf::internal::WireFormatLite::WriteFloat(4, this->offset_pitch(), output); } // required float offset_yaw = 5; if (has_offset_yaw()) { ::google::protobuf::internal::WireFormatLite::WriteFloat(5, this->offset_yaw(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:roborts_detection.CameraGimbalTransform) } ::google::protobuf::uint8* CameraGimbalTransform::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:roborts_detection.CameraGimbalTransform) // required float offset_x = 1; if (has_offset_x()) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(1, this->offset_x(), target); } // required float offset_y = 2; if (has_offset_y()) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(2, this->offset_y(), target); } // required float offset_z = 3; if (has_offset_z()) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(3, this->offset_z(), target); } // required float offset_pitch = 4; if (has_offset_pitch()) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(4, this->offset_pitch(), target); } // required float offset_yaw = 5; if (has_offset_yaw()) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(5, this->offset_yaw(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:roborts_detection.CameraGimbalTransform) return target; } int CameraGimbalTransform::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required float offset_x = 1; if (has_offset_x()) { total_size += 1 + 4; } // required float offset_y = 2; if (has_offset_y()) { total_size += 1 + 4; } // required float offset_z = 3; if (has_offset_z()) { total_size += 1 + 4; } // required float offset_pitch = 4; if (has_offset_pitch()) { total_size += 1 + 4; } // required float offset_yaw = 5; if (has_offset_yaw()) { total_size += 1 + 4; } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void CameraGimbalTransform::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const CameraGimbalTransform* source = ::google::protobuf::internal::dynamic_cast_if_available<const CameraGimbalTransform*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void CameraGimbalTransform::MergeFrom(const CameraGimbalTransform& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_offset_x()) { set_offset_x(from.offset_x()); } if (from.has_offset_y()) { set_offset_y(from.offset_y()); } if (from.has_offset_z()) { set_offset_z(from.offset_z()); } if (from.has_offset_pitch()) { set_offset_pitch(from.offset_pitch()); } if (from.has_offset_yaw()) { set_offset_yaw(from.offset_yaw()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void CameraGimbalTransform::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void CameraGimbalTransform::CopyFrom(const CameraGimbalTransform& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool CameraGimbalTransform::IsInitialized() const { if ((_has_bits_[0] & 0x0000001f) != 0x0000001f) return false; return true; } void CameraGimbalTransform::Swap(CameraGimbalTransform* other) { if (other != this) { std::swap(offset_x_, other->offset_x_); std::swap(offset_y_, other->offset_y_); std::swap(offset_z_, other->offset_z_); std::swap(offset_pitch_, other->offset_pitch_); std::swap(offset_yaw_, other->offset_yaw_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata CameraGimbalTransform::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = CameraGimbalTransform_descriptor_; metadata.reflection = CameraGimbalTransform_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int ProjectileModelInfo::kInitVFieldNumber; const int ProjectileModelInfo::kInitKFieldNumber; #endif // !_MSC_VER ProjectileModelInfo::ProjectileModelInfo() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:roborts_detection.ProjectileModelInfo) } void ProjectileModelInfo::InitAsDefaultInstance() { } ProjectileModelInfo::ProjectileModelInfo(const ProjectileModelInfo& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:roborts_detection.ProjectileModelInfo) } void ProjectileModelInfo::SharedCtor() { _cached_size_ = 0; init_v_ = 0; init_k_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } ProjectileModelInfo::~ProjectileModelInfo() { // @@protoc_insertion_point(destructor:roborts_detection.ProjectileModelInfo) SharedDtor(); } void ProjectileModelInfo::SharedDtor() { if (this != default_instance_) { } } void ProjectileModelInfo::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* ProjectileModelInfo::descriptor() { protobuf_AssignDescriptorsOnce(); return ProjectileModelInfo_descriptor_; } const ProjectileModelInfo& ProjectileModelInfo::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_armor_5fdetection_2eproto(); return *default_instance_; } ProjectileModelInfo* ProjectileModelInfo::default_instance_ = NULL; ProjectileModelInfo* ProjectileModelInfo::New() const { return new ProjectileModelInfo; } void ProjectileModelInfo::Clear() { #define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>( \ &reinterpret_cast<ProjectileModelInfo*>(16)->f) - \ reinterpret_cast<char*>(16)) #define ZR_(first, last) do { \ size_t f = OFFSET_OF_FIELD_(first); \ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ ::memset(&first, 0, n); \ } while (0) ZR_(init_v_, init_k_); #undef OFFSET_OF_FIELD_ #undef ZR_ ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool ProjectileModelInfo::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:roborts_detection.ProjectileModelInfo) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional float init_v = 1; case 1: { if (tag == 13) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &init_v_))); set_has_init_v(); } else { goto handle_unusual; } if (input->ExpectTag(21)) goto parse_init_k; break; } // optional float init_k = 2; case 2: { if (tag == 21) { parse_init_k: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, &init_k_))); set_has_init_k(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:roborts_detection.ProjectileModelInfo) return true; failure: // @@protoc_insertion_point(parse_failure:roborts_detection.ProjectileModelInfo) return false; #undef DO_ } void ProjectileModelInfo::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:roborts_detection.ProjectileModelInfo) // optional float init_v = 1; if (has_init_v()) { ::google::protobuf::internal::WireFormatLite::WriteFloat(1, this->init_v(), output); } // optional float init_k = 2; if (has_init_k()) { ::google::protobuf::internal::WireFormatLite::WriteFloat(2, this->init_k(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:roborts_detection.ProjectileModelInfo) } ::google::protobuf::uint8* ProjectileModelInfo::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:roborts_detection.ProjectileModelInfo) // optional float init_v = 1; if (has_init_v()) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(1, this->init_v(), target); } // optional float init_k = 2; if (has_init_k()) { target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(2, this->init_k(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:roborts_detection.ProjectileModelInfo) return target; } int ProjectileModelInfo::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional float init_v = 1; if (has_init_v()) { total_size += 1 + 4; } // optional float init_k = 2; if (has_init_k()) { total_size += 1 + 4; } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void ProjectileModelInfo::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const ProjectileModelInfo* source = ::google::protobuf::internal::dynamic_cast_if_available<const ProjectileModelInfo*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void ProjectileModelInfo::MergeFrom(const ProjectileModelInfo& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_init_v()) { set_init_v(from.init_v()); } if (from.has_init_k()) { set_init_k(from.init_k()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void ProjectileModelInfo::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void ProjectileModelInfo::CopyFrom(const ProjectileModelInfo& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool ProjectileModelInfo::IsInitialized() const { return true; } void ProjectileModelInfo::Swap(ProjectileModelInfo* other) { if (other != this) { std::swap(init_v_, other->init_v_); std::swap(init_k_, other->init_k_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata ProjectileModelInfo::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = ProjectileModelInfo_descriptor_; metadata.reflection = ProjectileModelInfo_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int ArmorDetectionAlgorithms::kNameFieldNumber; const int ArmorDetectionAlgorithms::kSelectedAlgorithmFieldNumber; const int ArmorDetectionAlgorithms::kUndetectedArmorDelayFieldNumber; const int ArmorDetectionAlgorithms::kCameraNameFieldNumber; const int ArmorDetectionAlgorithms::kCameraGimbalTransformFieldNumber; const int ArmorDetectionAlgorithms::kProjectileModelInfoFieldNumber; #endif // !_MSC_VER ArmorDetectionAlgorithms::ArmorDetectionAlgorithms() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:roborts_detection.ArmorDetectionAlgorithms) } void ArmorDetectionAlgorithms::InitAsDefaultInstance() { camera_gimbal_transform_ = const_cast< ::roborts_detection::CameraGimbalTransform*>(&::roborts_detection::CameraGimbalTransform::default_instance()); projectile_model_info_ = const_cast< ::roborts_detection::ProjectileModelInfo*>(&::roborts_detection::ProjectileModelInfo::default_instance()); } ArmorDetectionAlgorithms::ArmorDetectionAlgorithms(const ArmorDetectionAlgorithms& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:roborts_detection.ArmorDetectionAlgorithms) } void ArmorDetectionAlgorithms::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; selected_algorithm_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); undetected_armor_delay_ = 0u; camera_name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); camera_gimbal_transform_ = NULL; projectile_model_info_ = NULL; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } ArmorDetectionAlgorithms::~ArmorDetectionAlgorithms() { // @@protoc_insertion_point(destructor:roborts_detection.ArmorDetectionAlgorithms) SharedDtor(); } void ArmorDetectionAlgorithms::SharedDtor() { if (selected_algorithm_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete selected_algorithm_; } if (camera_name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete camera_name_; } if (this != default_instance_) { delete camera_gimbal_transform_; delete projectile_model_info_; } } void ArmorDetectionAlgorithms::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* ArmorDetectionAlgorithms::descriptor() { protobuf_AssignDescriptorsOnce(); return ArmorDetectionAlgorithms_descriptor_; } const ArmorDetectionAlgorithms& ArmorDetectionAlgorithms::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_armor_5fdetection_2eproto(); return *default_instance_; } ArmorDetectionAlgorithms* ArmorDetectionAlgorithms::default_instance_ = NULL; ArmorDetectionAlgorithms* ArmorDetectionAlgorithms::New() const { return new ArmorDetectionAlgorithms; } void ArmorDetectionAlgorithms::Clear() { if (_has_bits_[0 / 32] & 62) { if (has_selected_algorithm()) { if (selected_algorithm_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { selected_algorithm_->clear(); } } undetected_armor_delay_ = 0u; if (has_camera_name()) { if (camera_name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { camera_name_->clear(); } } if (has_camera_gimbal_transform()) { if (camera_gimbal_transform_ != NULL) camera_gimbal_transform_->::roborts_detection::CameraGimbalTransform::Clear(); } if (has_projectile_model_info()) { if (projectile_model_info_ != NULL) projectile_model_info_->::roborts_detection::ProjectileModelInfo::Clear(); } } name_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool ArmorDetectionAlgorithms::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:roborts_detection.ArmorDetectionAlgorithms) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated string name = 1; case 1: { if (tag == 10) { parse_name: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_name())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name(this->name_size() - 1).data(), this->name(this->name_size() - 1).length(), ::google::protobuf::internal::WireFormat::PARSE, "name"); } else { goto handle_unusual; } if (input->ExpectTag(10)) goto parse_name; if (input->ExpectTag(18)) goto parse_selected_algorithm; break; } // optional string selected_algorithm = 2; case 2: { if (tag == 18) { parse_selected_algorithm: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_selected_algorithm())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->selected_algorithm().data(), this->selected_algorithm().length(), ::google::protobuf::internal::WireFormat::PARSE, "selected_algorithm"); } else { goto handle_unusual; } if (input->ExpectTag(24)) goto parse_undetected_armor_delay; break; } // optional uint32 undetected_armor_delay = 3; case 3: { if (tag == 24) { parse_undetected_armor_delay: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &undetected_armor_delay_))); set_has_undetected_armor_delay(); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_camera_name; break; } // optional string camera_name = 4; case 4: { if (tag == 34) { parse_camera_name: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_camera_name())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->camera_name().data(), this->camera_name().length(), ::google::protobuf::internal::WireFormat::PARSE, "camera_name"); } else { goto handle_unusual; } if (input->ExpectTag(42)) goto parse_camera_gimbal_transform; break; } // required .roborts_detection.CameraGimbalTransform camera_gimbal_transform = 5; case 5: { if (tag == 42) { parse_camera_gimbal_transform: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_camera_gimbal_transform())); } else { goto handle_unusual; } if (input->ExpectTag(50)) goto parse_projectile_model_info; break; } // optional .roborts_detection.ProjectileModelInfo projectile_model_info = 6; case 6: { if (tag == 50) { parse_projectile_model_info: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_projectile_model_info())); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:roborts_detection.ArmorDetectionAlgorithms) return true; failure: // @@protoc_insertion_point(parse_failure:roborts_detection.ArmorDetectionAlgorithms) return false; #undef DO_ } void ArmorDetectionAlgorithms::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:roborts_detection.ArmorDetectionAlgorithms) // repeated string name = 1; for (int i = 0; i < this->name_size(); i++) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name(i).data(), this->name(i).length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "name"); ::google::protobuf::internal::WireFormatLite::WriteString( 1, this->name(i), output); } // optional string selected_algorithm = 2; if (has_selected_algorithm()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->selected_algorithm().data(), this->selected_algorithm().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "selected_algorithm"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->selected_algorithm(), output); } // optional uint32 undetected_armor_delay = 3; if (has_undetected_armor_delay()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(3, this->undetected_armor_delay(), output); } // optional string camera_name = 4; if (has_camera_name()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->camera_name().data(), this->camera_name().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "camera_name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 4, this->camera_name(), output); } // required .roborts_detection.CameraGimbalTransform camera_gimbal_transform = 5; if (has_camera_gimbal_transform()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, this->camera_gimbal_transform(), output); } // optional .roborts_detection.ProjectileModelInfo projectile_model_info = 6; if (has_projectile_model_info()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 6, this->projectile_model_info(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:roborts_detection.ArmorDetectionAlgorithms) } ::google::protobuf::uint8* ArmorDetectionAlgorithms::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:roborts_detection.ArmorDetectionAlgorithms) // repeated string name = 1; for (int i = 0; i < this->name_size(); i++) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name(i).data(), this->name(i).length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "name"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(1, this->name(i), target); } // optional string selected_algorithm = 2; if (has_selected_algorithm()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->selected_algorithm().data(), this->selected_algorithm().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "selected_algorithm"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->selected_algorithm(), target); } // optional uint32 undetected_armor_delay = 3; if (has_undetected_armor_delay()) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(3, this->undetected_armor_delay(), target); } // optional string camera_name = 4; if (has_camera_name()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->camera_name().data(), this->camera_name().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "camera_name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 4, this->camera_name(), target); } // required .roborts_detection.CameraGimbalTransform camera_gimbal_transform = 5; if (has_camera_gimbal_transform()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 5, this->camera_gimbal_transform(), target); } // optional .roborts_detection.ProjectileModelInfo projectile_model_info = 6; if (has_projectile_model_info()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 6, this->projectile_model_info(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:roborts_detection.ArmorDetectionAlgorithms) return target; } int ArmorDetectionAlgorithms::ByteSize() const { int total_size = 0; if (_has_bits_[1 / 32] & (0xffu << (1 % 32))) { // optional string selected_algorithm = 2; if (has_selected_algorithm()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->selected_algorithm()); } // optional uint32 undetected_armor_delay = 3; if (has_undetected_armor_delay()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->undetected_armor_delay()); } // optional string camera_name = 4; if (has_camera_name()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->camera_name()); } // required .roborts_detection.CameraGimbalTransform camera_gimbal_transform = 5; if (has_camera_gimbal_transform()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->camera_gimbal_transform()); } // optional .roborts_detection.ProjectileModelInfo projectile_model_info = 6; if (has_projectile_model_info()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->projectile_model_info()); } } // repeated string name = 1; total_size += 1 * this->name_size(); for (int i = 0; i < this->name_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->name(i)); } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void ArmorDetectionAlgorithms::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const ArmorDetectionAlgorithms* source = ::google::protobuf::internal::dynamic_cast_if_available<const ArmorDetectionAlgorithms*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void ArmorDetectionAlgorithms::MergeFrom(const ArmorDetectionAlgorithms& from) { GOOGLE_CHECK_NE(&from, this); name_.MergeFrom(from.name_); if (from._has_bits_[1 / 32] & (0xffu << (1 % 32))) { if (from.has_selected_algorithm()) { set_selected_algorithm(from.selected_algorithm()); } if (from.has_undetected_armor_delay()) { set_undetected_armor_delay(from.undetected_armor_delay()); } if (from.has_camera_name()) { set_camera_name(from.camera_name()); } if (from.has_camera_gimbal_transform()) { mutable_camera_gimbal_transform()->::roborts_detection::CameraGimbalTransform::MergeFrom(from.camera_gimbal_transform()); } if (from.has_projectile_model_info()) { mutable_projectile_model_info()->::roborts_detection::ProjectileModelInfo::MergeFrom(from.projectile_model_info()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void ArmorDetectionAlgorithms::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void ArmorDetectionAlgorithms::CopyFrom(const ArmorDetectionAlgorithms& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool ArmorDetectionAlgorithms::IsInitialized() const { if ((_has_bits_[0] & 0x00000010) != 0x00000010) return false; if (has_camera_gimbal_transform()) { if (!this->camera_gimbal_transform().IsInitialized()) return false; } return true; } void ArmorDetectionAlgorithms::Swap(ArmorDetectionAlgorithms* other) { if (other != this) { name_.Swap(&other->name_); std::swap(selected_algorithm_, other->selected_algorithm_); std::swap(undetected_armor_delay_, other->undetected_armor_delay_); std::swap(camera_name_, other->camera_name_); std::swap(camera_gimbal_transform_, other->camera_gimbal_transform_); std::swap(projectile_model_info_, other->projectile_model_info_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata ArmorDetectionAlgorithms::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = ArmorDetectionAlgorithms_descriptor_; metadata.reflection = ArmorDetectionAlgorithms_reflection_; return metadata; } // @@protoc_insertion_point(namespace_scope) } // namespace roborts_detection // @@protoc_insertion_point(global_scope)
avlo/wasp
packages/util/auth/auth.go
package auth import ( "fmt" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) func AddAuthentication(e *echo.Echo, config map[string]string) { if len(config) == 0 { return } scheme, ok := config["scheme"] if !ok { return } switch scheme { case "basic": addBasicAuth(e, config["username"], config["password"]) default: panic(fmt.Sprintf("Unknown auth scheme %s", scheme)) } } func addBasicAuth(e *echo.Echo, username string, password string) { e.Use(middleware.BasicAuth(func(u, p string, c echo.Context) (bool, error) { return u == username && p == password, nil })) }
internaru/Pinetree_P
lsp_shiloh/common/nvram/src/nvram_dev_shim.h
<filename>lsp_shiloh/common/nvram/src/nvram_dev_shim.h /* * ============================================================================ * Copyright (c) 2008-2010 Marvell International, Ltd. All Rights Reserved * * Marvell Confidential * ============================================================================ */ /** * \file nvram_dev_shim.h * * \brief External interface for NVRAM variable block device shim layer * * This shim sits between the NV Manager and the Partition Manager and is * intended to hide device specific knowledge from the upper parts of the * application layer. Architectural location of this file: * +----------------------------------------------+ * | NVRAM API (Application Layer) | * +----------------------------------------------+ * | NV Device Shim Layer | * | (THIS FILE) | * +----------------------+-----------------------+ * | EEPROM Support | SPI Support | * | | | * +----------------------+-----------------------+ * | Partition Manager API | * +----------------------------------------------+ * | Memory Device Driver Layer | * +----------------------------------------------+ * * \warning * The current implementation only supports managing a container partition on * a single memory device: the device shim binds to a specific device at start * up. * **/ #ifndef INC_NVRAM_DEV_SHIM_H #define INC_NVRAM_DEV_SHIM_H #include <stdint.h> #include <stdbool.h> #include "error_types.h" #include "deviceid.h" #include "nvram_api.h" #ifdef __cplusplus extern "C" { #endif #define VARBLOCK_PART_ID 0xABCD /**< Container partition ID */ #define INVALID_ENTRY 0xffffffff /**< Invalid entry type flag */ /** * \brief NV Instance structure * * This structure is returned to the client when they register a variable block: * an instance handle is required to use most interfaces in this API. **/ typedef struct NVM_Handle_s { char BlockLabel[4]; /**< Block label: 4 ASCII characters */ uint32_t MaxLength; /**< Maximum length of the var block including header */ #ifdef HAVE_NVRAM_FILE int fd; #else MEMORY_DEVICE DeviceID; /**< Device storing the var block */ #endif } PrivateNvramInstance; /** * \brief NV storage header * * Every variable block placed into NV storage will have this header, followed * by the actual block data (in Vars). The header and the variables are * stored in a single memory allocation (header size + Len). **/ typedef struct VARBLOCK_DATA_s { uint32_t Version; /**< Block version */ int8_t Vars[]; /**< 'Len' bytes of variable data */ } VARBLOCK_DATA_t; typedef struct VARBLOCK_HEADER_s { uint32_t CRC; /**< Block CRC */ uint32_t Len; /**< Length of the variable block */ VARBLOCK_DATA_t Data; /**< CRC is calculated on this portion */ } VARBLOCK_HEADER_t; /* FUNCTION NAME: InitNvramDevShim */ /** * \brief Called once at power up, this function initializes the device shim * * This function needs to be called before any applications attempt to access * the NV store. This routine will: * - attempt to locate an existing container partition in the search path, * creating one if needed * - binds the device shim to a specific container * * \return error_type_t * \retval OK Successfully bound to container partition * \retval FAIL Error creating/binding to container **/ error_type_t InitNvramDevShim(void); /* FUNCTION NAME: LocateVarBlock */ /** * \brief Located a variable block in the container partition * * This routine attempts to locate a variable block in the NV store (the * container partition). The caller allocates an nvram_handle_t structure * and fills out the 'BlockLabel' field. If the block is located, this routine * will fill out the 'MaxLength' and 'DeviceID' fields in the instance structure. * * NOTE: the caller cannot specify a memory device to search, the device shim * binds to a single NV store at start up time. * * \param[in] *nHandle Pointer NV instance handle, allocated by caller * * \return error_type_t * \retval OK Variable block found * \retval FAIL Variable block not found **/ error_type_t LocateVarBlock(nvram_handle_t *nHandle); /* FUNCTION NAME: RegisterVarBlock */ /** * \brief Gets a handle to a variable block * * This routine attempts to return a valid variable block handle to the caller. * The caller allocates an nvram_handle_t structure and fills out the 'BlockLabel' * and 'MaxLength' fields. If an existing block cannot be located, a new one * will be created. This routine will fill out the 'DeviceID' field * in the instance structure. * * NOTE: the caller cannot specify a memory device, the device shim * binds to a single NV store at start up time. * * \warning * The NV API is responsible for making sure the size of the variable block is * correct. If the sizes don't match, this routine will fail and the handle * will not be usable. * * \param[in] *nHandle Pointer NV instance handle, allocated by caller * * \return error_type_t * \retval OK Valid variable block handle returned * \retval FAIL Unable to locate or create variable block (or size mismatch) **/ error_type_t RegisterVarBlock(nvram_handle_t *nHandle); /* FUNCTION NAME: ReleaseVarBlock */ /** * \brief Removes a registered variable block * * This routine removes a registered variable block from the NV store. * * \param[in] *nHandle Valid handle obtained from the register call * * \return error_type_t * \retval OK Variable block removed * \retval FAIL Variable block could not be removed **/ error_type_t ReleaseVarBlock(nvram_handle_t *nHandle); /* FUNCTION NAME: VarBlockRead */ /** * \brief Reads data from a registered variable block * * This routine reads data from a registered variable block. Note that this * command will allow the caller to read a subset of the block data by using * the offset and size parameters. Reading off the end of the var block is * not allowed (no data will be returned). * * \param[in] *nHandle Valid handle obtained from the register call * \param[in] *blockPtr Buffer pointer to receive the read data. Allocated * by the caller, must be at least 'size' bytes or * memory will be corrupted * \param[in] offset Offset from var block start to begin reading * \param[in] size Number of bytes to read * * \return uint32_t * \retval 0 if problem reading block (or parameters invalid) * \retval Actual number of bytes read from block **/ uint32_t VarBlockRead(nvram_handle_t *nHandle, int8_t *blockPtr, uint64_t offset, uint32_t size); /* FUNCTION NAME: VarBlockWrite */ /** * \brief Writes a registered variable block * * This routine writes data to a registered variable block. Note that this * command will NOT allow the caller to write a subset of the block data, the * entire block must be written (nHandle->MaxLength). * * \param[in] *nHandle Valid handle obtained from the register call * \param[in] *blockPtr Buffer pointer to data to be written, allocated by * the caller * * \return uint32_t * \retval 0 if problem writing the block (or parameters invalid) * \retval Actual number of bytes written to block **/ uint32_t VarBlockWrite(nvram_handle_t *nHandle, int8_t *blockPtr); /* FUNCTION NAME: VarBlockCheckCRC */ /** * \brief Validates variable block CRC * * This routine examines the CRC of the passed variable block. * * \param[in] *label 4 character ascii block label * \param[in] *varBlock Pointer to a variable block * \param[in] erased_data_val Data value of erased memory for the type of memory being checked. * Typically 0xFFFFFFFF for eeprom and spi flash. * * \return bool * \retval true variable block CRC is OK * \retval false bad CRC **/ bool VarBlockCheckCRC(char *label, VARBLOCK_HEADER_t *varBlock, uint32_t erased_data_val); #ifdef __cplusplus } #endif #endif /* INC_NVRAM_DEV_SHIM_H */
Adikteev/cuttle
flow/src/main/scala/com/criteo/cuttle/flow/Database.scala
package com.criteo.cuttle.flow import com.criteo.cuttle._ import java.time._ import scala.concurrent.duration.Duration import cats.Applicative import cats.data.{EitherT, OptionT} import cats.implicits._ import io.circe._ import io.circe.generic.auto._ import io.circe.syntax._ import doobie._ import doobie.implicits._ import com.criteo.cuttle.{utils => CriteoCoreUtils} private[flow] object Database { import FlowSchedulerUtils._ import com.criteo.cuttle.Database._ lazy val contextIdMigration: ConnectionIO[Unit] = { implicit val jobs: Set[FlowJob] = Set.empty val chunkSize = 1024 * 10 val stream = sql"SELECT id, json FROM flow_contexts" .query[(String, Json)] .streamWithChunkSize(chunkSize) val insert = Update[(String, String)]("INSERT into tmp (id, new_id) VALUES (? , ?)") for { _ <- sql"CREATE TEMPORARY TABLE tmp (id VARCHAR(1000), new_id VARCHAR(1000))".update.run _ <- stream .chunkLimit(chunkSize) .evalMap { oldContexts => insert.updateMany(oldContexts.map { case (id, json) => (id, json.as[FlowSchedulerContext].right.get.toId) }) } .compile .drain _ <- sql"""CREATE INDEX tmp_id ON tmp (id)""".update.run _ <- sql"""UPDATE flow_contexts SET id = tmp.new_id FROM tmp WHERE flow_contexts.id = tmp.id """.update.run _ <- sql"""UPDATE executions SET context_id = tmp.new_id FROM tmp WHERE executions.context_id = tmp.id """.update.run } yield () } /* * Schema describing the different tables necessary to run FlowWorkflow * * */ val schema = List( sql""" CREATE TABLE flow_state ( workflow_id TEXT NOT NULL, state JSONB NOT NULL, date TIMESTAMP WITHOUT TIME ZONE NOT NULL ); CREATE INDEX flow_state_workflowid ON flow_state (workflow_id); CREATE INDEX flow_state_by_date ON flow_state (date); CREATE TABLE flow_results ( workflow_id TEXT NOT NULL, from_graph VARCHAR(255) NOT NULL, step_id TEXT NOT NULL, inputs JSONB NULL, result JSONB NULL, PRIMARY KEY(workflow_id, step_id) ); CREATE INDEX flow_results_workflowid ON flow_results (workflow_id); CREATE INDEX flow_results_stepid ON flow_results (step_id); CREATE TABLE flow_contexts ( id TEXT NOT NULL, json JSONB NOT NULL, PRIMARY KEY (id) ); CREATE TABLE flow_graph ( id TEXT NOT NULL, json JSONB NOT NULL, PRIMARY KEY (id) ); CREATE INDEX flow_graph_id ON flow_graph (id); """.update.run, contextIdMigration, NoUpdate ) val doSchemaUpdates: ConnectionIO[Unit] = CriteoCoreUtils.updateSchema("flow", schema) def insertResult(wfHash : String, wfId : String, stepId : String, inputs : Json, result : Json) = sql""" INSERT INTO flow_results (workflow_id, from_graph, step_id, inputs, result) VALUES(${wfId}, ${wfHash}, ${stepId}, ${inputs}, ${result}) """.update.run // TODO : Maybe return list or one response. def retrieveResult(wfId : String, stepId : String) = OptionT { sql""" SELECT result FROM flow_results WHERE workflow_id = ${wfId} AND step_id = ${stepId} ORDER BY date LIMIT 1 """.query[Json].option }.value /** * Decode the state * @param json * @param jobs * @return a potential state */ def dbStateDecoder(json: Json)(implicit jobs: Set[FlowJob]): Option[JobState] = { type StoredState = List[(String, JobFlowState)] val stored = json.as[StoredState] stored.right.toOption.flatMap { jobsStored => val state = jobsStored.map { case (jobId, flowState) => jobs.find(_.id == jobId).map(job => job -> flowState) } Some(state.flatten.toMap) } } /** * Encode the state * @param state * @return */ def dbStateEncoder(state: JobState): Json = state.toList.map { case (job, flowState) => (job.id, flowState.asJson) }.asJson def deserializeState(workflowId: String)(implicit jobs: Set[FlowJob]): ConnectionIO[Option[JobState]] = { OptionT { sql"SELECT state FROM flow_state WHERE workflow_id = ${workflowId} ORDER BY date DESC LIMIT 1" .query[Json] .option }.map(json => dbStateDecoder(json).get).value } def serializeState(workflowid : String, state: JobState, retention: Option[Duration]): ConnectionIO[Int] = { val now = Instant.now() val cleanStateBefore = retention.map { duration => if (duration.toSeconds <= 0) sys.error(s"State retention is badly configured: ${duration}") else now.minusSeconds(duration.toSeconds) } val stateJson = dbStateEncoder(state) for { // Apply state retention if needed _ <- cleanStateBefore .map { t => sql"DELETE FROM flow_state where date < ${t}".update.run } .getOrElse(NoUpdate) // Insert the latest state x <- sql"INSERT INTO flow_state (workflow_id, state, date) VALUES (${workflowid}, ${stateJson}, ${now})".update.run } yield x } /** * Serialize context * @param context * @return the id of the context */ def serializeContext(context: FlowSchedulerContext): ConnectionIO[String] = { val id = context.toId sql"""INSERT INTO flow_contexts(id, json) VALUES(${id}, ${context.asJson}) ON CONFLICT (id) DO UPDATE SET json = excluded.json """.update.run *> Applicative[ConnectionIO].pure(id) } /** * Serialize the graph into the db * @param workflow * @return the hash of the workflow */ def serializeGraph(workflow: FlowWorkflow) = { val h = workflow.hash.toString val serializedGraph = workflow.asJson for { exist <- EitherT(sql"""SELECT exists(SELECT 1 FROM flow_graph WHERE id=${h})""".query[Boolean].option.attempt) _ <- if (exist.isEmpty || !exist.get) EitherT(sql"""INSERT INTO flow_graph VALUES(${h}, ${serializedGraph})""".update.run.attempt) else EitherT.rightT[doobie.ConnectionIO, Throwable](()) } yield () } }
RatJuggler/led-shim-effects
tests/test_effect_controller.py
<gh_stars>1-10 from unittest import TestCase from unittest.mock import patch from testfixtures import LogCapture from ledshimdemo.canvas import Canvas import ledshimdemo.configure_logging as cl from ledshimdemo.effect_controller import EffectController from tests.test_effects.dummy1_effect import Dummy1Effect from tests.test_effects.dummy2_effect import Dummy2Effect from tests.test_effects.dummy3_effect import Dummy3Effect class TestEffectControllerConstructorAndOptionsUsed(TestCase): def test_valid_options1(self): controller = EffectController("CYCLE", 10, 1, 8, False, []) expected_result = "Effect Options(parade=CYCLE, duration=10 secs, repeat=1, brightness=8, invert=False, " \ "effects=ALL)" options_used = controller.options_used() self.assertEqual(options_used, expected_result) def test_valid_options2(self): controller = EffectController("RANDOM", 15, 3, 9, True, ['Candle', 'Rainbow']) expected_result = "Effect Options(parade=RANDOM, duration=15 secs, repeat=3, brightness=9, invert=True, " \ "effects=['Candle', 'Rainbow'])" options_used = controller.options_used() self.assertEqual(options_used, expected_result) def test_invalid_options(self): controller = EffectController("TEST", 27, -1, 100, True, []) expected_result = "Effect Options(parade=TEST, duration=27 secs, repeat=-1, brightness=100, invert=True, " \ "effects=ALL)" options_used = controller.options_used() self.assertEqual(options_used, expected_result) @patch('ledshimdemo.effect_controller.AbstractEffectParade') class TestEffectControllerProcessDisplay(TestCase): TEST_CANVAS_SIZE = 3 # type: int def setUp(self): canvas = Canvas(self.TEST_CANVAS_SIZE) self.instances = [Dummy1Effect(canvas), Dummy2Effect(canvas), Dummy3Effect(canvas)] def test_display_default_options_default_log(self, effect_parade_mock): expected = "Effect Options(parade=CYCLE, duration=10 secs, repeat=1, brightness=8, invert=False, effects=ALL)" with LogCapture(level=cl.logging.INFO) as log_out: controller = EffectController("CYCLE", 10, 1, 8, False, []) controller.process(self.instances) log_out.check(("root", cl.logging.getLevelName(cl.logging.INFO), expected)) effect_parade_mock.select_effect_parade.assert_called_once() effect_parade_mock.select_effect_parade.return_value.render.assert_called_once() def test_display_default_options_warning_log(self, effect_parade_mock): with LogCapture(level=cl.logging.WARNING) as log_out: controller = EffectController("CYCLE", 10, 1, 8, False, []) controller.process(self.instances) log_out.check() effect_parade_mock.select_effect_parade.assert_called_once() effect_parade_mock.select_effect_parade.return_value.render.assert_called_once() def test_display_all_options_verbose_log(self, effect_parade_mock): expected = "Effect Options(parade=RANDOM, duration=180 secs, repeat=240, brightness=3, " \ "invert=True, effects=['Dummy1Effect', 'Dummy2Effect'])" with LogCapture(level=cl.VERBOSE) as log_out: controller = EffectController("RANDOM", 180, 240, 3, True, ['Dummy1Effect', 'Dummy2Effect']) controller.process(self.instances) log_out.check(("root", cl.logging.getLevelName(cl.logging.INFO), expected)) effect_parade_mock.select_effect_parade.assert_called_once() effect_parade_mock.select_effect_parade.return_value.render.assert_called_once()
Quizine/Quizine
databaseSeedScripts/orderSeedScript.js
<filename>databaseSeedScripts/orderSeedScript.js /* eslint-disable max-statements */ const {normalDistributionFunc} = require('./utilities') //DATABASE SEED SCRIPT VARIABLES: const orderNumber = 10000 //for seeding waiters let server = [ {id: 1, name: '<NAME>', sex: 'male', age: 27, restaurantId: 1}, {id: 2, name: '<NAME>', sex: 'female', age: 31, restaurantId: 1}, {id: 3, name: '<NAME>', sex: 'male', age: 24, restaurantId: 1}, {id: 4, name: '<NAME>', sex: 'female', age: 34, restaurantId: 1}, {id: 5, name: '<NAME>', sex: 'female', age: 26, restaurantId: 1}, {id: 6, name: '<NAME>', sex: 'male', age: 37, restaurantId: 1}, {id: 7, name: '<NAME>', sex: 'male', age: 32, restaurantId: 1}, {id: 8, name: '<NAME>', sex: 'male', age: 21, restaurantId: 1}, {id: 9, name: '<NAME>', sex: 'female', age: 28, restaurantId: 1}, {id: 10, name: '<NAME>', sex: 'female', age: 32, restaurantId: 1}, {id: 11, name: '<NAME>', sex: 'male', age: 22, restaurantId: 1}, {id: 12, name: '<NAME>', sex: 'male', age: 29, restaurantId: 1} ] //for seeding menu let menu = [ { id: 1, menuItemName: 'lobster', beverageType: null, foodType: 'main', mealType: 'dinner', price: 32, restaurantId: 1 }, { id: 2, menuItemName: 'steak', beverageType: null, foodType: 'main', mealType: 'dinner', price: 45, restaurantId: 1 }, { id: 3, menuItemName: 'chicken', beverageType: null, foodType: 'main', mealType: 'dinner', price: 27, restaurantId: 1 }, { id: 4, menuItemName: 'pasta', beverageType: null, foodType: 'main', mealType: 'dinner', price: 21, restaurantId: 1 }, { id: 5, menuItemName: 'lobster', beverageType: null, foodType: 'main', mealType: 'lunch', price: 22, restaurantId: 1 }, { id: 6, menuItemName: 'steak', beverageType: null, foodType: 'main', mealType: 'lunch', price: 35, restaurantId: 1 }, { id: 7, menuItemName: 'chicken', beverageType: null, foodType: 'main', mealType: 'lunch', price: 17, restaurantId: 1 }, { id: 8, menuItemName: 'pasta', beverageType: null, foodType: 'main', mealType: 'lunch', price: 11, restaurantId: 1 }, { id: 9, menuItemName: 'springRolls', beverageType: null, foodType: 'appetizer', mealType: 'dinner', price: 17, restaurantId: 1 }, { id: 10, menuItemName: 'deviledEggs', beverageType: null, foodType: 'appetizer', mealType: 'dinner', price: 15, restaurantId: 1 }, { id: 11, menuItemName: 'soup', beverageType: null, foodType: 'appetizer', mealType: 'dinner', price: 18, restaurantId: 1 }, { id: 12, menuItemName: 'salad', beverageType: null, foodType: 'appetizer', mealType: 'dinner', price: 19, restaurantId: 1 }, { id: 13, menuItemName: 'springRolls', beverageType: null, foodType: 'appetizer', mealType: 'lunch', price: 12, restaurantId: 1 }, { id: 14, menuItemName: 'deviledEggs', beverageType: null, foodType: 'appetizer', mealType: 'lunch', price: 10, restaurantId: 1 }, { id: 15, menuItemName: 'soup', beverageType: null, foodType: 'appetizer', mealType: 'lunch', price: 13, restaurantId: 1 }, { id: 16, menuItemName: 'salad', beverageType: null, foodType: 'appetizer', mealType: 'lunch', price: 14, restaurantId: 1 }, { id: 17, menuItemName: 'chocolateCake', beverageType: null, foodType: 'dessert', mealType: 'dinner', price: 18, restaurantId: 1 }, { id: 18, menuItemName: 'tiramisu', beverageType: null, foodType: 'dessert', mealType: 'dinner', price: 19, restaurantId: 1 }, { id: 19, menuItemName: 'iceCream', beverageType: null, foodType: 'dessert', mealType: 'dinner', price: 14, restaurantId: 1 }, { id: 20, menuItemName: 'fruit', beverageType: null, foodType: 'dessert', mealType: 'dinner', price: 15, restaurantId: 1 }, { id: 21, menuItemName: 'chocolateCake', beverageType: null, foodType: 'dessert', mealType: 'lunch', price: 13, restaurantId: 1 }, { id: 22, menuItemName: 'tiramisu', beverageType: null, foodType: 'dessert', mealType: 'lunch', price: 14, restaurantId: 1 }, { id: 23, menuItemName: 'iceCream', beverageType: null, foodType: 'dessert', mealType: 'lunch', price: 9, restaurantId: 1 }, { id: 24, menuItemName: 'fruit', beverageType: null, foodType: 'dessert', mealType: 'lunch', price: 10, restaurantId: 1 }, { id: 25, menuItemName: 'coke', beverageType: 'nonAlcohol', foodType: null, mealType: null, price: 5, restaurantId: 1 }, { id: 26, menuItemName: 'sprite', beverageType: 'nonAlcohol', foodType: null, mealType: null, price: 4, restaurantId: 1 }, { id: 27, menuItemName: 'redWine', beverageType: 'alcohol', foodType: null, mealType: null, price: 12, restaurantId: 1 }, { id: 28, menuItemName: 'whiteWine', beverageType: 'alcohol', foodType: null, mealType: null, price: 13, restaurantId: 1 } ] let serverSkill = [ {serverId: 1, skill_level: 0.9}, {serverId: 2, skill_level: 0.7}, {serverId: 3, skill_level: 0.65}, {serverId: 4, skill_level: 0.8}, {serverId: 5, skill_level: 0.75}, {serverId: 6, skill_level: 0.85}, {serverId: 7, skill_level: 0.78}, {serverId: 8, skill_level: 0.73}, {serverId: 9, skill_level: 0.85}, {serverId: 10, skill_level: 0.87}, {serverId: 11, skill_level: 0.76}, {serverId: 12, skill_level: 0.83} ] const selectRandomServer = function() { let serverIndex = Math.floor(Math.random() * serverSkill.length) return serverSkill[serverIndex] } let randomizeTime = function(mealType) { let meanTimeOfDay if (mealType === 'lunch') { meanTimeOfDay = 13 } else if (mealType === 'dinner') { meanTimeOfDay = 19 } let variance = 1.2 let time = meanTimeOfDay + variance * normalDistributionFunc() let openingTime = 11 let closingTime = 22 time = Math.max(openingTime, time) time = Math.min(time, closingTime) return time } const pickMenuItemName = function(menu) { let menuIndex = Math.floor(Math.random() * menu.length) let menuItemName = menu[menuIndex] return menuItemName } let randomizeMenuItemOrder = function(mealType, isFood, type) { let selectedList = [] if (isFood) { for (let i = 0; i < menu.length; i++) { if (menu[i].mealType === mealType && menu[i].foodType === type) { selectedList.push(menu[i]) } } } else { for (let i = 0; i < menu.length; i++) { if (menu[i].mealType === null && menu[i].beverageType === type) { selectedList.push(menu[i]) } } } const selectedMenu = pickMenuItemName(selectedList) return selectedMenu.id } let randomizeSinglePersonPurchase = function(orderHour) { let personOrder = [] let mealType let foodType = ['appetizer', 'dessert'] let beverageType = ['alcohol', 'nonAlcohol'] if (orderHour < 16) { mealType = 'lunch' } else { mealType = 'dinner' } personOrder.push(randomizeMenuItemOrder(mealType, true, 'main')) for (let i = 0; i < foodType.length; i++) { let foodRandomNumber = Math.random() if (foodRandomNumber < 0.5) { personOrder.push(randomizeMenuItemOrder(mealType, true, foodType[i])) } } let beverageRandomNumber = Math.random() if (mealType === 'lunch') { if (beverageRandomNumber < 0.8) { personOrder.push(randomizeMenuItemOrder(null, false, beverageType[1])) } else { personOrder.push(randomizeMenuItemOrder(null, false, beverageType[0])) } } else if (mealType === 'dinner') { if (beverageRandomNumber < 0.2) { personOrder.push(randomizeMenuItemOrder(null, false, beverageType[1])) } else { personOrder.push(randomizeMenuItemOrder(null, false, beverageType[0])) } } return personOrder } const generatePurchase = function() { let purchaseData = {} let earliestDate = new Date(2018, 0, 1) let latestDate = new Date(2020, 11, 1) let dateOfPurchase = new Date( +earliestDate + Math.random() * (latestDate - earliestDate) ) while ( [0, 6].indexOf(dateOfPurchase.getDay()) === -1 && Math.random() < 0.4 ) { dateOfPurchase = new Date( +earliestDate + Math.random() * (latestDate - earliestDate) ) } dateOfPurchase = new Date(dateOfPurchase.toDateString()) let dayOfWeekOfOrder = dateOfPurchase.getDay() let meal let mealRandomNumber = Math.random() let lunchProportion if (dayOfWeekOfOrder === 0 || dayOfWeekOfOrder === 6) { lunchProportion = 0.42 } else { lunchProportion = 0.26 } if (mealRandomNumber < lunchProportion) { meal = 'lunch' } else { meal = 'dinner' } let hour = randomizeTime(meal) dateOfPurchase.setHours(hour) dateOfPurchase.setMinutes((hour % 1) * 60) purchaseData.timeOfPurchase = dateOfPurchase purchaseData.waiterId = selectRandomServer().serverId let numberOfGuests let guestRandomNumber = Math.random() if (guestRandomNumber > 0.3) { numberOfGuests = Math.floor(Math.random() * (4 - 2 + 1)) + 2 } else { numberOfGuests = Math.floor(Math.random() * (8 - 5 + 1)) + 5 } purchaseData.numberOfGuests = numberOfGuests purchaseData.menuItemOrderList = [] for (let i = 1; i <= numberOfGuests; i++) { purchaseData.menuItemOrderList = purchaseData.menuItemOrderList.concat( randomizeSinglePersonPurchase(hour) ) } let hashOfMenuItemOrderList = {} menu.forEach(item => { hashOfMenuItemOrderList[item.id] = item.price }) purchaseData.subtotal = purchaseData.menuItemOrderList.reduce( (acc, currVal) => { return acc + hashOfMenuItemOrderList[currVal] }, 0 ) let tipPercentage = (20 + 4 * normalDistributionFunc()) * serverSkill[purchaseData.waiterId - 1].skill_level purchaseData.tip = Math.floor(tipPercentage / 100 * purchaseData.subtotal) purchaseData.tax = Math.floor(0.1 * purchaseData.subtotal) purchaseData.revenue = purchaseData.subtotal + purchaseData.tip + purchaseData.tax return purchaseData } let purchaseList = [] for (let i = 0; i < orderNumber; i++) { let potentialPurchase = generatePurchase() potentialPurchase.id = i + 1 potentialPurchase.restaurantId = 1 purchaseList.push(potentialPurchase) } let orderMenuTable = [] for (let i = 0; i < purchaseList.length; i++) { let singlePurchase = purchaseList[i] let hashOfMenuQty = {} for (let j = 0; j < singlePurchase.menuItemOrderList.length; j++) { let singleMenuId = singlePurchase.menuItemOrderList[j] let singleOrderPerMenu if (hashOfMenuQty[singleMenuId]) { for (let k = 0; k < orderMenuTable.length; k++) { if ( singleMenuId === orderMenuTable[k].menuItemId && singlePurchase.id === orderMenuTable[k].orderId ) { orderMenuTable[k].quantity++ } } } else { hashOfMenuQty[singleMenuId] = true singleOrderPerMenu = { quantity: 1, orderId: singlePurchase.id, menuItemId: singleMenuId } orderMenuTable.push(singleOrderPerMenu) } } delete singlePurchase.menuItemOrderList } module.exports = { server, menu, purchaseList, orderMenuTable }
ChDragon/Summer
src/test/java/com/swingfrog/summer/test/repository/TestRepositoryBootstrap.java
package com.swingfrog.summer.test.repository; import com.swingfrog.summer.app.Summer; import com.swingfrog.summer.app.SummerApp; import com.swingfrog.summer.app.SummerConfig; import lombok.extern.slf4j.Slf4j; @Slf4j public class TestRepositoryBootstrap implements SummerApp { @Override public void init() { log.info("init"); } @Override public void start() { log.info("start"); } @Override public void stop() { log.info("stop"); } public static void main(String[] args) { String resources = TestRepositoryBootstrap.class.getClassLoader().getResource("repository").getPath(); Summer.hot(SummerConfig.newBuilder() .app(new TestRepositoryBootstrap()) .dbProperties(resources + "/db.properties") .redisProperties(resources + "/redis.properties") .serverProperties(resources + "/server.properties") .taskProperties(resources + "/task.properties") .build()); // 请先创建数据库 } }
retrohacker/FunctionScript
tests/files/cases/function_invalid_multiple_schema_nested.js
<filename>tests/files/cases/function_invalid_multiple_schema_nested.js /** * Accepts multiple schemas for an object * @param {object} fileOrFolder * @ {string} name * @ {number} size * @ OR * @ {string} name2 * @ {number} size2 * @ {object} props * @ {string} label * @ OR * @ {number} size * @returns {object} */ module.exports = async (fileOrFolder) => { return true; };
thesourcestory/Core
src/main/java/realtech/items/components/Resistor.java
package realtech.items.components; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import realtech.init.Realtech; /** * Created by magnu on 23/02/2017. */ public class Resistor extends Item{ public Resistor(){ super(); this.setHasSubtypes(true); this.setCreativeTab(Realtech.realtechelements); } public String getUnlocalizedName(ItemStack stack){ String out = getDefaultName(stack); return out; } private String getDefaultName(ItemStack stack){ return super.getUnlocalizedName() + "." + stack.getItemDamage(); } @SideOnly(Side.CLIENT) public void getSubItems(Item item, CreativeTabs tabs, NonNullList<ItemStack> list){ for(int i = 0; i < 72; i++) { list.add(new ItemStack(item, 1, i)); } } }
AlpineNow/PluginSDK
plugin-core/src/main/scala/com/alpine/plugin/core/io/HdfsTabularDataset.scala
/** * COPYRIGHT (C) 2015 Alpine Data Labs Inc. All Rights Reserved. */ package com.alpine.plugin.core.io import com.alpine.plugin.core.annotation.AlpineSdkApi /** * :: AlpineSdkApi :: * Tabular dataset refers to table format datasets, such as CSV/TSV * Parquet/Avro, etc. that reside within Hdfs. */ @AlpineSdkApi trait HdfsTabularDataset extends HdfsFile with TabularDataset
norbekaiser/yatbcpp-macos
src/types_fromJson/PhotoSize_fromJson.cc
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // From JSON Specialication // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <json/json.h> #include "types/telegram_type.h" #include "exceptions/essential_key_missing.h" #include "types/PhotoSize.h" using namespace std; namespace yatbcpp { /** * Returns A PhotoSize based on a Json Object * @param Data a Json Object Containing the necessary and Optional Fields * @return Parsed PhotoSize */ template<> PhotoSize fromJson(Json::Value Data) { if (!Data.isMember("file_id")) { throw essential_key_missing("PhotoSize::file_id is missing"); } if (!Data.isMember("width")) { throw essential_key_missing("PhotoSize::width is missing"); } if (!Data.isMember("height")) { throw essential_key_missing("PhotoSize::height is missing"); } std::string file_id = Data["file_id"].asString(); std::int32_t width = Data["width"].asInt(); std::int32_t height = Data["height"].asInt(); PhotoSize ret(file_id, width, height); if (Data.isMember("file_size")) { ret.setFile_size(Data["file_size"].asInt()); } return ret; } }
0xflotus/csscritic
test/specs/regressionSpec.js
describe("Regression testing", function () { "use strict"; var regression, rendererBackend, imagediff; var util = csscriticLib.util(); var pageImage, referenceImage, viewport; var setUpRenderedImage = function (image, errors) { errors = errors || []; rendererBackend.render.and.returnValue(testHelper.successfulPromise({ image: image, errors: errors })); }; var setUpImageEqualityToBe = function (equal) { imagediff.equal.and.returnValue(equal); }; var testCaseWithReferenceImage = function (testCase) { return { testCase: testCase, referenceImage: referenceImage, viewport: viewport }; }; var testCaseWithMissingReferenceImage = function (testCase) { return { testCase: testCase }; }; beforeEach(function () { pageImage = jasmine.createSpy('pageImage'); referenceImage = { width: 42, height: 7 }; viewport = { width: 98, height: 76 }; spyOn(util, 'workAroundTransparencyIssueInFirefox').and.callFake(function (image) { return testHelper.successfulPromise(image); }); rendererBackend = jasmine.createSpyObj('renderer', ['render']); imagediff = jasmine.createSpyObj('imagediff', ['diff', 'equal']); regression = csscriticLib.regression(rendererBackend, util, imagediff); }); describe("comparison", function () { beforeEach(function () { setUpRenderedImage(pageImage); setUpImageEqualityToBe(true); }); it("should compare the rendered page against the reference image", function (done) { regression.compare(testCaseWithReferenceImage({ url: "differentpage.html" })).then(function () { expect(imagediff.equal).toHaveBeenCalledWith(pageImage, referenceImage, 1); done(); }); }); it("should render page using the viewport's size", function (done) { regression.compare(testCaseWithReferenceImage({ url: "samplepage.html" })).then(function () { expect(rendererBackend.render).toHaveBeenCalledWith(jasmine.objectContaining({ url: "samplepage.html", width: 98, height: 76 })); done(); }); }); it("should pass test case parameters to the renderer", function (done) { regression.compare(testCaseWithReferenceImage({ url: 'samplepage.html', hover: '.a.selector', active: '.another.selector', focus: '#some', target: 'section' })).then(function () { expect(rendererBackend.render).toHaveBeenCalledWith({ url: "samplepage.html", hover: '.a.selector', active: '.another.selector', focus: '#some', target: 'section', width: 98, height: 76 }); done(); }); }); }); describe("on a passing comparison", function () { beforeEach(function () { setUpRenderedImage(pageImage); setUpImageEqualityToBe(true); }); it("should report the comparison", function (done) { regression.compare(testCaseWithReferenceImage({ url: "differentpage.html" })).then(function (comparison) { expect(comparison).toEqual({ status: "passed", testCase: { url: "differentpage.html" }, pageImage: pageImage, referenceImage: referenceImage, renderErrors: [], viewport: viewport }); done(); }); }); it("should report a list of errors during rendering", function (done) { setUpRenderedImage(pageImage, ["oneUrl", "anotherUrl"]); regression.compare(testCaseWithReferenceImage({ url: "differentpage.html" })).then(function (comparison) { expect(comparison).toEqual(jasmine.objectContaining({ renderErrors: ["oneUrl", "anotherUrl"], })); done(); }); }); }); describe("on a failing comparison", function () { beforeEach(function () { setUpRenderedImage(pageImage); setUpImageEqualityToBe(false); }); it("should report the comparison", function (done) { regression.compare(testCaseWithReferenceImage({ url: "differentpage.html" })).then(function (comparison) { expect(comparison).toEqual({ status: "failed", testCase: { url: "differentpage.html" }, pageImage: pageImage, referenceImage: referenceImage, renderErrors: [], viewport: viewport }); done(); }); }); }); describe("on a reference missing", function () { beforeEach(function () { setUpRenderedImage(pageImage); }); it("should report the comparison", function (done) { regression.compare(testCaseWithMissingReferenceImage({ url: "differentpage.html" })).then(function (comparison) { expect(comparison).toEqual({ status: "referenceMissing", testCase: { url: "differentpage.html" }, pageImage: pageImage, renderErrors: [], viewport: jasmine.any(Object) }); done(); }); }); it("should provide a appropriately sized page rendering", function (done) { regression.compare(testCaseWithMissingReferenceImage({ url: "differentpage.html" })).then(function () { expect(rendererBackend.render).toHaveBeenCalledWith(jasmine.objectContaining({ url: "differentpage.html", width: 800, height: 100 })); done(); }); }); it("should use the specified width", function (done) { regression.compare(testCaseWithMissingReferenceImage({ url: "differentpage.html", width: 42 })).then(function () { expect(rendererBackend.render).toHaveBeenCalledWith(jasmine.objectContaining({ url: "differentpage.html", width: 42, height: 100 })); done(); }); }); it("should use the specified height", function (done) { regression.compare(testCaseWithMissingReferenceImage({ url: "differentpage.html", height: 21 })).then(function () { expect(rendererBackend.render).toHaveBeenCalledWith(jasmine.objectContaining({ url: "differentpage.html", width: 800, height: 21 })); done(); }); }); it("should report a list of errors during rendering", function (done) { setUpRenderedImage(pageImage, ["oneUrl", "anotherUrl"]); regression.compare(testCaseWithMissingReferenceImage({ url: "differentpage.html" })).then(function (comparison) { expect(comparison).toEqual(jasmine.objectContaining({ renderErrors: ["oneUrl", "anotherUrl"], })); done(); }); }); }); describe("on error", function () { var error; beforeEach(function () { error = {message: 'some message', originalError: new Error('original error')}; rendererBackend.render.and.returnValue(testHelper.failedPromise(error)); }); it("should report the comparison", function (done) { regression.compare(testCaseWithMissingReferenceImage({ url: "differentpage.html" })).then(function (comparison) { expect(comparison).toEqual(jasmine.objectContaining({ status: "error", testCase: { url: "differentpage.html" } })); done(); }); }); it("should report the default viewport", function (done) { regression.compare(testCaseWithMissingReferenceImage({ url: "differentpage.html" })).then(function (comparison) { expect(comparison).toEqual(jasmine.objectContaining({ viewport: { width: 800, height: 100 } })); done(); }); }); it("should report the error", function (done) { regression.compare(testCaseWithMissingReferenceImage({ url: "differentpage.html" })).then(function (comparison) { expect(comparison).toEqual(jasmine.objectContaining({ renderErrors: ['some message: original error'] })); done(); }); }); }); });
bazaarvoice/cloudbreak
cloud-api/src/main/java/com/sequenceiq/cloudbreak/cloud/model/VmTypeMeta.java
<reponame>bazaarvoice/cloudbreak package com.sequenceiq.cloudbreak.cloud.model; import java.util.HashMap; import java.util.Map; public class VmTypeMeta { public static final String CPU = "Cpu"; public static final String MEMORY = "Memory"; public static final String MAXIMUM_PERSISTENT_DISKS_SIZE_GB = "maximumPersistentDisksSizeGb"; public static final String PRICE = "Price"; private VolumeParameterConfig magneticConfig; private VolumeParameterConfig autoAttachedConfig; private VolumeParameterConfig ssdConfig; private VolumeParameterConfig ephemeralConfig; private VolumeParameterConfig st1Config; private Map<String, String> properties = new HashMap<>(); public VolumeParameterConfig getMagneticConfig() { return magneticConfig; } public void setMagneticConfig(VolumeParameterConfig magneticConfig) { this.magneticConfig = magneticConfig; } public VolumeParameterConfig getAutoAttachedConfig() { return autoAttachedConfig; } public void setAutoAttachedConfig(VolumeParameterConfig autoAttachedConfig) { this.autoAttachedConfig = autoAttachedConfig; } public VolumeParameterConfig getSsdConfig() { return ssdConfig; } public void setSsdConfig(VolumeParameterConfig ssdConfig) { this.ssdConfig = ssdConfig; } public VolumeParameterConfig getEphemeralConfig() { return ephemeralConfig; } public void setEphemeralConfig(VolumeParameterConfig ephemeralConfig) { this.ephemeralConfig = ephemeralConfig; } public VolumeParameterConfig getSt1Config() { return st1Config; } public void setSt1Config(VolumeParameterConfig st1Config) { this.st1Config = st1Config; } public Map<String, String> getProperties() { return properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } @Override public String toString() { return "VmTypeMeta{" + "magneticConfig=" + magneticConfig + ", autoAttachedConfig=" + autoAttachedConfig + ", ssdConfig=" + ssdConfig + ", ephemeralConfig=" + ephemeralConfig + ", st1Config=" + st1Config + ", properties=" + properties + '}'; } public static class VmTypeMetaBuilder { private VolumeParameterConfig magneticConfig; private VolumeParameterConfig autoAttachedConfig; private VolumeParameterConfig ssdConfig; private VolumeParameterConfig ephemeralConfig; private VolumeParameterConfig st1Config; private final Map<String, String> properties = new HashMap<>(); private VmTypeMetaBuilder() { } public static VmTypeMetaBuilder builder() { return new VmTypeMetaBuilder(); } public VmTypeMetaBuilder withMagneticConfig(Integer minimumSize, Integer maximumSize, Integer minimumNumber, Integer maximumNumber) { magneticConfig = new VolumeParameterConfig(VolumeParameterType.MAGNETIC, minimumSize, maximumSize, minimumNumber, maximumNumber); return this; } public VmTypeMetaBuilder withMagneticConfig(VolumeParameterConfig volumeParameterConfig) { magneticConfig = volumeParameterConfig; return this; } public VmTypeMetaBuilder withAutoAttachedConfig(Integer minimumSize, Integer maximumSize, Integer minimumNumber, Integer maximumNumber) { autoAttachedConfig = new VolumeParameterConfig(VolumeParameterType.AUTO_ATTACHED, minimumSize, maximumSize, minimumNumber, maximumNumber); return this; } public VmTypeMetaBuilder withAutoAttachedConfig(VolumeParameterConfig volumeParameterConfig) { autoAttachedConfig = volumeParameterConfig; return this; } public VmTypeMetaBuilder withSsdConfig(Integer minimumSize, Integer maximumSize, Integer minimumNumber, Integer maximumNumber) { ssdConfig = new VolumeParameterConfig(VolumeParameterType.SSD, minimumSize, maximumSize, minimumNumber, maximumNumber); return this; } public VmTypeMetaBuilder withSsdConfig(VolumeParameterConfig volumeParameterConfig) { ssdConfig = volumeParameterConfig; return this; } public VmTypeMetaBuilder withEphemeralConfig(Integer minimumSize, Integer maximumSize, Integer minimumNumber, Integer maximumNumber) { ephemeralConfig = new VolumeParameterConfig(VolumeParameterType.EPHEMERAL, minimumSize, maximumSize, minimumNumber, maximumNumber); return this; } public VmTypeMetaBuilder withEphemeralConfig(VolumeParameterConfig volumeParameterConfig) { ephemeralConfig = volumeParameterConfig; return this; } public VmTypeMetaBuilder withSt1Config(Integer minimumSize, Integer maximumSize, Integer minimumNumber, Integer maximumNumber) { st1Config = new VolumeParameterConfig(VolumeParameterType.ST1, minimumSize, maximumSize, minimumNumber, maximumNumber); return this; } public VmTypeMetaBuilder withSt1Config(VolumeParameterConfig volumeParameterConfig) { st1Config = volumeParameterConfig; return this; } public VmTypeMetaBuilder withProperty(String name, String value) { properties.put(name, value); return this; } public VmTypeMetaBuilder withCpuAndMemory(Integer cpu, Float memory) { properties.put(CPU, cpu.toString()); properties.put(MEMORY, memory.toString()); return this; } public VmTypeMetaBuilder withCpuAndMemory(int cpu, int memory) { properties.put(CPU, String.valueOf(cpu)); properties.put(MEMORY, String.valueOf(memory)); return this; } public VmTypeMetaBuilder withCpuAndMemory(String cpu, String memory) { properties.put(CPU, cpu); properties.put(MEMORY, memory); return this; } public VmTypeMetaBuilder withMaximumPersistentDisksSizeGb(Float maximumPersistentDisksSizeGb) { properties.put(MAXIMUM_PERSISTENT_DISKS_SIZE_GB, maximumPersistentDisksSizeGb.toString()); return this; } public VmTypeMetaBuilder withMaximumPersistentDisksSizeGb(String maximumPersistentDisksSizeGb) { properties.put(MAXIMUM_PERSISTENT_DISKS_SIZE_GB, maximumPersistentDisksSizeGb); return this; } public VmTypeMetaBuilder withPrice(Double price) { properties.put(PRICE, price.toString()); return this; } public VmTypeMeta create() { VmTypeMeta vmTypeMeta = new VmTypeMeta(); vmTypeMeta.setAutoAttachedConfig(autoAttachedConfig); vmTypeMeta.setEphemeralConfig(ephemeralConfig); vmTypeMeta.setMagneticConfig(magneticConfig); vmTypeMeta.setSsdConfig(ssdConfig); vmTypeMeta.setSt1Config(st1Config); vmTypeMeta.setProperties(properties); return vmTypeMeta; } } }
sillyhong/whongjiagou-learn
41.redux/src/redux/bindActionCreators.js
<gh_stars>1-10 export default function bindActionCreators(actions,dispatch){ let newActions = {}; for(let attr in actions){ newActions[attr] = function(){ dispatch(actions[attr].apply(null,arguments)); } } return newActions; }
AndreasKaratzas/stonne
pytorch-frontend/test/cpp/jit/test_interpreter.cpp
<reponame>AndreasKaratzas/stonne<filename>pytorch-frontend/test/cpp/jit/test_interpreter.cpp #include "test/cpp/jit/test_base.h" #include "test/cpp/jit/test_utils.h" #include <stdexcept> namespace torch { namespace jit { void testTypeCheck() { { auto graph = std::make_shared<Graph>(); std::unordered_map<std::string, Value*> vmap; parseIR( R"IR( graph(%a.1 : Tensor, %b.1 : Tensor): %t0 : Float(2:2, 2:1, device=cpu, requires_grad=1), %t1 : Float(3:3, 3:1), %type_matched : bool = prim::TypeCheck(%a.1, %b.1) return (%t0, %t1, %type_matched) )IR", &*graph, vmap); Code function(graph, ""); InterpreterState interp(function); { // TypeCheck yields to true! Shape, grad and device matches. auto a = at::zeros({2, 2}, at::kFloat); auto b = at::ones({3, 3}, at::kFloat); a.set_requires_grad(true); a = a.to(at::kCPU); std::vector<IValue> stack({a, b}); interp.run(stack); ASSERT_TRUE(exactlyEqual(stack[0].toTensor(), a)); ASSERT_TRUE(exactlyEqual(stack[1].toTensor(), b)); ASSERT_TRUE(stack[2].toBool()); } { auto a = at::zeros({2, 2}, at::kFloat); auto b = at::ones({2, 2}, at::kFloat); // Size mismatch a.set_requires_grad(true); a = a.to(at::kCPU); std::vector<IValue> stack({a, b}); interp.run(stack); ASSERT_FALSE(stack[2].toBool()); } { auto a = at::zeros({2, 2}, at::kFloat); auto b = at::ones({3, 3}, at::kFloat); a = a.to(at::kCPU); a.set_requires_grad(false); // Gradient mismatch std::vector<IValue> stack({a, b}); interp.run(stack); ASSERT_FALSE(stack[2].toBool()); } { auto a = at::zeros({2, 2}, at::kFloat); auto b = at::ones({3, 3}, at::kFloat); a = a.to(at::kCPU); a.set_requires_grad(true); a = a.to(at::kInt); // Scalar type mismatch std::vector<IValue> stack({a, b}); interp.run(stack); ASSERT_FALSE(stack[2].toBool()); } { auto a = at::zeros({2, 2}, at::kFloat); auto b = at::ones({3, 3}, at::kFloat); a.set_requires_grad(true); a = a.to(at::kCUDA); // Device mismatch std::vector<IValue> stack({a, b}); interp.run(stack); ASSERT_FALSE(stack[2].toBool()); } } try { // Test empty Typecheck raises an internal assertion auto graph = std::make_shared<Graph>(); std::unordered_map<std::string, Value*> vmap; parseIR( R"IR( graph(%a.1 : Tensor, %b.1 : Tensor): %type_matched : bool = prim::TypeCheck() return (%type_matched) )IR", &*graph, vmap); ASSERT_TRUE(false); } catch (const std::exception& e) { } try { // Test for assertion if num_inputs + 1 != num_outputs auto graph = std::make_shared<Graph>(); std::unordered_map<std::string, Value*> vmap; parseIR( R"IR( graph(%a.1 : Tensor, %b.1 : Tensor): %type_matched : bool = prim::TypeCheck(%a.1) return (%type_matched) )IR", &*graph, vmap); ASSERT_TRUE(false); } catch (const std::exception& e) { } } void testInterp() { constexpr int batch_size = 4; constexpr int input_size = 256; constexpr int seq_len = 32; int hidden_size = 2 * input_size; auto input = at::randn({seq_len, batch_size, input_size}, at::kCUDA); auto hx = at::randn({batch_size, hidden_size}, at::kCUDA); auto cx = at::randn({batch_size, hidden_size}, at::kCUDA); auto w_ih = t_def(at::randn({4 * hidden_size, input_size}, at::kCUDA)); auto w_hh = t_def(at::randn({4 * hidden_size, hidden_size}, at::kCUDA)); auto lstm_g = build_lstm(); Code lstm_function(lstm_g, ""); InterpreterState lstm_interp(lstm_function); auto outputs = run(lstm_interp, {input[0], hx, cx, w_ih, w_hh}); std::tie(hx, cx) = lstm(input[0], hx, cx, w_ih, w_hh); ASSERT_TRUE(exactlyEqual(outputs[0], hx)); ASSERT_TRUE(exactlyEqual(outputs[1], cx)); } } // namespace jit } // namespace torch
pass-by-value/salt
salt/states/pagerduty_escalation_policy.py
# -*- coding: utf-8 -*- ''' Manage PagerDuty escalation policies. Schedules and users can be referenced by pagerduty ID, or by name, or by email address. For example: .. code-block:: yaml ensure test escalation policy: pagerduty_escalation_policy.present: - name: bruce test escalation policy - escalation_rules: - targets: - type: schedule id: 'bruce test schedule level1' - type: user id: 'Bruce Sherrod' escalation_delay_in_minutes: 15 - targets: - type: schedule id: 'bruce test schedule level2' escalation_delay_in_minutes: 15 - targets: - type: user id: 'Bruce TestUser1' - type: user id: 'Bruce TestUser2' - type: user id: 'Bruce TestUser3' - type: user id: '<EMAIL>' escalation_delay_in_minutes: 15 ''' def __virtual__(): ''' Only load if the pygerduty module is available in __salt__ ''' return 'pagerduty_escalation_policy' if 'pagerduty_util.get_resource' in __salt__ else False def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs): ''' Ensure that a pagerduty escalation policy exists. Will create or update as needed. This method accepts as args everything defined in https://developer.pagerduty.com/documentation/rest/escalation_policies/create. In addition, user and schedule id's will be translated from name (or email address) into PagerDuty unique ids. For example: .. code-block:: yaml pagerduty_escalation_policy.present: - name: bruce test escalation policy - escalation_rules: - targets: - type: schedule id: 'bruce test schedule level1' - type: user id: 'Bruce Sherrod' In this example, '<NAME>' will be looked up and replaced with the PagerDuty id (usually a 7 digit all-caps string, e.g. PX6GQL7) ''' # for convenience, we accept id, name, or email for users # and we accept the id or name for schedules for escalation_rule in kwargs['escalation_rules']: for target in escalation_rule['targets']: target_id = None if target['type'] == 'user': user = __salt__['pagerduty_util.get_resource']('users', target['id'], ['email', 'name', 'id'], profile=profile, subdomain=subdomain, api_key=api_key) if user: target_id = user['id'] elif target['type'] == 'schedule': schedule = __salt__['pagerduty_util.get_resource']('schedules', target['id'], ['name', 'id'], profile=profile, subdomain=subdomain, api_key=api_key) if schedule: target_id = schedule['schedule']['id'] if target_id is None: raise Exception('unidentified target: {0}'.format(str(target))) target['id'] = target_id r = __salt__['pagerduty_util.resource_present']('escalation_policies', ['name', 'id'], _diff, profile, subdomain, api_key, **kwargs) return r def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs): ''' Ensure that a PagerDuty escalation policy does not exist. Accepts all the arguments that pagerduty_escalation_policy.present accepts; but ignores all arguments except the name. Name can be the escalation policy id or the escalation policy name. ''' r = __salt__['pagerduty_util.resource_absent']('escalation_policies', ['name', 'id'], profile, subdomain, api_key, **kwargs) return r def _diff(state_data, resource_object): '''helper method to compare salt state info with the PagerDuty API json structure, and determine if we need to update. returns the dict to pass to the PD API to perform the update, or empty dict if no update. ''' objects_differ = None for k, v in state_data.items(): if k == 'escalation_rules': v = _escalation_rules_to_string(v) resource_value = _escalation_rules_to_string(resource_object[k]) else: if k not in resource_object.keys(): objects_differ = True else: resource_value = resource_object[k] if v != resource_value: objects_differ = '{0} {1} {2}'.format(k, v, resource_value) break if objects_differ: return state_data else: return {} def _escalation_rules_to_string(escalation_rules): 'convert escalation_rules dict to a string for comparison' result = '' for rule in escalation_rules: result += 'escalation_delay_in_minutes: {0} '.format(rule['escalation_delay_in_minutes']) for target in rule['targets']: result += '{0}:{1} '.format(target['type'], target['id']) return result
witquicked/fetlife-android
FetLife/fetlife/src/main/java/com/bitlove/fetlife/view/adapter/GroupsRecyclerAdapter.java
<gh_stars>100-1000 package com.bitlove.fetlife.view.adapter; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.bitlove.fetlife.R; import com.bitlove.fetlife.model.pojos.fetlife.db.GroupMembershipReference; import com.bitlove.fetlife.model.pojos.fetlife.db.GroupMembershipReference_Table; import com.bitlove.fetlife.model.pojos.fetlife.dbjson.Group; import com.bitlove.fetlife.model.pojos.fetlife.dbjson.Group_Table; import com.bitlove.fetlife.util.ServerIdUtil; import com.raizlabs.android.dbflow.sql.language.OrderBy; import com.raizlabs.android.dbflow.sql.language.Select; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import androidx.recyclerview.widget.RecyclerView; public class GroupsRecyclerAdapter extends ResourceListRecyclerAdapter<Group, GroupsViewHolder> { private static final String DATE_INTERVAL_SEPARATOR = " - "; private static final String LOCATION_SEPARATOR = " - "; private static final int MAX_DESC_LENGTH = 125; private String memberId; protected List<Group> itemList; public GroupsRecyclerAdapter(String memberId) { this.memberId = memberId; loadItems(); } public void refresh() { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { //TODO: think of possibility of update only specific items instead of the whole list loadItems(); notifyDataSetChanged(); } }); } protected void loadItems() { //TODO: think of moving to separate thread with specific DB executor try { if (ServerIdUtil.isServerId(memberId)) { if (ServerIdUtil.containsServerId(memberId)) { memberId = ServerIdUtil.getLocalId(memberId); } else { return; } } List<GroupMembershipReference> groupMembershipReferences = new Select().from(GroupMembershipReference.class).where(GroupMembershipReference_Table.memberId.is(memberId)).orderBy(OrderBy.fromProperty(GroupMembershipReference_Table.lastVisitedAt).descending()).queryList(); final Map<String,Integer> orderReference = new HashMap<>(); int i = 0; for (GroupMembershipReference membershipReference : groupMembershipReferences) { orderReference.put(membershipReference.getGroupId(),i++); } List<String> groupIds = new ArrayList<>(); for (GroupMembershipReference groupMembershipReference : groupMembershipReferences) { groupIds.add(groupMembershipReference.getGroupId()); } itemList = new Select().from(Group.class).where(Group_Table.id.in(groupIds)).orderBy(OrderBy.fromProperty(Group_Table.name).ascending()).queryList(); Collections.sort(itemList, new Comparator<Group>() { @Override public int compare(Group o1, Group o2) { return orderReference.get(o1.getId()) - orderReference.get(o2.getId()); } }); } catch (Throwable t) { itemList = new ArrayList<>(); } } @Override public GroupsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem_profile_group, parent, false); return new GroupsViewHolder(itemView); } @Override public void onBindViewHolder(GroupsViewHolder holder, int position) { final Group group = itemList.get(position); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onResourceClickListener.onItemClick(group); } }); holder.groupName.setText(group.getName()); String description = group.getHtmlDescription().toString(); // description = StringUtil.parseMarkedHtml(description).toString(); String descPreview = description.substring(0,Math.min(MAX_DESC_LENGTH,description.length())).trim(); holder.groupDescription.setText(descPreview); holder.groupDescription.setVisibility(TextUtils.isEmpty(description) ? View.GONE : View.VISIBLE); String memberCount = holder.itemView.getContext().getString((group.getMemberCount() == 1 ? R.string.text_group_member_count : R.string.text_group_members_count),group.getMemberCount()); holder.groupMemberCount.setText(memberCount); } @Override public int getItemCount() { return itemList.size(); } @Override protected boolean useSwipe() { return false; } @Override protected void onItemRemove(GroupsViewHolder viewHolder, RecyclerView recyclerView, boolean swipedRight) { } } class GroupsViewHolder extends SwipeableViewHolder { TextView groupName, groupDescription, groupMemberCount; public GroupsViewHolder(View itemView) { super(itemView); groupName = (TextView) itemView.findViewById(R.id.group_name); groupDescription = (TextView) itemView.findViewById(R.id.group_description); groupMemberCount = (TextView) itemView.findViewById(R.id.group_member_count); } @Override public View getSwipeableLayout() { return null; } @Override public View getSwipeRightBackground() { return null; } @Override public View getSwipeLeftBackground() { return null; } }
tomhel/AoC_2019
2021/day7/1.py
<reponame>tomhel/AoC_2019 def load(): with open("input") as f: return [int(x) for x in f.read().strip().split(",")] def align_crabs(): crabs = load() min_fuel = None for pos in range(min(crabs), max(crabs) + 1): fuel = sum(abs(c - pos) for c in crabs) min_fuel = fuel if min_fuel is None else min(min_fuel, fuel) return min_fuel print(align_crabs())
narenarjun/learn-scala
book-code/src/script/scala/progscala3/contexts/GivenImports.scala
// tag::O1[] // src/script/scala/progscala3/contexts/GivenImports.scala object O1: val name = "O1" def m(s: String) = s"$s, hello from $name" class C1 class C2 given c1: C1 = C1() given c2: C2 = C2() // end::O1[] // tag::imports[] import O1.* // Import everything EXCEPT the givens, c1 and c2 import O1.given // Import ONLY the givens (of type C1 and C2) import O1.{given, *} // Import everything, givens and nongivens in O1 import O1.{given C1} // Import just the given of type C1 import O1.c2 // Import just the given c2 of type C2 // end::imports[] // tag::O2[] trait Marker[T] object O2: class C1 given C1 = C1() given Marker[Int] with {} // <1> given Marker[List[?]] with {} // <2> import O2.{given Marker[?]} // Import all given Markers import O2.{given Marker[Int]} // Import just the Marker[Int] // end::O2[]
lakeslove/springSourceCodeTest
spring-jms/src/main/java/org/springframework/jms/annotation/package-info.java
<filename>spring-jms/src/main/java/org/springframework/jms/annotation/package-info.java /** * Annotations and support classes for declarative JMS listener endpoints. */ package org.springframework.jms.annotation;
SchrodingersCat00/frontend-rdfa-editor-demo
node_modules/ember-source/dist/dependencies/@glimmer/encoder.js
<gh_stars>0 class InstructionEncoder { constructor(buffer) { this.buffer = buffer; this.typePos = 0; this.size = 0; } encode(type, machine) { if (type > 255 /* TYPE_SIZE */ ) { throw new Error(`Opcode type over 8-bits. Got ${type}.`); } this.buffer.push(type | machine | arguments.length - 2 << 8 /* ARG_SHIFT */ ); this.typePos = this.buffer.length - 1; for (let i = 2; i < arguments.length; i++) { let op = arguments[i]; if (typeof op === 'number' && op > 4294967295 /* MAX_SIZE */ ) { throw new Error(`Operand over 32-bits. Got ${op}.`); } this.buffer.push(op); } this.size = this.buffer.length; } patch(position, target) { if (this.buffer[position + 1] === -1) { this.buffer[position + 1] = target; } else { throw new Error('Trying to patch operand in populated slot instead of a reserved slot.'); } } patchWith(position, target, operand) { if (this.buffer[position + 1] === -1) { this.buffer[position + 1] = target; this.buffer[position + 2] = operand; } else { throw new Error('Trying to patch operand in populated slot instead of a reserved slot.'); } } } export { InstructionEncoder };
opensha/opensha-svn-archive
dev/scratch/martinez/util/Ss2009Tester.java
<filename>dev/scratch/martinez/util/Ss2009Tester.java package scratch.martinez.util; import org.opensha.commons.data.function.ArbitrarilyDiscretizedFunc; import org.opensha.nshmp.sha.calc.SsS1Calculator; import org.opensha.nshmp.util.GlobalConstants; public class Ss2009Tester { //--------------------------------------------------------------------------- // Member Variables //--------------------------------------------------------------------------- //---------------------------- Constant Members ---------------------------// //---------------------------- Static Members ---------------------------// //---------------------------- Instance Members ---------------------------// //--------------------------------------------------------------------------- // Constructors/Initializers //--------------------------------------------------------------------------- public static void main(String [] args) { double latitude = 39.0; double longitude = -105.0; String edition = GlobalConstants.NEHRP_2009; String region = GlobalConstants.CONTER_48_STATES; SsS1Calculator calc = new SsS1Calculator(); ArbitrarilyDiscretizedFunc func = calc.getSsS1(region, edition, latitude, longitude); System.out.println(func.getInfo()); } //--------------------------------------------------------------------------- // Public Methods //--------------------------------------------------------------------------- //------------------------- Public Setter Methods ------------------------// //------------------------- Public Getter Methods ------------------------// //------------------------- Public Utility Methods ------------------------// //--------------------------------------------------------------------------- // Private Methods //--------------------------------------------------------------------------- }
cocoatomo/asakusafw
mapreduce/compiler/core/src/main/java/com/asakusafw/compiler/flow/stage/CompiledReduce.java
<gh_stars>0 /** * Copyright 2011-2017 Asakusa Framework Team. * * 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.asakusafw.compiler.flow.stage; import com.asakusafw.compiler.common.Precondition; /** * Represents a compiled reduce actions. */ public class CompiledReduce { private final CompiledType reducerType; private final CompiledType combinerTypeOrNull; /** * Creates a new instance. * @param reducerType the target reducer type * @param combinerTypeOrNull the target combiner type (nullable) * @throws IllegalArgumentException if the parameters are {@code null} */ public CompiledReduce(CompiledType reducerType, CompiledType combinerTypeOrNull) { Precondition.checkMustNotBeNull(reducerType, "reducerType"); //$NON-NLS-1$ this.reducerType = reducerType; this.combinerTypeOrNull = combinerTypeOrNull; } /** * Returns the target reducer type. * @return the target reducer type */ public CompiledType getReducerType() { return reducerType; } /** * Returns the target combiner type. * @return the target combiner type, or {@code null} if this does not use combiner */ public CompiledType getCombinerTypeOrNull() { return combinerTypeOrNull; } }
WooDzu/PhalconEye
public/external/pydio/plugins/access.ajxp_user/class.UserProfileEditor.js
/* * Copyright 2007-2013 <NAME> - Abstrium SAS <team (at) pyd.io> * This file is part of Pydio. * * Pydio is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pydio 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Pydio. If not, see <http://www.gnu.org/licenses/>. * * The latest code can be found at <http://pyd.io/>. * */ Class.create("UserProfileEditor", AjxpPane, { _formManager: null, initialize: function($super, oFormObject, editorOptions){ $super(oFormObject, editorOptions); if(ajaxplorer.actionBar.getActionByName('custom_data_edit')){ this._formManager = new FormManager(); var definitions = this._formManager.parseParameters(ajaxplorer.getXmlRegistry(), "user/preferences/pref[@exposed='true']|//param[contains(@scope,'user') and @expose='true']"); this._formManager.createParametersInputs(oFormObject.down('#user_profile_form'), definitions, true, ajaxplorer.user.preferences, false, true); this._formManager.disableShortcutsOnForm(oFormObject.down('#user_profile_form')); var saveButton = new Element('a', {}).update('<span class="icon-save"></span> <span>'+MessageHash[53]+'</span>'); oFormObject.down('.toolbarGroup').insert({top: saveButton}); saveButton.observe("click", function(){ var params = $H(); this._formManager.serializeParametersInputs(oFormObject.down('#user_profile_form'), params, 'PREFERENCES_'); var conn = new Connexion(); params.set("get_action", "custom_data_edit"); conn.setParameters(params); conn.setMethod("POST"); conn.onComplete = function(transport){ ajaxplorer.actionBar.parseXmlMessage(transport.responseXML); document.observeOnce("ajaxplorer:registry_part_loaded", function(event){ if(event.memo != "user/preferences") return; ajaxplorer.logXmlUser(ajaxplorer.getXmlRegistry()); }); ajaxplorer.loadXmlRegistry(false, "user/preferences"); }; conn.sendAsync(); }.bind(this)); fitHeightToBottom(oFormObject); fitHeightToBottom(oFormObject.down('#user_profile_form')); oFormObject.down('#user_profile_form').setStyle({overflow:'auto'}); } if(ajaxplorer.actionBar.getActionByName('pass_change')){ var chPassButton = new Element('a', {className:''}).update('<span class="icon-key"></span> <span>'+MessageHash[194]+'</span>'); oFormObject.down('.toolbarGroup').insert(chPassButton); chPassButton.observe("click", function(){ ajaxplorer.actionBar.getActionByName('pass_change').apply(); }); } }, resize: function(size){ fitHeightToBottom(this.htmlElement.down('#user_profile_form')); } });
DeltaV235/Learning-notes
18-springboot/tutorial/spring-boot-04-web-war/src/test/java/com/wuyue/springboot04webwar/SpringBoot04WebWarApplicationTests.java
<gh_stars>0 package com.wuyue.springboot04webwar; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SpringBoot04WebWarApplicationTests { @Test void contextLoads() { } }
a4-data/a4-UI-EXT
packages/ext-web-components-kitchensink/src/view/d3/hierarchy/pack/PackComponent.js
import './PackComponent.html'; export default class PackComponent { onTooltip = (component, tooltip, node) => { const record = node.data, size = record.get('size'), n = record.childNodes.length; let html = '<span style="font-weight: bold">' + record.get('text') + '</span><br>'; if (size) { html += Ext.util.Format.fileSize(size); } else { html += n + ' file' + (n === 1 ? '' : 's') + ' inside.'; } tooltip.setHtml(html); } d3onReady = (event) => { const store = Ext.create('Ext.data.TreeStore', { autoLoad: true, defaultRootText: 'd3', fields: [ 'name', 'path', 'size', { name: 'leaf', calculate: function(data) { return data.root ? false : !data.children; } }, { name: 'text', calculate: function(data) { return data.name; } } ], proxy: { type: 'ajax', url: 'resources/data/tree/tree.json' }, idProperty: 'path' }); this.d3Cmp = event.detail.cmp; this.d3Cmp.setStore(store); this.d3Cmp.setTooltip({ renderer: this.onTooltip.bind(this) }); } }
pricetula/react-coolcat
src/common/api/post/user.js
/* eslint-disable import/no-extraneous-dependencies */ import Promise from 'promise'; import axiosInstance from '../instance'; export const postUserSignin = ( { email, password, }, ) => new Promise( ( resolve, reject, ) => { axiosInstance.post( '/user/signin', { email, password, }, ) .then( resolve, ) .catch( reject, ); }, ); export const postUserSignup = ( { firstName, lastName, email, password, }, ) => new Promise( ( resolve, reject, ) => { axiosInstance.post( '/user/signup', { firstName, lastName, email, password, }, ) .then( resolve, ) .catch( reject, ); }, );
HIOTio/original_HIOT
platform/server/routes/sensor_types.js
<gh_stars>0 var express = require('express') var router = express.Router() var sensorTypesController = require('../controllers/sensor_types') router.get('/', sensorTypesController.sensor_types_list) router.get('/:id', sensorTypesController.sensor_types_detail) router.post('/', sensorTypesController.sensor_types_create) router.delete('/', sensorTypesController.sensor_types_delete) router.put('/', sensorTypesController.sensor_types_update) module.exports = router
abel-navarro/midonet
brain/midonet-brain/src/main/java/org/midonet/brain/southbound/vtep/VtepMAC.java
/* * Copyright 2014 Midokura SARL * * 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.midonet.brain.southbound.vtep; import com.google.common.base.Objects; import org.midonet.packets.Ethernet; import org.midonet.packets.MAC; /** * A wrapper over the IEEE 802 MAC that supports the unknown-dst wildcard used * by the OVSDB VTEP schema. */ public final class VtepMAC { /** * This constant is defined in the OVSDB spec for the VTEP schema, it is * used to designate a "unknown-dst" mac in mcast_remote tables. Refer to * http://openvswitch.org/docs/vtep.5.pdf for further details. */ private static final String S_UNKNOWN_DST = "unknown-dst"; public static VtepMAC UNKNOWN_DST = new VtepMAC(); public static VtepMAC fromString(String s) { return S_UNKNOWN_DST.equals(s) ? UNKNOWN_DST : new VtepMAC(s); } public static VtepMAC fromMac(MAC m) { return new VtepMAC(m); } private final MAC mac; // null means UNKNOWN-DST private VtepMAC() { this.mac = null; } private VtepMAC(String mac) { this.mac = MAC.fromString(mac); } private VtepMAC(final MAC mac) { this.mac = mac; } public boolean isMcast() { return mac == null || Ethernet.isMcast(mac); } public boolean isUcast() { return mac != null && mac.unicast(); } @Override public String toString() { return mac == null ? S_UNKNOWN_DST : mac.toString(); } @Override public int hashCode() { return mac == null ? 0 : mac.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VtepMAC that = (VtepMAC) o; return Objects.equal(this.mac, that.mac); } /** * Returns an IEEE 802 representation of the MAC, or null when the wrapped * MAC is the VTEP's non-standard unknown-dst wildcard. */ public MAC IEEE802() { return mac; } public boolean isIEEE802() { return this != UNKNOWN_DST; } }
pbaun/rere
modules/sasl/src/main/scala/rere/sasl/util/SafeString.scala
package rere.sasl.util import scala.annotation.switch /** * String without ',' that can be safely sent as value in attr-val pair */ sealed trait SafeString /** * Escaped string without ',' and NUL. ',' and '=' replaced with "=2C" and "=3D". * @param str - representation */ final class EscapedString private[sasl](private[sasl] val str: String) extends SafeString { override def equals(obj: Any): Boolean = { obj match { case that: EscapedString => EscapedString.from(this) == EscapedString.from(that) case _ => false } } override def hashCode(): Int = EscapedString.from(this).hashCode() override def toString: String = EscapedString.from(this) } object EscapedString { private val expectedExpansion = 1.2 def to(str: String): EscapedString = { val builder = new StringBuilder((str.length * expectedExpansion).toInt) str foreach { case ',' => builder.append("=2C") case '=' => builder.append("=3D") case ch => builder.append(ch) } new EscapedString(builder.toString()) } def from(safe: EscapedString): String = { val s = safe.str val builder = new StringBuilder(s.length) val end = s.length - 2 var i = 0 while(i < end) { val ch1 = s.charAt(i) if (ch1 == '=') { val ch2 = s.charAt(i + 1) (ch2: @switch) match { case '2' => val ch3 = s.charAt(i + 2) if (ch3 == 'C' || ch3 == 'c') { builder.append(',') i += 3 } else { throw new IllegalArgumentException(s"Invalid character sequence: '$ch1$ch2$ch3'") } case '3' => val ch3 = s.charAt(i + 2) if (ch3 == 'D' || ch3 == 'd') { builder.append('=') i += 3 } else { throw new IllegalArgumentException(s"Invalid character sequence: '$ch1$ch2$ch3'") } case _ => throw new IllegalArgumentException(s"Invalid character sequence: '$ch1$ch2'") } } else { builder.append(ch1) i += 1 } } while(i < s.length) { builder.append(s.charAt(i)) i += 1 } builder.toString() } } /** * String without comma * @param str - representation */ final class NoCommaString private[sasl](private[sasl] val str: String) extends SafeString { override def equals(obj: Any): Boolean = { obj match { case that: NoCommaString => this.str == that.str case _ => false } } override def hashCode(): Int = str.hashCode() override def toString: String = str } /** * String with only printable chars and without commas */ sealed trait PrintableAndSafe extends SafeString /** * Naive implementation of string with only printable chars and without commas * @param str - representation */ final class PrintableString private[sasl](private[sasl] val str: String) extends PrintableAndSafe { override def equals(obj: Any): Boolean = { obj match { case that: PrintableString => this.str == that.str case _ => false } } override def hashCode(): Int = str.hashCode() override def toString: String = str } object PrintableString { private[rere] def apply(str: String): PrintableString = { val filtered = str.filter { char => ('\u0021' <= char && char <= '\u002b') || ('\u002d' <= char && char <= '\u007e') } new PrintableString(filtered) } } /** * Base64 encoded string. Also with only printable chars and without commas * @param str - representation */ final class Base64String private[sasl](private[sasl] val str: String) extends PrintableAndSafe { override def equals(obj: Any): Boolean = { obj match { case that: Base64String => this.str == that.str case _ => false } } override def hashCode(): Int = str.hashCode() override def toString: String = str }
mrfengyong/code-set
src/main/java/com/feyon/codeset/exception/CodeSetException.java
package com.feyon.codeset.exception; /** * @author <NAME> */ public class CodeSetException extends RuntimeException { public CodeSetException() { } public CodeSetException(String message) { super(message); } public CodeSetException(String message, Throwable cause) { super(message, cause); } }
penghaiYin/bm-work-2020
server/src/main/java/edp/core/utils/DateUtils.java
<reponame>penghaiYin/bm-work-2020 package edp.core.utils; import com.alibaba.druid.util.StringUtils; import org.joda.time.DateTime; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DateUtils { public static final String DATE_BASE_REGEX = "\\d{4}-\\d{1,2}-\\d{1,2}"; public static final String SEPARATOR_REGEX = "(T?|\\s*)"; public static final String DATE_REGEX = "^\\s*" + DATE_BASE_REGEX + "\\s*$"; public static final String DATE_H_REGEX = "^\\s*" + DATE_BASE_REGEX + SEPARATOR_REGEX + "\\d\\d\\s*$"; public static final String DATE_HM_REGEX = "^\\s*" + DATE_BASE_REGEX + SEPARATOR_REGEX + "\\d{1,2}:\\dd{1,2}\\s*$"; public static final String DATE_HMS_REGEX = "^\\s*" + DATE_BASE_REGEX + SEPARATOR_REGEX + "\\d{1,2}:\\d{1,2}:\\d{1,2}\\s*$"; public static final String DATE_HMS_M_REGEX = "^\\s*" + DATE_BASE_REGEX + SEPARATOR_REGEX + "\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}\\s*$"; private enum DATE_FORMAT_ENUM { DATE(Pattern.compile(DATE_REGEX), "yyyy-M-d"), DATE_H(Pattern.compile(DATE_H_REGEX), "yyyy-M-d H"), DATE_HM(Pattern.compile(DATE_HM_REGEX), "yyyy-M-d H:m"), DATE_HMS(Pattern.compile(DATE_HMS_REGEX), "yyyy-M-d H:m:s"), DATE_HMS_M(Pattern.compile(DATE_HMS_M_REGEX), "yyyy-M-d H:m:s.SSS"); private Pattern pattern; private String format; DATE_FORMAT_ENUM(Pattern pattern, String format) { this.pattern = pattern; this.format = format; } static Date formatDate(String timeString) throws Exception { timeString = prepare(timeString); for (DATE_FORMAT_ENUM formatEnum : values()) { Matcher matcher = formatEnum.pattern.matcher(timeString); if (matcher.find()) { SimpleDateFormat sdf = new SimpleDateFormat(formatEnum.format); return sdf.parse(timeString); } } throw new Exception("Unparseable date: " + timeString); } private static String prepare(String timeString) { String s = null; if (!StringUtils.isEmpty(timeString)) { if (timeString.contains("-")) { s = timeString; } else if (timeString.contains("/")) { s = timeString.replaceAll("[/]", "-"); } else { s = timeString.substring(0, 4) + "-" + timeString.substring(4, 6) + "-" + timeString.substring(6); } int dotStart = s.indexOf(".") + 1; boolean hasDot = dotStart > 0; int msLength = dotStart + 3; int overMsLength = s.length() - msLength; int lessMsLength = msLength - s.length(); if (hasDot && overMsLength >= 0) { return s.substring(0, s.length() - overMsLength); } else if (hasDot && lessMsLength >= 0) { for (int i = 0; i < lessMsLength; i++) { s += "0"; } return s; } if (hasDot) { s += ".000"; } } return s; } } public static Date currentData() { return new Date(); } public static long getNowMilliSecondTime() { return currentData().getTime(); } public static String getNowDateYYYYMM() { SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM"); return formatter.format(currentData()); } public static String getNowDateYYYYMMDD() { SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); return formatter.format(currentData()); } public static String getTheDayBeforNowDateYYYYMMDD() { SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); Calendar calendar = Calendar.getInstance(); calendar.setTime(currentData()); calendar.add(Calendar.DAY_OF_MONTH, -1); return formatter.format(calendar.getTime()); } public static String getTheDayBeforAWeekYYYYMMDD() { SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); Calendar calendar = Calendar.getInstance(); calendar.setTime(currentData()); calendar.add(Calendar.DAY_OF_MONTH, -7); return formatter.format(calendar.getTime()); } public static String getNowDateFormatCustom(String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); return formatter.format(currentData()); } public static long getNowDaySecondTime0() { Calendar c = Calendar.getInstance(); Date d = currentData(); c.setTime(d); c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), 0, 0, 0); return c.getTime().getTime() / 1000; } public static int getDayOfMonth() { Calendar now = Calendar.getInstance(); return now.get(Calendar.DAY_OF_MONTH); } public static String toyyyyMMddHHmmss(long currentTime) { Date date = new Date(currentTime); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String timeStr = sdf.format(date); return timeStr; } public static String toyyyyMMddHHmmss(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String timeStr = sdf.format(date); return timeStr; } public static Date getUtilDate(String date, String formatter) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(formatter); return sdf.parse(date); } public static long getOldTime(int unitCount, int unit) { Calendar c = Calendar.getInstance(); c.add(unit, -unitCount); return c.getTimeInMillis(); } public static Date toDate(String timeString) throws Exception { if (StringUtils.isEmpty(timeString)) { return null; } return DATE_FORMAT_ENUM.formatDate(timeString); } public static Date toDate(DateTime dateTime) { if (null == dateTime) { return null; } return dateTime.toDate(); } public static Date toDate(Timestamp timestamp) { if (null == timestamp) { return null; } return new Date(timestamp.getTime()); } public static DateTime toDateTime(Date date) { if (null == date) { return null; } return new DateTime(date); } public static DateTime toDateTime(Long timeLongInMicros) { if (null == timeLongInMicros || timeLongInMicros.longValue() == 0L) { return null; } return toDateTime(new Date(timeLongInMicros)); } public static DateTime toDateTime(String timeString) throws Exception { if (StringUtils.isEmpty(timeString)) { return null; } return toDateTime(toDate(timeString)); } public static Timestamp toTimestamp(Date date) { if (null == date) { return null; } return new Timestamp(date.getTime()); } public static Timestamp toTimestamp(Long timeLongInMicros) { if (null == timeLongInMicros || timeLongInMicros.longValue() == 0L) { return null; } return toTimestamp(new Date(timeLongInMicros)); } public static Timestamp toTimestamp(String timeString) throws Exception { if (StringUtils.isEmpty(timeString)) { return null; } return toTimestamp(toDate(timeString)); } public static DateTime toDateTime(Timestamp timestamp) throws Exception { if (null == timestamp) { return null; } return toDateTime(toDate(timestamp)); } public static Timestamp toTimestamp(DateTime dateTime) throws Exception { if (null == dateTime) { return null; } return toTimestamp(toDate(dateTime)); } public static Long toLong(Date date) { if (null == date) { return null; } return date.getTime() * 1000; } public static Long toLong(String timeString) throws Exception { if (null == timeString) { return null; } return toLong(toDate(timeString)); } public static Long toLong(DateTime dateTime) throws Exception { if (null == dateTime) { return null; } return toLong(toDate(dateTime)); } public static Long toLong(Timestamp timestamp) throws Exception { if (null == timestamp) { return null; } return toLong(toDate(timestamp)); } public static java.sql.Date toSqlDate(Date date) { if (null == date) { return null; } return new java.sql.Date(date.getTime()); } public static java.sql.Date toSqlDate(DateTime dateTime) { if (null == dateTime) { return null; } return new java.sql.Date(toDate(dateTime).getTime()); } public static java.sql.Date toSqlDate(Long timeLongInMicros) { if (null == timeLongInMicros || timeLongInMicros.longValue() == 0L) { return null; } return toSqlDate(new Date(timeLongInMicros)); } }
AbhinavMehrotra/SenSocial-Library
SenSocial/src/com/ubhave/sensocial/manager/Stream.java
/******************************************************************************* * * SenSocial Middleware * * Copyright (c) ${2014}, University of Birmingham * <NAME>, <EMAIL> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Birmingham * nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *******************************************************************************/ package com.ubhave.sensocial.manager; import java.util.ArrayList; import java.util.UUID; import android.content.Context; import android.util.Log; import com.ubhave.sensocial.exceptions.PPDException; import com.ubhave.sensocial.exceptions.SensorDataTypeException; import com.ubhave.sensocial.filters.Condition; import com.ubhave.sensocial.filters.ConfigurationHandler; import com.ubhave.sensocial.filters.Filter; import com.ubhave.sensocial.filters.FilterSettings; import com.ubhave.sensocial.filters.ModalityType; import com.ubhave.sensocial.sensormanager.SensorUtils; /** * Stream class can be used to instantiate the stream of sensor data on device */ public class Stream { private int sensorId; private String streamId; private String dataType; private Context context; private Filter filter; private final String TAG = "SNnMB"; /** * Constructor * @param StringsensorId * @param String dataType * @param Context Appplication context * @throws PPDException * @throws SensorDataTypeException */ protected Stream(int sensorId, String dataType, Context context) throws PPDException,SensorDataTypeException{ this.sensorId=sensorId; this.dataType=dataType; this.context=context; this.filter=null; this.streamId=UUID.randomUUID().toString(); //check PPD for the sensors associated to stream // PrivacyPolicyDescriptorParser ppd= new PrivacyPolicyDescriptorParser(context); // if(dataType.equalsIgnoreCase("raw")){ // if(!ppd.isAllowed(new AllPullSensors(context).getSensorNameById(sensorId).toLowerCase(), null, "raw")){ // throw new PPDException(new AllPullSensors(context).getSensorNameById(sensorId)); // } // }else if(dataType.equalsIgnoreCase("classified")){ // if(!ppd.isAllowed(new AllPullSensors(context).getSensorNameById(sensorId).toLowerCase(), null, "raw") || // !ppd.isAllowed(new AllPullSensors(context).getSensorNameById(sensorId), null, "classified")){ // throw new PPDException(new AllPullSensors(context).getSensorNameById(sensorId)); // } // } // else{ // throw new SensorDataTypeException(dataType); // } } /** * Sets filter on stream and returns new stream with the filter * @return Stream object * @throws PPDException If there exists any activity of which the associated sensor * (or SensorData from this sensor on client) is not declared in PPD. */ public Stream setFilter(Filter filter) throws PPDException{ Stream newStream; try { newStream = new Stream(this.sensorId, this.dataType, this.context); Log.i("SNnMB","Filter set & stream id is: "+ newStream.getStreamId()); newStream.filter=filter; } catch (SensorDataTypeException e) { newStream=this; Log.e(TAG, "Something went wrong while creating a new stream"); } return newStream; } /** * Getter for sensor-id * @return String sensor-id */ public int getSensorId() { return sensorId; } /** * Getter for stream-id * @return String stream-id */ public String getStreamId() { return streamId; } /** * Getter for stream's required data type * @return String data-type */ public String getDataType() { return dataType; } /** * Getter for filter * @return Filter object */ public Filter getFilter(){ return (this.filter); } /** * Starts the stream */ public void startStream(){ Log.e(TAG, "Start stream: "+ getStreamId()); if(this.getFilter()==null){ Log.e(TAG, "Filter is null"); ArrayList<Condition> conditions= new ArrayList<Condition>(); conditions.add(new Condition(ModalityType.null_condition, "", "")); GenerateFilter.createXML(context,conditions, this.getStreamId(), new SensorUtils(context).getSensorNameById(this.sensorId), dataType); } else{ Log.e(TAG, "Filter present"); ArrayList<Condition> conditions=new ArrayList<Condition>(); conditions=this.getFilter().getConditions(); //check PPD for the sensors associated to activities // PrivacyPolicyDescriptorParser ppd= new PrivacyPolicyDescriptorParser(context); // for(int i=0;i<activities.size();i++){ // if(!ppd.isAllowed(activities.get(i).getSensorName(), null, "classified")){ // throw new PPDException(activities.get(i).getSensorName()); // } // } GenerateFilter.createXML(context, conditions, getStreamId(), new SensorUtils(context).getSensorNameById(this.sensorId), dataType); } FilterSettings.startConfiguration(getStreamId()); ConfigurationHandler.run(context); } /** * Pauses the stream */ public void pauseStream(){ Log.e(TAG, "Pause stream: "+ getStreamId()); FilterSettings.stopConfiguration(this.getStreamId()); ConfigurationHandler.run(context); } /** * Unpauses the stream */ public void unpauseStream(){ Log.e(TAG, "Unpause stream: "+ getStreamId()); FilterSettings.startConfiguration(this.getStreamId()); ConfigurationHandler.run(context); } }
r3c/tesca
src/provision/reader/line/csv.hpp
#ifndef __TESCA_PROVISION_READER_LINE_CSV_HPP #define __TESCA_PROVISION_READER_LINE_CSV_HPP #include <cstdlib> #include <functional> #include <vector> #include "../../../storage/config.hpp" #include "../../row/array.hpp" #include "../../lookup.hpp" #include "../line.hpp" namespace Tesca { namespace Provision { class CSVLineReader : public LineReader { public: CSVLineReader (CSVLineReader const&); CSVLineReader (Glay::Pipe::SeekIStream*, Lookup const&, Storage::Config const&); CSVLineReader& operator = (CSVLineReader const&); virtual Row const& current () const; protected: virtual bool parse (const char*, Glay::Size); private: typedef std::function<void (Glay::Int32u, const char*, Glay::Size)> Callback; typedef std::vector<Glay::Int32u> Mapping; void split (const char*, Glay::Size, Callback); Mapping mapping; ArrayRow row; char* types; }; } } #endif
ericatsydney/mybabyjournal
resources/assets/js/components/app/NavigationMenu.js
<filename>resources/assets/js/components/app/NavigationMenu.js import React, { Component } from 'react' import { Link } from 'react-router' class NavMenu extends Component { render() { return ( <div className="nav-menu"> <Link className="brand-logo" to="#">My Baby Journal</Link> <Link to="#" data-activates="mobile-demo" className="button-collapse"><i className="material-icons">menu</i></Link> <ul id="nav-mobile" className="right hide-on-med-and-down"> <li> <Link to="/profiles">Profiles</Link> </li> <li> <Link to="/moments">Albums</Link> </li> </ul> <ul className="side-nav" id="mobile-demo"> <li><a href="sass.html">Sass</a></li> <li><a href="badges.html">Components</a></li> <li><a href="collapsible.html">Javascript</a></li> <li><a href="mobile.html">Mobile</a></li> </ul> </div> ) } } export default NavMenu
jdacosta/remindme
gulpfile.js/tasks/clean.js
<gh_stars>0 var del = require('del'); var gulp = require('gulp'); var config = require('../config'); var icons = require('../config/icons'); gulp.task('clean', function (callback) { del([ config.publicDirectory, config.serverDirectory, icons.sassDest ], callback); });
nightskylark/DevExtreme
js/viz/docs/docpiechartseries.js
/** * @name dxPieChartSeriesTypes * @publicName dxPieChartSeriesTypes * @type object */ /** * @name dxPieChartSeriesTypes_CommonPieChartSeries * @publicName CommonPieChartSeries * @type object * @hidden */ var commonPieChartSeries = { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_color * @publicName color * @type string * @default undefined */ color: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_minsegmentsize * @publicName minSegmentSize * @type number * @default undefined */ minSegmentSize: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_smallvaluesgrouping * @publicName smallValuesGrouping * @type object */ smallValuesGrouping: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_smallvaluesgrouping_mode * @publicName mode * @type Enums.SmallValuesGroupingMode * @default 'none' */ mode: 'none', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_smallvaluesgrouping_topcount * @publicName topCount * @type number * @default undefined */ topCount: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_smallvaluesgrouping_threshold * @publicName threshold * @type number * @default undefined */ threshold: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_smallvaluesgrouping_groupname * @publicName groupName * @type string * @default 'others' */ groupName: 'others', }, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_valuefield * @publicName valueField * @type string * @default 'val' */ valueField: 'val', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_argumentfield * @publicName argumentField * @type string * @default 'arg' */ argumentField: 'arg', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_argumentType * @publicName argumentType * @type Enums.ChartDataType * @default undefined */ argumentType: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_tagfield * @publicName tagField * @type string * @default 'tag' */ tagField: 'tag', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_border * @publicName border * @type object */ border: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_border_visible * @publicName visible * @type boolean * @default false */ visible: false, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_border_width * @publicName width * @type number * @default 2 */ width: 2, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_border_color * @publicName color * @type string * @default undefined */ color: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_border_dashstyle * @publicName dashStyle * @type Enums.DashStyle * @default undefined */ dashStyle: undefined }, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hovermode * @publicName hoverMode * @type Enums.PieChartSeriesInteractionMode * @default 'onlyPoint' */ hoverMode: 'onlyPoint', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionmode * @publicName selectionMode * @type Enums.PieChartSeriesInteractionMode * @default 'onlyPoint' */ selectionMode: 'onlyPoint', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle * @publicName hoverStyle * @type object */ hoverStyle: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle_color * @publicName color * @type string * @default undefined */ color: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle_hatching * @publicName hatching * @type object */ hatching: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle_hatching_direction * @publicName direction * @type Enums.HatchingDirection * @default 'right' */ direction: 'right', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle_hatching_width * @publicName width * @type number * @default 4 */ width: 4, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle_hatching_step * @publicName step * @type number * @default 10 */ step: 10, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle_hatching_opacity * @publicName opacity * @type number * @default 0.75 */ opacity: 0.75 }, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle_border * @publicName border * @type object */ border: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle_border_visible * @publicName visible * @type boolean * @default false */ visible: false, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle_border_width * @publicName width * @type number * @default 3 */ width: 3, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle_border_color * @publicName color * @type string * @default undefined */ color: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_hoverstyle_border_dashstyle * @publicName dashStyle * @type Enums.DashStyle * @default undefined */ dashStyle: undefined } }, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle * @publicName selectionStyle * @type object */ selectionStyle: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle_color * @publicName color * @type string * @default undefined */ color: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle_hatching * @publicName hatching * @type object */ hatching: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle_hatching_direction * @publicName direction * @type Enums.HatchingDirection * @default 'right' */ direction: 'right', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle_hatching_width * @publicName width * @type number * @default 4 */ width: 4, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle_hatching_step * @publicName step * @type number * @default 10 */ step: 10, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle_hatching_opacity * @publicName opacity * @type number * @default 0.5 */ opacity: 0.5 }, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle_border * @publicName border * @type object */ border: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle_border_visible * @publicName visible * @type boolean * @default false */ visible: false, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle_border_width * @publicName width * @type number * @default 3 */ width: 3, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle_border_color * @publicName color * @type string * @default undefined */ color: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_selectionstyle_border_dashstyle * @publicName dashStyle * @type Enums.DashStyle * @default undefined */ dashStyle: undefined } }, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_maxlabelcount * @publicName maxLabelCount * @type number * @default undefined */ maxLabelCount: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_segmentsdirection * @publicName segmentsDirection * @type Enums.PieChartSegmentsDirection * @default 'clockwise' * @deprecated dxpiechartoptions_segmentsdirection */ segmentsDirection: 'clockwise', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_startangle * @publicName startAngle * @type number * @default 0 * @deprecated dxpiechartoptions_startangle */ startAngle: 0, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_innerradius * @publicName innerRadius * @type number * @default 0.5 * @propertyOf dxPieChartSeriesTypes_DoughnutSeries * @deprecated dxpiechartoptions_innerradius */ innerRadius: 0.5, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label * @publicName label * @type object */ label: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_customizetext * @publicName customizeText * @type function(pointInfo) * @type_function_param1 pointInfo:object * @type_function_return string * @notUsedInTheme */ customizeText: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_visible * @publicName visible * @type boolean * @default false */ visible: false, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_rotationangle * @publicName rotationAngle * @type number * @default 0 */ rotationAngle: 0, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_radialoffset * @publicName radialOffset * @type number * @default 0 */ radialOffset: 0, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_format * @publicName format * @extends CommonVizFormat */ format: '', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_precision * @publicName precision * @extends CommonVizPrecision */ precision: 0, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_argumentFormat * @publicName argumentFormat * @extends CommonVizFormat */ argumentFormat: '', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_argumentprecision * @publicName argumentPrecision * @extends CommonVizPrecision * @deprecated */ argumentPrecision: 0, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_percentprecision * @publicName percentPrecision * @extends CommonVizPrecision * @deprecated */ percentPrecision: 0, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_position * @publicName position * @type Enums.PieChartLabelPosition * @default 'outside' */ position: 'outside', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_font * @publicName font * @type object */ font: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_font_family * @publicName family * @type string * @default "'Segoe UI', 'Helvetica Neue', 'Trebuchet MS', Verdana" */ family: "'Segoe UI', 'Helvetica Neue', 'Trebuchet MS', Verdana", /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_font_weight * @publicName weight * @type number * @default 400 */ weight: 400, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_font_color * @publicName color * @type string * @default '#FFFFFF' */ color: '#FFFFFF', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_font_size * @publicName size * @type number|string * @default 14 */ size: 14, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_font_opacity * @publicName opacity * @type number * @default undefined */ opacity: undefined }, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_backgroundcolor * @publicName backgroundColor * @type string * @default undefined */ backgroundColor: undefined, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_border * @publicName border * @type object */ border: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_border_visible * @publicName visible * @type boolean * @default false */ visible: false, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_border_width * @publicName width * @type number * @default 1 */ width: 1, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_border_color * @publicName color * @type string * @default '#d3d3d3' */ color: '#d3d3d3', /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_border_dashstyle * @publicName dashStyle * @type Enums.DashStyle * @default 'solid' */ dashStyle: 'solid' }, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_connector * @publicName connector * @type object */ connector: { /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_connector_visible * @publicName visible * @type boolean * @default false */ visible: false, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_connector_width * @publicName width * @type number * @default 1 */ width: 1, /** * @name dxPieChartSeriesTypes_CommonPieChartSeries_label_connector_color * @publicName color * @type string * @default undefined */ color: undefined } } }; /** * @name dxPieChartSeriesTypes_DoughnutSeries * @publicName DoughnutSeries * @type object * @inherits dxPieChartSeriesTypes_CommonPieChartSeries * @hidePropertyOf */ var doughnutSeries = { }; /** * @name dxPieChartSeriesTypes_PieSeries * @publicName PieSeries * @type object * @inherits dxPieChartSeriesTypes_CommonPieChartSeries * @hidePropertyOf */ var pieSeries = { };
KittyMcMitty/spiritumDuoDocker
pseudotie/src/placeholder_data/__init__.py
from .placeholder_data import getTestResultFromCharacteristics
eventstorm-projects/eventstorm
eventstorm-sql-spring/src/test/java/eu/eventstorm/sql/spring/ex001/AbstractStudentRepository.java
<reponame>eventstorm-projects/eventstorm package eu.eventstorm.sql.spring.ex001; import static eu.eventstorm.sql.expression.Expressions.eq; import static eu.eventstorm.sql.spring.ex001.StudentDescriptor.ALL; import static eu.eventstorm.sql.spring.ex001.StudentDescriptor.CODE; import static eu.eventstorm.sql.spring.ex001.StudentDescriptor.COLUMNS; import static eu.eventstorm.sql.spring.ex001.StudentDescriptor.ID; import static eu.eventstorm.sql.spring.ex001.StudentDescriptor.IDS; import static eu.eventstorm.sql.spring.ex001.StudentDescriptor.TABLE; import eu.eventstorm.sql.SqlQuery; public abstract class AbstractStudentRepository extends eu.eventstorm.sql.Repository { public static final eu.eventstorm.sql.jdbc.Mapper<Student> STUDENT = new StudentMapper(); private final SqlQuery findById; private final SqlQuery findByBusinessKey; private final SqlQuery findByIdForUpdate; private final SqlQuery insert; private final SqlQuery update; protected AbstractStudentRepository(eu.eventstorm.sql.Database database) { super(database); this.findById = select(ALL).from(TABLE).where(eq(ID)).build(); this.findByIdForUpdate = select(ALL).from(TABLE).where(eq(ID)).forUpdate().build(); this.findByBusinessKey = select(ALL).from(TABLE).where(eq(CODE)).build(); this.insert = insert(TABLE, IDS, COLUMNS).build(); this.update = update(TABLE, COLUMNS, IDS).build(); } public final eu.eventstorm.sql.spring.ex001.Student findById(int id) { return executeSelect(this.findById, ps -> { ps.setInt(1, id); },STUDENT); } public final eu.eventstorm.sql.spring.ex001.Student findByIdForUpdate(int id) { return executeSelect(this.findByIdForUpdate, ps -> ps.setInt(1, id), STUDENT); } public final void insert(Student pojo) { // set create timestamp pojo.setCreatedAt(new java.sql.Timestamp(System.currentTimeMillis())); // execute insert executeInsert(this.insert, STUDENT, pojo); } public final void update(Student pojo) { // execute update executeUpdate(this.update, STUDENT, pojo); } public final Student findByBusinessKey(java.lang.String code) { return executeSelect(this.findByBusinessKey, ps -> ps.setString(1, code), STUDENT); } }
Naotsun19B/PulldownBuilder
Plugins/PulldownBuilder/Source/PulldownBuilder/Private/PulldownBuilder/RowNameUpdaters/BlueprintUpdater.cpp
<filename>Plugins/PulldownBuilder/Source/PulldownBuilder/Private/PulldownBuilder/RowNameUpdaters/BlueprintUpdater.cpp // Copyright 2021 Naotsun. All Rights Reserved. #include "PulldownBuilder/RowNameUpdaters/BlueprintUpdater.h" #include "PulldownBuilder/Assets/PulldownContents.h" #include "PulldownBuilder/Utilities/PulldownBuilderUtils.h" #include "PulldownStruct/PulldownStructBase.h" #include "PulldownStruct/NativeLessPulldownStruct.h" #include "Engine/Blueprint.h" #include "EdGraph/EdGraph.h" #include "EdGraphSchema_K2.h" void UBlueprintUpdater::UpdateRowNamesInternal( UPulldownContents* PulldownContents, const FName& PreChangeName, const FName& PostChangeName ) { EnumerateAssets<UBlueprint>([&](UBlueprint* Blueprint) -> bool { return UpdateMemberVariables(Blueprint->GeneratedClass, PulldownContents, PreChangeName, PostChangeName) || UpdateGraphPins(Blueprint, PulldownContents, PreChangeName, PostChangeName); }); } bool UBlueprintUpdater::UpdateGraphPins( UBlueprint* Blueprint, UPulldownContents* PulldownContents, const FName& PreChangeName, const FName& PostChangeName ) { bool bIsModified = false; TArray<UEdGraph*> Graphs; Blueprint->GetAllGraphs(Graphs); for (const auto& Graph : Graphs) { if (!IsValid(Graph)) { continue; } TArray<UEdGraphNode*> Nodes = Graph->Nodes; for (const auto& Node : Nodes) { if (!IsValid(Node)) { continue; } TArray<UEdGraphPin*> Pins = Node->Pins; for (const auto& Pin : Pins) { if (Pin == nullptr) { continue; } if (Pin->PinType.PinCategory == UEdGraphSchema_K2::PC_Struct) { if (auto* Struct = Cast<UScriptStruct>(Pin->PinType.PinSubCategoryObject)) { if (PulldownBuilder::FPulldownBuilderUtils::IsPulldownStruct(Struct) && Struct == PulldownContents->GetPulldownStructType().SelectedStruct) { const TSharedPtr<FName> CurrentValue = PulldownBuilder::FPulldownBuilderUtils::StructStringToMemberValue( Pin->DefaultValue, GET_MEMBER_NAME_CHECKED(FPulldownStructBase, SelectedValue) ); if (CurrentValue.IsValid() && *CurrentValue == PreChangeName) { const TSharedPtr<FString> UpdatedValue = PulldownBuilder::FPulldownBuilderUtils::MemberValueToStructString( Pin->DefaultValue, GET_MEMBER_NAME_CHECKED(FPulldownStructBase, SelectedValue), PostChangeName ); if (UpdatedValue.IsValid()) { Pin->DefaultValue = *UpdatedValue; bIsModified = true; } } } else if (PulldownBuilder::FPulldownBuilderUtils::IsNativeLessPulldownStruct(Struct)) { const TSharedPtr<FName> CurrentSource = PulldownBuilder::FPulldownBuilderUtils::StructStringToMemberValue( Pin->DefaultValue, GET_MEMBER_NAME_CHECKED(FNativeLessPulldownStruct, PulldownSource) ); if (CurrentSource.IsValid() && *CurrentSource == PulldownContents->GetFName()) { const TSharedPtr<FName> CurrentValue = PulldownBuilder::FPulldownBuilderUtils::StructStringToMemberValue( Pin->DefaultValue, GET_MEMBER_NAME_CHECKED(FNativeLessPulldownStruct, SelectedValue) ); if (CurrentValue.IsValid() && *CurrentValue == PreChangeName) { const TSharedPtr<FString> UpdatedValue = PulldownBuilder::FPulldownBuilderUtils::MemberValueToStructString( Pin->DefaultValue, GET_MEMBER_NAME_CHECKED(FNativeLessPulldownStruct, SelectedValue), PostChangeName ); if (UpdatedValue.IsValid()) { Pin->DefaultValue = *UpdatedValue; bIsModified = true; } } } } } } } } } return bIsModified; }
netSensTeam/netSens
agent/app/listener/filequeue.py
import threading import time class FileQueue: def __init__(self, env): if env.mode == "live": self.queue = [] self.lock = threading.Lock() elif env.mode == "test": self.queue = env.test_file self.env = env def enqueue(self, item): if self.env.mode == "live": with self.lock: self.queue.append(item) def dequeue(self): if self.env.mode == "live": with self.lock: if self.queue: return self.queue.pop(0) else: return None elif self.env.mode == "test": return { "ts": time.time(), "path": self.queue }
atship/FinalBurn-X
Core/burn/drv/sms/sms.h
extern UINT8 SMSPaletteRecalc; extern UINT8 SMSReset; extern UINT8 MastInput[2]; extern UINT8 SMSDips[3]; extern UINT8 SMSJoy1[12]; INT32 SMSGetZipName(char** pszName, UINT32 i); INT32 SMSInit(); INT32 SMSExit(); INT32 SMSDraw(); INT32 SMSFrame(); INT32 SMSScan(INT32 nAction, INT32 *pnMin);
timfel/netbeans
java/java.editor/test/qa-functional/data/projects/java_editor_test/src/org/netbeans/test/java/editor/smart_bracket/JavaSmartBracketTest/testComment.java
<gh_stars>1000+ package org.netbeans.test.java.editor.smart_bracket.JavaSmartBracketTest; public class testComment { public void test() { if (true) { // line-comment } }
mattp94/johnny-five
eg/imu-lsm303c.js
const {Board, IMU} = require("../"); const board = new Board(); board.on("ready", () => { // Hookup Guide // https://learn.sparkfun.com/tutorials/lsm303c-6dof-hookup-guide#hardware-assembly // // Basically uses I2C, so only 4 pins are needed: // VCC --> VDD // GND --> GND // SCL --> SCL // SDA --> SDA const layout = ` Board layout: +---------------+ | *| GND | *| VDD_IO | *| SDA | *| SCL | *| INT_XL | *| DRYM | *| CS_XL | *| VDD | *| CS_MAG | *| INT_MAG +---------------+ `; console.log(layout); const imu = new IMU({ controller: "LSM303C" }); imu.on("change", () => { if (Math.random() > 0.05) { return; } if (this.accelerometer) { console.log("Accelerometer"); console.log(" x : ", imu.accelerometer.x); console.log(" y : ", imu.accelerometer.y); console.log(" z : ", imu.accelerometer.z); console.log(" pitch : ", imu.accelerometer.pitch); console.log(" roll : ", imu.accelerometer.roll); console.log(" acceleration : ", imu.accelerometer.acceleration); console.log(" inclination : ", imu.accelerometer.inclination); console.log(" orientation : ", imu.accelerometer.orientation); console.log("--------------------------------------"); } if (imu.magnetometer) { console.log("magnetometer"); console.log(" heading : ", Math.floor(imu.magnetometer.heading)); console.log(" bearing : ", imu.magnetometer.bearing.name); console.log(" x : ", imu.magnetometer.raw.x); console.log(" y : ", imu.magnetometer.raw.y); console.log(" z : ", imu.magnetometer.raw.z); console.log("--------------------------------------"); } if (imu.thermometer) { console.log("Thermometer"); console.log(" celsius : ", imu.thermometer.celsius); console.log(" fahrenheit : ", imu.thermometer.fahrenheit); console.log("--------------------------------------"); } console.log(""); console.log(""); console.log(""); }); });
Oracle-Exam-Preparation/OCP
src/main/java/com/trl/theoreticalKnowledge/nestedClass/innerClass/initialization/b/b1/Example.java
package com.trl.theoreticalKnowledge.nestedClass.innerClass.initialization.b.b1; import java.util.Objects; public class Example { public static void main(String[] args) { Human human = new Human("Sapiens"); Human.Arm arm_1 = human.new Arm("right"); Human.Arm arm_2 = human.new Arm("left"); System.out.println(arm_1); System.out.println(arm_2); System.out.println(); Human.Arm arm_11 = new Human("Sapiens_2").new Arm("right"); Human.Arm arm_22 = new Human("Sapiens_3").new Arm("left"); System.out.println(arm_11); System.out.println(arm_22); } } class Human { String name; public Human(final String name) { this.name = name; } class Arm { String name; public Arm(final String name) { this.name = name; } @Override public String toString() { return Human.this.toString() + " --> Arm{" + "name='" + name + '\'' + '}' + " " + hashCode(); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; final Arm arm = (Arm) o; return Objects.equals(this.name, arm.name); } @Override public int hashCode() { return Objects.hash(this.name); } } @Override public String toString() { return "Human{" + "name='" + name + '\'' + '}' + " " + hashCode(); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; final Human human = (Human) o; return Objects.equals(this.name, human.name); } @Override public int hashCode() { return Objects.hash(this.name); } }
thefourtheye/elasticsearch-client
elasticsearch-client-jts-jdk5/src/main/java/com/vividsolutions/jtsexample/io/gml2/KMLReaderExample.java
package com.vividsolutions.jtsexample.io.gml2; import com.vividsolutions.jts.geom.*; import com.vividsolutions.jts.io.gml2.*; import java.util.*; import java.io.*; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; /** * An example of using the {@link GMLHandler} class * to read geometry data out of KML files. * * @author mbdavis * */ public class KMLReaderExample { public static void main(String[] args) throws Exception { String filename = "C:\\proj\\JTS\\KML\\usPop-STUS-p06.kml"; KMLReader rdr = new KMLReader(filename); rdr.read(); } } class KMLReader { private String filename; public KMLReader(String filename) { this.filename = filename; } public void read() throws IOException, SAXException { XMLReader xr; xr = XMLReaderFactory.createXMLReader(); //xr = new org.apache.xerces.parsers.SAXParser(); KMLHandler kmlHandler = new KMLHandler(); xr.setContentHandler(kmlHandler); xr.setErrorHandler(kmlHandler); Reader r = new BufferedReader(new FileReader(filename)); LineNumberReader myReader = new LineNumberReader(r); xr.parse(new InputSource(myReader)); List geoms = kmlHandler.getGeometries(); } } class KMLHandler extends DefaultHandler { private List geoms = new ArrayList();; private GMLHandler currGeomHandler; private String lastEltName = null; private GeometryFactory fact = new FixingGeometryFactory(); public KMLHandler() { super(); } public List getGeometries() { return geoms; } /** * SAX handler. Handle state and state transitions based on an element * starting. * *@param uri Description of the Parameter *@param name Description of the Parameter *@param qName Description of the Parameter *@param atts Description of the Parameter *@exception SAXException Description of the Exception */ public void startElement(String uri, String name, String qName, Attributes atts) throws SAXException { if (name.equalsIgnoreCase(GMLConstants.GML_POLYGON)) { currGeomHandler = new GMLHandler(fact, null); } if (currGeomHandler != null) currGeomHandler.startElement(uri, name, qName, atts); if (currGeomHandler == null) { lastEltName = name; //System.out.println(name); } } public void characters(char[] ch, int start, int length) throws SAXException { if (currGeomHandler != null) { currGeomHandler.characters(ch, start, length); } else { String content = new String(ch, start, length).trim(); if (content.length() > 0) { System.out.println(lastEltName + "= " + content); } } } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (currGeomHandler != null) currGeomHandler.ignorableWhitespace(ch, start, length); } /** * SAX handler - handle state information and transitions based on ending * elements. * *@param uri Description of the Parameter *@param name Description of the Parameter *@param qName Description of the Parameter *@exception SAXException Description of the Exception */ public void endElement(String uri, String name, String qName) throws SAXException { // System.out.println("/" + name); if (currGeomHandler != null) { currGeomHandler.endElement(uri, name, qName); if (currGeomHandler.isGeometryComplete()) { Geometry g = currGeomHandler.getGeometry(); System.out.println(g); geoms.add(g); // reset to indicate no longer parsing geometry currGeomHandler = null; } } } } /** * A GeometryFactory extension which fixes structurally bad coordinate sequences * used to create LinearRings. * * @author mbdavis * */ class FixingGeometryFactory extends GeometryFactory { public LinearRing createLinearRing(CoordinateSequence cs) { if (cs.getCoordinate(0).equals(cs.getCoordinate(cs.size() - 1))) return super.createLinearRing(cs); // add a new coordinate to close the ring CoordinateSequenceFactory csFact = getCoordinateSequenceFactory(); CoordinateSequence csNew = csFact.create(cs.size() + 1, cs.getDimension()); CoordinateSequences.copy(cs, 0, csNew, 0, cs.size()); CoordinateSequences.copyCoord(csNew, 0, csNew, csNew.size() - 1); return super.createLinearRing(csNew); } }
ets-mlb/emissary
src/main/java/emissary/kff/ChecksumCalculator.java
<reponame>ets-mlb/emissary<filename>src/main/java/emissary/kff/ChecksumCalculator.java package emissary.kff; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.zip.CRC32; /** * ChecksumCalculator is a utility class which computes checksums and message digests. * * @see java.util.zip.CRC32 java.util.zip.CRC32 * @see java.security.MessageDigest java.security.MessageDigest */ public class ChecksumCalculator { /** Used for CRC32 calculations */ private CRC32 crc = null; /** Used for SSDEEP calculations */ private Ssdeep ssdeep = null; /** Used for hash calculations */ private List<MessageDigest> digest = new ArrayList<MessageDigest>(); /** * Constructor initializes SHA-1 generator and turns on the CRC32 processing as well * * @throws NoSuchAlgorithmException if the SHA algorithm isn't available */ public ChecksumCalculator() throws NoSuchAlgorithmException { this("SHA-1", true); } /** * Constructor initializes specified algorithm * * @param alg string name of algorightm, e.g. SHA * @param useCRC true if CRC32 should be calculated * @throws NoSuchAlgorithmException if the algorithm isn't available */ public ChecksumCalculator(String alg, boolean useCRC) throws NoSuchAlgorithmException { this(new String[] {alg}); setUseCRC(useCRC); } /** * Constructor initializes specified set of algorithms * * @param algs array of String algorithm names, put CRC32 on list to enable * @throws NoSuchAlgorithmException if an algorithm isn't available */ public ChecksumCalculator(String[] algs) throws NoSuchAlgorithmException { if (algs != null && algs.length > 0) { for (String alg : algs) { if (alg.equals("CRC32")) { setUseCRC(true); } else if (alg.equals("SSDEEP")) { setUseSsdeep(true); } else { digest.add(MessageDigest.getInstance(alg)); } } } } /** * Constructor initializes specified set of algorithms * * @param algs Collection of String algorithm names, put CRC32 on list to enable * @throws NoSuchAlgorithmException if an algorithm isn't available */ public ChecksumCalculator(Collection<String> algs) throws NoSuchAlgorithmException { if (algs != null && algs.size() > 0) { for (String alg : algs) { if (alg.equals("CRC32")) { setUseCRC(true); } else if (alg.equals("SSDEEP")) { setUseSsdeep(true); } else { digest.add(MessageDigest.getInstance(alg)); } } } } /** * Determine if we are using CRC summing */ public boolean getUseCRC() { return (crc != null); } /** * Turn on or off CRC processing * * @param use true if CRC processing is desired */ public void setUseCRC(boolean use) { if (use) { crc = new CRC32(); } else { crc = null; } } /** * Determine if we are using ssdeep summing */ public boolean getUseSsdeep() { return (ssdeep != null); } /** * Turn on or off CRC processing * * @param use true if CRC processing is desired */ public void setUseSsdeep(boolean use) { if (use) { ssdeep = new Ssdeep(); } else { ssdeep = null; } } /** * Calculates a CRC32 and a digest on a byte array. * * @param buffer Data to compute results for * @return results of computing the requested hashes on the data */ public ChecksumResults digest(byte[] buffer) { // return object to hold results ChecksumResults res = new ChecksumResults(); // Reset and compute for (MessageDigest d : digest) { d.reset(); d.update(buffer, 0, buffer.length); res.setHash(d.getAlgorithm(), d.digest()); } // Only use CRC if non-null if (crc != null) { crc.reset(); crc.update(buffer, 0, buffer.length); res.setCrc(crc.getValue()); } // Only use ssdeep if non-null if (ssdeep != null) { res.setSsdeep(ssdeep.fuzzy_hash(buffer)); } return res; } }
xsky-storage/go-sdk
dp_site_resp.go
<reponame>xsky-storage/go-sdk<filename>dp_site_resp.go /* * XMS API * * XMS is the controller of distributed storage system * * API version: SDS_4.2.000.0.200302 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package xmsclient type DpSiteResp struct { // data protection site DpSite *DpSite `json:"dp_site"` }
PathVisio/pathvisio4
org.pathvisio.desktop/src/test/java/org/pathvisio/desktop/debug/TestAndMeasure.java
/******************************************************************************* * PathVisio, a tool for data visualization and analysis using biological pathways * Copyright 2006-2021 BiGCaT Bioinformatics, WikiPathways * * 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.pathvisio.desktop.debug; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import org.bridgedb.DataSource; import org.bridgedb.Xref; import org.pathvisio.core.Engine; import org.pathvisio.debug.StopWatch; import org.pathvisio.model.ConverterException; import org.pathvisio.model.PathwayModel; import org.pathvisio.model.type.DataNodeType; import org.pathvisio.util.XrefUtils; import org.pathvisio.model.DataNode; import org.pathvisio.model.Interaction; import org.pathvisio.model.PathwayElement; import org.pathvisio.core.preferences.PreferenceManager; import org.pathvisio.core.view.model.VDataNode; import org.pathvisio.core.view.model.VElement; import org.pathvisio.core.view.model.VLineElement; import org.pathvisio.core.view.model.VPathwayModel; import org.pathvisio.core.view.model.VPathwayObject; import org.pathvisio.gui.view.VPathwayModelSwing; import buildsystem.Measure; import junit.framework.TestCase; /** * Test memory usage and speed of object creation, pathway loading, selection, * and drag operations. */ public class TestAndMeasure extends TestCase { private static final File PATHVISIO_BASEDIR = new File("../.."); private static final File TEST_PATHWAY = new File(PATHVISIO_BASEDIR, "testData/WP248_2008a.gpml"); private Measure measure; @Override public void setUp() { measure = new Measure("pv_mut.log"); } private interface ObjectTester { String getName(); public Object create(); } private static class MemWatch { private Runtime runtime = Runtime.getRuntime(); private void runGC() { for (int i = 0; i < 20; ++i) { System.gc(); try { Thread.sleep(100); } catch (InterruptedException ex) { } } } private long memStart; public void start() { runGC(); memStart = (runtime.totalMemory() - runtime.freeMemory()); } public long stop() { runGC(); long memEnd = (runtime.totalMemory() - runtime.freeMemory()); return (memEnd - memStart); } } static final int N = 1000; private void individialTest(ObjectTester tester) { // 1000 warm-up rounds for (int i = 0; i < 1000; ++i) { Object o = tester.create(); } Runtime runtime = Runtime.getRuntime(); for (int i = 0; i < 20; ++i) { System.gc(); try { Thread.sleep(100); } catch (InterruptedException ex) { } } Object[] array = new Object[N]; StopWatch sw = new StopWatch(); for (int i = 0; i < 20; ++i) { System.gc(); try { Thread.sleep(100); } catch (InterruptedException ex) { } } long memStart = (runtime.totalMemory() - runtime.freeMemory()); sw.start(); for (int i = 0; i < N; ++i) { array[i] = tester.create(); } long msec = sw.stop(); for (int i = 0; i < 20; ++i) { System.gc(); try { Thread.sleep(100); } catch (InterruptedException ex) { } } long memEnd = (runtime.totalMemory() - runtime.freeMemory()); measure.add("Memory::" + tester.getName() + " " + N + "x", "" + (memEnd - memStart) / N, "bytes"); measure.add("Speed::" + tester.getName() + " " + N + "x", "" + (float) (msec) / (float) (N), "msec"); } public void testFile() { assertTrue("Missing file required for test: " + TEST_PATHWAY, TEST_PATHWAY.exists()); } public void testObjectCreation() { PreferenceManager.init(); final PathwayModel pwy1 = new PathwayModel(); final PathwayModel pwy2 = new PathwayModel(); final PathwayModel pwy3 = new PathwayModel(); final VPathwayModel vpwy3 = new VPathwayModel(null); final PathwayModel pwy4 = new PathwayModel(); final VPathwayModel vpwy4 = new VPathwayModel(null); individialTest(new ObjectTester() { public Object create() { return new Xref("ENS0000001", DataSource.getByCompactIdentifierPrefix("ncbigene")); } public String getName() { return "Xref"; } }); individialTest(new ObjectTester() { public Object create() { DataNode elt = new DataNode("INSR", DataNodeType.GENEPRODUCT); elt.setCenterX(5); elt.setCenterY(10); elt.setWidth(8); elt.setHeight(10); elt.setXref(XrefUtils.createXref("3463", "ncbigene")); pwy1.add(elt); return elt; } public String getName() { return "PathwayElement - DataNode"; } }); individialTest(new ObjectTester() { public Object create() { Interaction elt = new Interaction(); elt.setStartLinePointX(5); elt.setStartLinePointY(10); elt.setEndLinePointX(8); elt.setEndLinePointY(10); // elt.setStartGraphRef("abc"); TODO // elt.setEndGraphRef("def"); TODO pwy2.add(elt); return elt; } public String getName() { return "PathwayElement - Line"; } }); individialTest(new ObjectTester() { public Object create() { DataNode elt = new DataNode("INSR", DataNodeType.GENEPRODUCT); elt.setCenterX(5); elt.setCenterY(10); elt.setWidth(8); elt.setHeight(10); elt.setXref(XrefUtils.createXref("3463", "ncbigene")); pwy3.add(elt); VDataNode velt = new VDataNode(vpwy3, elt); return velt; } public String getName() { return "M/V GeneProduct pair"; } }); individialTest(new ObjectTester() { public Object create() { Interaction elt = new Interaction(); elt.setStartLinePointX(5); elt.setStartLinePointY(10); elt.setEndLinePointX(8); elt.setEndLinePointY(10); // elt.setStartGraphRef("abc"); TODO // elt.setEndGraphRef("def"); TODO pwy4.add(elt); VLineElement velt = new VLineElement(vpwy4, elt); return velt; } public String getName() { return "M/V Line pair"; } }); } public void testPathwayLoading() throws ConverterException { PreferenceManager.init(); StopWatch sw = new StopWatch(); MemWatch mw = new MemWatch(); mw.start(); sw.start(); PathwayModel pwy = new PathwayModel(); pwy.readFromXml(TEST_PATHWAY, true); measure.add("Speed::Hs_Apoptosis readFromXml (+validate)", "" + sw.stop(), "msec"); measure.add("Memory::Hs_Apoptosis readFromXml (+validate)", "" + mw.stop() / 1024, "kb"); mw.start(); sw.start(); JScrollPane sp = new JScrollPane(); VPathwayModelSwing wrapper = new VPathwayModelSwing(sp); Engine engine = new Engine(); VPathwayModel vpwy = wrapper.createVPathway(); vpwy.activateUndoManager(engine); vpwy.fromModel(pwy); measure.add("Speed::Hs_Apoptosis create VPathway", "" + sw.stop(), "msec"); measure.add("Memory::Hs_Apoptosis create VPathway", "" + mw.stop() / 1024, "kb"); mw.start(); sw.start(); wrapper.setSize(vpwy.getVWidth(), vpwy.getVHeight()); BufferedImage image = new BufferedImage(vpwy.getVWidth(), vpwy.getVHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); wrapper.paint(g2); measure.add("Speed::Hs_Apoptosis paint", "" + sw.stop(), "msec"); measure.add("Memory::Hs_Apoptosis paint", "" + mw.stop() / 1024, "kb"); g2.dispose(); mw.start(); sw.start(); for (VElement elt : vpwy.getDrawingObjects()) { elt.select(); } measure.add("Speed::Hs_Apoptosis select all", "" + sw.stop(), "msec"); measure.add("Memory::Hs_Apoptosis select all", "" + mw.stop() / 1024, "kb"); image = new BufferedImage(vpwy.getVWidth(), vpwy.getVHeight(), BufferedImage.TYPE_INT_RGB); g2 = image.createGraphics(); wrapper.paint(g2); g2.dispose(); mw.start(); sw.start(); // move all selected items, triggers undo action for (int i = 0; i < 10; ++i) vpwy.moveByKey(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), 10); measure.add("Speed::Hs_Apoptosis move up 10x", "" + sw.stop(), "msec"); measure.add("Memory::Hs_Apoptosis move up 10x", "" + mw.stop() / 1024, "kb"); } }
fanhubgt/StreamEPS
core/src/test/java/org/streameps/test/EngineTestWithCassandra.java
/* * ==================================================================== * StreamEPS Platform * * (C) Copyright 2011. * * Distributed under the Modified BSD License. * Copyright notice: The copyright for this software and a full listing * of individual contributors are as shown in the packaged copyright.txt * file. * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the ORGANIZATION nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ============================================================================= */ package org.streameps.test; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; import junit.framework.TestCase; import org.streameps.aggregation.SumAggregation; import org.streameps.client.EPSRuntimeClient; import org.streameps.client.IEPSRuntimeClient; import org.streameps.context.ContextDimType; import org.streameps.context.IContextPartition; import org.streameps.context.PredicateOperator; import org.streameps.context.segment.SegmentParam; import org.streameps.context.temporal.IFixedIntervalContext; import org.streameps.core.IStreamEvent; import org.streameps.core.sys.DefaultSystemEventProvider; import org.streameps.core.util.IDUtil; import org.streameps.dispatch.DispatcherService; import org.streameps.engine.EPSProducer; import org.streameps.engine.builder.EngineBuilder; import org.streameps.engine.IEPSDecider; import org.streameps.engine.IEPSEngine; import org.streameps.engine.IEPSProducer; import org.streameps.engine.IEPSReceiver; import org.streameps.engine.builder.AggregateContextBuilder; import org.streameps.engine.builder.FilterContextBuilder; import org.streameps.engine.builder.PatternBuilder; import org.streameps.engine.builder.ReceiverContextBuilder; import org.streameps.engine.builder.StoreContextBuilder; import org.streameps.engine.segment.SegmentDecider; import org.streameps.engine.segment.SegmentEngine; import org.streameps.engine.segment.SegmentReceiver; import org.streameps.filter.FilterType; import org.streameps.filter.IEPSFilter; import org.streameps.filter.eval.ComparisonContentEval; import org.streameps.operator.assertion.AssertionType; import org.streameps.operator.assertion.trend.IncreasingAssertion; import org.streameps.processor.pattern.HighestSubsetPE; import org.streameps.processor.pattern.NullPatternPE; import org.streameps.processor.pattern.TrendPatternPE; /** */ public class EngineTestWithCassandra extends TestCase { public EngineTestWithCassandra(String testName) { super(testName); } public void testEngine() { //1: initialize the engine, decider, reciever and producer. IEPSDecider<IContextPartition<IFixedIntervalContext>> decider = new SegmentDecider(); IEPSReceiver<IContextPartition<IFixedIntervalContext>, IStreamEvent> receiver = new SegmentReceiver(); IEPSEngine<IContextPartition<IFixedIntervalContext>, IStreamEvent> engine = new SegmentEngine(); IEPSProducer producer = new EPSProducer(); EngineBuilder engineBuilder; { //2: set the engine, decider and receiver properties. engineBuilder = new EngineBuilder(decider, engine, receiver); engineBuilder.setProducer(producer); } //decider aggregate context AggregateContextBuilder aggregatebuilder = new AggregateContextBuilder(); aggregatebuilder.buildDeciderAggregateContext("value", new SumAggregation(), 20, AssertionType.GREATER); // engineBuilder.setAggregatedDetectEnabled(aggregatebuilder.getAggregateContext(), new TestAggregateListener()); //producer aggregate context aggregatebuilder.buildProducerAggregateContext("value", new SumAggregation()); engineBuilder.setAggregatedEnabled(aggregatebuilder.getAggregateContext(), new TestAggregateListener(), true); //build the store context for cassandra big store StoreContextBuilder storeContextBuilder = new StoreContextBuilder(); storeContextBuilder.setExecutorManager(engine.getExecutorManager()); storeContextBuilder.buildCassandraColumnFamilies("PatternContext", "AggregateContext", "KnowledgeContext", "FilterContext", "AssertionContext", "StreamContext").buildCassandraStore("127.0.0.1", "9160", "StreamEPSClustr", "ParticipationContext", "StreamEPSLite"); Map<String, List<String>> groupColumnNames = new HashMap<String, List<String>>(); List<String> columns = new ArrayList<String>(); columns.add("name"); columns.add("value"); groupColumnNames.put("participant", columns); columns = new ArrayList<String>(); columns.add("name"); columns.add("value"); groupColumnNames.put("filter", columns); columns = new ArrayList<String>(); columns.add("name"); columns.add("value"); groupColumnNames.put("aggregate", columns); columns = new ArrayList<String>(); columns.add("name"); columns.add("value"); groupColumnNames.put("match", columns); columns = new ArrayList<String>(); columns.add("name"); columns.add("value"); groupColumnNames.put("stream", columns); columns = new ArrayList<String>(); columns.add("name"); columns.add("value"); groupColumnNames.put("match", columns); columns = new ArrayList<String>(); columns.add("name"); columns.add("value"); groupColumnNames.put("unmatch", columns); engineBuilder.buildAuditStore(storeContextBuilder.getCassandraEventStore(groupColumnNames, true)); engineBuilder.buildDeciderStore(storeContextBuilder.getCassandraEventStore(groupColumnNames, true)); engineBuilder.buildReceiverStore(storeContextBuilder.getCassandraEventStore(groupColumnNames, true)); //producer decider listener engineBuilder.setDeciderListener(new TestDeciderListener()); //set the properties: sequence size, asychronous flag, queue flag, saveonReceive flag, saveonDecide flag. engineBuilder.buildProperties(5, true, false, true, true); engineBuilder.buildExecutorManagerProperties(2, "EPS"); engineBuilder.buildDispatcher(3, 0, 1, TimeUnit.MILLISECONDS, new DispatcherService()); //3: set up a pattern detector for the decider. PatternBuilder patternBuilder = new PatternBuilder(new NullPatternPE()) //patternBuilder.buildParameter("value", 16);/*No comparison operator needed.*/ .buildPatternMatchListener(new TestPatternMatchListener()).buildPatternUnMatchListener(new TestUnPatternMatchListener()); //add the pattern 1 detector built to the engine/decider. engineBuilder.buildPattern(patternBuilder.getBasePattern()); //pattern 2: repeated process. patternBuilder = new PatternBuilder(new TrendPatternPE(new IncreasingAssertion())); patternBuilder.buildParameter("value"); //.buildPatternMatchListener(new TestPatternMatchListener()) //.buildPatternUnMatchListener(new TestUnPatternMatchListener()); engineBuilder.buildPattern(patternBuilder.getBasePattern()); //pattern 3: repeated pattern detector process. patternBuilder = new PatternBuilder(new HighestSubsetPE<TestEvent>()); patternBuilder.buildParameter("value", 12); //.buildPatternMatchListener(new TestPatternMatchListener()) //.buildPatternUnMatchListener(new TestUnPatternMatchListener()); engineBuilder.buildPattern(patternBuilder.getBasePattern());//, // new TestPatternMatchListener(), // new TestUnPatternMatchListener()); //4: create the receiver context to be used for the segment partition. ReceiverContextBuilder contextBuilder = new ReceiverContextBuilder(new SegmentParam()); contextBuilder.buildIdentifier(IDUtil.getUniqueID(new Date().toString())).buildContextDetail(IDUtil.getUniqueID(new Date().toString()), ContextDimType.SEGMENT_ORIENTED) // .buildSegmentParameter(new ComparisonContentEval(), // new PredicateTerm("value", PredicateOperator.GREATER_THAN_OR_EQUAL, 18)) .buildSegmentParamAttribute("name") //.buildSegmentParamAttribute("name") .buildContextParameter("Test Event", contextBuilder.getSegmentParam()); receiver.setReceiverContext(contextBuilder.getContext()); //create the filter context for a filtering process. FilterContextBuilder filterContextBuilder = new FilterContextBuilder(); filterContextBuilder.buildPredicateTerm("value", PredicateOperator.GREATER_THAN_OR_EQUAL, 4).buildContextEntry("TestEvent", new ComparisonContentEval()).buildEvaluatorContext(FilterType.COMPARISON).buildEPSFilter().buildFilterListener(new TestFilterObserver()).buildFilterContext(); IEPSFilter filter = filterContextBuilder.getFilter(); assertNotNull("Filter is not functional", filter); //producer.addFilterContext(filterContextBuilder.getFilterContext()); //5: build and retrieve the modified engine and shoot some events. IEPSRuntimeClient epsRuntimeClient = new EPSRuntimeClient(engineBuilder, aggregatebuilder, filterContextBuilder, patternBuilder, storeContextBuilder, contextBuilder); engine = epsRuntimeClient.getEngine(); assertNotNull(engine); Random rand = new Random(50); //Un-comment to send the events. for (int i = 0; i < 40; i++) { TestEvent event = new TestEvent("E" + i, ((double) rand.nextDouble()) + 29 - (2 * i)); String id = IDUtil.getUniqueID(new Date().toString()); System.out.println(id); IStreamEvent streamEvent = new DefaultSystemEventProvider().createStreamEvent(event, "test-engine", id, "test-event"); engine.sendStreamEvent(streamEvent); } System.out.println(""); } }
arista-eosplus/puppet-eos
lib/puppet/type/eos_ospf_instance.rb
<reponame>arista-eosplus/puppet-eos<filename>lib/puppet/type/eos_ospf_instance.rb # # Copyright (c) 2014, Arista Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # Neither the name of Arista Networks nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # encoding: utf-8 Puppet::Type.newtype(:eos_ospf_instance) do @doc = <<-EOS Manage OSPF instance configuration. Example: eos_ospf_instance { '1': router_id => 192.168.1.1, max_lsa => 12000, maximum_paths => 16, passive_interfaces => [], active_interfaces => ['Ethernet49', 'Ethernet50'], passive_interface_default => true, } EOS ensurable # Parameters newparam(:name, :namevar => true) do @doc = <<-EOS The name parameter specifies the ospf intstance identifier of the Arista EOS ospf instance to manage. This value must correspond to a valid ospf instance identifier in EOS and must have a value between 1 and 65535. EOS # min: 1 max: 65535 munge do |value| Integer(value).to_s end validate do |value| unless value.to_i.between?(1, 65_535) fail "value #{value.inspect} is not between 1 and 65535" end end end # Properties (state management) newproperty(:router_id) do desc <<-EOS The router_id property configures the router id on the specified ospf instance. The router_id value must be a valid IPv4 address. The router ID is a 32-bit number assigned to a router running OSPFv2. This number uniquely labels the router within an Autonomous System. Status commands identify the switch through the router ID. For example router_id => 192.168.1.1 EOS # IPV4 Address # min: 0.0.0.0 max: 255.255.255.255 validate do |value| case value when String super(value) validate_features_per_value(value) else fail "value #{value.inspect} is invalid, must be a string." end end end newproperty(:max_lsa) do desc <<-EOS The max_lsa property configures the LSA Overload on the specified ospf instance. The max_lsa property must have a value between 0 and 100000. The max_lsa property specifies the maximum number of LSAs allowed in an LSDB database and configures the switch behavior when the limit is approached or exceeded. For example max_lsa => 12000, EOS munge { |value| Integer(value) } validate do |value| unless value.to_i.between?(0, 100_000) fail "value #{value.inspect} is not between 0 and 100000" end end end newproperty(:maximum_paths) do desc <<-EOS The maximum_paths property configures the maximum-paths on the specified ospf instance. The maximum_paths property must have a value between 1 and N where N is the number of interfaces available per ECMP group. The maximum_paths command controls the number of parallel routes that OSPFv2 supports. The default maximum is 16 paths. For example maximum_paths => 16, EOS munge { |value| Integer(value) } validate do |value| unless value.to_i.between?(1, 32) fail "value #{value.inspect} is not between 1 and 32" end end end newproperty(:passive_interfaces, :array_matching => :all) do desc <<-EOS The passive_interface property configures all ospf disabled interfaces on the specified ospf instance. The passive_interface property must be an array of EOS interfaces. For example passive_interfaces => ['Loopback0'], EOS def insync?(is) is = [] if (is == :absent) || is.nil? is.sort == @should.sort.map(&:to_s) end end newproperty(:active_interfaces, :array_matching => :all) do desc <<-EOS The active_interface property configures all ospf enabled interfaces on the specified ospf instance. The active_interface property must be an array of EOS interfaces. For example active_interfaces => ['Ethernet49', 'Ethernet50', 'Vlan4093'], EOS def insync?(is) is = [] if (is == :absent) || is.nil? is.sort == @should.sort.map(&:to_s) end end newproperty(:passive_interface_default) do desc <<-EOS The passive_interface_default property configures all interfaces passive by default on the specified ospf instance. The switch advertises the passive interface as part of the router LSA. The passive_interface_default value must be true or false. When it is set to false, all interfaces are OSPFv2 active by default and passive interfaces must be specified in the passive_interfaces property. When passive_interface_default is set to true, all interfaces are OSPFv2 passive by default and active interfaces must be specified in the active_interfaces property. For example passive_interface_default => false, EOS newvalues(:true, :false) end end
manu-ki/sechub
sechub-integrationtest/src/main/java/com/daimler/sechub/integrationtest/internal/IntegrationTestExampleConstants.java
// SPDX-License-Identifier: MIT package com.daimler.sechub.integrationtest.internal; public class IntegrationTestExampleConstants { public static final String EXAMPLE_CONTENT_ROOT_PATH = "sechub-integrationtest/build/sechub/example/content/"; }
duartegroup/cgbind
examples/ex9_adding_substrates_from_files.py
<filename>examples/ex9_adding_substrates_from_files.py from cgbind import Cage, Substrate, Linker, CageSubstrateComplex # Generate an M4L6 bipyridyl Fe(III) based metallocage linker = Linker(name='linker', smiles='C1(C2=CC=C(C#CC3=CN=C(C4=NC=CC=C4)C=C3)C=N2)=NC=CC=C1', arch_name='m4l6n') cage = Cage(linker, metal='Fe', metal_charge='3') # Initialise a substrate from the .xyz file, setting the charge and spin # multiplicity substrate = Substrate(name='PhO-', filename='phenoxide.xyz', charge=-1, mult=1) cs = CageSubstrateComplex(cage, substrate) cs.print_xyz_file()
umjammer/vavi-nio-file-discutils
src/main/java/DiscUtils/Iscsi/Session.java
<filename>src/main/java/DiscUtils/Iscsi/Session.java // // Copyright (c) 2008-2011, <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // package DiscUtils.Iscsi; import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Field; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import DiscUtils.Core.CoreCompat.ReflectionHelper; import dotnet4j.io.FileAccess; /** * Represents a connection to a particular Target. */ public final class Session implements Closeable { private static AtomicInteger _nextInitiatorSessionId = new AtomicInteger(new SecureRandom().nextInt()); private final List<TargetAddress> _addresses; /** * The set of all 'parameters' we've negotiated. */ private final Map<String, String> _negotiatedParameters; private short _nextConnectionId; Session(SessionType type, String targetName, List<TargetAddress> addresses) { this(type, targetName, null, null, addresses); } Session(SessionType type, String targetName, String userName, String password, List<TargetAddress> addresses) { _initiatorSessionId = _nextInitiatorSessionId.incrementAndGet(); _addresses = addresses; _sessionType = type; _targetName = targetName; setCommandSequenceNumber(1); setCurrentTaskTag(1); // Default negotiated values... _maxConnections = 1; _initialR2T = true; _immediateData = true; _maxBurstLength = 262144; _firstBurstLength = 65536; _defaultTime2Wait = 0; _defaultTime2Retain = 60; _maxOutstandingR2T = 1; _dataPDUInOrder = true; _dataSequenceInOrder = true; _negotiatedParameters = new HashMap<>(); if (userName == null || userName.isEmpty()) { setActiveConnection(new Connection(this, _addresses.get(0), new Authenticator[] { new NullAuthenticator() })); } else { setActiveConnection(new Connection(this, _addresses.get(0), new Authenticator[] { new NullAuthenticator(), new ChapAuthenticator(userName, password) })); } } private Connection _activeConnection; Connection getActiveConnection() { return _activeConnection; } void setActiveConnection(Connection value) { _activeConnection = value; } private int _commandSequenceNumber; int getCommandSequenceNumber() { return _commandSequenceNumber; } void setCommandSequenceNumber(int value) { _commandSequenceNumber = value; } private int _currentTaskTag; int getCurrentTaskTag() { return _currentTaskTag; } void setCurrentTaskTag(int value) { _currentTaskTag = value; } private int _initiatorSessionId; int getInitiatorSessionId() { return _initiatorSessionId; } private short _targetSessionId; short getTargetSessionId() { return _targetSessionId; } void setTargetSessionId(short value) { _targetSessionId = value; } /** * Disposes of this instance, closing the session with the Target. */ public void close() throws IOException { if (getActiveConnection() != null) { getActiveConnection().close(); } setActiveConnection(null); } /** * Enumerates all of the Targets. * * @return The list of Targets.In practice, for an established session, this * just returns details of the connected Target. */ public TargetInfo[] enumerateTargets() { return getActiveConnection().enumerateTargets(); } /** * Gets information about the LUNs available from the Target. * * @return The LUNs available. */ public LunInfo[] getLuns() { ScsiReportLunsCommand cmd = new ScsiReportLunsCommand(ScsiReportLunsCommand.InitialResponseSize); ScsiReportLunsResponse resp = send(ScsiReportLunsResponse.class, cmd, null, 0, 0, ScsiReportLunsCommand.InitialResponseSize); if (resp.getTruncated()) { cmd = new ScsiReportLunsCommand(resp.getNeededDataLength()); resp = send(ScsiReportLunsResponse.class, cmd, null, 0, 0, resp.getNeededDataLength()); } if (resp.getTruncated()) { throw new IllegalArgumentException("Truncated response"); } LunInfo[] result = new LunInfo[resp.getLuns().size()]; for (int i = 0; i < resp.getLuns().size(); ++i) { result[i] = getInfo(resp.getLuns().get(i)); } return result; } /** * Gets all the block-device LUNs available from the Target. * * @return The block-device LUNs. */ public List<Long> getBlockDeviceLuns() { List<Long> luns = new ArrayList<>(); for (LunInfo info : getLuns()) { if (info.getDeviceType() == LunClass.BlockStorage) { luns.add(info.getLun()); } } return luns; } /** * Gets information about a particular LUN. * * @param lun The LUN to query. * @return Information about the LUN. */ public LunInfo getInfo(long lun) { ScsiInquiryCommand cmd = new ScsiInquiryCommand(lun, ScsiInquiryCommand.InitialResponseDataLength); ScsiInquiryStandardResponse resp = send(ScsiInquiryStandardResponse.class, cmd, null, 0, 0, ScsiInquiryCommand.InitialResponseDataLength); TargetInfo targetInfo = new TargetInfo(_targetName, _addresses); return new LunInfo(targetInfo, lun, resp.getDeviceType(), resp.getRemovable(), resp.getVendorId(), resp.getProductId(), resp.getProductRevision()); } /** * Gets the capacity of a particular LUN. * * @param lun The LUN to query. * @return The LUN's capacity. */ public LunCapacity getCapacity(long lun) { ScsiReadCapacityCommand cmd = new ScsiReadCapacityCommand(lun); ScsiReadCapacityResponse resp = send(ScsiReadCapacityResponse.class, cmd, null, 0, 0, ScsiReadCapacityCommand.ResponseDataLength); if (resp.getTruncated()) { throw new IllegalArgumentException("Truncated response"); } return new LunCapacity(resp.getNumLogicalBlocks(), resp.getLogicalBlockSize()); } /** * Provides read-write access to a LUN as a VirtualDisk. * * @param lun The LUN to access. * @return The new VirtualDisk instance. */ public Disk openDisk(long lun) { return openDisk(lun, FileAccess.ReadWrite); } /** * Provides access to a LUN as a VirtualDisk. * * @param lun The LUN to access. * @param access The type of access desired. * @return The new VirtualDisk instance. */ public Disk openDisk(long lun, FileAccess access) { return new Disk(this, lun, access); } /** * Reads some data from a LUN. * * @param lun The LUN to read from. * @param startBlock The first block to read. * @param blockCount The number of blocks to read. * @param buffer The buffer to fill. * @param offset The offset of the first byte to fill. * @return The number of bytes read. */ public int read(long lun, long startBlock, short blockCount, byte[] buffer, int offset) { ScsiReadCommand cmd = new ScsiReadCommand(lun, (int) startBlock, blockCount); return send(cmd, null, 0, 0, buffer, offset, buffer.length - offset); } /** * Writes some data to a LUN. * * @param lun The LUN to write to. * @param startBlock The first block to write. * @param blockCount The number of blocks to write. * @param blockSize The size of each block (must match the actual LUN * geometry). * @param buffer The data to write. * @param offset The offset of the first byte to write in buffer. */ public void write(long lun, long startBlock, short blockCount, int blockSize, byte[] buffer, int offset) { ScsiWriteCommand cmd = new ScsiWriteCommand(lun, (int) startBlock, blockCount); send(cmd, buffer, offset, blockCount * blockSize, null, 0, 0); } /** * Performs a raw SCSI command. * * This method permits the caller to send raw SCSI commands to a LUN.The * command . * * @param lun The target LUN for the command. * @param command The command (a SCSI Command Descriptor Block, aka CDB). * @param outBuffer Buffer of data to send with the command (or * {@code null}). * @param outBufferOffset Offset of first byte of data to send with the * command. * @param outBufferLength Amount of data to send with the command. * @param inBuffer Buffer to receive data from the command (or * {@code null}). * @param inBufferOffset Offset of the first byte position to fill with * received data. * @param inBufferLength The expected amount of data to receive. * @return The number of bytes of data received. */ public int rawCommand(long lun, byte[] command, byte[] outBuffer, int outBufferOffset, int outBufferLength, byte[] inBuffer, int inBufferOffset, int inBufferLength) { if (outBuffer == null && outBufferLength != 0) { throw new IllegalArgumentException("outBufferLength must be 0 if outBuffer null"); } if (inBuffer == null && inBufferLength != 0) { throw new IllegalArgumentException("inBufferLength must be 0 if inBuffer null"); } ScsiRawCommand cmd = new ScsiRawCommand(lun, command, 0, command.length); return send(cmd, outBuffer, outBufferOffset, outBufferLength, inBuffer, inBufferOffset, inBufferLength); } int nextCommandSequenceNumber() { return ++_commandSequenceNumber; } int nextTaskTag() { return ++_currentTaskTag; } short nextConnectionId() { return ++_nextConnectionId; } void getParametersToNegotiate(TextBuffer parameters, KeyUsagePhase phase) { try { for (Field propInfo : getClass().getDeclaredFields()) { ProtocolKeyAttribute attr = ReflectionHelper.getCustomAttribute(propInfo, ProtocolKeyAttribute.class); if (attr != null) { Object value = propInfo.get(this); if (ProtocolKeyAttribute.Util.shouldTransmit(attr, value, propInfo.getType(), phase, _sessionType == SessionType.Discovery)) { parameters.add(attr.name(), ProtocolKeyAttribute.Util.getValueAsString(value, propInfo.getType())); _negotiatedParameters.put(attr.name(), ""); } } } } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException(e); } } void consumeParameters(TextBuffer inParameters, TextBuffer outParameters) { try { for (Field propInfo : getClass().getDeclaredFields()) { ProtocolKeyAttribute attr = ReflectionHelper.getCustomAttribute(propInfo, ProtocolKeyAttribute.class); if (attr != null) { if (inParameters.get___idx(attr.name()) != null) { Object value = ProtocolKeyAttribute.Util.getValueAsObject(inParameters.get___idx(attr.name()), propInfo.getType()); propInfo.set(this, value); inParameters.remove(attr.name()); if (attr.type() == KeyType.Negotiated && !_negotiatedParameters.containsKey(attr.name())) { value = propInfo.get(this); outParameters.add(attr.name(), ProtocolKeyAttribute.Util.getValueAsString(value, propInfo.getType())); _negotiatedParameters.put(attr.name(), ""); } } } } } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException(e); } } /** * Gets the name of the iSCSI target this session is connected to. */ @ProtocolKeyAttribute(name = "TargetName", phase = KeyUsagePhase.SecurityNegotiation, sender = KeySender.Initiator, type = KeyType.Declarative, usedForDiscovery = true) public String _targetName; /** * Gets the name of the iSCSI initiator seen by the target for this session. */ @ProtocolKeyAttribute(name = "InitiatorName", phase = KeyUsagePhase.SecurityNegotiation, sender = KeySender.Initiator, type = KeyType.Declarative, usedForDiscovery = true) public String _initiatorName = "iqn.2008-2010-04.discutils.codeplex.com"; /** * Gets the friendly name of the iSCSI target this session is connected to. */ @ProtocolKeyAttribute(name = "TargetAlias", defaultValue = "", phase = KeyUsagePhase.All, sender = KeySender.Target, type = KeyType.Declarative) String _targetAlias; @ProtocolKeyAttribute(name = "SessionType", phase = KeyUsagePhase.SecurityNegotiation, sender = KeySender.Initiator, type = KeyType.Declarative, usedForDiscovery = true) SessionType _sessionType = SessionType.Discovery; @ProtocolKeyAttribute(name = "MaxConnections", defaultValue = "1", phase = KeyUsagePhase.OperationalNegotiation, sender = KeySender.Both, type = KeyType.Negotiated, leadingConnectionOnly = true) int _maxConnections; @ProtocolKeyAttribute(name = "InitiatorAlias", defaultValue = "", phase = KeyUsagePhase.All, sender = KeySender.Initiator, type = KeyType.Declarative) String _initiatorAlias; @ProtocolKeyAttribute(name = "TargetPortalGroupTag", phase = KeyUsagePhase.SecurityNegotiation, sender = KeySender.Target, type = KeyType.Declarative) int _targetPortalGroupTag; @ProtocolKeyAttribute(name = "InitialR2T", defaultValue = "Yes", phase = KeyUsagePhase.OperationalNegotiation, sender = KeySender.Both, type = KeyType.Negotiated, leadingConnectionOnly = true) boolean _initialR2T; @ProtocolKeyAttribute(name = "ImmediateData", defaultValue = "Yes", phase = KeyUsagePhase.OperationalNegotiation, sender = KeySender.Both, type = KeyType.Negotiated, leadingConnectionOnly = true) boolean _immediateData; @ProtocolKeyAttribute(name = "MaxBurstLength", defaultValue = "262144", phase = KeyUsagePhase.OperationalNegotiation, sender = KeySender.Both, type = KeyType.Negotiated, leadingConnectionOnly = true) int _maxBurstLength; @ProtocolKeyAttribute(name = "FirstBurstLength", defaultValue = "65536", phase = KeyUsagePhase.OperationalNegotiation, sender = KeySender.Both, type = KeyType.Negotiated, leadingConnectionOnly = true) int _firstBurstLength; @ProtocolKeyAttribute(name = "DefaultTime2Wait", defaultValue = "2", phase = KeyUsagePhase.OperationalNegotiation, sender = KeySender.Both, type = KeyType.Negotiated, leadingConnectionOnly = true) int _defaultTime2Wait; @ProtocolKeyAttribute(name = "DefaultTime2Retain", defaultValue = "20", phase = KeyUsagePhase.OperationalNegotiation, sender = KeySender.Both, type = KeyType.Negotiated, leadingConnectionOnly = true) int _defaultTime2Retain; @ProtocolKeyAttribute(name = "MaxOutstandingR2T", defaultValue = "1", phase = KeyUsagePhase.OperationalNegotiation, sender = KeySender.Both, type = KeyType.Negotiated, leadingConnectionOnly = true) int _maxOutstandingR2T; @ProtocolKeyAttribute(name = "DataPDUInOrder", defaultValue = "Yes", phase = KeyUsagePhase.OperationalNegotiation, sender = KeySender.Both, type = KeyType.Negotiated, leadingConnectionOnly = true) boolean _dataPDUInOrder; @ProtocolKeyAttribute(name = "DataSequenceInOrder", defaultValue = "Yes", phase = KeyUsagePhase.OperationalNegotiation, sender = KeySender.Both, type = KeyType.Negotiated, leadingConnectionOnly = true) boolean _dataSequenceInOrder; @ProtocolKeyAttribute(name = "ErrorRecoveryLevel", defaultValue = "0", phase = KeyUsagePhase.OperationalNegotiation, sender = KeySender.Both, type = KeyType.Negotiated, leadingConnectionOnly = true) int _errorRecoveryLevel; /** * Sends an SCSI command (aka task) to a LUN via the connected target. * * @param cmd The command to send. * @param outBuffer The data to send with the command. * @param outBufferOffset The offset of the first byte to send. * @param outBufferCount The number of bytes to send, if any. * @param inBuffer The buffer to fill with returned data. * @param inBufferOffset The first byte to fill with returned data. * @param inBufferMax The maximum amount of data to receive. * @return The number of bytes received. */ private int send(ScsiCommand cmd, byte[] outBuffer, int outBufferOffset, int outBufferCount, byte[] inBuffer, int inBufferOffset, int inBufferMax) { return getActiveConnection() .send(cmd, outBuffer, outBufferOffset, outBufferCount, inBuffer, inBufferOffset, inBufferMax); } private <T extends ScsiResponse> T send(Class<T> clazz, ScsiCommand cmd, byte[] buffer, int offset, int count, int expected) { return getActiveConnection().send(clazz, cmd, buffer, offset, count, expected); } }
Azquelt/cdi-tck
impl/src/main/java/org/jboss/cdi/tck/tests/definition/stereotype/priority/PriorityStereotype.java
package org.jboss.cdi.tck.tests.definition.stereotype.priority; import jakarta.annotation.Priority; import jakarta.enterprise.inject.Stereotype; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Simple stereotype with @Priority */ @Stereotype @Priority(100) @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface PriorityStereotype { }
Maledictus/leechcraft
src/plugins/azoth/msgformatterwidget.h
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 <NAME> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #ifndef PLUGINS_AZOTH_MSGFORMATTERWIDGET_H #define PLUGINS_AZOTH_MSGFORMATTERWIDGET_H #include <functional> #include <QWidget> #include <QTextCharFormat> #include <QTextBlockFormat> #include <QTextFrameFormat> class QTextEdit; namespace LC { namespace Azoth { class MsgFormatterWidget : public QWidget { Q_OBJECT QTextEdit *Edit_; const QTextCharFormat StockCharFormat_; const QTextBlockFormat StockBlockFormat_; const QTextFrameFormat StockFrameFormat_; QAction *FormatBold_; QAction *FormatItalic_; QAction *FormatUnderline_; QAction *FormatStrikeThrough_; QAction *FormatColor_; QAction *FormatFont_; QAction *FormatAlignLeft_; QAction *FormatAlignCenter_; QAction *FormatAlignRight_; QAction *FormatAlignJustify_; QAction *AddEmoticon_; bool HasCustomFormatting_; QWidget *SmilesTooltip_; public: MsgFormatterWidget (QTextEdit*, QWidget* = 0); bool HasCustomFormatting () const; void Clear (); QString GetNormalizedRichText () const; void HidePopups (); private: void CharFormatActor (std::function<void (QTextCharFormat*)>); void BlockFormatActor (std::function<void (QTextBlockFormat*)>); QTextCharFormat GetActualCharFormat () const; private slots: void handleBold (); void handleItalic (); void handleUnderline (); void handleStrikeThrough (); void handleTextColor (); void handleFont (); void handleParaAlignment (); void handleAddEmoticon (); void handleEmoPackChanged (); void insertEmoticon (); void checkCleared (); void updateState (const QTextCharFormat&); }; } } #endif
agaveplatform/science-apis
agave-uuids/uuids-api/src/main/java/org/iplantc/service/uuid/resource/impl/AbstractUuidResource.java
<filename>agave-uuids/uuids-api/src/main/java/org/iplantc/service/uuid/resource/impl/AbstractUuidResource.java package org.iplantc.service.uuid.resource.impl; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.StatusLine; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.log4j.Logger; import org.iplantc.service.common.auth.JWTClient; import org.iplantc.service.common.clients.AgaveLogServiceClient; import org.iplantc.service.common.clients.AgaveLogServiceClient.ServiceKeys; import org.iplantc.service.common.exceptions.TenantException; import org.iplantc.service.common.exceptions.UUIDException; import org.iplantc.service.common.persistence.TenancyHelper; import org.iplantc.service.common.restlet.resource.AbstractAgaveResource; import org.iplantc.service.common.uuid.AgaveUUID; import org.iplantc.service.uuid.exceptions.UUIDResolutionException; import org.restlet.Request; import org.restlet.data.Header; import org.restlet.data.Status; import org.restlet.resource.ResourceException; import org.restlet.util.Series; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import java.io.InputStream; import java.net.URI; import java.net.URLEncoder; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.*; import java.util.concurrent.Callable; /** * @author dooley * */ public class AbstractUuidResource extends AbstractAgaveResource { private static final Logger log = Logger .getLogger(AbstractUuidResource.class); /** * */ public AbstractUuidResource() { } /** * Creates a {@link AgaveUUID} object for the uuid in the URL or throws an * exception that can be re-thrown from the route method. * * @param uuid the uuid from the request path to resolve * @return AgaveUUID object referenced in the path * @throws ResourceException if the uuid cannot be resolved */ protected AgaveUUID getAgaveUUIDInPath(String uuid) throws ResourceException { AgaveUUID agaveUuid; if (StringUtils.isEmpty(uuid)) { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No uuid provided"); } else { try { agaveUuid = new AgaveUUID(uuid); } catch (UUIDException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "No resource found matching " + uuid, e); } catch (Throwable e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Unable to resolve uuid " + uuid, e); } } return agaveUuid; } /** * Convenience class to log usage info per request * * @param activityKey the key to log */ protected void logUsage(AgaveLogServiceClient.ActivityKeys activityKey) { AgaveLogServiceClient.log(getServiceKey().name(), activityKey.name(), getAuthenticatedUsername(), "", org.restlet.Request .getCurrent().getClientInfo().getUpstreamAddress()); } protected ServiceKeys getServiceKey() { return AgaveLogServiceClient.ServiceKeys.UUID02; } /** Try to ping a URL. Return true only if successful. */ final class ResourceResolutionTask implements Callable<JsonNode> { private final JsonNode json; private final String url; private final String filter; private final Map<String,String> headerMap; ResourceResolutionTask(String url, String filter, Map<String,String> headerMap) { this.url = url; this.json = null; this.filter = filter; this.headerMap = headerMap; } ResourceResolutionTask(JsonNode json, String filter, Map<String,String> headerMap) { this.url = null; this.json = json; this.filter = filter; this.headerMap = headerMap; } /** Access a URL, and see if you get a healthy response. */ @Override public JsonNode call() { if (json == null) { try { return fetchResource(this.url, this.filter, this.headerMap); } catch (UUIDResolutionException e) { log.error(e); return new ObjectMapper().createObjectNode() .put("status", "error") .put("message", e.getMessage()); } } else { return json; } } } /** * * @author dooley * */ private static final class ApiResponse { String url; Boolean success; Long timing; JsonNode response; @Override public String toString() { return response == null ? "{}" : response.toString(); } } /** * Fetches the resource at the given URL using a HTTP Get and pass through * auth headers. * * @param resourceUrl the url to the resource requested * @param filter the url filter to use on the remote request * @param headerMap the auth and client headers used to request the resource * @return JsonNode representation of the naked response * @throws UUIDResolutionException if unable to resolve the uuid to a valid resource */ protected JsonNode fetchResource(String resourceUrl, String filter, Map<String,String> headerMap) throws UUIDResolutionException { ObjectMapper mapper = new ObjectMapper(); JsonNode attemptResponse; String internalUrl = null; try { internalUrl = getInternalResourceUrl(resourceUrl); if (StringUtils.isNotEmpty(filter)) { if (StringUtils.contains(internalUrl, "?")) { internalUrl += "&filter="+URLEncoder.encode(StringUtils.stripToEmpty(filter), "utf-8"); } else { internalUrl += "?filter="+URLEncoder.encode(StringUtils.stripToEmpty(filter), "utf-8"); } } log.debug(String.format("Resolving %s to %s", resourceUrl, internalUrl)); URI escapedUri = URI.create(internalUrl); CloseableHttpClient httpclient; if (escapedUri.getScheme().equalsIgnoreCase("https")) { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted( final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }) .useTLS() .build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext, new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"}, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf) .setRedirectStrategy(LaxRedirectStrategy.INSTANCE) .build(); } else { httpclient = HttpClients.custom() .setRedirectStrategy(LaxRedirectStrategy.INSTANCE) .build(); } HttpGet httpGet = new HttpGet(escapedUri); // add the auth and client headers provided to this method RequestConfig config = RequestConfig.custom() .setConnectTimeout(30000) .setSocketTimeout(30000) .build(); httpGet.setConfig(config); for (String headerName: headerMap.keySet()) { httpGet.addHeader(headerName, headerMap.get(headerName)); } long callstart = System.currentTimeMillis(); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { InputStream in = null; try { int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); long contentLength = entity.getContentLength(); if (contentLength > 0 || contentLength == -1) { in = entity.getContent(); attemptResponse = mapper.readTree(in); // if successful, just return the result from the response if (statusCode >= 200 && statusCode <= 300) { if (attemptResponse.hasNonNull("result")) { // calls to the files api will return an array. the first (and only // since we appended limit=1 to files api queries) object is // always the one we're interested in. if (attemptResponse.get("result").isArray()) { return attemptResponse.get("result").get(0); } else { return attemptResponse.get("result"); } } else { return mapper.createObjectNode(); } } // if failed, just return the error message and status from teh response. else { if (attemptResponse.hasNonNull("version")) ((ObjectNode) attemptResponse).remove("version"); if (attemptResponse.hasNonNull("result")) ((ObjectNode) attemptResponse).remove("result"); return attemptResponse; } } // if no content is returned, return an empty object. else { return mapper.createObjectNode(); } } catch (Exception e) { int statusCode = 0; String message = null; if (response != null) { StatusLine statusLine = response.getStatusLine(); if (statusLine != null) { statusCode = statusLine.getStatusCode(); message = statusLine.getReasonPhrase(); } } throw new UUIDResolutionException("Failed to resolve " + internalUrl + ". Server responded with: " + statusCode + " - " + message, e); } finally { try { assert in != null; in.close(); } catch (Exception ignore) {} } } catch (ConnectTimeoutException e) { throw new UUIDResolutionException("Failed to resolve " + resourceUrl + ". Remote call to " + escapedUri + " timed out after " + (System.currentTimeMillis() - callstart) + " milliseconds.", e); } catch (SSLException e) { if (StringUtils.equalsIgnoreCase(escapedUri.getScheme(), "https")) { throw new UUIDResolutionException("Failed to resolve " + resourceUrl + ". Remote call to " + escapedUri + " failed due to the remote side not supporting SSL.", e); } else { throw new UUIDResolutionException("Failed to resolve " + resourceUrl + ". Remote call to " + escapedUri + " failed due a server side SSL failure."); } } } catch (UUIDResolutionException e) { throw e; } catch (Throwable e) { throw new UUIDResolutionException("Failed to resolve " + resourceUrl + " due to internal server error."); } } /** * Converts the proper external tenant resource url into an internal URI that can be forwarded * to the other services for resolution without hitting the frontend. * @param filteredResourceUrl the external url to translate * @return an internal url representation of the resource */ protected String getInternalResourceUrl(String filteredResourceUrl) { URI externalUri = URI.create(filteredResourceUrl); // splitting the path will remove the trailing slash, and we will lose it in the final reassembly, so // we record it here so we can add it back later. String trailingSlash = filteredResourceUrl.endsWith("/") ? "/" : ""; // tokenize the resource path. We remove the leading slash so we don't have to deal with // an empty first token String[] tokens = externalUri.getPath().replaceFirst("/", "").split("/"); List<String> pathList = new ArrayList<>(); pathList.addAll(Arrays.asList(tokens)); // the first token is the name of the api resource, which is also the service name String serviceName = "meta".equals(pathList.get(0)) ? "metadata" : pathList.get(0); // files and jobs services both have their respective service names as the first token in the path, so // we simply use the existing path, sans the version. if ("jobs".equals(serviceName)) { // the second token is the version of the api, which we remove as the backend service does not // use this in its path resolution. pathList.remove(1); } else if ("files".equals(serviceName)) { // the second token is the version of the api, which we remove as the backend service does not // use this in its path resolution. pathList.remove(1); String[] filePathTokens = pathList.toArray(new String[]{}); if (filePathTokens[1].equals("media")) { filePathTokens[1] = "listings"; } pathList.clear(); pathList.addAll(Arrays.asList(filePathTokens)); } else { // the remaining paths do not have the service name or version in the path, so we ensure both are // removed, then use the remaining path in the internal url. pathList.remove(0); // service name pathList.remove(0); // service version } return String.format("http://%s/%s%s", serviceName, String.join("/", pathList), trailingSlash); } /** * Creates a {@link Map} of header names and values used in the requests * to resolve resource representations. * * @return the auth credentials for this request * @throws TenantException if unable to look up current tenant */ protected Map<String,String> getRequestAuthCredentials() throws TenantException { Map<String,String> headerMap = new HashMap<String,String>(); // these will uniquely identify the requesting client headerMap.put("Content-Type", "application/json"); headerMap.put("User-Agent", "Agave-UUID-API/"+ org.iplantc.service.common.Settings.getContainerId()); // we add the jwt header for backend (dev) access String jwtHeaderKey = JWTClient.getJwtHeaderKeyForTenant(TenancyHelper.getCurrentTenantId()); Series<Header> headers = Request.getCurrent().getHeaders(); Header jwtHeader = headers.getFirst(jwtHeaderKey); if (jwtHeader != null) { headerMap.put(jwtHeaderKey, jwtHeader.getValue()); } // we add the frontend bearer token if present. Header authHeader = headers.getFirst("authorization"); if (authHeader != null) { headerMap.put("Authorization", authHeader.getValue()); } return headerMap; } }
threefishes/springCloudMainService
cloud-api/src/main/java/cn/threefishes/cloudapi/config/hikari/DBProperties.java
package cn.threefishes.cloudapi.config.hikari; import com.zaxxer.hikari.HikariDataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "hikari") public class DBProperties { private HikariDataSource master; private HikariDataSource slave; public HikariDataSource getMaster() { return master; } public void setMaster(HikariDataSource master) { this.master = master; } public HikariDataSource getSlave() { return slave; } public void setSlave(HikariDataSource slave) { this.slave = slave; } }
VT-Visionarium/osnap
src/main/java/x3d/model/Background.java
<filename>src/main/java/x3d/model/Background.java // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.06.16 at 09:21:15 AM EDT // package x3d.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import x3d.fields.MFString; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{}X3DBackgroundNode"> * &lt;attribute name="backUrl" type="{}MFString" /> * &lt;attribute name="bottomUrl" type="{}MFString" /> * &lt;attribute name="frontUrl" type="{}MFString" /> * &lt;attribute name="leftUrl" type="{}MFString" /> * &lt;attribute name="rightUrl" type="{}MFString" /> * &lt;attribute name="topUrl" type="{}MFString" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "Background") public class Background extends X3DBackgroundNode { @XmlAttribute(name = "backUrl") protected MFString backUrl; @XmlAttribute(name = "bottomUrl") protected MFString bottomUrl; @XmlAttribute(name = "frontUrl") protected MFString frontUrl; @XmlAttribute(name = "leftUrl") protected MFString leftUrl; @XmlAttribute(name = "rightUrl") protected MFString rightUrl; @XmlAttribute(name = "topUrl") protected MFString topUrl; /** * Gets the value of the backUrl property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the backUrl property. * * <p> * For example, to add a new item, do as follows: * <pre> * getBackUrl().add(newItem); * </pre> * * * <p> * Objects of the following type(scale) are allowed in the list * {@link x3d.fields.SFString } * * */ public MFString getBackUrl() { if (backUrl == null) { backUrl = new MFString(); } return this.backUrl; } /** * Gets the value of the bottomUrl property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the bottomUrl property. * * <p> * For example, to add a new item, do as follows: * <pre> * getBottomUrl().add(newItem); * </pre> * * * <p> * Objects of the following type(scale) are allowed in the list * {@link x3d.fields.SFString } * * */ public MFString getBottomUrl() { if (bottomUrl == null) { bottomUrl = new MFString(); } return this.bottomUrl; } /** * Gets the value of the frontUrl property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the frontUrl property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFrontUrl().add(newItem); * </pre> * * * <p> * Objects of the following type(scale) are allowed in the list * {@link x3d.fields.SFString } * * */ public MFString getFrontUrl() { if (frontUrl == null) { frontUrl = new MFString(); } return this.frontUrl; } /** * Gets the value of the leftUrl property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the leftUrl property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLeftUrl().add(newItem); * </pre> * * * <p> * Objects of the following type(scale) are allowed in the list * {@link x3d.fields.SFString } * * */ public MFString getLeftUrl() { if (leftUrl == null) { leftUrl = new MFString(); } return this.leftUrl; } /** * Gets the value of the rightUrl property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the rightUrl property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRightUrl().add(newItem); * </pre> * * * <p> * Objects of the following type(scale) are allowed in the list * {@link x3d.fields.SFString } * * */ public MFString getRightUrl() { if (rightUrl == null) { rightUrl = new MFString(); } return this.rightUrl; } /** * Gets the value of the topUrl property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the topUrl property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTopUrl().add(newItem); * </pre> * * * <p> * Objects of the following type(scale) are allowed in the list * {@link x3d.fields.SFString } * * */ public MFString getTopUrl() { if (topUrl == null) { topUrl = new MFString(); } return this.topUrl; } }
keithliam/bayung-angeles-website
src/pages/Landing/QuoteSection.js
import React, { useEffect, useRef, useState } from 'react'; import { CSSTransition } from 'react-transition-group'; import Img from 'react-cool-img'; import classNames from 'classnames'; import logoBlue from '../../assets/images/ba-logo-blue.png'; import { registerScrollResizeEventListeners } from '../../helpers'; const QuoteSection = () => { const sectionRef = useRef(); const highlightJusticeTimeout = useRef(); const highlightHumanityTimeout = useRef(); const [imageAppear, setImageAppear] = useState(false); const [highlightJustice, setHighlightJustice] = useState(false); const [highlightHumanity, setHighlightHumanity] = useState(false); const startHighlightTimers = () => { if (!highlightJusticeTimeout.current) { highlightJusticeTimeout.current = setTimeout(() => setHighlightJustice(true), 500); } if (!highlightHumanityTimeout.current) { highlightHumanityTimeout.current = setTimeout(() => setHighlightHumanity(true), 2500); } }; const clearHighlightTimers = () => { clearTimeout(highlightJusticeTimeout.current); clearTimeout(highlightHumanityTimeout.current); highlightJusticeTimeout.current = null; highlightHumanityTimeout.current = null; }; useEffect(() => { const handleScrollResizeEvent = () => { if (sectionRef.current) { const { top } = sectionRef.current.getBoundingClientRect(); const newImageAppear = top <= window.innerHeight / 2; setImageAppear(newImageAppear); if (newImageAppear) { startHighlightTimers(); } else { clearHighlightTimers(); setHighlightJustice(false); setHighlightHumanity(false); } } }; const unregisterScrollResizeEventListeners = registerScrollResizeEventListeners(handleScrollResizeEvent); return () => { unregisterScrollResizeEventListeners(); clearHighlightTimers(); }; }, []); return ( <div ref={sectionRef} className="quote"> <CSSTransition in={imageAppear} classNames="fade" timeout={3000} unmountOnExit> <Img className="quote-bg" src={logoBlue} alt="BA logo" /> </CSSTransition> <div className="heading-line"> <span className="quote-line">We need leaders</span> <span className="quote-line">not in love with money</span> <span className="quote-line"> but in love with{' '} <span className={classNames('quote-highlight', { 'quote-highlight-show': highlightJustice })} > justice </span> . </span> <span className="quote-line">Not in love with publicity</span> <span className="quote-line"> but in love with{' '} <span className={classNames('quote-highlight', { 'quote-highlight-show': highlightHumanity })} > humanity </span> </span> </div> <span className="quote-credit"><NAME>.</span> </div> ); }; export default QuoteSection;
mattweldon/indie-ui
app/components/indie-button.js
<reponame>mattweldon/indie-ui<filename>app/components/indie-button.js export { default } from 'indie-ui/components/indie-button';
FrolovOlegVladimirovich/job4j
chess/src/main/java/ru/job4j/chess/figures/black/BishopBlack.java
<reponame>FrolovOlegVladimirovich/job4j package ru.job4j.chess.figures.black; import ru.job4j.chess.figures.Bishop; import ru.job4j.chess.figures.Cell; import ru.job4j.chess.figures.Figure; /** * Фигура "Черный слон". * * @author <NAME> (<EMAIL>) * @version $Id$ * @since 27.06.2019 */ public class BishopBlack extends Bishop implements Figure { private final Cell position; public BishopBlack(final Cell position) { this.position = position; } @Override public Cell position() { return this.position; } @Override public Figure copy(Cell dest) { return new BishopBlack(dest); } }
Switch-Mexico/switch
src/imports/ui/components/Navigation/Dropdown.js
<gh_stars>1-10 import { NavLink } from 'react-router-dom'; import { push as MenuContainer } from 'react-burger-menu'; import { Menu, Dropdown, Label, Header } from 'semantic-ui-react'; import 'semantic-ui-css/semantic.min.css'; const HeaderBar = ({ actions }) => <Menu.Menu position="right"> <Dropdown item icon="user"> <Dropdown.Menu> <NavLink id="chart" className="menu-item" to="/query"> <Dropdown.Item> <span>Profil</span> </Dropdown.Item> </NavLink> <NavLink id="chart" className="menu-item" to="/mutation"> <Dropdown.Item> <span>Profil</span> </Dropdown.Item> </NavLink> <Dropdown.Item>Abmelden</Dropdown.Item> </Dropdown.Menu> </Dropdown> </Menu.Menu>; export default HeaderBar;
dounine/clouddisk
src/main/java/com/dounine/clouddisk360/store/BasicCookieStore3.java
package com.dounine.clouddisk360.store; import java.util.Date; public class BasicCookieStore3 { private Date creationDate; private String domain; private Date expiryDate; private String name; private String path; private Boolean persistent; private Boolean secure; private String value; private Integer version; public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Date getExpiryDate() { return expiryDate; } public void setExpiryDate(Date expiryDate) { this.expiryDate = expiryDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Boolean getPersistent() { return persistent; } public void setPersistent(Boolean persistent) { this.persistent = persistent; } public Boolean getSecure() { return secure; } public void setSecure(Boolean secure) { this.secure = secure; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } }
cmlimm/uni-projects
C-Course/Workshops/HW4/concatstring.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> int len(char *str){ int len = 0; while (str[len] != '\0'){ len += 1; } return len; } char *concat_string(char *str1, char *str2){ int n1 = len(str1); int n2 = len(str2); int i; char *concat = malloc(n1 + n2); for (i = 0; i < n1; i++){ concat[i] = str1[i]; } for (i = 0; i < n2; i++){ concat[n1 + i] = str2[i]; } return concat; } int main() { char str1[40]; char str2[40]; char *concat; scanf("%39s", str1); scanf("%39s", str2); concat = concat_string(str1, str2); printf("Concatenated strings: %s\n", concat); free(concat); return 0; }
FeodorFitsner/learning_computer-science
src/InterviewBit/src/Courses/Programming/Level2_Math/Examples/VerifyPrime/Java/Solution.java
package InterviewBit.src.Courses.Programming.Level2_Math.Examples.VerifyPrime.Java; public class Solution { public static void main(String[] args) { int result = isPrime(10); System.out.println(result); } public static int isPrime(int A) { if (A == 1) { return 0; } int upperLimit = (int)(Math.sqrt(A)); for (int i = 2; i <= upperLimit; i++) { if (i < A && A % i == 0) { return 0; } } return 1; } }
sockduct/Hackerrank
Python/arrayhg.py
def hglist(arr): size = 6 hgres = [] for row in range(size - 2): for col in range(size - 2): hgres.append(sum(arr[row][col:col + 3]) + arr[row + 1][col + 1] + sum(arr[row + 2][col:col + 3])) return hgres def arrstr(arr, colwidth=3): size = 6 res = '' for row in arr: for col in row: res += f'{col:>{colwidth}}' res += '\n' return res def main(): matrix = [list(map(int, input().split())) for _ in range(6)] ''' print(f'\n{arrstr(matrix)}') res = hglist(matrix) hgmatrix = [res[step:step + 4] for step in range(0, 13, 4)] print(f'{arrstr(hgmatrix, 4)}') ''' print(f'{max(hglist(matrix))}') if __name__ == '__main__': main()
ctishen/LuatOS
bsp/air001/impl/luat_gpio_air001.c
#include "luat_vdev_gpio.h" #include "luat_gpio.h" int luat_vdev_gpio_init(void) { return 0; } void luat_gpio_mode(int pin, int mode, int pull, int initOutput) { } int luat_gpio_setup(luat_gpio_t* gpio) { return -1; } int luat_gpio_set(int pin, int level) { return -1; } int luat_gpio_get(int pin) { return -1; } void luat_gpio_close(int pin) { // nop }
Toinounet21/crabalanchego
utils/crypto/secp256k1r.go
// Copyright (C) 2019-2021, <NAME>, Inc. All rights reserved. // See the file LICENSE for licensing terms. package crypto import ( "bytes" "errors" "sort" stdecdsa "crypto/ecdsa" "github.com/decred/dcrd/dcrec/secp256k1/v3/ecdsa" secp256k1 "github.com/decred/dcrd/dcrec/secp256k1/v3" "github.com/Toinounet21/swapalanchego/cache" "github.com/Toinounet21/swapalanchego/ids" "github.com/Toinounet21/swapalanchego/utils" "github.com/Toinounet21/swapalanchego/utils/hashing" ) const ( // SECP256K1RSigLen is the number of bytes in a secp2561k recoverable // signature SECP256K1RSigLen = 65 // SECP256K1RSKLen is the number of bytes in a secp2561k recoverable private // key SECP256K1RSKLen = 32 // SECP256K1RPKLen is the number of bytes in a secp2561k recoverable public // key SECP256K1RPKLen = 33 // from the decred library: // compactSigMagicOffset is a value used when creating the compact signature // recovery code inherited from Bitcoin and has no meaning, but has been // retained for compatibility. For historical purposes, it was originally // picked to avoid a binary representation that would allow compact // signatures to be mistaken for other components. compactSigMagicOffset = 27 ) var errCompressed = errors.New("wasn't expecting a compresses key") type FactorySECP256K1R struct{ Cache cache.LRU } // NewPrivateKey implements the Factory interface func (*FactorySECP256K1R) NewPrivateKey() (PrivateKey, error) { k, err := secp256k1.GeneratePrivateKey() return &PrivateKeySECP256K1R{sk: k}, err } // ToPublicKey implements the Factory interface func (*FactorySECP256K1R) ToPublicKey(b []byte) (PublicKey, error) { key, err := secp256k1.ParsePubKey(b) return &PublicKeySECP256K1R{ pk: key, bytes: b, }, err } // ToPrivateKey implements the Factory interface func (*FactorySECP256K1R) ToPrivateKey(b []byte) (PrivateKey, error) { return &PrivateKeySECP256K1R{ sk: secp256k1.PrivKeyFromBytes(b), bytes: b, }, nil } // RecoverPublicKey returns the public key from a 65 byte signature func (f *FactorySECP256K1R) RecoverPublicKey(msg, sig []byte) (PublicKey, error) { return f.RecoverHashPublicKey(hashing.ComputeHash256(msg), sig) } // RecoverHashPublicKey returns the public key from a 65 byte signature func (f *FactorySECP256K1R) RecoverHashPublicKey(hash, sig []byte) (PublicKey, error) { cacheBytes := make([]byte, len(hash)+len(sig)) copy(cacheBytes, hash) copy(cacheBytes[len(hash):], sig) id := hashing.ComputeHash256Array(cacheBytes) if cachedPublicKey, ok := f.Cache.Get(id); ok { return cachedPublicKey.(*PublicKeySECP256K1R), nil } if err := verifySECP256K1RSignatureFormat(sig); err != nil { return nil, err } sig, err := sigToRawSig(sig) if err != nil { return nil, err } rawPubkey, compressed, err := ecdsa.RecoverCompact(sig, hash) if err != nil { return nil, err } if compressed { return nil, errCompressed } pubkey := &PublicKeySECP256K1R{pk: rawPubkey} f.Cache.Put(id, pubkey) return pubkey, nil } type PublicKeySECP256K1R struct { pk *secp256k1.PublicKey addr ids.ShortID bytes []byte } // Verify implements the PublicKey interface func (k *PublicKeySECP256K1R) Verify(msg, sig []byte) bool { return k.VerifyHash(hashing.ComputeHash256(msg), sig) } // VerifyHash implements the PublicKey interface func (k *PublicKeySECP256K1R) VerifyHash(hash, sig []byte) bool { factory := FactorySECP256K1R{} pk, err := factory.RecoverHashPublicKey(hash, sig) if err != nil { return false } return k.Address() == pk.Address() } // ToECDSA returns the ecdsa representation of this public key func (k *PublicKeySECP256K1R) ToECDSA() *stdecdsa.PublicKey { return k.pk.ToECDSA() } // Address implements the PublicKey interface func (k *PublicKeySECP256K1R) Address() ids.ShortID { if k.addr == ids.ShortEmpty { addr, err := ids.ToShortID(hashing.PubkeyBytesToAddress(k.Bytes())) if err != nil { panic(err) } k.addr = addr } return k.addr } // Bytes implements the PublicKey interface func (k *PublicKeySECP256K1R) Bytes() []byte { if k.bytes == nil { k.bytes = k.pk.SerializeCompressed() } return k.bytes } type PrivateKeySECP256K1R struct { sk *secp256k1.PrivateKey pk *PublicKeySECP256K1R bytes []byte } // PublicKey implements the PrivateKey interface func (k *PrivateKeySECP256K1R) PublicKey() PublicKey { if k.pk == nil { k.pk = &PublicKeySECP256K1R{pk: k.sk.PubKey()} } return k.pk } // Sign implements the PrivateKey interface func (k *PrivateKeySECP256K1R) Sign(msg []byte) ([]byte, error) { return k.SignHash(hashing.ComputeHash256(msg)) } // SignHash implements the PrivateKey interface func (k *PrivateKeySECP256K1R) SignHash(hash []byte) ([]byte, error) { sig := ecdsa.SignCompact(k.sk, hash, false) // returns [v || r || s] return rawSigToSig(sig) } // ToECDSA returns the ecdsa representation of this private key func (k *PrivateKeySECP256K1R) ToECDSA() *stdecdsa.PrivateKey { return k.sk.ToECDSA() } // Bytes implements the PrivateKey interface func (k *PrivateKeySECP256K1R) Bytes() []byte { if k.bytes == nil { k.bytes = k.sk.Serialize() } return k.bytes } // raw sig has format [v || r || s] whereas the sig has format [r || s || v] func rawSigToSig(sig []byte) ([]byte, error) { if len(sig) != SECP256K1RSigLen { return nil, errInvalidSigLen } recCode := sig[0] copy(sig, sig[1:]) sig[SECP256K1RSigLen-1] = recCode - compactSigMagicOffset return sig, nil } // sig has format [r || s || v] whereas the raw sig has format [v || r || s] func sigToRawSig(sig []byte) ([]byte, error) { if len(sig) != SECP256K1RSigLen { return nil, errInvalidSigLen } newSig := make([]byte, SECP256K1RSigLen) newSig[0] = sig[SECP256K1RSigLen-1] + compactSigMagicOffset copy(newSig[1:], sig) return newSig, nil } // verifies the signature format in format [r || s || v] func verifySECP256K1RSignatureFormat(sig []byte) error { if len(sig) != SECP256K1RSigLen { return errInvalidSigLen } var s secp256k1.ModNScalar s.SetByteSlice(sig[32:64]) if s.IsOverHalfOrder() { return errMutatedSig } return nil } type innerSortSECP2561RSigs [][SECP256K1RSigLen]byte func (lst innerSortSECP2561RSigs) Less(i, j int) bool { return bytes.Compare(lst[i][:], lst[j][:]) < 0 } func (lst innerSortSECP2561RSigs) Len() int { return len(lst) } func (lst innerSortSECP2561RSigs) Swap(i, j int) { lst[j], lst[i] = lst[i], lst[j] } // SortSECP2561RSigs sorts a slice of SECP2561R signatures func SortSECP2561RSigs(lst [][SECP256K1RSigLen]byte) { sort.Sort(innerSortSECP2561RSigs(lst)) } // IsSortedAndUniqueSECP2561RSigs returns true if [sigs] is sorted func IsSortedAndUniqueSECP2561RSigs(sigs [][SECP256K1RSigLen]byte) bool { return utils.IsSortedAndUnique(innerSortSECP2561RSigs(sigs)) }
fjfd/microscope
microscope-storage/src/main/java/net/opentsdb/stats/StatsCollector.java
<gh_stars>10-100 // This file is part of OpenTSDB. // Copyright (C) 2010-2012 The OpenTSDB Authors. // // This program 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.1 of the License, or (at your // option) any later version. This program is distributed in the hope that it // will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser // General Public License for more details. You should have received a copy // of the GNU Lesser General Public License along with this program. If not, // see <http://www.gnu.org/licenses/>. package net.opentsdb.stats; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; /** * Receives various stats/metrics from the current process. * <p/> * Instances of this class are passed around to other classes to collect * their stats/metrics and do something with them (presumably send them * to a client). * <p/> * This class does not do any synchronization and is not thread-safe. */ public abstract class StatsCollector { private static final Logger LOG = LoggerFactory.getLogger(StatsCollector.class); /** * Prefix to save to every metric name, for example `tsd'. */ private final String prefix; /** * Extra tags to save to every data point emitted. */ private HashMap<String, String> extratags; /** * Buffer used to build lines emitted. */ private final StringBuilder buf = new StringBuilder(); /** * Constructor. * * @param prefix A prefix to save to every metric name, for example * `tsd'. */ public StatsCollector(final String prefix) { this.prefix = prefix; } /** * Method to override to actually emit a data point. * * @param datapoint A data point in a format suitable for a text * import. */ public abstract void emit(String datapoint); /** * Records a data point. * * @param name The name of the metric. * @param value The current value for that metric. */ public final void record(final String name, final long value) { record(name, value, null); } /** * Records a data point. * * @param name The name of the metric. * @param value The current value for that metric. */ public final void record(final String name, final Number value) { record(name, value.longValue(), null); } /** * Records a data point. * * @param name The name of the metric. * @param value The current value for that metric. * @param xtratag An extra tag ({@code name=value}) to save to those * data points (ignored if {@code null}). * @throws IllegalArgumentException if {@code xtratag != null} and it * doesn't follow the {@code name=value} format. */ public final void record(final String name, final Number value, final String xtratag) { record(name, value.longValue(), xtratag); } /** * Records a number of data points from a {@link net.opentsdb.stats.Histogram}. * * @param name The name of the metric. * @param histo The histogram to collect data points from. * @param xtratag An extra tag ({@code name=value}) to save to those * data points (ignored if {@code null}). * @throws IllegalArgumentException if {@code xtratag != null} and it * doesn't follow the {@code name=value} format. */ public final void record(final String name, final Histogram histo, final String xtratag) { record(name + "_50pct", histo.percentile(50), xtratag); record(name + "_75pct", histo.percentile(75), xtratag); record(name + "_90pct", histo.percentile(90), xtratag); record(name + "_95pct", histo.percentile(95), xtratag); } /** * Records a data point. * * @param name The name of the metric. * @param value The current value for that metric. * @param xtratag An extra tag ({@code name=value}) to save to this * data point (ignored if {@code null}). * @throws IllegalArgumentException if {@code xtratag != null} and it * doesn't follow the {@code name=value} format. */ public final void record(final String name, final long value, final String xtratag) { buf.setLength(0); buf.append(prefix).append(".") .append(name) .append(' ') .append(System.currentTimeMillis() / 1000) .append(' ') .append(value); if (xtratag != null) { if (xtratag.indexOf('=') != xtratag.lastIndexOf('=')) { throw new IllegalArgumentException("invalid xtratag: " + xtratag + " (multiple '=' signs), name=" + name + ", value=" + value); } else if (xtratag.indexOf('=') < 0) { throw new IllegalArgumentException("invalid xtratag: " + xtratag + " (missing '=' signs), name=" + name + ", value=" + value); } buf.append(' ').append(xtratag); } if (extratags != null) { for (final Map.Entry<String, String> entry : extratags.entrySet()) { buf.append(' ').append(entry.getKey()) .append('=').append(entry.getValue()); } } buf.append('\n'); emit(buf.toString()); } /** * Adds a tag to all the subsequent data points recorded. * <p/> * All subsequent calls to one of the {@code record} methods will * associate the tag given to this method with the data point. * <p/> * This method can be called multiple times to associate multiple tags * with all the subsequent data points. * * @param name The name of the tag. * @param value The value of the tag. * @throws IllegalArgumentException if the name or the value are empty * or otherwise invalid. * @see #clearExtraTag */ public final void addExtraTag(final String name, final String value) { if (name.length() <= 0) { throw new IllegalArgumentException("empty tag name, value=" + value); } else if (value.length() <= 0) { throw new IllegalArgumentException("empty value, tag name=" + name); } else if (name.indexOf('=') != -1) { throw new IllegalArgumentException("tag name contains `=': " + name + " (value = " + value + ')'); } else if (value.indexOf('=') != -1) { throw new IllegalArgumentException("tag value contains `=': " + value + " (name = " + name + ')'); } if (extratags == null) { extratags = new HashMap<String, String>(); } extratags.put(name, value); } /** * Adds a {@code host=hostname} tag. * <p/> * This uses {@link java.net.InetAddress#getLocalHost} to find the hostname of the * current host. If the hostname cannot be looked up, {@code (unknown)} * is used instead. */ public final void addHostTag() { try { addExtraTag("host", InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException x) { LOG.error("WTF? Can't find hostname for localhost!", x); addExtraTag("host", "(unknown)"); } } /** * Clears a tag added using {@link #addExtraTag addExtraTag}. * * @param name The name of the tag to remove from the set of extra * tags. * @throws IllegalStateException if there's no extra tag currently * recorded. * @throws IllegalArgumentException if the given name isn't in the * set of extra tags currently recorded. * @see #addExtraTag */ public final void clearExtraTag(final String name) { if (extratags == null) { throw new IllegalStateException("no extra tags added"); } if (extratags.get(name) == null) { throw new IllegalArgumentException("tag '" + name + "' not in" + extratags); } extratags.remove(name); } }
wzshare/Leetcode
easy/141_Linked_List_Cycle.cpp
<gh_stars>0 #include "../libstruct.h" using namespace std; /* * NO.141 * Given a linked list, determine if it has a cycle in it. */ class Solution { public: bool hasCycle(ListNode *head) { ListNode *fast = head, *slow = head; while(fast) { fast = fast->next; if (fast && (slow = slow->next)) fast = fast->next; else return false; if (slow == fast) return true; } return false; } }; int main(int argc, char const *argv[]) { Solution solution; return 0; }
mbarkley/jbpm-wb
jbpm-console-ng-human-tasks/jbpm-console-ng-human-tasks-backend/src/main/java/org/jbpm/console/ng/ht/backend/server/TaskLifeCycleServiceImpl.java
/* * Copyright 2014 JBoss by Red Hat. * * 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.jbpm.console.ng.ht.backend.server; import java.util.Map; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.jboss.errai.bus.server.annotations.Service; import org.jbpm.console.ng.ht.service.TaskLifeCycleService; import org.jbpm.services.api.UserTaskService; import org.jbpm.services.task.commands.ClaimTaskCommand; import org.jbpm.services.task.commands.CompositeCommand; import org.jbpm.services.task.commands.StartTaskCommand; import org.kie.api.task.model.Task; /** * * @author salaboy */ @Service @ApplicationScoped public class TaskLifeCycleServiceImpl implements TaskLifeCycleService { @Inject private UserTaskService taskService; public TaskLifeCycleServiceImpl() { } @Override public void start(long taskId, String user) { taskService.start(taskId, user); } @Override public void complete(long taskId, String user, Map<String, Object> params) { taskService.complete(taskId, user, params); } @Override public void claim(long taskId, String user, String deploymentId) { taskService.execute(deploymentId, new CompositeCommand<Void>(new StartTaskCommand(taskId, user), new ClaimTaskCommand(taskId, user))); } @Override public void release(long taskId, String user) { taskService.release(taskId, user); } @Override public void delegate(long taskId, String userId, String targetEntityId) { taskService.delegate(taskId, userId, targetEntityId); } }
calcacuervo/drools
drools-compiler/src/main/java/org/drools/compiler/compiler/ResourceConversionResult.java
<filename>drools-compiler/src/main/java/org/drools/compiler/compiler/ResourceConversionResult.java /* * Copyright 2015 JBoss by Red Hat * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.compiler.compiler; import org.kie.api.io.ResourceType; /** * Result of conversion from custom resource (like guided dtable or guided template) into DRL or DSLR. */ public class ResourceConversionResult { private final String content; private final ResourceType type; public ResourceConversionResult(String content, ResourceType type) { this.content = content; this.type = type; } public String getContent() { return content; } public ResourceType getType() { return type; } @Override public String toString() { return "ResourceConversionResult{" + "content='" + content + '\'' + ", type=" + type + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceConversionResult that = (ResourceConversionResult) o; if (content != null ? !content.equals(that.content) : that.content != null) return false; return !(type != null ? !type.equals(that.type) : that.type != null); } @Override public int hashCode() { int result = content != null ? content.hashCode() : 0; result = 31 * result + (type != null ? type.hashCode() : 0); return result; } }
AriasBros/ember-material
addon/components/dialog.js
import Component from '@ember/component'; import { computed } from '@ember/object'; import { addListener, removeListener } from '@ember/object/events'; import { inject as service } from '@ember/service'; import { later } from '@ember/runloop'; import { tryInvoke } from '@ember/utils'; import { A } from '@ember/array'; export default Component.extend({ dialog: service(), /** * @since 1.0.0 * @type {string} */ tagName: "div", /** * @since 1.0.0 * @type {string} */ layoutName: 'components/dialog', /** * @since 1.0.0 * @type {string[]} */ classNames: ["dialog-scrim"], /** * @since 1.0.0 * @type {string[]} */ classNameBindings: ["visible:dialog-scrim--visible", "hiding:dialog-scrim--hiding", "clickable:dialog-scrim--clickable", "identifierClass"], /** * @private * @since 1.0.0 * @return {string} */ identifierClass: computed("name", function() { return "dialog--" + this.get("name"); }), /** * @since 1.0.0 * @type {string} */ type: null, /** * @since 1.0.0 * @type {string} */ name: null, /** * @since 1.0.0 * @type {string} */ title: null, /** * @since 1.0.0 * @type {boolean} */ clickable: true, /** * @since 1.0.0 * @type {boolean} */ dismissable: true, /** * @since 1.0.0 * @type {string} */ dismissive: "Cancel", /** * @since 1.0.0 * @type {string} */ confirmation: "Accept", /** * @since 1.0.0 * @return {boolean} */ hasActions: computed("dismissive", "confirmation", function() { return this.get("dismissive") || this.get("confirmation"); }), /** * @since 1.0.0 * @type {boolean} */ actionsDisabled: computed("confirmationDisabled", "dismissiveDisabled", { get() { return this.get("confirmationDisabled") && this.get("dismissiveDisabled"); }, set(key, value) { this.setProperties({ confirmationDisabled: value, dismissiveDisabled: value }); return value; } }), /** * @since 1.0.0 * @type {boolean} */ confirmationDisabled: false, /** * @since 1.0.0 * @type {boolean} */ dismissiveDisabled: false, /** * @private * @since 1.0.0 * @type {boolean} */ visible: false, /** * @private * @since 1.0.0 * @type {boolean} */ hiding: false, present(...params) { this.presentedParams = params ? A(params) : A([]); this.set("visible", true); }, dismiss() { if (this.get("dismissable")) { this.set("hiding", true); later(this, function() { this.enabled(); this.set("hiding", false); this.set("visible", false); }, 350); } }, /** * @public * @since 1.0.0 */ disabled() { this.set("clickable", false); this.set("actionsDisabled", true); }, /** * @public * @since 1.0.0 */ enabled() { this.set("clickable", true); this.set("actionsDisabled", false); }, /** * @protected * @since 1.0.0 */ click(event) { if (this.get("clickable") && this.element === event.target) { this.send("onDismissDialog"); } }, /** * @protected * @since 1.0.0 */ keyUp(event) { if (event.keyCode === 27) { // Escape key this.send("onDismissDialog"); } }, /** * @protected * @since 1.0.0 */ didInsertElement() { const service = this.get("dialog"); const name = this.get("name"); addListener(service, `dialog.${name}.present`, this, "present"); addListener(service, `dialog.${name}.dismiss`, this, "dismiss"); this.$(document).on("keyup", (event) => { if (this.visible) { this.keyUp(event); } }); }, /** * @protected * @since 1.0.0 */ willDestroyElement() { const service = this.get("dialog"); const name = this.get("name"); removeListener(service, `dialog.${name}.present`, this, "present"); removeListener(service, `dialog.${name}.dismiss`, this, "dismiss"); this.$(document).off("keyup"); }, /** * @since 1.0.0 * @type {object} */ actions: { onDismissDialog() { const params = this.presentedParams.insertAt(0, this); const dismiss = tryInvoke(this, "onDismiss", params); if (dismiss === true || dismiss === undefined) { this.dismiss(); } return dismiss; }, onConfirmDialog() { const params = this.presentedParams.insertAt(0, this); const dismiss = tryInvoke(this, "onConfirm", params); if (dismiss === true || dismiss === undefined) { this.dismiss(); } return dismiss; }, } }).reopenClass({ /** * @since 1.0.0 * @type {string[]} */ positionalParams: ["name", "title", "confirmation", "dismissive"], });
RobotLocomotion/drake-python3.7
systems/primitives/integrator.h
#pragma once #include "drake/common/drake_copyable.h" #include "drake/systems/framework/context.h" #include "drake/systems/framework/vector_system.h" namespace drake { namespace systems { /// An integrator for a continuous vector input. /// /// @tparam_default_scalar /// @ingroup primitive_systems template <typename T> class Integrator final : public VectorSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Integrator) /// Constructs an %Integrator system. /// @param size number of elements in the signal to be processed. explicit Integrator(int size); /// Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit Integrator(const Integrator<U>&); ~Integrator() final; /// Sets the value of the integral modifying the state in the context. /// @p value must be a column vector of the appropriate size. void set_integral_value(Context<T>* context, const Eigen::Ref<const VectorX<T>>& value) const; private: // VectorSystem<T> override. void DoCalcVectorOutput( const Context<T>& context, const Eigen::VectorBlock<const VectorX<T>>& input, const Eigen::VectorBlock<const VectorX<T>>& state, Eigen::VectorBlock<VectorX<T>>* output) const final; // VectorSystem<T> override. void DoCalcVectorTimeDerivatives( const Context<T>& context, const Eigen::VectorBlock<const VectorX<T>>& input, const Eigen::VectorBlock<const VectorX<T>>& state, Eigen::VectorBlock<VectorX<T>>* derivatives) const final; }; } // namespace systems } // namespace drake
Andreas237/AndroidPolicyAutomation
ExtractedJars/RT_News_com.rt.mobile.english/javafiles/android/support/v4/media/session/MediaControllerCompat$TransportControls.java
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.v4.media.session; import android.net.Uri; import android.os.Bundle; import android.support.v4.media.RatingCompat; // Referenced classes of package android.support.v4.media.session: // MediaControllerCompat public static abstract class MediaControllerCompat$TransportControls { public abstract void fastForward(); public abstract void pause(); public abstract void play(); public abstract void playFromMediaId(String s, Bundle bundle); public abstract void playFromSearch(String s, Bundle bundle); public abstract void playFromUri(Uri uri, Bundle bundle); public abstract void prepare(); public abstract void prepareFromMediaId(String s, Bundle bundle); public abstract void prepareFromSearch(String s, Bundle bundle); public abstract void prepareFromUri(Uri uri, Bundle bundle); public abstract void rewind(); public abstract void seekTo(long l); public abstract void sendCustomAction(PlaybackStateCompat.CustomAction customaction, Bundle bundle); public abstract void sendCustomAction(String s, Bundle bundle); public abstract void setCaptioningEnabled(boolean flag); public abstract void setRating(RatingCompat ratingcompat); public abstract void setRating(RatingCompat ratingcompat, Bundle bundle); public abstract void setRepeatMode(int i); public abstract void setShuffleMode(int i); public abstract void skipToNext(); public abstract void skipToPrevious(); public abstract void skipToQueueItem(long l); public abstract void stop(); public static final String EXTRA_LEGACY_STREAM_TYPE = "android.media.session.extra.LEGACY_STREAM_TYPE"; MediaControllerCompat$TransportControls() { // 0 0:aload_0 // 1 1:invokespecial #15 <Method void Object()> // 2 4:return } }
jimmccusker/callimachus
test/org/callimachusproject/server/SPARQLEndPointTest.java
/* * Copyright (c) 2013 3 Round Stones Inc., Some 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 org.callimachusproject.server; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import javax.ws.rs.core.MultivaluedMap; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.ProtocolVersion; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHttpResponse; import org.callimachusproject.annotations.method; import org.callimachusproject.annotations.requires; import org.callimachusproject.annotations.type; import org.callimachusproject.server.base.MetadataServerTestCase; import org.callimachusproject.server.behaviours.NamedGraphSupport; import org.callimachusproject.server.behaviours.PUTSupport; import org.openrdf.annotations.Matching; import org.openrdf.model.Literal; import org.openrdf.model.Model; import org.openrdf.model.URI; import org.openrdf.model.impl.LinkedHashModel; import org.openrdf.model.vocabulary.RDF; import org.openrdf.query.BooleanQuery; import org.openrdf.query.GraphQuery; import org.openrdf.query.GraphQueryResult; import org.openrdf.query.Query; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.query.resultio.BooleanQueryResultFormat; import org.openrdf.query.resultio.BooleanQueryResultWriter; import org.openrdf.query.resultio.BooleanQueryResultWriterRegistry; import org.openrdf.query.resultio.TupleQueryResultFormat; import org.openrdf.query.resultio.TupleQueryResultWriter; import org.openrdf.query.resultio.TupleQueryResultWriterRegistry; import org.openrdf.repository.object.ObjectConnection; import org.openrdf.repository.object.RDFObject; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFWriter; import org.openrdf.rio.RDFWriterRegistry; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; public class SPARQLEndPointTest extends MetadataServerTestCase { @Matching("/sparql") public interface SPARQLEndPoint { } public static abstract class SPARQLEndPointSupport implements SPARQLEndPoint, RDFObject { @type("message/http") @method("POST") @requires("urn:test:grant") public HttpResponse post(@type("*/*") Map<String, String> parameters) throws Exception { ObjectConnection con = getObjectConnection(); ProtocolVersion ver = HttpVersion.HTTP_1_1; HttpResponse resp = new BasicHttpResponse(ver, 200, "OK"); Query query = con.prepareQuery(parameters.get("query")); if (query instanceof GraphQuery) { final GraphQueryResult result = ((GraphQuery) query).evaluate(); resp.setEntity(new BasicHttpEntity() { public InputStream getContent() throws IllegalStateException { ByteArrayOutputStream out = new ByteArrayOutputStream(); RDFWriter writer = RDFWriterRegistry.getInstance().get( RDFFormat.RDFXML).getWriter(out); try { writer.startRDF(); while (result.hasNext()) { writer.handleStatement(result.next()); } writer.endRDF(); return new ByteArrayInputStream(out.toByteArray()) { @Override public void close() throws IOException { try { super.close(); } finally { try { result.close(); } catch (QueryEvaluationException e) { throw new AssertionError(e); } } }}; } catch (Exception e) { throw new AssertionError(e); } } public Header getContentType() { return new BasicHeader("Content-Type", "application/rdf+xml"); } }); } else if (query instanceof TupleQuery) { final TupleQueryResult result = ((TupleQuery) query).evaluate(); resp.setEntity(new BasicHttpEntity() { public InputStream getContent() throws IllegalStateException { ByteArrayOutputStream out = new ByteArrayOutputStream(); TupleQueryResultWriter writer = TupleQueryResultWriterRegistry .getInstance().get( TupleQueryResultFormat.SPARQL) .getWriter(out); try { writer.startQueryResult(result.getBindingNames()); while (result.hasNext()) { writer.handleSolution(result.next()); } writer.endQueryResult(); return new ByteArrayInputStream(out.toByteArray()) { @Override public void close() throws IOException { try { super.close(); } finally { try { result.close(); } catch (QueryEvaluationException e) { throw new AssertionError(e); } } }}; } catch (Exception e) { throw new AssertionError(e); } } public Header getContentType() { return new BasicHeader("Content-Type", "application/sparql-results+xml"); } }); } else if (query instanceof BooleanQuery) { final boolean result = ((BooleanQuery) query).evaluate(); resp.setEntity(new BasicHttpEntity() { public InputStream getContent() throws IllegalStateException { ByteArrayOutputStream out = new ByteArrayOutputStream(); BooleanQueryResultWriter writer = BooleanQueryResultWriterRegistry .getInstance().get( BooleanQueryResultFormat.SPARQL) .getWriter(out); try { writer.write(result); return new ByteArrayInputStream(out.toByteArray()); } catch (Exception e) { throw new AssertionError(e); } } public Header getContentType() { return new BasicHeader("Content-Type", "application/sparql-results+xml"); } }); } else { throw new IllegalArgumentException(); } return resp; } } @Override public void setUp() throws Exception { config.addConcept(SPARQLEndPoint.class); config.addBehaviour(SPARQLEndPointSupport.class); config.addBehaviour(PUTSupport.class); config.addBehaviour(NamedGraphSupport.class); super.setUp(); server.setEnvelopeType("message/http"); } public void testGET_evaluateGraph() throws Exception { Model model = new LinkedHashModel(); WebResource root = client.path("root"); URI subj = vf.createURI(root.getURI().toASCIIString()); URI pred = vf .createURI("http://www.openrdf.org/rdf/2009/httpobject#inSparql"); Literal obj = vf .createLiteral("CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }"); URI NamedQuery = vf .createURI("http://www.openrdf.org/rdf/2009/httpobject#NamedQuery"); model.add(subj, RDF.TYPE, NamedQuery); model.add(subj, pred, obj); WebResource graph = client.path("graph"); graph.type("application/x-turtle").put(model); MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("query", "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }"); Model result = client.path("/sparql").post(Model.class, map); assertFalse(result.isEmpty()); } public void testGET_evaluateTuple() throws Exception { Model model = new LinkedHashModel(); WebResource root = client.path("root"); URI subj = vf.createURI(root.getURI().toASCIIString()); URI pred = vf .createURI("http://www.openrdf.org/rdf/2009/httpobject#inSparql"); Literal obj = vf.createLiteral("SELECT ?s ?p ?o WHERE { ?s ?p ?o }"); URI NamedQuery = vf .createURI("http://www.openrdf.org/rdf/2009/httpobject#NamedQuery"); model.add(subj, RDF.TYPE, NamedQuery); model.add(subj, pred, obj); WebResource graph = client.path("graph"); graph.type("application/x-turtle").put(model); MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("query", "SELECT ?s ?p ?o WHERE { ?s ?p ?o }"); String result = client.path("/sparql").post(String.class, map); assertTrue(result.startsWith("<?xml")); } }
ypiel-talend/components
components/components-processing/processing-runtime/src/main/java/org/talend/components/processing/runtime/typeconverter/TypeConverterFunction.java
package org.talend.components.processing.runtime.typeconverter; import java.util.Stack; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.generic.IndexedRecord; import org.talend.components.api.component.runtime.RuntimableRuntime; import org.talend.components.api.container.RuntimeContainer; import org.talend.components.processing.definition.typeconverter.TypeConverterProperties; import org.talend.daikon.java8.SerializableFunction; import org.talend.daikon.properties.ValidationResult; public class TypeConverterFunction implements SerializableFunction<IndexedRecord, IndexedRecord>, RuntimableRuntime<TypeConverterProperties> { private TypeConverterProperties properties; @Override public ValidationResult initialize(RuntimeContainer container, TypeConverterProperties properties) { this.properties = properties; return ValidationResult.OK; } @Override public IndexedRecord apply(IndexedRecord inputRecord) { Schema inputSchema = inputRecord.getSchema(); // Compute new schema Schema outputSchema = inputSchema; for (TypeConverterProperties.TypeConverterPropertiesInner currentPathConverter : properties.converters.subProperties) { if (currentPathConverter.field.getValue() != null && !currentPathConverter.field.getValue().isEmpty() && currentPathConverter.outputType.getValue() != null) { Stack<String> pathSteps = TypeConverterUtils.getPathSteps(currentPathConverter.field.getValue()); outputSchema = TypeConverterUtils.convertSchema(outputSchema, pathSteps, TypeConverterProperties.TypeConverterOutputTypes.valueOf(currentPathConverter.outputType.getValue()), currentPathConverter.outputFormat.getValue()); } } // Compute new fields final GenericRecordBuilder outputRecordBuilder = new GenericRecordBuilder(outputSchema); // Copy original values TypeConverterUtils.copyFieldsValues(inputRecord, outputRecordBuilder); // Convert values for (TypeConverterProperties.TypeConverterPropertiesInner currentValueConverter : properties.converters.subProperties) { // Loop on converters if (currentValueConverter.field.getValue() != null && !currentValueConverter.field.getValue().isEmpty() && currentValueConverter.outputType.getValue() != null) { Stack<String> pathSteps = TypeConverterUtils.getPathSteps(currentValueConverter.field.getValue()); TypeConverterUtils.convertValue(inputSchema, outputRecordBuilder, pathSteps, TypeConverterProperties.TypeConverterOutputTypes.valueOf(currentValueConverter.outputType.getValue()), currentValueConverter.outputFormat.getValue()); } } return outputRecordBuilder.build(); } }
godnoTA/acm.bsu.by
2. Рекуррентные соотношения/0.3. Порядок перемножения матриц #3537/[OK]172039.java
<reponame>godnoTA/acm.bsu.by import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; public class Priority { final static String filename = "input.txt"; static File fin = new File(filename); static File fout = new File("output.txt"); static int quantity = 0; static long[] sizes; public static void main (String args[]) throws IOException{ exists(filename); try { BufferedReader in = new BufferedReader(new FileReader( fin.getAbsoluteFile())); String s; if((s = in.readLine()) != null){ quantity = Integer.parseInt(s); } sizes = new long[quantity + 1]; int i = 0; s = in.readLine(); String[] str = s.split(" "); sizes[i] = Long.parseLong(str[0]); sizes[i + 1] = Long.parseLong(str[1]); i += 2; while ((s = in.readLine()) != null) { str = s.split(" "); sizes[i] = Long.parseLong(str[1]); i++; } try { if(!fout.exists()){ fout.createNewFile(); } PrintWriter out = new PrintWriter(fout.getAbsoluteFile()); try { out.print(multiplyOrder(sizes)); } finally { out.close(); } } catch(IOException e) { throw new RuntimeException(e); } finally { in.close(); } } catch(IOException e) { throw new RuntimeException(e); } } private static void exists(String fileName) throws FileNotFoundException { File file = new File(fileName); if (!file.exists()){ throw new FileNotFoundException(fin.getName()); } } public static int multiplyOrder(long[] p) { int n = p.length - 1; int[][] dp = new int[n + 1][n + 1]; for (int i = 1; i <= n; i++) { dp[i][i] = 0; } for (int l = 2; l <= n; l++) { for (int i = 1; i <= n - l + 1; i++) { int j = i + l - 1; dp[i][j] = Integer.MAX_VALUE; for (int k = i; k <= j - 1; k++) { dp[i][j] = (int) Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j]); } } } return dp[1][n]; } }
glenga/c_programming_a_modern_approach_2nd
chapter03/program/program3.1.c
<filename>chapter03/program/program3.1.c #include <stdio.h> int main(void) { int month, day, year; printf("Enter a date(mm/dd/yyyy): "); scanf("%d /%d /%d", &month, &day, &year); printf("You entered the date %.4d%.2d%2d", year, month, day); return 0; } // Enter a date(mm/dd/yyyy): 2/17/2011 // You entered the date 20110217
aliyun/alibabacloud-cpp-sdk
config-20190108/include/alibabacloud/config_20190108.hpp
// This file is auto-generated, don't edit it. Thanks. #ifndef ALIBABACLOUD_CONFIG20190108_H_ #define ALIBABACLOUD_CONFIG20190108_H_ #include <alibabacloud/open_api.hpp> #include <boost/any.hpp> #include <boost/throw_exception.hpp> #include <darabonba/core.hpp> #include <darabonba/util.hpp> #include <iostream> #include <map> #include <vector> using namespace std; namespace Alibabacloud_Config20190108 { class ActiveConfigRulesRequest : public Darabonba::Model { public: shared_ptr<string> configRuleIds{}; ActiveConfigRulesRequest() {} explicit ActiveConfigRulesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRuleIds) { res["ConfigRuleIds"] = boost::any(*configRuleIds); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRuleIds") != m.end() && !m["ConfigRuleIds"].empty()) { configRuleIds = make_shared<string>(boost::any_cast<string>(m["ConfigRuleIds"])); } } virtual ~ActiveConfigRulesRequest() = default; }; class ActiveConfigRulesResponseBodyOperateRuleResultOperateRuleItemList : public Darabonba::Model { public: shared_ptr<string> configRuleId{}; shared_ptr<string> errorCode{}; shared_ptr<bool> success{}; ActiveConfigRulesResponseBodyOperateRuleResultOperateRuleItemList() {} explicit ActiveConfigRulesResponseBodyOperateRuleResultOperateRuleItemList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (errorCode) { res["ErrorCode"] = boost::any(*errorCode); } if (success) { res["Success"] = boost::any(*success); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) { errorCode = make_shared<string>(boost::any_cast<string>(m["ErrorCode"])); } if (m.find("Success") != m.end() && !m["Success"].empty()) { success = make_shared<bool>(boost::any_cast<bool>(m["Success"])); } } virtual ~ActiveConfigRulesResponseBodyOperateRuleResultOperateRuleItemList() = default; }; class ActiveConfigRulesResponseBodyOperateRuleResult : public Darabonba::Model { public: shared_ptr<vector<ActiveConfigRulesResponseBodyOperateRuleResultOperateRuleItemList>> operateRuleItemList{}; ActiveConfigRulesResponseBodyOperateRuleResult() {} explicit ActiveConfigRulesResponseBodyOperateRuleResult(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (operateRuleItemList) { vector<boost::any> temp1; for(auto item1:*operateRuleItemList){ temp1.push_back(boost::any(item1.toMap())); } res["OperateRuleItemList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OperateRuleItemList") != m.end() && !m["OperateRuleItemList"].empty()) { if (typeid(vector<boost::any>) == m["OperateRuleItemList"].type()) { vector<ActiveConfigRulesResponseBodyOperateRuleResultOperateRuleItemList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["OperateRuleItemList"])){ if (typeid(map<string, boost::any>) == item1.type()) { ActiveConfigRulesResponseBodyOperateRuleResultOperateRuleItemList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } operateRuleItemList = make_shared<vector<ActiveConfigRulesResponseBodyOperateRuleResultOperateRuleItemList>>(expect1); } } } virtual ~ActiveConfigRulesResponseBodyOperateRuleResult() = default; }; class ActiveConfigRulesResponseBody : public Darabonba::Model { public: shared_ptr<ActiveConfigRulesResponseBodyOperateRuleResult> operateRuleResult{}; shared_ptr<string> requestId{}; ActiveConfigRulesResponseBody() {} explicit ActiveConfigRulesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (operateRuleResult) { res["OperateRuleResult"] = operateRuleResult ? boost::any(operateRuleResult->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OperateRuleResult") != m.end() && !m["OperateRuleResult"].empty()) { if (typeid(map<string, boost::any>) == m["OperateRuleResult"].type()) { ActiveConfigRulesResponseBodyOperateRuleResult model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["OperateRuleResult"])); operateRuleResult = make_shared<ActiveConfigRulesResponseBodyOperateRuleResult>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ActiveConfigRulesResponseBody() = default; }; class ActiveConfigRulesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ActiveConfigRulesResponseBody> body{}; ActiveConfigRulesResponse() {} explicit ActiveConfigRulesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ActiveConfigRulesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ActiveConfigRulesResponseBody>(model1); } } } virtual ~ActiveConfigRulesResponse() = default; }; class DeleteConfigRulesRequest : public Darabonba::Model { public: shared_ptr<string> configRuleIds{}; DeleteConfigRulesRequest() {} explicit DeleteConfigRulesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRuleIds) { res["ConfigRuleIds"] = boost::any(*configRuleIds); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRuleIds") != m.end() && !m["ConfigRuleIds"].empty()) { configRuleIds = make_shared<string>(boost::any_cast<string>(m["ConfigRuleIds"])); } } virtual ~DeleteConfigRulesRequest() = default; }; class DeleteConfigRulesResponseBodyOperateRuleResultOperateRuleItemList : public Darabonba::Model { public: shared_ptr<string> configRuleId{}; shared_ptr<string> errorCode{}; shared_ptr<bool> success{}; DeleteConfigRulesResponseBodyOperateRuleResultOperateRuleItemList() {} explicit DeleteConfigRulesResponseBodyOperateRuleResultOperateRuleItemList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (errorCode) { res["ErrorCode"] = boost::any(*errorCode); } if (success) { res["Success"] = boost::any(*success); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) { errorCode = make_shared<string>(boost::any_cast<string>(m["ErrorCode"])); } if (m.find("Success") != m.end() && !m["Success"].empty()) { success = make_shared<bool>(boost::any_cast<bool>(m["Success"])); } } virtual ~DeleteConfigRulesResponseBodyOperateRuleResultOperateRuleItemList() = default; }; class DeleteConfigRulesResponseBodyOperateRuleResult : public Darabonba::Model { public: shared_ptr<vector<DeleteConfigRulesResponseBodyOperateRuleResultOperateRuleItemList>> operateRuleItemList{}; DeleteConfigRulesResponseBodyOperateRuleResult() {} explicit DeleteConfigRulesResponseBodyOperateRuleResult(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (operateRuleItemList) { vector<boost::any> temp1; for(auto item1:*operateRuleItemList){ temp1.push_back(boost::any(item1.toMap())); } res["OperateRuleItemList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OperateRuleItemList") != m.end() && !m["OperateRuleItemList"].empty()) { if (typeid(vector<boost::any>) == m["OperateRuleItemList"].type()) { vector<DeleteConfigRulesResponseBodyOperateRuleResultOperateRuleItemList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["OperateRuleItemList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DeleteConfigRulesResponseBodyOperateRuleResultOperateRuleItemList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } operateRuleItemList = make_shared<vector<DeleteConfigRulesResponseBodyOperateRuleResultOperateRuleItemList>>(expect1); } } } virtual ~DeleteConfigRulesResponseBodyOperateRuleResult() = default; }; class DeleteConfigRulesResponseBody : public Darabonba::Model { public: shared_ptr<DeleteConfigRulesResponseBodyOperateRuleResult> operateRuleResult{}; shared_ptr<string> requestId{}; DeleteConfigRulesResponseBody() {} explicit DeleteConfigRulesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (operateRuleResult) { res["OperateRuleResult"] = operateRuleResult ? boost::any(operateRuleResult->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OperateRuleResult") != m.end() && !m["OperateRuleResult"].empty()) { if (typeid(map<string, boost::any>) == m["OperateRuleResult"].type()) { DeleteConfigRulesResponseBodyOperateRuleResult model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["OperateRuleResult"])); operateRuleResult = make_shared<DeleteConfigRulesResponseBodyOperateRuleResult>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DeleteConfigRulesResponseBody() = default; }; class DeleteConfigRulesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DeleteConfigRulesResponseBody> body{}; DeleteConfigRulesResponse() {} explicit DeleteConfigRulesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DeleteConfigRulesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DeleteConfigRulesResponseBody>(model1); } } } virtual ~DeleteConfigRulesResponse() = default; }; class DescribeComplianceRequest : public Darabonba::Model { public: shared_ptr<string> complianceType{}; shared_ptr<string> configRuleId{}; shared_ptr<long> memberId{}; shared_ptr<bool> multiAccount{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceType{}; DescribeComplianceRequest() {} explicit DescribeComplianceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceType) { res["ComplianceType"] = boost::any(*complianceType); } if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceType") != m.end() && !m["ComplianceType"].empty()) { complianceType = make_shared<string>(boost::any_cast<string>(m["ComplianceType"])); } if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<long>(boost::any_cast<long>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } } virtual ~DescribeComplianceRequest() = default; }; class DescribeComplianceResponseBodyComplianceResultCompliances : public Darabonba::Model { public: shared_ptr<string> complianceType{}; shared_ptr<long> count{}; DescribeComplianceResponseBodyComplianceResultCompliances() {} explicit DescribeComplianceResponseBodyComplianceResultCompliances(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceType) { res["ComplianceType"] = boost::any(*complianceType); } if (count) { res["Count"] = boost::any(*count); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceType") != m.end() && !m["ComplianceType"].empty()) { complianceType = make_shared<string>(boost::any_cast<string>(m["ComplianceType"])); } if (m.find("Count") != m.end() && !m["Count"].empty()) { count = make_shared<long>(boost::any_cast<long>(m["Count"])); } } virtual ~DescribeComplianceResponseBodyComplianceResultCompliances() = default; }; class DescribeComplianceResponseBodyComplianceResult : public Darabonba::Model { public: shared_ptr<vector<DescribeComplianceResponseBodyComplianceResultCompliances>> compliances{}; shared_ptr<long> totalCount{}; DescribeComplianceResponseBodyComplianceResult() {} explicit DescribeComplianceResponseBodyComplianceResult(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (compliances) { vector<boost::any> temp1; for(auto item1:*compliances){ temp1.push_back(boost::any(item1.toMap())); } res["Compliances"] = boost::any(temp1); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Compliances") != m.end() && !m["Compliances"].empty()) { if (typeid(vector<boost::any>) == m["Compliances"].type()) { vector<DescribeComplianceResponseBodyComplianceResultCompliances> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Compliances"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeComplianceResponseBodyComplianceResultCompliances model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } compliances = make_shared<vector<DescribeComplianceResponseBodyComplianceResultCompliances>>(expect1); } } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } } virtual ~DescribeComplianceResponseBodyComplianceResult() = default; }; class DescribeComplianceResponseBody : public Darabonba::Model { public: shared_ptr<DescribeComplianceResponseBodyComplianceResult> complianceResult{}; shared_ptr<string> requestId{}; DescribeComplianceResponseBody() {} explicit DescribeComplianceResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceResult) { res["ComplianceResult"] = complianceResult ? boost::any(complianceResult->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceResult") != m.end() && !m["ComplianceResult"].empty()) { if (typeid(map<string, boost::any>) == m["ComplianceResult"].type()) { DescribeComplianceResponseBodyComplianceResult model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ComplianceResult"])); complianceResult = make_shared<DescribeComplianceResponseBodyComplianceResult>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeComplianceResponseBody() = default; }; class DescribeComplianceResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeComplianceResponseBody> body{}; DescribeComplianceResponse() {} explicit DescribeComplianceResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeComplianceResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeComplianceResponseBody>(model1); } } } virtual ~DescribeComplianceResponse() = default; }; class DescribeComplianceSummaryRequest : public Darabonba::Model { public: shared_ptr<long> memberId{}; shared_ptr<bool> multiAccount{}; DescribeComplianceSummaryRequest() {} explicit DescribeComplianceSummaryRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<long>(boost::any_cast<long>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } } virtual ~DescribeComplianceSummaryRequest() = default; }; class DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByConfigRule : public Darabonba::Model { public: shared_ptr<long> complianceSummaryTimestamp{}; shared_ptr<long> compliantCount{}; shared_ptr<long> nonCompliantCount{}; shared_ptr<long> totalCount{}; DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByConfigRule() {} explicit DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByConfigRule(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceSummaryTimestamp) { res["ComplianceSummaryTimestamp"] = boost::any(*complianceSummaryTimestamp); } if (compliantCount) { res["CompliantCount"] = boost::any(*compliantCount); } if (nonCompliantCount) { res["NonCompliantCount"] = boost::any(*nonCompliantCount); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceSummaryTimestamp") != m.end() && !m["ComplianceSummaryTimestamp"].empty()) { complianceSummaryTimestamp = make_shared<long>(boost::any_cast<long>(m["ComplianceSummaryTimestamp"])); } if (m.find("CompliantCount") != m.end() && !m["CompliantCount"].empty()) { compliantCount = make_shared<long>(boost::any_cast<long>(m["CompliantCount"])); } if (m.find("NonCompliantCount") != m.end() && !m["NonCompliantCount"].empty()) { nonCompliantCount = make_shared<long>(boost::any_cast<long>(m["NonCompliantCount"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } } virtual ~DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByConfigRule() = default; }; class DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByResource : public Darabonba::Model { public: shared_ptr<long> complianceSummaryTimestamp{}; shared_ptr<long> compliantCount{}; shared_ptr<long> nonCompliantCount{}; shared_ptr<long> totalCount{}; DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByResource() {} explicit DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByResource(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceSummaryTimestamp) { res["ComplianceSummaryTimestamp"] = boost::any(*complianceSummaryTimestamp); } if (compliantCount) { res["CompliantCount"] = boost::any(*compliantCount); } if (nonCompliantCount) { res["NonCompliantCount"] = boost::any(*nonCompliantCount); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceSummaryTimestamp") != m.end() && !m["ComplianceSummaryTimestamp"].empty()) { complianceSummaryTimestamp = make_shared<long>(boost::any_cast<long>(m["ComplianceSummaryTimestamp"])); } if (m.find("CompliantCount") != m.end() && !m["CompliantCount"].empty()) { compliantCount = make_shared<long>(boost::any_cast<long>(m["CompliantCount"])); } if (m.find("NonCompliantCount") != m.end() && !m["NonCompliantCount"].empty()) { nonCompliantCount = make_shared<long>(boost::any_cast<long>(m["NonCompliantCount"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } } virtual ~DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByResource() = default; }; class DescribeComplianceSummaryResponseBodyComplianceSummary : public Darabonba::Model { public: shared_ptr<DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByConfigRule> complianceSummaryByConfigRule{}; shared_ptr<DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByResource> complianceSummaryByResource{}; DescribeComplianceSummaryResponseBodyComplianceSummary() {} explicit DescribeComplianceSummaryResponseBodyComplianceSummary(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceSummaryByConfigRule) { res["ComplianceSummaryByConfigRule"] = complianceSummaryByConfigRule ? boost::any(complianceSummaryByConfigRule->toMap()) : boost::any(map<string,boost::any>({})); } if (complianceSummaryByResource) { res["ComplianceSummaryByResource"] = complianceSummaryByResource ? boost::any(complianceSummaryByResource->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceSummaryByConfigRule") != m.end() && !m["ComplianceSummaryByConfigRule"].empty()) { if (typeid(map<string, boost::any>) == m["ComplianceSummaryByConfigRule"].type()) { DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByConfigRule model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ComplianceSummaryByConfigRule"])); complianceSummaryByConfigRule = make_shared<DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByConfigRule>(model1); } } if (m.find("ComplianceSummaryByResource") != m.end() && !m["ComplianceSummaryByResource"].empty()) { if (typeid(map<string, boost::any>) == m["ComplianceSummaryByResource"].type()) { DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByResource model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ComplianceSummaryByResource"])); complianceSummaryByResource = make_shared<DescribeComplianceSummaryResponseBodyComplianceSummaryComplianceSummaryByResource>(model1); } } } virtual ~DescribeComplianceSummaryResponseBodyComplianceSummary() = default; }; class DescribeComplianceSummaryResponseBody : public Darabonba::Model { public: shared_ptr<DescribeComplianceSummaryResponseBodyComplianceSummary> complianceSummary{}; shared_ptr<string> requestId{}; DescribeComplianceSummaryResponseBody() {} explicit DescribeComplianceSummaryResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceSummary) { res["ComplianceSummary"] = complianceSummary ? boost::any(complianceSummary->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceSummary") != m.end() && !m["ComplianceSummary"].empty()) { if (typeid(map<string, boost::any>) == m["ComplianceSummary"].type()) { DescribeComplianceSummaryResponseBodyComplianceSummary model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ComplianceSummary"])); complianceSummary = make_shared<DescribeComplianceSummaryResponseBodyComplianceSummary>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeComplianceSummaryResponseBody() = default; }; class DescribeComplianceSummaryResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeComplianceSummaryResponseBody> body{}; DescribeComplianceSummaryResponse() {} explicit DescribeComplianceSummaryResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeComplianceSummaryResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeComplianceSummaryResponseBody>(model1); } } } virtual ~DescribeComplianceSummaryResponse() = default; }; class DescribeConfigRuleRequest : public Darabonba::Model { public: shared_ptr<string> configRuleId{}; shared_ptr<long> memberId{}; shared_ptr<bool> multiAccount{}; DescribeConfigRuleRequest() {} explicit DescribeConfigRuleRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<long>(boost::any_cast<long>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } } virtual ~DescribeConfigRuleRequest() = default; }; class DescribeConfigRuleResponseBodyConfigRuleConfigRuleEvaluationStatus : public Darabonba::Model { public: shared_ptr<long> firstActivatedTimestamp{}; shared_ptr<bool> firstEvaluationStarted{}; shared_ptr<string> lastErrorCode{}; shared_ptr<string> lastErrorMessage{}; shared_ptr<long> lastFailedEvaluationTimestamp{}; shared_ptr<long> lastFailedInvocationTimestamp{}; shared_ptr<long> lastSuccessfulEvaluationTimestamp{}; shared_ptr<long> lastSuccessfulInvocationTimestamp{}; DescribeConfigRuleResponseBodyConfigRuleConfigRuleEvaluationStatus() {} explicit DescribeConfigRuleResponseBodyConfigRuleConfigRuleEvaluationStatus(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (firstActivatedTimestamp) { res["FirstActivatedTimestamp"] = boost::any(*firstActivatedTimestamp); } if (firstEvaluationStarted) { res["FirstEvaluationStarted"] = boost::any(*firstEvaluationStarted); } if (lastErrorCode) { res["LastErrorCode"] = boost::any(*lastErrorCode); } if (lastErrorMessage) { res["LastErrorMessage"] = boost::any(*lastErrorMessage); } if (lastFailedEvaluationTimestamp) { res["LastFailedEvaluationTimestamp"] = boost::any(*lastFailedEvaluationTimestamp); } if (lastFailedInvocationTimestamp) { res["LastFailedInvocationTimestamp"] = boost::any(*lastFailedInvocationTimestamp); } if (lastSuccessfulEvaluationTimestamp) { res["LastSuccessfulEvaluationTimestamp"] = boost::any(*lastSuccessfulEvaluationTimestamp); } if (lastSuccessfulInvocationTimestamp) { res["LastSuccessfulInvocationTimestamp"] = boost::any(*lastSuccessfulInvocationTimestamp); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("FirstActivatedTimestamp") != m.end() && !m["FirstActivatedTimestamp"].empty()) { firstActivatedTimestamp = make_shared<long>(boost::any_cast<long>(m["FirstActivatedTimestamp"])); } if (m.find("FirstEvaluationStarted") != m.end() && !m["FirstEvaluationStarted"].empty()) { firstEvaluationStarted = make_shared<bool>(boost::any_cast<bool>(m["FirstEvaluationStarted"])); } if (m.find("LastErrorCode") != m.end() && !m["LastErrorCode"].empty()) { lastErrorCode = make_shared<string>(boost::any_cast<string>(m["LastErrorCode"])); } if (m.find("LastErrorMessage") != m.end() && !m["LastErrorMessage"].empty()) { lastErrorMessage = make_shared<string>(boost::any_cast<string>(m["LastErrorMessage"])); } if (m.find("LastFailedEvaluationTimestamp") != m.end() && !m["LastFailedEvaluationTimestamp"].empty()) { lastFailedEvaluationTimestamp = make_shared<long>(boost::any_cast<long>(m["LastFailedEvaluationTimestamp"])); } if (m.find("LastFailedInvocationTimestamp") != m.end() && !m["LastFailedInvocationTimestamp"].empty()) { lastFailedInvocationTimestamp = make_shared<long>(boost::any_cast<long>(m["LastFailedInvocationTimestamp"])); } if (m.find("LastSuccessfulEvaluationTimestamp") != m.end() && !m["LastSuccessfulEvaluationTimestamp"].empty()) { lastSuccessfulEvaluationTimestamp = make_shared<long>(boost::any_cast<long>(m["LastSuccessfulEvaluationTimestamp"])); } if (m.find("LastSuccessfulInvocationTimestamp") != m.end() && !m["LastSuccessfulInvocationTimestamp"].empty()) { lastSuccessfulInvocationTimestamp = make_shared<long>(boost::any_cast<long>(m["LastSuccessfulInvocationTimestamp"])); } } virtual ~DescribeConfigRuleResponseBodyConfigRuleConfigRuleEvaluationStatus() = default; }; class DescribeConfigRuleResponseBodyConfigRuleManagedRuleSourceDetails : public Darabonba::Model { public: shared_ptr<string> eventSource{}; shared_ptr<string> maximumExecutionFrequency{}; shared_ptr<string> messageType{}; DescribeConfigRuleResponseBodyConfigRuleManagedRuleSourceDetails() {} explicit DescribeConfigRuleResponseBodyConfigRuleManagedRuleSourceDetails(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (eventSource) { res["EventSource"] = boost::any(*eventSource); } if (maximumExecutionFrequency) { res["MaximumExecutionFrequency"] = boost::any(*maximumExecutionFrequency); } if (messageType) { res["MessageType"] = boost::any(*messageType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EventSource") != m.end() && !m["EventSource"].empty()) { eventSource = make_shared<string>(boost::any_cast<string>(m["EventSource"])); } if (m.find("MaximumExecutionFrequency") != m.end() && !m["MaximumExecutionFrequency"].empty()) { maximumExecutionFrequency = make_shared<string>(boost::any_cast<string>(m["MaximumExecutionFrequency"])); } if (m.find("MessageType") != m.end() && !m["MessageType"].empty()) { messageType = make_shared<string>(boost::any_cast<string>(m["MessageType"])); } } virtual ~DescribeConfigRuleResponseBodyConfigRuleManagedRuleSourceDetails() = default; }; class DescribeConfigRuleResponseBodyConfigRuleManagedRule : public Darabonba::Model { public: shared_ptr<map<string, boost::any>> compulsoryInputParameterDetails{}; shared_ptr<string> description{}; shared_ptr<string> identifier{}; shared_ptr<vector<string>> labels{}; shared_ptr<string> managedRuleName{}; shared_ptr<map<string, boost::any>> optionalInputParameterDetails{}; shared_ptr<vector<DescribeConfigRuleResponseBodyConfigRuleManagedRuleSourceDetails>> sourceDetails{}; DescribeConfigRuleResponseBodyConfigRuleManagedRule() {} explicit DescribeConfigRuleResponseBodyConfigRuleManagedRule(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (compulsoryInputParameterDetails) { res["CompulsoryInputParameterDetails"] = boost::any(*compulsoryInputParameterDetails); } if (description) { res["Description"] = boost::any(*description); } if (identifier) { res["Identifier"] = boost::any(*identifier); } if (labels) { res["Labels"] = boost::any(*labels); } if (managedRuleName) { res["ManagedRuleName"] = boost::any(*managedRuleName); } if (optionalInputParameterDetails) { res["OptionalInputParameterDetails"] = boost::any(*optionalInputParameterDetails); } if (sourceDetails) { vector<boost::any> temp1; for(auto item1:*sourceDetails){ temp1.push_back(boost::any(item1.toMap())); } res["SourceDetails"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("CompulsoryInputParameterDetails") != m.end() && !m["CompulsoryInputParameterDetails"].empty()) { map<string, boost::any> map1 = boost::any_cast<map<string, boost::any>>(m["CompulsoryInputParameterDetails"]); map<string, boost::any> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } compulsoryInputParameterDetails = make_shared<map<string, boost::any>>(toMap1); } if (m.find("Description") != m.end() && !m["Description"].empty()) { description = make_shared<string>(boost::any_cast<string>(m["Description"])); } if (m.find("Identifier") != m.end() && !m["Identifier"].empty()) { identifier = make_shared<string>(boost::any_cast<string>(m["Identifier"])); } if (m.find("Labels") != m.end() && !m["Labels"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["Labels"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["Labels"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } labels = make_shared<vector<string>>(toVec1); } if (m.find("ManagedRuleName") != m.end() && !m["ManagedRuleName"].empty()) { managedRuleName = make_shared<string>(boost::any_cast<string>(m["ManagedRuleName"])); } if (m.find("OptionalInputParameterDetails") != m.end() && !m["OptionalInputParameterDetails"].empty()) { map<string, boost::any> map1 = boost::any_cast<map<string, boost::any>>(m["OptionalInputParameterDetails"]); map<string, boost::any> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } optionalInputParameterDetails = make_shared<map<string, boost::any>>(toMap1); } if (m.find("SourceDetails") != m.end() && !m["SourceDetails"].empty()) { if (typeid(vector<boost::any>) == m["SourceDetails"].type()) { vector<DescribeConfigRuleResponseBodyConfigRuleManagedRuleSourceDetails> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SourceDetails"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeConfigRuleResponseBodyConfigRuleManagedRuleSourceDetails model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } sourceDetails = make_shared<vector<DescribeConfigRuleResponseBodyConfigRuleManagedRuleSourceDetails>>(expect1); } } } virtual ~DescribeConfigRuleResponseBodyConfigRuleManagedRule() = default; }; class DescribeConfigRuleResponseBodyConfigRuleScope : public Darabonba::Model { public: shared_ptr<string> complianceResourceId{}; shared_ptr<vector<string>> complianceResourceTypes{}; DescribeConfigRuleResponseBodyConfigRuleScope() {} explicit DescribeConfigRuleResponseBodyConfigRuleScope(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceResourceId) { res["ComplianceResourceId"] = boost::any(*complianceResourceId); } if (complianceResourceTypes) { res["ComplianceResourceTypes"] = boost::any(*complianceResourceTypes); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceResourceId") != m.end() && !m["ComplianceResourceId"].empty()) { complianceResourceId = make_shared<string>(boost::any_cast<string>(m["ComplianceResourceId"])); } if (m.find("ComplianceResourceTypes") != m.end() && !m["ComplianceResourceTypes"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["ComplianceResourceTypes"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["ComplianceResourceTypes"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } complianceResourceTypes = make_shared<vector<string>>(toVec1); } } virtual ~DescribeConfigRuleResponseBodyConfigRuleScope() = default; }; class DescribeConfigRuleResponseBodyConfigRuleSourceSourceConditions : public Darabonba::Model { public: shared_ptr<string> desiredValue{}; shared_ptr<string> name{}; shared_ptr<string> operator_{}; shared_ptr<string> tips{}; DescribeConfigRuleResponseBodyConfigRuleSourceSourceConditions() {} explicit DescribeConfigRuleResponseBodyConfigRuleSourceSourceConditions(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (desiredValue) { res["DesiredValue"] = boost::any(*desiredValue); } if (name) { res["Name"] = boost::any(*name); } if (operator_) { res["Operator"] = boost::any(*operator_); } if (tips) { res["Tips"] = boost::any(*tips); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DesiredValue") != m.end() && !m["DesiredValue"].empty()) { desiredValue = make_shared<string>(boost::any_cast<string>(m["DesiredValue"])); } if (m.find("Name") != m.end() && !m["Name"].empty()) { name = make_shared<string>(boost::any_cast<string>(m["Name"])); } if (m.find("Operator") != m.end() && !m["Operator"].empty()) { operator_ = make_shared<string>(boost::any_cast<string>(m["Operator"])); } if (m.find("Tips") != m.end() && !m["Tips"].empty()) { tips = make_shared<string>(boost::any_cast<string>(m["Tips"])); } } virtual ~DescribeConfigRuleResponseBodyConfigRuleSourceSourceConditions() = default; }; class DescribeConfigRuleResponseBodyConfigRuleSourceSourceDetails : public Darabonba::Model { public: shared_ptr<string> eventSource{}; shared_ptr<string> maximumExecutionFrequency{}; shared_ptr<string> messageType{}; DescribeConfigRuleResponseBodyConfigRuleSourceSourceDetails() {} explicit DescribeConfigRuleResponseBodyConfigRuleSourceSourceDetails(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (eventSource) { res["EventSource"] = boost::any(*eventSource); } if (maximumExecutionFrequency) { res["MaximumExecutionFrequency"] = boost::any(*maximumExecutionFrequency); } if (messageType) { res["MessageType"] = boost::any(*messageType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EventSource") != m.end() && !m["EventSource"].empty()) { eventSource = make_shared<string>(boost::any_cast<string>(m["EventSource"])); } if (m.find("MaximumExecutionFrequency") != m.end() && !m["MaximumExecutionFrequency"].empty()) { maximumExecutionFrequency = make_shared<string>(boost::any_cast<string>(m["MaximumExecutionFrequency"])); } if (m.find("MessageType") != m.end() && !m["MessageType"].empty()) { messageType = make_shared<string>(boost::any_cast<string>(m["MessageType"])); } } virtual ~DescribeConfigRuleResponseBodyConfigRuleSourceSourceDetails() = default; }; class DescribeConfigRuleResponseBodyConfigRuleSource : public Darabonba::Model { public: shared_ptr<string> identifier{}; shared_ptr<string> owner{}; shared_ptr<vector<DescribeConfigRuleResponseBodyConfigRuleSourceSourceConditions>> sourceConditions{}; shared_ptr<vector<DescribeConfigRuleResponseBodyConfigRuleSourceSourceDetails>> sourceDetails{}; DescribeConfigRuleResponseBodyConfigRuleSource() {} explicit DescribeConfigRuleResponseBodyConfigRuleSource(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (identifier) { res["Identifier"] = boost::any(*identifier); } if (owner) { res["Owner"] = boost::any(*owner); } if (sourceConditions) { vector<boost::any> temp1; for(auto item1:*sourceConditions){ temp1.push_back(boost::any(item1.toMap())); } res["SourceConditions"] = boost::any(temp1); } if (sourceDetails) { vector<boost::any> temp1; for(auto item1:*sourceDetails){ temp1.push_back(boost::any(item1.toMap())); } res["SourceDetails"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Identifier") != m.end() && !m["Identifier"].empty()) { identifier = make_shared<string>(boost::any_cast<string>(m["Identifier"])); } if (m.find("Owner") != m.end() && !m["Owner"].empty()) { owner = make_shared<string>(boost::any_cast<string>(m["Owner"])); } if (m.find("SourceConditions") != m.end() && !m["SourceConditions"].empty()) { if (typeid(vector<boost::any>) == m["SourceConditions"].type()) { vector<DescribeConfigRuleResponseBodyConfigRuleSourceSourceConditions> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SourceConditions"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeConfigRuleResponseBodyConfigRuleSourceSourceConditions model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } sourceConditions = make_shared<vector<DescribeConfigRuleResponseBodyConfigRuleSourceSourceConditions>>(expect1); } } if (m.find("SourceDetails") != m.end() && !m["SourceDetails"].empty()) { if (typeid(vector<boost::any>) == m["SourceDetails"].type()) { vector<DescribeConfigRuleResponseBodyConfigRuleSourceSourceDetails> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SourceDetails"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeConfigRuleResponseBodyConfigRuleSourceSourceDetails model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } sourceDetails = make_shared<vector<DescribeConfigRuleResponseBodyConfigRuleSourceSourceDetails>>(expect1); } } } virtual ~DescribeConfigRuleResponseBodyConfigRuleSource() = default; }; class DescribeConfigRuleResponseBodyConfigRule : public Darabonba::Model { public: shared_ptr<string> configRuleArn{}; shared_ptr<DescribeConfigRuleResponseBodyConfigRuleConfigRuleEvaluationStatus> configRuleEvaluationStatus{}; shared_ptr<string> configRuleId{}; shared_ptr<string> configRuleName{}; shared_ptr<string> configRuleState{}; shared_ptr<long> createTimestamp{}; shared_ptr<string> description{}; shared_ptr<map<string, boost::any>> inputParameters{}; shared_ptr<DescribeConfigRuleResponseBodyConfigRuleManagedRule> managedRule{}; shared_ptr<string> maximumExecutionFrequency{}; shared_ptr<long> modifiedTimestamp{}; shared_ptr<long> riskLevel{}; shared_ptr<DescribeConfigRuleResponseBodyConfigRuleScope> scope{}; shared_ptr<DescribeConfigRuleResponseBodyConfigRuleSource> source{}; DescribeConfigRuleResponseBodyConfigRule() {} explicit DescribeConfigRuleResponseBodyConfigRule(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRuleArn) { res["ConfigRuleArn"] = boost::any(*configRuleArn); } if (configRuleEvaluationStatus) { res["ConfigRuleEvaluationStatus"] = configRuleEvaluationStatus ? boost::any(configRuleEvaluationStatus->toMap()) : boost::any(map<string,boost::any>({})); } if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (configRuleName) { res["ConfigRuleName"] = boost::any(*configRuleName); } if (configRuleState) { res["ConfigRuleState"] = boost::any(*configRuleState); } if (createTimestamp) { res["CreateTimestamp"] = boost::any(*createTimestamp); } if (description) { res["Description"] = boost::any(*description); } if (inputParameters) { res["InputParameters"] = boost::any(*inputParameters); } if (managedRule) { res["ManagedRule"] = managedRule ? boost::any(managedRule->toMap()) : boost::any(map<string,boost::any>({})); } if (maximumExecutionFrequency) { res["MaximumExecutionFrequency"] = boost::any(*maximumExecutionFrequency); } if (modifiedTimestamp) { res["ModifiedTimestamp"] = boost::any(*modifiedTimestamp); } if (riskLevel) { res["RiskLevel"] = boost::any(*riskLevel); } if (scope) { res["Scope"] = scope ? boost::any(scope->toMap()) : boost::any(map<string,boost::any>({})); } if (source) { res["Source"] = source ? boost::any(source->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRuleArn") != m.end() && !m["ConfigRuleArn"].empty()) { configRuleArn = make_shared<string>(boost::any_cast<string>(m["ConfigRuleArn"])); } if (m.find("ConfigRuleEvaluationStatus") != m.end() && !m["ConfigRuleEvaluationStatus"].empty()) { if (typeid(map<string, boost::any>) == m["ConfigRuleEvaluationStatus"].type()) { DescribeConfigRuleResponseBodyConfigRuleConfigRuleEvaluationStatus model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ConfigRuleEvaluationStatus"])); configRuleEvaluationStatus = make_shared<DescribeConfigRuleResponseBodyConfigRuleConfigRuleEvaluationStatus>(model1); } } if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("ConfigRuleName") != m.end() && !m["ConfigRuleName"].empty()) { configRuleName = make_shared<string>(boost::any_cast<string>(m["ConfigRuleName"])); } if (m.find("ConfigRuleState") != m.end() && !m["ConfigRuleState"].empty()) { configRuleState = make_shared<string>(boost::any_cast<string>(m["ConfigRuleState"])); } if (m.find("CreateTimestamp") != m.end() && !m["CreateTimestamp"].empty()) { createTimestamp = make_shared<long>(boost::any_cast<long>(m["CreateTimestamp"])); } if (m.find("Description") != m.end() && !m["Description"].empty()) { description = make_shared<string>(boost::any_cast<string>(m["Description"])); } if (m.find("InputParameters") != m.end() && !m["InputParameters"].empty()) { map<string, boost::any> map1 = boost::any_cast<map<string, boost::any>>(m["InputParameters"]); map<string, boost::any> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } inputParameters = make_shared<map<string, boost::any>>(toMap1); } if (m.find("ManagedRule") != m.end() && !m["ManagedRule"].empty()) { if (typeid(map<string, boost::any>) == m["ManagedRule"].type()) { DescribeConfigRuleResponseBodyConfigRuleManagedRule model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ManagedRule"])); managedRule = make_shared<DescribeConfigRuleResponseBodyConfigRuleManagedRule>(model1); } } if (m.find("MaximumExecutionFrequency") != m.end() && !m["MaximumExecutionFrequency"].empty()) { maximumExecutionFrequency = make_shared<string>(boost::any_cast<string>(m["MaximumExecutionFrequency"])); } if (m.find("ModifiedTimestamp") != m.end() && !m["ModifiedTimestamp"].empty()) { modifiedTimestamp = make_shared<long>(boost::any_cast<long>(m["ModifiedTimestamp"])); } if (m.find("RiskLevel") != m.end() && !m["RiskLevel"].empty()) { riskLevel = make_shared<long>(boost::any_cast<long>(m["RiskLevel"])); } if (m.find("Scope") != m.end() && !m["Scope"].empty()) { if (typeid(map<string, boost::any>) == m["Scope"].type()) { DescribeConfigRuleResponseBodyConfigRuleScope model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Scope"])); scope = make_shared<DescribeConfigRuleResponseBodyConfigRuleScope>(model1); } } if (m.find("Source") != m.end() && !m["Source"].empty()) { if (typeid(map<string, boost::any>) == m["Source"].type()) { DescribeConfigRuleResponseBodyConfigRuleSource model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Source"])); source = make_shared<DescribeConfigRuleResponseBodyConfigRuleSource>(model1); } } } virtual ~DescribeConfigRuleResponseBodyConfigRule() = default; }; class DescribeConfigRuleResponseBody : public Darabonba::Model { public: shared_ptr<DescribeConfigRuleResponseBodyConfigRule> configRule{}; shared_ptr<string> requestId{}; DescribeConfigRuleResponseBody() {} explicit DescribeConfigRuleResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRule) { res["ConfigRule"] = configRule ? boost::any(configRule->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRule") != m.end() && !m["ConfigRule"].empty()) { if (typeid(map<string, boost::any>) == m["ConfigRule"].type()) { DescribeConfigRuleResponseBodyConfigRule model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ConfigRule"])); configRule = make_shared<DescribeConfigRuleResponseBodyConfigRule>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeConfigRuleResponseBody() = default; }; class DescribeConfigRuleResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeConfigRuleResponseBody> body{}; DescribeConfigRuleResponse() {} explicit DescribeConfigRuleResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeConfigRuleResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeConfigRuleResponseBody>(model1); } } } virtual ~DescribeConfigRuleResponse() = default; }; class DescribeConfigurationRecorderResponseBodyConfigurationRecorder : public Darabonba::Model { public: shared_ptr<long> accountId{}; shared_ptr<string> configurationRecorderStatus{}; shared_ptr<string> organizationEnableStatus{}; shared_ptr<long> organizationMasterId{}; shared_ptr<vector<string>> resourceTypes{}; DescribeConfigurationRecorderResponseBodyConfigurationRecorder() {} explicit DescribeConfigurationRecorderResponseBodyConfigurationRecorder(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accountId) { res["AccountId"] = boost::any(*accountId); } if (configurationRecorderStatus) { res["ConfigurationRecorderStatus"] = boost::any(*configurationRecorderStatus); } if (organizationEnableStatus) { res["OrganizationEnableStatus"] = boost::any(*organizationEnableStatus); } if (organizationMasterId) { res["OrganizationMasterId"] = boost::any(*organizationMasterId); } if (resourceTypes) { res["ResourceTypes"] = boost::any(*resourceTypes); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccountId") != m.end() && !m["AccountId"].empty()) { accountId = make_shared<long>(boost::any_cast<long>(m["AccountId"])); } if (m.find("ConfigurationRecorderStatus") != m.end() && !m["ConfigurationRecorderStatus"].empty()) { configurationRecorderStatus = make_shared<string>(boost::any_cast<string>(m["ConfigurationRecorderStatus"])); } if (m.find("OrganizationEnableStatus") != m.end() && !m["OrganizationEnableStatus"].empty()) { organizationEnableStatus = make_shared<string>(boost::any_cast<string>(m["OrganizationEnableStatus"])); } if (m.find("OrganizationMasterId") != m.end() && !m["OrganizationMasterId"].empty()) { organizationMasterId = make_shared<long>(boost::any_cast<long>(m["OrganizationMasterId"])); } if (m.find("ResourceTypes") != m.end() && !m["ResourceTypes"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["ResourceTypes"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["ResourceTypes"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } resourceTypes = make_shared<vector<string>>(toVec1); } } virtual ~DescribeConfigurationRecorderResponseBodyConfigurationRecorder() = default; }; class DescribeConfigurationRecorderResponseBody : public Darabonba::Model { public: shared_ptr<DescribeConfigurationRecorderResponseBodyConfigurationRecorder> configurationRecorder{}; shared_ptr<string> requestId{}; DescribeConfigurationRecorderResponseBody() {} explicit DescribeConfigurationRecorderResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configurationRecorder) { res["ConfigurationRecorder"] = configurationRecorder ? boost::any(configurationRecorder->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigurationRecorder") != m.end() && !m["ConfigurationRecorder"].empty()) { if (typeid(map<string, boost::any>) == m["ConfigurationRecorder"].type()) { DescribeConfigurationRecorderResponseBodyConfigurationRecorder model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ConfigurationRecorder"])); configurationRecorder = make_shared<DescribeConfigurationRecorderResponseBodyConfigurationRecorder>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeConfigurationRecorderResponseBody() = default; }; class DescribeConfigurationRecorderResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeConfigurationRecorderResponseBody> body{}; DescribeConfigurationRecorderResponse() {} explicit DescribeConfigurationRecorderResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeConfigurationRecorderResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeConfigurationRecorderResponseBody>(model1); } } } virtual ~DescribeConfigurationRecorderResponse() = default; }; class DescribeDeliveryChannelsRequest : public Darabonba::Model { public: shared_ptr<string> deliveryChannelIds{}; DescribeDeliveryChannelsRequest() {} explicit DescribeDeliveryChannelsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (deliveryChannelIds) { res["DeliveryChannelIds"] = boost::any(*deliveryChannelIds); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DeliveryChannelIds") != m.end() && !m["DeliveryChannelIds"].empty()) { deliveryChannelIds = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelIds"])); } } virtual ~DescribeDeliveryChannelsRequest() = default; }; class DescribeDeliveryChannelsResponseBodyDeliveryChannels : public Darabonba::Model { public: shared_ptr<bool> configurationItemChangeNotification{}; shared_ptr<bool> configurationSnapshot{}; shared_ptr<string> deliveryChannelAssumeRoleArn{}; shared_ptr<string> deliveryChannelCondition{}; shared_ptr<string> deliveryChannelId{}; shared_ptr<string> deliveryChannelName{}; shared_ptr<string> deliveryChannelTargetArn{}; shared_ptr<string> deliveryChannelType{}; shared_ptr<string> description{}; shared_ptr<bool> nonCompliantNotification{}; shared_ptr<string> oversizedDataOSSTargetArn{}; shared_ptr<long> status{}; DescribeDeliveryChannelsResponseBodyDeliveryChannels() {} explicit DescribeDeliveryChannelsResponseBodyDeliveryChannels(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configurationItemChangeNotification) { res["ConfigurationItemChangeNotification"] = boost::any(*configurationItemChangeNotification); } if (configurationSnapshot) { res["ConfigurationSnapshot"] = boost::any(*configurationSnapshot); } if (deliveryChannelAssumeRoleArn) { res["DeliveryChannelAssumeRoleArn"] = boost::any(*deliveryChannelAssumeRoleArn); } if (deliveryChannelCondition) { res["DeliveryChannelCondition"] = boost::any(*deliveryChannelCondition); } if (deliveryChannelId) { res["DeliveryChannelId"] = boost::any(*deliveryChannelId); } if (deliveryChannelName) { res["DeliveryChannelName"] = boost::any(*deliveryChannelName); } if (deliveryChannelTargetArn) { res["DeliveryChannelTargetArn"] = boost::any(*deliveryChannelTargetArn); } if (deliveryChannelType) { res["DeliveryChannelType"] = boost::any(*deliveryChannelType); } if (description) { res["Description"] = boost::any(*description); } if (nonCompliantNotification) { res["NonCompliantNotification"] = boost::any(*nonCompliantNotification); } if (oversizedDataOSSTargetArn) { res["OversizedDataOSSTargetArn"] = boost::any(*oversizedDataOSSTargetArn); } if (status) { res["Status"] = boost::any(*status); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigurationItemChangeNotification") != m.end() && !m["ConfigurationItemChangeNotification"].empty()) { configurationItemChangeNotification = make_shared<bool>(boost::any_cast<bool>(m["ConfigurationItemChangeNotification"])); } if (m.find("ConfigurationSnapshot") != m.end() && !m["ConfigurationSnapshot"].empty()) { configurationSnapshot = make_shared<bool>(boost::any_cast<bool>(m["ConfigurationSnapshot"])); } if (m.find("DeliveryChannelAssumeRoleArn") != m.end() && !m["DeliveryChannelAssumeRoleArn"].empty()) { deliveryChannelAssumeRoleArn = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelAssumeRoleArn"])); } if (m.find("DeliveryChannelCondition") != m.end() && !m["DeliveryChannelCondition"].empty()) { deliveryChannelCondition = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelCondition"])); } if (m.find("DeliveryChannelId") != m.end() && !m["DeliveryChannelId"].empty()) { deliveryChannelId = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelId"])); } if (m.find("DeliveryChannelName") != m.end() && !m["DeliveryChannelName"].empty()) { deliveryChannelName = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelName"])); } if (m.find("DeliveryChannelTargetArn") != m.end() && !m["DeliveryChannelTargetArn"].empty()) { deliveryChannelTargetArn = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelTargetArn"])); } if (m.find("DeliveryChannelType") != m.end() && !m["DeliveryChannelType"].empty()) { deliveryChannelType = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelType"])); } if (m.find("Description") != m.end() && !m["Description"].empty()) { description = make_shared<string>(boost::any_cast<string>(m["Description"])); } if (m.find("NonCompliantNotification") != m.end() && !m["NonCompliantNotification"].empty()) { nonCompliantNotification = make_shared<bool>(boost::any_cast<bool>(m["NonCompliantNotification"])); } if (m.find("OversizedDataOSSTargetArn") != m.end() && !m["OversizedDataOSSTargetArn"].empty()) { oversizedDataOSSTargetArn = make_shared<string>(boost::any_cast<string>(m["OversizedDataOSSTargetArn"])); } if (m.find("Status") != m.end() && !m["Status"].empty()) { status = make_shared<long>(boost::any_cast<long>(m["Status"])); } } virtual ~DescribeDeliveryChannelsResponseBodyDeliveryChannels() = default; }; class DescribeDeliveryChannelsResponseBody : public Darabonba::Model { public: shared_ptr<vector<DescribeDeliveryChannelsResponseBodyDeliveryChannels>> deliveryChannels{}; shared_ptr<string> requestId{}; DescribeDeliveryChannelsResponseBody() {} explicit DescribeDeliveryChannelsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (deliveryChannels) { vector<boost::any> temp1; for(auto item1:*deliveryChannels){ temp1.push_back(boost::any(item1.toMap())); } res["DeliveryChannels"] = boost::any(temp1); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DeliveryChannels") != m.end() && !m["DeliveryChannels"].empty()) { if (typeid(vector<boost::any>) == m["DeliveryChannels"].type()) { vector<DescribeDeliveryChannelsResponseBodyDeliveryChannels> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["DeliveryChannels"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDeliveryChannelsResponseBodyDeliveryChannels model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } deliveryChannels = make_shared<vector<DescribeDeliveryChannelsResponseBodyDeliveryChannels>>(expect1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeDeliveryChannelsResponseBody() = default; }; class DescribeDeliveryChannelsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDeliveryChannelsResponseBody> body{}; DescribeDeliveryChannelsResponse() {} explicit DescribeDeliveryChannelsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDeliveryChannelsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDeliveryChannelsResponseBody>(model1); } } } virtual ~DescribeDeliveryChannelsResponse() = default; }; class DescribeDiscoveredResourceRequest : public Darabonba::Model { public: shared_ptr<long> memberId{}; shared_ptr<bool> multiAccount{}; shared_ptr<string> region{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceType{}; DescribeDiscoveredResourceRequest() {} explicit DescribeDiscoveredResourceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } if (region) { res["Region"] = boost::any(*region); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<long>(boost::any_cast<long>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } } virtual ~DescribeDiscoveredResourceRequest() = default; }; class DescribeDiscoveredResourceResponseBodyDiscoveredResourceDetail : public Darabonba::Model { public: shared_ptr<long> accountId{}; shared_ptr<string> availabilityZone{}; shared_ptr<string> configuration{}; shared_ptr<string> region{}; shared_ptr<long> resourceCreationTime{}; shared_ptr<long> resourceDeleted{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceName{}; shared_ptr<string> resourceStatus{}; shared_ptr<string> resourceType{}; shared_ptr<string> tags{}; DescribeDiscoveredResourceResponseBodyDiscoveredResourceDetail() {} explicit DescribeDiscoveredResourceResponseBodyDiscoveredResourceDetail(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accountId) { res["AccountId"] = boost::any(*accountId); } if (availabilityZone) { res["AvailabilityZone"] = boost::any(*availabilityZone); } if (configuration) { res["Configuration"] = boost::any(*configuration); } if (region) { res["Region"] = boost::any(*region); } if (resourceCreationTime) { res["ResourceCreationTime"] = boost::any(*resourceCreationTime); } if (resourceDeleted) { res["ResourceDeleted"] = boost::any(*resourceDeleted); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceName) { res["ResourceName"] = boost::any(*resourceName); } if (resourceStatus) { res["ResourceStatus"] = boost::any(*resourceStatus); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (tags) { res["Tags"] = boost::any(*tags); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccountId") != m.end() && !m["AccountId"].empty()) { accountId = make_shared<long>(boost::any_cast<long>(m["AccountId"])); } if (m.find("AvailabilityZone") != m.end() && !m["AvailabilityZone"].empty()) { availabilityZone = make_shared<string>(boost::any_cast<string>(m["AvailabilityZone"])); } if (m.find("Configuration") != m.end() && !m["Configuration"].empty()) { configuration = make_shared<string>(boost::any_cast<string>(m["Configuration"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("ResourceCreationTime") != m.end() && !m["ResourceCreationTime"].empty()) { resourceCreationTime = make_shared<long>(boost::any_cast<long>(m["ResourceCreationTime"])); } if (m.find("ResourceDeleted") != m.end() && !m["ResourceDeleted"].empty()) { resourceDeleted = make_shared<long>(boost::any_cast<long>(m["ResourceDeleted"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceName") != m.end() && !m["ResourceName"].empty()) { resourceName = make_shared<string>(boost::any_cast<string>(m["ResourceName"])); } if (m.find("ResourceStatus") != m.end() && !m["ResourceStatus"].empty()) { resourceStatus = make_shared<string>(boost::any_cast<string>(m["ResourceStatus"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("Tags") != m.end() && !m["Tags"].empty()) { tags = make_shared<string>(boost::any_cast<string>(m["Tags"])); } } virtual ~DescribeDiscoveredResourceResponseBodyDiscoveredResourceDetail() = default; }; class DescribeDiscoveredResourceResponseBody : public Darabonba::Model { public: shared_ptr<DescribeDiscoveredResourceResponseBodyDiscoveredResourceDetail> discoveredResourceDetail{}; shared_ptr<string> requestId{}; DescribeDiscoveredResourceResponseBody() {} explicit DescribeDiscoveredResourceResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (discoveredResourceDetail) { res["DiscoveredResourceDetail"] = discoveredResourceDetail ? boost::any(discoveredResourceDetail->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DiscoveredResourceDetail") != m.end() && !m["DiscoveredResourceDetail"].empty()) { if (typeid(map<string, boost::any>) == m["DiscoveredResourceDetail"].type()) { DescribeDiscoveredResourceResponseBodyDiscoveredResourceDetail model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["DiscoveredResourceDetail"])); discoveredResourceDetail = make_shared<DescribeDiscoveredResourceResponseBodyDiscoveredResourceDetail>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeDiscoveredResourceResponseBody() = default; }; class DescribeDiscoveredResourceResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDiscoveredResourceResponseBody> body{}; DescribeDiscoveredResourceResponse() {} explicit DescribeDiscoveredResourceResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDiscoveredResourceResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDiscoveredResourceResponseBody>(model1); } } } virtual ~DescribeDiscoveredResourceResponse() = default; }; class DescribeEvaluationResultsRequest : public Darabonba::Model { public: shared_ptr<string> complianceType{}; shared_ptr<string> configRuleId{}; shared_ptr<long> memberId{}; shared_ptr<bool> multiAccount{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceType{}; DescribeEvaluationResultsRequest() {} explicit DescribeEvaluationResultsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceType) { res["ComplianceType"] = boost::any(*complianceType); } if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceType") != m.end() && !m["ComplianceType"].empty()) { complianceType = make_shared<string>(boost::any_cast<string>(m["ComplianceType"])); } if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<long>(boost::any_cast<long>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } } virtual ~DescribeEvaluationResultsRequest() = default; }; class DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifierEvaluationResultQualifier : public Darabonba::Model { public: shared_ptr<string> configRuleArn{}; shared_ptr<string> configRuleId{}; shared_ptr<string> configRuleName{}; shared_ptr<string> regionId{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceName{}; shared_ptr<string> resourceType{}; DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifierEvaluationResultQualifier() {} explicit DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifierEvaluationResultQualifier(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRuleArn) { res["ConfigRuleArn"] = boost::any(*configRuleArn); } if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (configRuleName) { res["ConfigRuleName"] = boost::any(*configRuleName); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceName) { res["ResourceName"] = boost::any(*resourceName); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRuleArn") != m.end() && !m["ConfigRuleArn"].empty()) { configRuleArn = make_shared<string>(boost::any_cast<string>(m["ConfigRuleArn"])); } if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("ConfigRuleName") != m.end() && !m["ConfigRuleName"].empty()) { configRuleName = make_shared<string>(boost::any_cast<string>(m["ConfigRuleName"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceName") != m.end() && !m["ResourceName"].empty()) { resourceName = make_shared<string>(boost::any_cast<string>(m["ResourceName"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } } virtual ~DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifierEvaluationResultQualifier() = default; }; class DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifier : public Darabonba::Model { public: shared_ptr<DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifierEvaluationResultQualifier> evaluationResultQualifier{}; shared_ptr<long> orderingTimestamp{}; DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifier() {} explicit DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifier(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (evaluationResultQualifier) { res["EvaluationResultQualifier"] = evaluationResultQualifier ? boost::any(evaluationResultQualifier->toMap()) : boost::any(map<string,boost::any>({})); } if (orderingTimestamp) { res["OrderingTimestamp"] = boost::any(*orderingTimestamp); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EvaluationResultQualifier") != m.end() && !m["EvaluationResultQualifier"].empty()) { if (typeid(map<string, boost::any>) == m["EvaluationResultQualifier"].type()) { DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifierEvaluationResultQualifier model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["EvaluationResultQualifier"])); evaluationResultQualifier = make_shared<DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifierEvaluationResultQualifier>(model1); } } if (m.find("OrderingTimestamp") != m.end() && !m["OrderingTimestamp"].empty()) { orderingTimestamp = make_shared<long>(boost::any_cast<long>(m["OrderingTimestamp"])); } } virtual ~DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifier() = default; }; class DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultList : public Darabonba::Model { public: shared_ptr<string> annotation{}; shared_ptr<string> complianceType{}; shared_ptr<long> configRuleInvokedTimestamp{}; shared_ptr<DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifier> evaluationResultIdentifier{}; shared_ptr<string> invokingEventMessageType{}; shared_ptr<bool> remediationEnabled{}; shared_ptr<long> resultRecordedTimestamp{}; shared_ptr<long> riskLevel{}; DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultList() {} explicit DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (annotation) { res["Annotation"] = boost::any(*annotation); } if (complianceType) { res["ComplianceType"] = boost::any(*complianceType); } if (configRuleInvokedTimestamp) { res["ConfigRuleInvokedTimestamp"] = boost::any(*configRuleInvokedTimestamp); } if (evaluationResultIdentifier) { res["EvaluationResultIdentifier"] = evaluationResultIdentifier ? boost::any(evaluationResultIdentifier->toMap()) : boost::any(map<string,boost::any>({})); } if (invokingEventMessageType) { res["InvokingEventMessageType"] = boost::any(*invokingEventMessageType); } if (remediationEnabled) { res["RemediationEnabled"] = boost::any(*remediationEnabled); } if (resultRecordedTimestamp) { res["ResultRecordedTimestamp"] = boost::any(*resultRecordedTimestamp); } if (riskLevel) { res["RiskLevel"] = boost::any(*riskLevel); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Annotation") != m.end() && !m["Annotation"].empty()) { annotation = make_shared<string>(boost::any_cast<string>(m["Annotation"])); } if (m.find("ComplianceType") != m.end() && !m["ComplianceType"].empty()) { complianceType = make_shared<string>(boost::any_cast<string>(m["ComplianceType"])); } if (m.find("ConfigRuleInvokedTimestamp") != m.end() && !m["ConfigRuleInvokedTimestamp"].empty()) { configRuleInvokedTimestamp = make_shared<long>(boost::any_cast<long>(m["ConfigRuleInvokedTimestamp"])); } if (m.find("EvaluationResultIdentifier") != m.end() && !m["EvaluationResultIdentifier"].empty()) { if (typeid(map<string, boost::any>) == m["EvaluationResultIdentifier"].type()) { DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifier model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["EvaluationResultIdentifier"])); evaluationResultIdentifier = make_shared<DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultListEvaluationResultIdentifier>(model1); } } if (m.find("InvokingEventMessageType") != m.end() && !m["InvokingEventMessageType"].empty()) { invokingEventMessageType = make_shared<string>(boost::any_cast<string>(m["InvokingEventMessageType"])); } if (m.find("RemediationEnabled") != m.end() && !m["RemediationEnabled"].empty()) { remediationEnabled = make_shared<bool>(boost::any_cast<bool>(m["RemediationEnabled"])); } if (m.find("ResultRecordedTimestamp") != m.end() && !m["ResultRecordedTimestamp"].empty()) { resultRecordedTimestamp = make_shared<long>(boost::any_cast<long>(m["ResultRecordedTimestamp"])); } if (m.find("RiskLevel") != m.end() && !m["RiskLevel"].empty()) { riskLevel = make_shared<long>(boost::any_cast<long>(m["RiskLevel"])); } } virtual ~DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultList() = default; }; class DescribeEvaluationResultsResponseBodyEvaluationResults : public Darabonba::Model { public: shared_ptr<vector<DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultList>> evaluationResultList{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<long> totalCount{}; DescribeEvaluationResultsResponseBodyEvaluationResults() {} explicit DescribeEvaluationResultsResponseBodyEvaluationResults(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (evaluationResultList) { vector<boost::any> temp1; for(auto item1:*evaluationResultList){ temp1.push_back(boost::any(item1.toMap())); } res["EvaluationResultList"] = boost::any(temp1); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EvaluationResultList") != m.end() && !m["EvaluationResultList"].empty()) { if (typeid(vector<boost::any>) == m["EvaluationResultList"].type()) { vector<DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["EvaluationResultList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } evaluationResultList = make_shared<vector<DescribeEvaluationResultsResponseBodyEvaluationResultsEvaluationResultList>>(expect1); } } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } } virtual ~DescribeEvaluationResultsResponseBodyEvaluationResults() = default; }; class DescribeEvaluationResultsResponseBody : public Darabonba::Model { public: shared_ptr<DescribeEvaluationResultsResponseBodyEvaluationResults> evaluationResults{}; shared_ptr<string> requestId{}; DescribeEvaluationResultsResponseBody() {} explicit DescribeEvaluationResultsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (evaluationResults) { res["EvaluationResults"] = evaluationResults ? boost::any(evaluationResults->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EvaluationResults") != m.end() && !m["EvaluationResults"].empty()) { if (typeid(map<string, boost::any>) == m["EvaluationResults"].type()) { DescribeEvaluationResultsResponseBodyEvaluationResults model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["EvaluationResults"])); evaluationResults = make_shared<DescribeEvaluationResultsResponseBodyEvaluationResults>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeEvaluationResultsResponseBody() = default; }; class DescribeEvaluationResultsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeEvaluationResultsResponseBody> body{}; DescribeEvaluationResultsResponse() {} explicit DescribeEvaluationResultsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeEvaluationResultsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeEvaluationResultsResponseBody>(model1); } } } virtual ~DescribeEvaluationResultsResponse() = default; }; class GetAggregateDiscoveredResourceRequest : public Darabonba::Model { public: shared_ptr<string> aggregatorId{}; shared_ptr<string> region{}; shared_ptr<string> resourceId{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> resourceType{}; GetAggregateDiscoveredResourceRequest() {} explicit GetAggregateDiscoveredResourceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (aggregatorId) { res["AggregatorId"] = boost::any(*aggregatorId); } if (region) { res["Region"] = boost::any(*region); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AggregatorId") != m.end() && !m["AggregatorId"].empty()) { aggregatorId = make_shared<string>(boost::any_cast<string>(m["AggregatorId"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } } virtual ~GetAggregateDiscoveredResourceRequest() = default; }; class GetAggregateDiscoveredResourceResponseBodyDiscoveredResourceDetail : public Darabonba::Model { public: shared_ptr<long> accountId{}; shared_ptr<string> availabilityZone{}; shared_ptr<string> configuration{}; shared_ptr<string> region{}; shared_ptr<long> resourceCreationTime{}; shared_ptr<long> resourceDeleted{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceName{}; shared_ptr<string> resourceStatus{}; shared_ptr<string> resourceType{}; shared_ptr<string> tags{}; GetAggregateDiscoveredResourceResponseBodyDiscoveredResourceDetail() {} explicit GetAggregateDiscoveredResourceResponseBodyDiscoveredResourceDetail(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accountId) { res["AccountId"] = boost::any(*accountId); } if (availabilityZone) { res["AvailabilityZone"] = boost::any(*availabilityZone); } if (configuration) { res["Configuration"] = boost::any(*configuration); } if (region) { res["Region"] = boost::any(*region); } if (resourceCreationTime) { res["ResourceCreationTime"] = boost::any(*resourceCreationTime); } if (resourceDeleted) { res["ResourceDeleted"] = boost::any(*resourceDeleted); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceName) { res["ResourceName"] = boost::any(*resourceName); } if (resourceStatus) { res["ResourceStatus"] = boost::any(*resourceStatus); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (tags) { res["Tags"] = boost::any(*tags); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccountId") != m.end() && !m["AccountId"].empty()) { accountId = make_shared<long>(boost::any_cast<long>(m["AccountId"])); } if (m.find("AvailabilityZone") != m.end() && !m["AvailabilityZone"].empty()) { availabilityZone = make_shared<string>(boost::any_cast<string>(m["AvailabilityZone"])); } if (m.find("Configuration") != m.end() && !m["Configuration"].empty()) { configuration = make_shared<string>(boost::any_cast<string>(m["Configuration"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("ResourceCreationTime") != m.end() && !m["ResourceCreationTime"].empty()) { resourceCreationTime = make_shared<long>(boost::any_cast<long>(m["ResourceCreationTime"])); } if (m.find("ResourceDeleted") != m.end() && !m["ResourceDeleted"].empty()) { resourceDeleted = make_shared<long>(boost::any_cast<long>(m["ResourceDeleted"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceName") != m.end() && !m["ResourceName"].empty()) { resourceName = make_shared<string>(boost::any_cast<string>(m["ResourceName"])); } if (m.find("ResourceStatus") != m.end() && !m["ResourceStatus"].empty()) { resourceStatus = make_shared<string>(boost::any_cast<string>(m["ResourceStatus"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("Tags") != m.end() && !m["Tags"].empty()) { tags = make_shared<string>(boost::any_cast<string>(m["Tags"])); } } virtual ~GetAggregateDiscoveredResourceResponseBodyDiscoveredResourceDetail() = default; }; class GetAggregateDiscoveredResourceResponseBody : public Darabonba::Model { public: shared_ptr<GetAggregateDiscoveredResourceResponseBodyDiscoveredResourceDetail> discoveredResourceDetail{}; shared_ptr<string> requestId{}; GetAggregateDiscoveredResourceResponseBody() {} explicit GetAggregateDiscoveredResourceResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (discoveredResourceDetail) { res["DiscoveredResourceDetail"] = discoveredResourceDetail ? boost::any(discoveredResourceDetail->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DiscoveredResourceDetail") != m.end() && !m["DiscoveredResourceDetail"].empty()) { if (typeid(map<string, boost::any>) == m["DiscoveredResourceDetail"].type()) { GetAggregateDiscoveredResourceResponseBodyDiscoveredResourceDetail model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["DiscoveredResourceDetail"])); discoveredResourceDetail = make_shared<GetAggregateDiscoveredResourceResponseBodyDiscoveredResourceDetail>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~GetAggregateDiscoveredResourceResponseBody() = default; }; class GetAggregateDiscoveredResourceResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<GetAggregateDiscoveredResourceResponseBody> body{}; GetAggregateDiscoveredResourceResponse() {} explicit GetAggregateDiscoveredResourceResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { GetAggregateDiscoveredResourceResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<GetAggregateDiscoveredResourceResponseBody>(model1); } } } virtual ~GetAggregateDiscoveredResourceResponse() = default; }; class GetDiscoveredResourceCountsRequest : public Darabonba::Model { public: shared_ptr<string> groupByKey{}; shared_ptr<long> memberId{}; shared_ptr<bool> multiAccount{}; GetDiscoveredResourceCountsRequest() {} explicit GetDiscoveredResourceCountsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (groupByKey) { res["GroupByKey"] = boost::any(*groupByKey); } if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("GroupByKey") != m.end() && !m["GroupByKey"].empty()) { groupByKey = make_shared<string>(boost::any_cast<string>(m["GroupByKey"])); } if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<long>(boost::any_cast<long>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } } virtual ~GetDiscoveredResourceCountsRequest() = default; }; class GetDiscoveredResourceCountsResponseBodyGroupedResourceCountsGroupedResourceCountList : public Darabonba::Model { public: shared_ptr<string> groupName{}; shared_ptr<long> resourceCount{}; GetDiscoveredResourceCountsResponseBodyGroupedResourceCountsGroupedResourceCountList() {} explicit GetDiscoveredResourceCountsResponseBodyGroupedResourceCountsGroupedResourceCountList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (groupName) { res["GroupName"] = boost::any(*groupName); } if (resourceCount) { res["ResourceCount"] = boost::any(*resourceCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("GroupName") != m.end() && !m["GroupName"].empty()) { groupName = make_shared<string>(boost::any_cast<string>(m["GroupName"])); } if (m.find("ResourceCount") != m.end() && !m["ResourceCount"].empty()) { resourceCount = make_shared<long>(boost::any_cast<long>(m["ResourceCount"])); } } virtual ~GetDiscoveredResourceCountsResponseBodyGroupedResourceCountsGroupedResourceCountList() = default; }; class GetDiscoveredResourceCountsResponseBodyGroupedResourceCounts : public Darabonba::Model { public: shared_ptr<string> groupByKey{}; shared_ptr<vector<GetDiscoveredResourceCountsResponseBodyGroupedResourceCountsGroupedResourceCountList>> groupedResourceCountList{}; GetDiscoveredResourceCountsResponseBodyGroupedResourceCounts() {} explicit GetDiscoveredResourceCountsResponseBodyGroupedResourceCounts(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (groupByKey) { res["GroupByKey"] = boost::any(*groupByKey); } if (groupedResourceCountList) { vector<boost::any> temp1; for(auto item1:*groupedResourceCountList){ temp1.push_back(boost::any(item1.toMap())); } res["GroupedResourceCountList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("GroupByKey") != m.end() && !m["GroupByKey"].empty()) { groupByKey = make_shared<string>(boost::any_cast<string>(m["GroupByKey"])); } if (m.find("GroupedResourceCountList") != m.end() && !m["GroupedResourceCountList"].empty()) { if (typeid(vector<boost::any>) == m["GroupedResourceCountList"].type()) { vector<GetDiscoveredResourceCountsResponseBodyGroupedResourceCountsGroupedResourceCountList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["GroupedResourceCountList"])){ if (typeid(map<string, boost::any>) == item1.type()) { GetDiscoveredResourceCountsResponseBodyGroupedResourceCountsGroupedResourceCountList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } groupedResourceCountList = make_shared<vector<GetDiscoveredResourceCountsResponseBodyGroupedResourceCountsGroupedResourceCountList>>(expect1); } } } virtual ~GetDiscoveredResourceCountsResponseBodyGroupedResourceCounts() = default; }; class GetDiscoveredResourceCountsResponseBody : public Darabonba::Model { public: shared_ptr<GetDiscoveredResourceCountsResponseBodyGroupedResourceCounts> groupedResourceCounts{}; shared_ptr<string> requestId{}; GetDiscoveredResourceCountsResponseBody() {} explicit GetDiscoveredResourceCountsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (groupedResourceCounts) { res["GroupedResourceCounts"] = groupedResourceCounts ? boost::any(groupedResourceCounts->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("GroupedResourceCounts") != m.end() && !m["GroupedResourceCounts"].empty()) { if (typeid(map<string, boost::any>) == m["GroupedResourceCounts"].type()) { GetDiscoveredResourceCountsResponseBodyGroupedResourceCounts model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["GroupedResourceCounts"])); groupedResourceCounts = make_shared<GetDiscoveredResourceCountsResponseBodyGroupedResourceCounts>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~GetDiscoveredResourceCountsResponseBody() = default; }; class GetDiscoveredResourceCountsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<GetDiscoveredResourceCountsResponseBody> body{}; GetDiscoveredResourceCountsResponse() {} explicit GetDiscoveredResourceCountsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { GetDiscoveredResourceCountsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<GetDiscoveredResourceCountsResponseBody>(model1); } } } virtual ~GetDiscoveredResourceCountsResponse() = default; }; class GetDiscoveredResourceSummaryRequest : public Darabonba::Model { public: shared_ptr<long> memberId{}; shared_ptr<bool> multiAccount{}; GetDiscoveredResourceSummaryRequest() {} explicit GetDiscoveredResourceSummaryRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<long>(boost::any_cast<long>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } } virtual ~GetDiscoveredResourceSummaryRequest() = default; }; class GetDiscoveredResourceSummaryResponseBodyDiscoveredResourceSummary : public Darabonba::Model { public: shared_ptr<long> regionCount{}; shared_ptr<long> resourceCount{}; shared_ptr<long> resourceTypeCount{}; GetDiscoveredResourceSummaryResponseBodyDiscoveredResourceSummary() {} explicit GetDiscoveredResourceSummaryResponseBodyDiscoveredResourceSummary(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (regionCount) { res["RegionCount"] = boost::any(*regionCount); } if (resourceCount) { res["ResourceCount"] = boost::any(*resourceCount); } if (resourceTypeCount) { res["ResourceTypeCount"] = boost::any(*resourceTypeCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RegionCount") != m.end() && !m["RegionCount"].empty()) { regionCount = make_shared<long>(boost::any_cast<long>(m["RegionCount"])); } if (m.find("ResourceCount") != m.end() && !m["ResourceCount"].empty()) { resourceCount = make_shared<long>(boost::any_cast<long>(m["ResourceCount"])); } if (m.find("ResourceTypeCount") != m.end() && !m["ResourceTypeCount"].empty()) { resourceTypeCount = make_shared<long>(boost::any_cast<long>(m["ResourceTypeCount"])); } } virtual ~GetDiscoveredResourceSummaryResponseBodyDiscoveredResourceSummary() = default; }; class GetDiscoveredResourceSummaryResponseBody : public Darabonba::Model { public: shared_ptr<GetDiscoveredResourceSummaryResponseBodyDiscoveredResourceSummary> discoveredResourceSummary{}; shared_ptr<string> requestId{}; GetDiscoveredResourceSummaryResponseBody() {} explicit GetDiscoveredResourceSummaryResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (discoveredResourceSummary) { res["DiscoveredResourceSummary"] = discoveredResourceSummary ? boost::any(discoveredResourceSummary->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DiscoveredResourceSummary") != m.end() && !m["DiscoveredResourceSummary"].empty()) { if (typeid(map<string, boost::any>) == m["DiscoveredResourceSummary"].type()) { GetDiscoveredResourceSummaryResponseBodyDiscoveredResourceSummary model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["DiscoveredResourceSummary"])); discoveredResourceSummary = make_shared<GetDiscoveredResourceSummaryResponseBodyDiscoveredResourceSummary>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~GetDiscoveredResourceSummaryResponseBody() = default; }; class GetDiscoveredResourceSummaryResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<GetDiscoveredResourceSummaryResponseBody> body{}; GetDiscoveredResourceSummaryResponse() {} explicit GetDiscoveredResourceSummaryResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { GetDiscoveredResourceSummaryResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<GetDiscoveredResourceSummaryResponseBody>(model1); } } } virtual ~GetDiscoveredResourceSummaryResponse() = default; }; class GetResourceComplianceTimelineRequest : public Darabonba::Model { public: shared_ptr<long> endTime{}; shared_ptr<long> limit{}; shared_ptr<string> memberId{}; shared_ptr<bool> multiAccount{}; shared_ptr<string> nextToken{}; shared_ptr<string> region{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceType{}; shared_ptr<long> startTime{}; GetResourceComplianceTimelineRequest() {} explicit GetResourceComplianceTimelineRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (endTime) { res["EndTime"] = boost::any(*endTime); } if (limit) { res["Limit"] = boost::any(*limit); } if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } if (nextToken) { res["NextToken"] = boost::any(*nextToken); } if (region) { res["Region"] = boost::any(*region); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (startTime) { res["StartTime"] = boost::any(*startTime); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<long>(boost::any_cast<long>(m["EndTime"])); } if (m.find("Limit") != m.end() && !m["Limit"].empty()) { limit = make_shared<long>(boost::any_cast<long>(m["Limit"])); } if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<string>(boost::any_cast<string>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } if (m.find("NextToken") != m.end() && !m["NextToken"].empty()) { nextToken = make_shared<string>(boost::any_cast<string>(m["NextToken"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<long>(boost::any_cast<long>(m["StartTime"])); } } virtual ~GetResourceComplianceTimelineRequest() = default; }; class GetResourceComplianceTimelineResponseBodyResourceComplianceTimelineComplianceList : public Darabonba::Model { public: shared_ptr<string> accountId{}; shared_ptr<string> availabilityZone{}; shared_ptr<long> captureTime{}; shared_ptr<string> configuration{}; shared_ptr<string> configurationDiff{}; shared_ptr<string> region{}; shared_ptr<long> resourceCreateTime{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceName{}; shared_ptr<string> resourceStatus{}; shared_ptr<string> resourceType{}; shared_ptr<string> tags{}; GetResourceComplianceTimelineResponseBodyResourceComplianceTimelineComplianceList() {} explicit GetResourceComplianceTimelineResponseBodyResourceComplianceTimelineComplianceList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accountId) { res["AccountId"] = boost::any(*accountId); } if (availabilityZone) { res["AvailabilityZone"] = boost::any(*availabilityZone); } if (captureTime) { res["CaptureTime"] = boost::any(*captureTime); } if (configuration) { res["Configuration"] = boost::any(*configuration); } if (configurationDiff) { res["ConfigurationDiff"] = boost::any(*configurationDiff); } if (region) { res["Region"] = boost::any(*region); } if (resourceCreateTime) { res["ResourceCreateTime"] = boost::any(*resourceCreateTime); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceName) { res["ResourceName"] = boost::any(*resourceName); } if (resourceStatus) { res["ResourceStatus"] = boost::any(*resourceStatus); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (tags) { res["Tags"] = boost::any(*tags); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccountId") != m.end() && !m["AccountId"].empty()) { accountId = make_shared<string>(boost::any_cast<string>(m["AccountId"])); } if (m.find("AvailabilityZone") != m.end() && !m["AvailabilityZone"].empty()) { availabilityZone = make_shared<string>(boost::any_cast<string>(m["AvailabilityZone"])); } if (m.find("CaptureTime") != m.end() && !m["CaptureTime"].empty()) { captureTime = make_shared<long>(boost::any_cast<long>(m["CaptureTime"])); } if (m.find("Configuration") != m.end() && !m["Configuration"].empty()) { configuration = make_shared<string>(boost::any_cast<string>(m["Configuration"])); } if (m.find("ConfigurationDiff") != m.end() && !m["ConfigurationDiff"].empty()) { configurationDiff = make_shared<string>(boost::any_cast<string>(m["ConfigurationDiff"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("ResourceCreateTime") != m.end() && !m["ResourceCreateTime"].empty()) { resourceCreateTime = make_shared<long>(boost::any_cast<long>(m["ResourceCreateTime"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceName") != m.end() && !m["ResourceName"].empty()) { resourceName = make_shared<string>(boost::any_cast<string>(m["ResourceName"])); } if (m.find("ResourceStatus") != m.end() && !m["ResourceStatus"].empty()) { resourceStatus = make_shared<string>(boost::any_cast<string>(m["ResourceStatus"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("Tags") != m.end() && !m["Tags"].empty()) { tags = make_shared<string>(boost::any_cast<string>(m["Tags"])); } } virtual ~GetResourceComplianceTimelineResponseBodyResourceComplianceTimelineComplianceList() = default; }; class GetResourceComplianceTimelineResponseBodyResourceComplianceTimeline : public Darabonba::Model { public: shared_ptr<vector<GetResourceComplianceTimelineResponseBodyResourceComplianceTimelineComplianceList>> complianceList{}; shared_ptr<long> limit{}; shared_ptr<string> nextToken{}; shared_ptr<long> totalCount{}; GetResourceComplianceTimelineResponseBodyResourceComplianceTimeline() {} explicit GetResourceComplianceTimelineResponseBodyResourceComplianceTimeline(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceList) { vector<boost::any> temp1; for(auto item1:*complianceList){ temp1.push_back(boost::any(item1.toMap())); } res["ComplianceList"] = boost::any(temp1); } if (limit) { res["Limit"] = boost::any(*limit); } if (nextToken) { res["NextToken"] = boost::any(*nextToken); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceList") != m.end() && !m["ComplianceList"].empty()) { if (typeid(vector<boost::any>) == m["ComplianceList"].type()) { vector<GetResourceComplianceTimelineResponseBodyResourceComplianceTimelineComplianceList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["ComplianceList"])){ if (typeid(map<string, boost::any>) == item1.type()) { GetResourceComplianceTimelineResponseBodyResourceComplianceTimelineComplianceList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } complianceList = make_shared<vector<GetResourceComplianceTimelineResponseBodyResourceComplianceTimelineComplianceList>>(expect1); } } if (m.find("Limit") != m.end() && !m["Limit"].empty()) { limit = make_shared<long>(boost::any_cast<long>(m["Limit"])); } if (m.find("NextToken") != m.end() && !m["NextToken"].empty()) { nextToken = make_shared<string>(boost::any_cast<string>(m["NextToken"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } } virtual ~GetResourceComplianceTimelineResponseBodyResourceComplianceTimeline() = default; }; class GetResourceComplianceTimelineResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<GetResourceComplianceTimelineResponseBodyResourceComplianceTimeline> resourceComplianceTimeline{}; GetResourceComplianceTimelineResponseBody() {} explicit GetResourceComplianceTimelineResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (resourceComplianceTimeline) { res["ResourceComplianceTimeline"] = resourceComplianceTimeline ? boost::any(resourceComplianceTimeline->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("ResourceComplianceTimeline") != m.end() && !m["ResourceComplianceTimeline"].empty()) { if (typeid(map<string, boost::any>) == m["ResourceComplianceTimeline"].type()) { GetResourceComplianceTimelineResponseBodyResourceComplianceTimeline model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ResourceComplianceTimeline"])); resourceComplianceTimeline = make_shared<GetResourceComplianceTimelineResponseBodyResourceComplianceTimeline>(model1); } } } virtual ~GetResourceComplianceTimelineResponseBody() = default; }; class GetResourceComplianceTimelineResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<GetResourceComplianceTimelineResponseBody> body{}; GetResourceComplianceTimelineResponse() {} explicit GetResourceComplianceTimelineResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { GetResourceComplianceTimelineResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<GetResourceComplianceTimelineResponseBody>(model1); } } } virtual ~GetResourceComplianceTimelineResponse() = default; }; class GetResourceConfigurationTimelineRequest : public Darabonba::Model { public: shared_ptr<long> endTime{}; shared_ptr<long> limit{}; shared_ptr<long> memberId{}; shared_ptr<bool> multiAccount{}; shared_ptr<string> nextToken{}; shared_ptr<string> region{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceType{}; shared_ptr<long> startTime{}; GetResourceConfigurationTimelineRequest() {} explicit GetResourceConfigurationTimelineRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (endTime) { res["EndTime"] = boost::any(*endTime); } if (limit) { res["Limit"] = boost::any(*limit); } if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } if (nextToken) { res["NextToken"] = boost::any(*nextToken); } if (region) { res["Region"] = boost::any(*region); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (startTime) { res["StartTime"] = boost::any(*startTime); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<long>(boost::any_cast<long>(m["EndTime"])); } if (m.find("Limit") != m.end() && !m["Limit"].empty()) { limit = make_shared<long>(boost::any_cast<long>(m["Limit"])); } if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<long>(boost::any_cast<long>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } if (m.find("NextToken") != m.end() && !m["NextToken"].empty()) { nextToken = make_shared<string>(boost::any_cast<string>(m["NextToken"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<long>(boost::any_cast<long>(m["StartTime"])); } } virtual ~GetResourceConfigurationTimelineRequest() = default; }; class GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimelineConfigurationList : public Darabonba::Model { public: shared_ptr<long> accountId{}; shared_ptr<string> availabilityZone{}; shared_ptr<string> captureTime{}; shared_ptr<string> configurationDiff{}; shared_ptr<string> region{}; shared_ptr<string> resourceCreateTime{}; shared_ptr<string> resourceEventType{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceName{}; shared_ptr<string> resourceType{}; shared_ptr<string> tags{}; GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimelineConfigurationList() {} explicit GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimelineConfigurationList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accountId) { res["AccountId"] = boost::any(*accountId); } if (availabilityZone) { res["AvailabilityZone"] = boost::any(*availabilityZone); } if (captureTime) { res["CaptureTime"] = boost::any(*captureTime); } if (configurationDiff) { res["ConfigurationDiff"] = boost::any(*configurationDiff); } if (region) { res["Region"] = boost::any(*region); } if (resourceCreateTime) { res["ResourceCreateTime"] = boost::any(*resourceCreateTime); } if (resourceEventType) { res["ResourceEventType"] = boost::any(*resourceEventType); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceName) { res["ResourceName"] = boost::any(*resourceName); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (tags) { res["Tags"] = boost::any(*tags); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccountId") != m.end() && !m["AccountId"].empty()) { accountId = make_shared<long>(boost::any_cast<long>(m["AccountId"])); } if (m.find("AvailabilityZone") != m.end() && !m["AvailabilityZone"].empty()) { availabilityZone = make_shared<string>(boost::any_cast<string>(m["AvailabilityZone"])); } if (m.find("CaptureTime") != m.end() && !m["CaptureTime"].empty()) { captureTime = make_shared<string>(boost::any_cast<string>(m["CaptureTime"])); } if (m.find("ConfigurationDiff") != m.end() && !m["ConfigurationDiff"].empty()) { configurationDiff = make_shared<string>(boost::any_cast<string>(m["ConfigurationDiff"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("ResourceCreateTime") != m.end() && !m["ResourceCreateTime"].empty()) { resourceCreateTime = make_shared<string>(boost::any_cast<string>(m["ResourceCreateTime"])); } if (m.find("ResourceEventType") != m.end() && !m["ResourceEventType"].empty()) { resourceEventType = make_shared<string>(boost::any_cast<string>(m["ResourceEventType"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceName") != m.end() && !m["ResourceName"].empty()) { resourceName = make_shared<string>(boost::any_cast<string>(m["ResourceName"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("Tags") != m.end() && !m["Tags"].empty()) { tags = make_shared<string>(boost::any_cast<string>(m["Tags"])); } } virtual ~GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimelineConfigurationList() = default; }; class GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimeline : public Darabonba::Model { public: shared_ptr<vector<GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimelineConfigurationList>> configurationList{}; shared_ptr<long> limit{}; shared_ptr<string> nextToken{}; shared_ptr<long> totalCount{}; GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimeline() {} explicit GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimeline(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configurationList) { vector<boost::any> temp1; for(auto item1:*configurationList){ temp1.push_back(boost::any(item1.toMap())); } res["ConfigurationList"] = boost::any(temp1); } if (limit) { res["Limit"] = boost::any(*limit); } if (nextToken) { res["NextToken"] = boost::any(*nextToken); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigurationList") != m.end() && !m["ConfigurationList"].empty()) { if (typeid(vector<boost::any>) == m["ConfigurationList"].type()) { vector<GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimelineConfigurationList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["ConfigurationList"])){ if (typeid(map<string, boost::any>) == item1.type()) { GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimelineConfigurationList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } configurationList = make_shared<vector<GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimelineConfigurationList>>(expect1); } } if (m.find("Limit") != m.end() && !m["Limit"].empty()) { limit = make_shared<long>(boost::any_cast<long>(m["Limit"])); } if (m.find("NextToken") != m.end() && !m["NextToken"].empty()) { nextToken = make_shared<string>(boost::any_cast<string>(m["NextToken"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } } virtual ~GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimeline() = default; }; class GetResourceConfigurationTimelineResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimeline> resourceConfigurationTimeline{}; GetResourceConfigurationTimelineResponseBody() {} explicit GetResourceConfigurationTimelineResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (resourceConfigurationTimeline) { res["ResourceConfigurationTimeline"] = resourceConfigurationTimeline ? boost::any(resourceConfigurationTimeline->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("ResourceConfigurationTimeline") != m.end() && !m["ResourceConfigurationTimeline"].empty()) { if (typeid(map<string, boost::any>) == m["ResourceConfigurationTimeline"].type()) { GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimeline model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ResourceConfigurationTimeline"])); resourceConfigurationTimeline = make_shared<GetResourceConfigurationTimelineResponseBodyResourceConfigurationTimeline>(model1); } } } virtual ~GetResourceConfigurationTimelineResponseBody() = default; }; class GetResourceConfigurationTimelineResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<GetResourceConfigurationTimelineResponseBody> body{}; GetResourceConfigurationTimelineResponse() {} explicit GetResourceConfigurationTimelineResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { GetResourceConfigurationTimelineResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<GetResourceConfigurationTimelineResponseBody>(model1); } } } virtual ~GetResourceConfigurationTimelineResponse() = default; }; class GetSupportedResourceTypesResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<vector<string>> resourceTypes{}; GetSupportedResourceTypesResponseBody() {} explicit GetSupportedResourceTypesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (resourceTypes) { res["ResourceTypes"] = boost::any(*resourceTypes); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("ResourceTypes") != m.end() && !m["ResourceTypes"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["ResourceTypes"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["ResourceTypes"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } resourceTypes = make_shared<vector<string>>(toVec1); } } virtual ~GetSupportedResourceTypesResponseBody() = default; }; class GetSupportedResourceTypesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<GetSupportedResourceTypesResponseBody> body{}; GetSupportedResourceTypesResponse() {} explicit GetSupportedResourceTypesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { GetSupportedResourceTypesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<GetSupportedResourceTypesResponseBody>(model1); } } } virtual ~GetSupportedResourceTypesResponse() = default; }; class ListAggregateDiscoveredResourcesRequest : public Darabonba::Model { public: shared_ptr<string> aggregatorId{}; shared_ptr<string> complianceType{}; shared_ptr<string> folderId{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<string> regions{}; shared_ptr<long> resourceDeleted{}; shared_ptr<string> resourceId{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> resourceTypes{}; ListAggregateDiscoveredResourcesRequest() {} explicit ListAggregateDiscoveredResourcesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (aggregatorId) { res["AggregatorId"] = boost::any(*aggregatorId); } if (complianceType) { res["ComplianceType"] = boost::any(*complianceType); } if (folderId) { res["FolderId"] = boost::any(*folderId); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (regions) { res["Regions"] = boost::any(*regions); } if (resourceDeleted) { res["ResourceDeleted"] = boost::any(*resourceDeleted); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (resourceTypes) { res["ResourceTypes"] = boost::any(*resourceTypes); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AggregatorId") != m.end() && !m["AggregatorId"].empty()) { aggregatorId = make_shared<string>(boost::any_cast<string>(m["AggregatorId"])); } if (m.find("ComplianceType") != m.end() && !m["ComplianceType"].empty()) { complianceType = make_shared<string>(boost::any_cast<string>(m["ComplianceType"])); } if (m.find("FolderId") != m.end() && !m["FolderId"].empty()) { folderId = make_shared<string>(boost::any_cast<string>(m["FolderId"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("Regions") != m.end() && !m["Regions"].empty()) { regions = make_shared<string>(boost::any_cast<string>(m["Regions"])); } if (m.find("ResourceDeleted") != m.end() && !m["ResourceDeleted"].empty()) { resourceDeleted = make_shared<long>(boost::any_cast<long>(m["ResourceDeleted"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("ResourceTypes") != m.end() && !m["ResourceTypes"].empty()) { resourceTypes = make_shared<string>(boost::any_cast<string>(m["ResourceTypes"])); } } virtual ~ListAggregateDiscoveredResourcesRequest() = default; }; class ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList : public Darabonba::Model { public: shared_ptr<long> accountId{}; shared_ptr<string> region{}; shared_ptr<long> resourceCreationTime{}; shared_ptr<long> resourceDeleted{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceName{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> resourceStatus{}; shared_ptr<string> resourceType{}; shared_ptr<string> tags{}; ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList() {} explicit ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accountId) { res["AccountId"] = boost::any(*accountId); } if (region) { res["Region"] = boost::any(*region); } if (resourceCreationTime) { res["ResourceCreationTime"] = boost::any(*resourceCreationTime); } if (resourceDeleted) { res["ResourceDeleted"] = boost::any(*resourceDeleted); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceName) { res["ResourceName"] = boost::any(*resourceName); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (resourceStatus) { res["ResourceStatus"] = boost::any(*resourceStatus); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (tags) { res["Tags"] = boost::any(*tags); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccountId") != m.end() && !m["AccountId"].empty()) { accountId = make_shared<long>(boost::any_cast<long>(m["AccountId"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("ResourceCreationTime") != m.end() && !m["ResourceCreationTime"].empty()) { resourceCreationTime = make_shared<long>(boost::any_cast<long>(m["ResourceCreationTime"])); } if (m.find("ResourceDeleted") != m.end() && !m["ResourceDeleted"].empty()) { resourceDeleted = make_shared<long>(boost::any_cast<long>(m["ResourceDeleted"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceName") != m.end() && !m["ResourceName"].empty()) { resourceName = make_shared<string>(boost::any_cast<string>(m["ResourceName"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("ResourceStatus") != m.end() && !m["ResourceStatus"].empty()) { resourceStatus = make_shared<string>(boost::any_cast<string>(m["ResourceStatus"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("Tags") != m.end() && !m["Tags"].empty()) { tags = make_shared<string>(boost::any_cast<string>(m["Tags"])); } } virtual ~ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList() = default; }; class ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfiles : public Darabonba::Model { public: shared_ptr<vector<ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList>> discoveredResourceProfileList{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<long> totalCount{}; ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfiles() {} explicit ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfiles(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (discoveredResourceProfileList) { vector<boost::any> temp1; for(auto item1:*discoveredResourceProfileList){ temp1.push_back(boost::any(item1.toMap())); } res["DiscoveredResourceProfileList"] = boost::any(temp1); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DiscoveredResourceProfileList") != m.end() && !m["DiscoveredResourceProfileList"].empty()) { if (typeid(vector<boost::any>) == m["DiscoveredResourceProfileList"].type()) { vector<ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["DiscoveredResourceProfileList"])){ if (typeid(map<string, boost::any>) == item1.type()) { ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } discoveredResourceProfileList = make_shared<vector<ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList>>(expect1); } } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } } virtual ~ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfiles() = default; }; class ListAggregateDiscoveredResourcesResponseBody : public Darabonba::Model { public: shared_ptr<ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfiles> discoveredResourceProfiles{}; shared_ptr<string> requestId{}; ListAggregateDiscoveredResourcesResponseBody() {} explicit ListAggregateDiscoveredResourcesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (discoveredResourceProfiles) { res["DiscoveredResourceProfiles"] = discoveredResourceProfiles ? boost::any(discoveredResourceProfiles->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DiscoveredResourceProfiles") != m.end() && !m["DiscoveredResourceProfiles"].empty()) { if (typeid(map<string, boost::any>) == m["DiscoveredResourceProfiles"].type()) { ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfiles model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["DiscoveredResourceProfiles"])); discoveredResourceProfiles = make_shared<ListAggregateDiscoveredResourcesResponseBodyDiscoveredResourceProfiles>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ListAggregateDiscoveredResourcesResponseBody() = default; }; class ListAggregateDiscoveredResourcesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ListAggregateDiscoveredResourcesResponseBody> body{}; ListAggregateDiscoveredResourcesResponse() {} explicit ListAggregateDiscoveredResourcesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ListAggregateDiscoveredResourcesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ListAggregateDiscoveredResourcesResponseBody>(model1); } } } virtual ~ListAggregateDiscoveredResourcesResponse() = default; }; class ListConfigRulesRequest : public Darabonba::Model { public: shared_ptr<string> compliancePackId{}; shared_ptr<string> complianceType{}; shared_ptr<string> configRuleName{}; shared_ptr<string> configRuleState{}; shared_ptr<long> memberId{}; shared_ptr<bool> multiAccount{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<long> riskLevel{}; ListConfigRulesRequest() {} explicit ListConfigRulesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (compliancePackId) { res["CompliancePackId"] = boost::any(*compliancePackId); } if (complianceType) { res["ComplianceType"] = boost::any(*complianceType); } if (configRuleName) { res["ConfigRuleName"] = boost::any(*configRuleName); } if (configRuleState) { res["ConfigRuleState"] = boost::any(*configRuleState); } if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (riskLevel) { res["RiskLevel"] = boost::any(*riskLevel); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("CompliancePackId") != m.end() && !m["CompliancePackId"].empty()) { compliancePackId = make_shared<string>(boost::any_cast<string>(m["CompliancePackId"])); } if (m.find("ComplianceType") != m.end() && !m["ComplianceType"].empty()) { complianceType = make_shared<string>(boost::any_cast<string>(m["ComplianceType"])); } if (m.find("ConfigRuleName") != m.end() && !m["ConfigRuleName"].empty()) { configRuleName = make_shared<string>(boost::any_cast<string>(m["ConfigRuleName"])); } if (m.find("ConfigRuleState") != m.end() && !m["ConfigRuleState"].empty()) { configRuleState = make_shared<string>(boost::any_cast<string>(m["ConfigRuleState"])); } if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<long>(boost::any_cast<long>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("RiskLevel") != m.end() && !m["RiskLevel"].empty()) { riskLevel = make_shared<long>(boost::any_cast<long>(m["RiskLevel"])); } } virtual ~ListConfigRulesRequest() = default; }; class ListConfigRulesResponseBodyConfigRulesConfigRuleListCompliance : public Darabonba::Model { public: shared_ptr<string> complianceType{}; shared_ptr<long> count{}; ListConfigRulesResponseBodyConfigRulesConfigRuleListCompliance() {} explicit ListConfigRulesResponseBodyConfigRulesConfigRuleListCompliance(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceType) { res["ComplianceType"] = boost::any(*complianceType); } if (count) { res["Count"] = boost::any(*count); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceType") != m.end() && !m["ComplianceType"].empty()) { complianceType = make_shared<string>(boost::any_cast<string>(m["ComplianceType"])); } if (m.find("Count") != m.end() && !m["Count"].empty()) { count = make_shared<long>(boost::any_cast<long>(m["Count"])); } } virtual ~ListConfigRulesResponseBodyConfigRulesConfigRuleListCompliance() = default; }; class ListConfigRulesResponseBodyConfigRulesConfigRuleListCreateBy : public Darabonba::Model { public: shared_ptr<string> compliancePackId{}; shared_ptr<string> compliancePackName{}; ListConfigRulesResponseBodyConfigRulesConfigRuleListCreateBy() {} explicit ListConfigRulesResponseBodyConfigRulesConfigRuleListCreateBy(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (compliancePackId) { res["CompliancePackId"] = boost::any(*compliancePackId); } if (compliancePackName) { res["CompliancePackName"] = boost::any(*compliancePackName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("CompliancePackId") != m.end() && !m["CompliancePackId"].empty()) { compliancePackId = make_shared<string>(boost::any_cast<string>(m["CompliancePackId"])); } if (m.find("CompliancePackName") != m.end() && !m["CompliancePackName"].empty()) { compliancePackName = make_shared<string>(boost::any_cast<string>(m["CompliancePackName"])); } } virtual ~ListConfigRulesResponseBodyConfigRulesConfigRuleListCreateBy() = default; }; class ListConfigRulesResponseBodyConfigRulesConfigRuleList : public Darabonba::Model { public: shared_ptr<long> accountId{}; shared_ptr<string> automationType{}; shared_ptr<ListConfigRulesResponseBodyConfigRulesConfigRuleListCompliance> compliance{}; shared_ptr<string> compliancePackId{}; shared_ptr<string> configRuleArn{}; shared_ptr<string> configRuleId{}; shared_ptr<string> configRuleName{}; shared_ptr<string> configRuleState{}; shared_ptr<ListConfigRulesResponseBodyConfigRulesConfigRuleListCreateBy> createBy{}; shared_ptr<string> description{}; shared_ptr<long> riskLevel{}; shared_ptr<string> sourceIdentifier{}; shared_ptr<string> sourceOwner{}; ListConfigRulesResponseBodyConfigRulesConfigRuleList() {} explicit ListConfigRulesResponseBodyConfigRulesConfigRuleList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accountId) { res["AccountId"] = boost::any(*accountId); } if (automationType) { res["AutomationType"] = boost::any(*automationType); } if (compliance) { res["Compliance"] = compliance ? boost::any(compliance->toMap()) : boost::any(map<string,boost::any>({})); } if (compliancePackId) { res["CompliancePackId"] = boost::any(*compliancePackId); } if (configRuleArn) { res["ConfigRuleArn"] = boost::any(*configRuleArn); } if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (configRuleName) { res["ConfigRuleName"] = boost::any(*configRuleName); } if (configRuleState) { res["ConfigRuleState"] = boost::any(*configRuleState); } if (createBy) { res["CreateBy"] = createBy ? boost::any(createBy->toMap()) : boost::any(map<string,boost::any>({})); } if (description) { res["Description"] = boost::any(*description); } if (riskLevel) { res["RiskLevel"] = boost::any(*riskLevel); } if (sourceIdentifier) { res["SourceIdentifier"] = boost::any(*sourceIdentifier); } if (sourceOwner) { res["SourceOwner"] = boost::any(*sourceOwner); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccountId") != m.end() && !m["AccountId"].empty()) { accountId = make_shared<long>(boost::any_cast<long>(m["AccountId"])); } if (m.find("AutomationType") != m.end() && !m["AutomationType"].empty()) { automationType = make_shared<string>(boost::any_cast<string>(m["AutomationType"])); } if (m.find("Compliance") != m.end() && !m["Compliance"].empty()) { if (typeid(map<string, boost::any>) == m["Compliance"].type()) { ListConfigRulesResponseBodyConfigRulesConfigRuleListCompliance model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Compliance"])); compliance = make_shared<ListConfigRulesResponseBodyConfigRulesConfigRuleListCompliance>(model1); } } if (m.find("CompliancePackId") != m.end() && !m["CompliancePackId"].empty()) { compliancePackId = make_shared<string>(boost::any_cast<string>(m["CompliancePackId"])); } if (m.find("ConfigRuleArn") != m.end() && !m["ConfigRuleArn"].empty()) { configRuleArn = make_shared<string>(boost::any_cast<string>(m["ConfigRuleArn"])); } if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("ConfigRuleName") != m.end() && !m["ConfigRuleName"].empty()) { configRuleName = make_shared<string>(boost::any_cast<string>(m["ConfigRuleName"])); } if (m.find("ConfigRuleState") != m.end() && !m["ConfigRuleState"].empty()) { configRuleState = make_shared<string>(boost::any_cast<string>(m["ConfigRuleState"])); } if (m.find("CreateBy") != m.end() && !m["CreateBy"].empty()) { if (typeid(map<string, boost::any>) == m["CreateBy"].type()) { ListConfigRulesResponseBodyConfigRulesConfigRuleListCreateBy model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["CreateBy"])); createBy = make_shared<ListConfigRulesResponseBodyConfigRulesConfigRuleListCreateBy>(model1); } } if (m.find("Description") != m.end() && !m["Description"].empty()) { description = make_shared<string>(boost::any_cast<string>(m["Description"])); } if (m.find("RiskLevel") != m.end() && !m["RiskLevel"].empty()) { riskLevel = make_shared<long>(boost::any_cast<long>(m["RiskLevel"])); } if (m.find("SourceIdentifier") != m.end() && !m["SourceIdentifier"].empty()) { sourceIdentifier = make_shared<string>(boost::any_cast<string>(m["SourceIdentifier"])); } if (m.find("SourceOwner") != m.end() && !m["SourceOwner"].empty()) { sourceOwner = make_shared<string>(boost::any_cast<string>(m["SourceOwner"])); } } virtual ~ListConfigRulesResponseBodyConfigRulesConfigRuleList() = default; }; class ListConfigRulesResponseBodyConfigRules : public Darabonba::Model { public: shared_ptr<vector<ListConfigRulesResponseBodyConfigRulesConfigRuleList>> configRuleList{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<long> totalCount{}; ListConfigRulesResponseBodyConfigRules() {} explicit ListConfigRulesResponseBodyConfigRules(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRuleList) { vector<boost::any> temp1; for(auto item1:*configRuleList){ temp1.push_back(boost::any(item1.toMap())); } res["ConfigRuleList"] = boost::any(temp1); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRuleList") != m.end() && !m["ConfigRuleList"].empty()) { if (typeid(vector<boost::any>) == m["ConfigRuleList"].type()) { vector<ListConfigRulesResponseBodyConfigRulesConfigRuleList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["ConfigRuleList"])){ if (typeid(map<string, boost::any>) == item1.type()) { ListConfigRulesResponseBodyConfigRulesConfigRuleList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } configRuleList = make_shared<vector<ListConfigRulesResponseBodyConfigRulesConfigRuleList>>(expect1); } } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } } virtual ~ListConfigRulesResponseBodyConfigRules() = default; }; class ListConfigRulesResponseBody : public Darabonba::Model { public: shared_ptr<ListConfigRulesResponseBodyConfigRules> configRules{}; shared_ptr<string> requestId{}; ListConfigRulesResponseBody() {} explicit ListConfigRulesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRules) { res["ConfigRules"] = configRules ? boost::any(configRules->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRules") != m.end() && !m["ConfigRules"].empty()) { if (typeid(map<string, boost::any>) == m["ConfigRules"].type()) { ListConfigRulesResponseBodyConfigRules model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ConfigRules"])); configRules = make_shared<ListConfigRulesResponseBodyConfigRules>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ListConfigRulesResponseBody() = default; }; class ListConfigRulesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ListConfigRulesResponseBody> body{}; ListConfigRulesResponse() {} explicit ListConfigRulesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ListConfigRulesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ListConfigRulesResponseBody>(model1); } } } virtual ~ListConfigRulesResponse() = default; }; class ListDiscoveredResourcesRequest : public Darabonba::Model { public: shared_ptr<string> complianceType{}; shared_ptr<long> memberId{}; shared_ptr<bool> multiAccount{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<string> regions{}; shared_ptr<long> resourceDeleted{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceTypes{}; ListDiscoveredResourcesRequest() {} explicit ListDiscoveredResourcesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (complianceType) { res["ComplianceType"] = boost::any(*complianceType); } if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (regions) { res["Regions"] = boost::any(*regions); } if (resourceDeleted) { res["ResourceDeleted"] = boost::any(*resourceDeleted); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceTypes) { res["ResourceTypes"] = boost::any(*resourceTypes); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ComplianceType") != m.end() && !m["ComplianceType"].empty()) { complianceType = make_shared<string>(boost::any_cast<string>(m["ComplianceType"])); } if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<long>(boost::any_cast<long>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("Regions") != m.end() && !m["Regions"].empty()) { regions = make_shared<string>(boost::any_cast<string>(m["Regions"])); } if (m.find("ResourceDeleted") != m.end() && !m["ResourceDeleted"].empty()) { resourceDeleted = make_shared<long>(boost::any_cast<long>(m["ResourceDeleted"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceTypes") != m.end() && !m["ResourceTypes"].empty()) { resourceTypes = make_shared<string>(boost::any_cast<string>(m["ResourceTypes"])); } } virtual ~ListDiscoveredResourcesRequest() = default; }; class ListDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList : public Darabonba::Model { public: shared_ptr<long> accountId{}; shared_ptr<string> region{}; shared_ptr<long> resourceCreationTime{}; shared_ptr<long> resourceDeleted{}; shared_ptr<string> resourceId{}; shared_ptr<string> resourceName{}; shared_ptr<string> resourceStatus{}; shared_ptr<string> resourceType{}; shared_ptr<string> tags{}; ListDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList() {} explicit ListDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accountId) { res["AccountId"] = boost::any(*accountId); } if (region) { res["Region"] = boost::any(*region); } if (resourceCreationTime) { res["ResourceCreationTime"] = boost::any(*resourceCreationTime); } if (resourceDeleted) { res["ResourceDeleted"] = boost::any(*resourceDeleted); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (resourceName) { res["ResourceName"] = boost::any(*resourceName); } if (resourceStatus) { res["ResourceStatus"] = boost::any(*resourceStatus); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (tags) { res["Tags"] = boost::any(*tags); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccountId") != m.end() && !m["AccountId"].empty()) { accountId = make_shared<long>(boost::any_cast<long>(m["AccountId"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("ResourceCreationTime") != m.end() && !m["ResourceCreationTime"].empty()) { resourceCreationTime = make_shared<long>(boost::any_cast<long>(m["ResourceCreationTime"])); } if (m.find("ResourceDeleted") != m.end() && !m["ResourceDeleted"].empty()) { resourceDeleted = make_shared<long>(boost::any_cast<long>(m["ResourceDeleted"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("ResourceName") != m.end() && !m["ResourceName"].empty()) { resourceName = make_shared<string>(boost::any_cast<string>(m["ResourceName"])); } if (m.find("ResourceStatus") != m.end() && !m["ResourceStatus"].empty()) { resourceStatus = make_shared<string>(boost::any_cast<string>(m["ResourceStatus"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("Tags") != m.end() && !m["Tags"].empty()) { tags = make_shared<string>(boost::any_cast<string>(m["Tags"])); } } virtual ~ListDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList() = default; }; class ListDiscoveredResourcesResponseBodyDiscoveredResourceProfiles : public Darabonba::Model { public: shared_ptr<vector<ListDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList>> discoveredResourceProfileList{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<long> totalCount{}; ListDiscoveredResourcesResponseBodyDiscoveredResourceProfiles() {} explicit ListDiscoveredResourcesResponseBodyDiscoveredResourceProfiles(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (discoveredResourceProfileList) { vector<boost::any> temp1; for(auto item1:*discoveredResourceProfileList){ temp1.push_back(boost::any(item1.toMap())); } res["DiscoveredResourceProfileList"] = boost::any(temp1); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DiscoveredResourceProfileList") != m.end() && !m["DiscoveredResourceProfileList"].empty()) { if (typeid(vector<boost::any>) == m["DiscoveredResourceProfileList"].type()) { vector<ListDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["DiscoveredResourceProfileList"])){ if (typeid(map<string, boost::any>) == item1.type()) { ListDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } discoveredResourceProfileList = make_shared<vector<ListDiscoveredResourcesResponseBodyDiscoveredResourceProfilesDiscoveredResourceProfileList>>(expect1); } } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } } virtual ~ListDiscoveredResourcesResponseBodyDiscoveredResourceProfiles() = default; }; class ListDiscoveredResourcesResponseBody : public Darabonba::Model { public: shared_ptr<ListDiscoveredResourcesResponseBodyDiscoveredResourceProfiles> discoveredResourceProfiles{}; shared_ptr<string> requestId{}; ListDiscoveredResourcesResponseBody() {} explicit ListDiscoveredResourcesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (discoveredResourceProfiles) { res["DiscoveredResourceProfiles"] = discoveredResourceProfiles ? boost::any(discoveredResourceProfiles->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DiscoveredResourceProfiles") != m.end() && !m["DiscoveredResourceProfiles"].empty()) { if (typeid(map<string, boost::any>) == m["DiscoveredResourceProfiles"].type()) { ListDiscoveredResourcesResponseBodyDiscoveredResourceProfiles model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["DiscoveredResourceProfiles"])); discoveredResourceProfiles = make_shared<ListDiscoveredResourcesResponseBodyDiscoveredResourceProfiles>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ListDiscoveredResourcesResponseBody() = default; }; class ListDiscoveredResourcesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ListDiscoveredResourcesResponseBody> body{}; ListDiscoveredResourcesResponse() {} explicit ListDiscoveredResourcesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ListDiscoveredResourcesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ListDiscoveredResourcesResponseBody>(model1); } } } virtual ~ListDiscoveredResourcesResponse() = default; }; class ListRemediationTemplatesRequest : public Darabonba::Model { public: shared_ptr<string> managedRuleIdentifier{}; shared_ptr<string> remediationType{}; ListRemediationTemplatesRequest() {} explicit ListRemediationTemplatesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (managedRuleIdentifier) { res["ManagedRuleIdentifier"] = boost::any(*managedRuleIdentifier); } if (remediationType) { res["RemediationType"] = boost::any(*remediationType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ManagedRuleIdentifier") != m.end() && !m["ManagedRuleIdentifier"].empty()) { managedRuleIdentifier = make_shared<string>(boost::any_cast<string>(m["ManagedRuleIdentifier"])); } if (m.find("RemediationType") != m.end() && !m["RemediationType"].empty()) { remediationType = make_shared<string>(boost::any_cast<string>(m["RemediationType"])); } } virtual ~ListRemediationTemplatesRequest() = default; }; class ListRemediationTemplatesResponseBodyRemediationTemplates : public Darabonba::Model { public: shared_ptr<string> remediationType{}; shared_ptr<string> templateDefinition{}; shared_ptr<string> templateIdentifier{}; shared_ptr<string> templateName{}; ListRemediationTemplatesResponseBodyRemediationTemplates() {} explicit ListRemediationTemplatesResponseBodyRemediationTemplates(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (remediationType) { res["RemediationType"] = boost::any(*remediationType); } if (templateDefinition) { res["TemplateDefinition"] = boost::any(*templateDefinition); } if (templateIdentifier) { res["TemplateIdentifier"] = boost::any(*templateIdentifier); } if (templateName) { res["TemplateName"] = boost::any(*templateName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RemediationType") != m.end() && !m["RemediationType"].empty()) { remediationType = make_shared<string>(boost::any_cast<string>(m["RemediationType"])); } if (m.find("TemplateDefinition") != m.end() && !m["TemplateDefinition"].empty()) { templateDefinition = make_shared<string>(boost::any_cast<string>(m["TemplateDefinition"])); } if (m.find("TemplateIdentifier") != m.end() && !m["TemplateIdentifier"].empty()) { templateIdentifier = make_shared<string>(boost::any_cast<string>(m["TemplateIdentifier"])); } if (m.find("TemplateName") != m.end() && !m["TemplateName"].empty()) { templateName = make_shared<string>(boost::any_cast<string>(m["TemplateName"])); } } virtual ~ListRemediationTemplatesResponseBodyRemediationTemplates() = default; }; class ListRemediationTemplatesResponseBody : public Darabonba::Model { public: shared_ptr<vector<ListRemediationTemplatesResponseBodyRemediationTemplates>> remediationTemplates{}; shared_ptr<string> requestId{}; ListRemediationTemplatesResponseBody() {} explicit ListRemediationTemplatesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (remediationTemplates) { vector<boost::any> temp1; for(auto item1:*remediationTemplates){ temp1.push_back(boost::any(item1.toMap())); } res["RemediationTemplates"] = boost::any(temp1); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RemediationTemplates") != m.end() && !m["RemediationTemplates"].empty()) { if (typeid(vector<boost::any>) == m["RemediationTemplates"].type()) { vector<ListRemediationTemplatesResponseBodyRemediationTemplates> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["RemediationTemplates"])){ if (typeid(map<string, boost::any>) == item1.type()) { ListRemediationTemplatesResponseBodyRemediationTemplates model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } remediationTemplates = make_shared<vector<ListRemediationTemplatesResponseBodyRemediationTemplates>>(expect1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ListRemediationTemplatesResponseBody() = default; }; class ListRemediationTemplatesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ListRemediationTemplatesResponseBody> body{}; ListRemediationTemplatesResponse() {} explicit ListRemediationTemplatesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ListRemediationTemplatesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ListRemediationTemplatesResponseBody>(model1); } } } virtual ~ListRemediationTemplatesResponse() = default; }; class PutConfigRuleRequest : public Darabonba::Model { public: shared_ptr<string> clientToken{}; shared_ptr<string> configRuleId{}; shared_ptr<string> configRuleName{}; shared_ptr<string> description{}; shared_ptr<string> inputParameters{}; shared_ptr<long> memberId{}; shared_ptr<bool> multiAccount{}; shared_ptr<long> riskLevel{}; shared_ptr<string> scopeComplianceResourceId{}; shared_ptr<string> scopeComplianceResourceTypes{}; shared_ptr<string> sourceDetailMessageType{}; shared_ptr<string> sourceIdentifier{}; shared_ptr<string> sourceMaximumExecutionFrequency{}; shared_ptr<string> sourceOwner{}; PutConfigRuleRequest() {} explicit PutConfigRuleRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (clientToken) { res["ClientToken"] = boost::any(*clientToken); } if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (configRuleName) { res["ConfigRuleName"] = boost::any(*configRuleName); } if (description) { res["Description"] = boost::any(*description); } if (inputParameters) { res["InputParameters"] = boost::any(*inputParameters); } if (memberId) { res["MemberId"] = boost::any(*memberId); } if (multiAccount) { res["MultiAccount"] = boost::any(*multiAccount); } if (riskLevel) { res["RiskLevel"] = boost::any(*riskLevel); } if (scopeComplianceResourceId) { res["ScopeComplianceResourceId"] = boost::any(*scopeComplianceResourceId); } if (scopeComplianceResourceTypes) { res["ScopeComplianceResourceTypes"] = boost::any(*scopeComplianceResourceTypes); } if (sourceDetailMessageType) { res["SourceDetailMessageType"] = boost::any(*sourceDetailMessageType); } if (sourceIdentifier) { res["SourceIdentifier"] = boost::any(*sourceIdentifier); } if (sourceMaximumExecutionFrequency) { res["SourceMaximumExecutionFrequency"] = boost::any(*sourceMaximumExecutionFrequency); } if (sourceOwner) { res["SourceOwner"] = boost::any(*sourceOwner); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ClientToken") != m.end() && !m["ClientToken"].empty()) { clientToken = make_shared<string>(boost::any_cast<string>(m["ClientToken"])); } if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("ConfigRuleName") != m.end() && !m["ConfigRuleName"].empty()) { configRuleName = make_shared<string>(boost::any_cast<string>(m["ConfigRuleName"])); } if (m.find("Description") != m.end() && !m["Description"].empty()) { description = make_shared<string>(boost::any_cast<string>(m["Description"])); } if (m.find("InputParameters") != m.end() && !m["InputParameters"].empty()) { inputParameters = make_shared<string>(boost::any_cast<string>(m["InputParameters"])); } if (m.find("MemberId") != m.end() && !m["MemberId"].empty()) { memberId = make_shared<long>(boost::any_cast<long>(m["MemberId"])); } if (m.find("MultiAccount") != m.end() && !m["MultiAccount"].empty()) { multiAccount = make_shared<bool>(boost::any_cast<bool>(m["MultiAccount"])); } if (m.find("RiskLevel") != m.end() && !m["RiskLevel"].empty()) { riskLevel = make_shared<long>(boost::any_cast<long>(m["RiskLevel"])); } if (m.find("ScopeComplianceResourceId") != m.end() && !m["ScopeComplianceResourceId"].empty()) { scopeComplianceResourceId = make_shared<string>(boost::any_cast<string>(m["ScopeComplianceResourceId"])); } if (m.find("ScopeComplianceResourceTypes") != m.end() && !m["ScopeComplianceResourceTypes"].empty()) { scopeComplianceResourceTypes = make_shared<string>(boost::any_cast<string>(m["ScopeComplianceResourceTypes"])); } if (m.find("SourceDetailMessageType") != m.end() && !m["SourceDetailMessageType"].empty()) { sourceDetailMessageType = make_shared<string>(boost::any_cast<string>(m["SourceDetailMessageType"])); } if (m.find("SourceIdentifier") != m.end() && !m["SourceIdentifier"].empty()) { sourceIdentifier = make_shared<string>(boost::any_cast<string>(m["SourceIdentifier"])); } if (m.find("SourceMaximumExecutionFrequency") != m.end() && !m["SourceMaximumExecutionFrequency"].empty()) { sourceMaximumExecutionFrequency = make_shared<string>(boost::any_cast<string>(m["SourceMaximumExecutionFrequency"])); } if (m.find("SourceOwner") != m.end() && !m["SourceOwner"].empty()) { sourceOwner = make_shared<string>(boost::any_cast<string>(m["SourceOwner"])); } } virtual ~PutConfigRuleRequest() = default; }; class PutConfigRuleResponseBody : public Darabonba::Model { public: shared_ptr<string> configRuleId{}; shared_ptr<string> requestId{}; PutConfigRuleResponseBody() {} explicit PutConfigRuleResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~PutConfigRuleResponseBody() = default; }; class PutConfigRuleResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<PutConfigRuleResponseBody> body{}; PutConfigRuleResponse() {} explicit PutConfigRuleResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { PutConfigRuleResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<PutConfigRuleResponseBody>(model1); } } } virtual ~PutConfigRuleResponse() = default; }; class PutConfigurationRecorderRequest : public Darabonba::Model { public: shared_ptr<string> resourceTypes{}; PutConfigurationRecorderRequest() {} explicit PutConfigurationRecorderRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (resourceTypes) { res["ResourceTypes"] = boost::any(*resourceTypes); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ResourceTypes") != m.end() && !m["ResourceTypes"].empty()) { resourceTypes = make_shared<string>(boost::any_cast<string>(m["ResourceTypes"])); } } virtual ~PutConfigurationRecorderRequest() = default; }; class PutConfigurationRecorderResponseBodyConfigurationRecorder : public Darabonba::Model { public: shared_ptr<long> accountId{}; shared_ptr<string> configurationRecorderStatus{}; shared_ptr<vector<string>> resourceTypes{}; PutConfigurationRecorderResponseBodyConfigurationRecorder() {} explicit PutConfigurationRecorderResponseBodyConfigurationRecorder(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accountId) { res["AccountId"] = boost::any(*accountId); } if (configurationRecorderStatus) { res["ConfigurationRecorderStatus"] = boost::any(*configurationRecorderStatus); } if (resourceTypes) { res["ResourceTypes"] = boost::any(*resourceTypes); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccountId") != m.end() && !m["AccountId"].empty()) { accountId = make_shared<long>(boost::any_cast<long>(m["AccountId"])); } if (m.find("ConfigurationRecorderStatus") != m.end() && !m["ConfigurationRecorderStatus"].empty()) { configurationRecorderStatus = make_shared<string>(boost::any_cast<string>(m["ConfigurationRecorderStatus"])); } if (m.find("ResourceTypes") != m.end() && !m["ResourceTypes"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["ResourceTypes"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["ResourceTypes"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } resourceTypes = make_shared<vector<string>>(toVec1); } } virtual ~PutConfigurationRecorderResponseBodyConfigurationRecorder() = default; }; class PutConfigurationRecorderResponseBody : public Darabonba::Model { public: shared_ptr<PutConfigurationRecorderResponseBodyConfigurationRecorder> configurationRecorder{}; shared_ptr<string> requestId{}; PutConfigurationRecorderResponseBody() {} explicit PutConfigurationRecorderResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configurationRecorder) { res["ConfigurationRecorder"] = configurationRecorder ? boost::any(configurationRecorder->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigurationRecorder") != m.end() && !m["ConfigurationRecorder"].empty()) { if (typeid(map<string, boost::any>) == m["ConfigurationRecorder"].type()) { PutConfigurationRecorderResponseBodyConfigurationRecorder model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ConfigurationRecorder"])); configurationRecorder = make_shared<PutConfigurationRecorderResponseBodyConfigurationRecorder>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~PutConfigurationRecorderResponseBody() = default; }; class PutConfigurationRecorderResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<PutConfigurationRecorderResponseBody> body{}; PutConfigurationRecorderResponse() {} explicit PutConfigurationRecorderResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { PutConfigurationRecorderResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<PutConfigurationRecorderResponseBody>(model1); } } } virtual ~PutConfigurationRecorderResponse() = default; }; class PutDeliveryChannelRequest : public Darabonba::Model { public: shared_ptr<string> clientToken{}; shared_ptr<string> deliveryChannelAssumeRoleArn{}; shared_ptr<string> deliveryChannelCondition{}; shared_ptr<string> deliveryChannelId{}; shared_ptr<string> deliveryChannelName{}; shared_ptr<string> deliveryChannelTargetArn{}; shared_ptr<string> deliveryChannelType{}; shared_ptr<string> description{}; shared_ptr<long> status{}; PutDeliveryChannelRequest() {} explicit PutDeliveryChannelRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (clientToken) { res["ClientToken"] = boost::any(*clientToken); } if (deliveryChannelAssumeRoleArn) { res["DeliveryChannelAssumeRoleArn"] = boost::any(*deliveryChannelAssumeRoleArn); } if (deliveryChannelCondition) { res["DeliveryChannelCondition"] = boost::any(*deliveryChannelCondition); } if (deliveryChannelId) { res["DeliveryChannelId"] = boost::any(*deliveryChannelId); } if (deliveryChannelName) { res["DeliveryChannelName"] = boost::any(*deliveryChannelName); } if (deliveryChannelTargetArn) { res["DeliveryChannelTargetArn"] = boost::any(*deliveryChannelTargetArn); } if (deliveryChannelType) { res["DeliveryChannelType"] = boost::any(*deliveryChannelType); } if (description) { res["Description"] = boost::any(*description); } if (status) { res["Status"] = boost::any(*status); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ClientToken") != m.end() && !m["ClientToken"].empty()) { clientToken = make_shared<string>(boost::any_cast<string>(m["ClientToken"])); } if (m.find("DeliveryChannelAssumeRoleArn") != m.end() && !m["DeliveryChannelAssumeRoleArn"].empty()) { deliveryChannelAssumeRoleArn = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelAssumeRoleArn"])); } if (m.find("DeliveryChannelCondition") != m.end() && !m["DeliveryChannelCondition"].empty()) { deliveryChannelCondition = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelCondition"])); } if (m.find("DeliveryChannelId") != m.end() && !m["DeliveryChannelId"].empty()) { deliveryChannelId = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelId"])); } if (m.find("DeliveryChannelName") != m.end() && !m["DeliveryChannelName"].empty()) { deliveryChannelName = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelName"])); } if (m.find("DeliveryChannelTargetArn") != m.end() && !m["DeliveryChannelTargetArn"].empty()) { deliveryChannelTargetArn = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelTargetArn"])); } if (m.find("DeliveryChannelType") != m.end() && !m["DeliveryChannelType"].empty()) { deliveryChannelType = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelType"])); } if (m.find("Description") != m.end() && !m["Description"].empty()) { description = make_shared<string>(boost::any_cast<string>(m["Description"])); } if (m.find("Status") != m.end() && !m["Status"].empty()) { status = make_shared<long>(boost::any_cast<long>(m["Status"])); } } virtual ~PutDeliveryChannelRequest() = default; }; class PutDeliveryChannelResponseBody : public Darabonba::Model { public: shared_ptr<string> deliveryChannelId{}; shared_ptr<string> requestId{}; PutDeliveryChannelResponseBody() {} explicit PutDeliveryChannelResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (deliveryChannelId) { res["DeliveryChannelId"] = boost::any(*deliveryChannelId); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DeliveryChannelId") != m.end() && !m["DeliveryChannelId"].empty()) { deliveryChannelId = make_shared<string>(boost::any_cast<string>(m["DeliveryChannelId"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~PutDeliveryChannelResponseBody() = default; }; class PutDeliveryChannelResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<PutDeliveryChannelResponseBody> body{}; PutDeliveryChannelResponse() {} explicit PutDeliveryChannelResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { PutDeliveryChannelResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<PutDeliveryChannelResponseBody>(model1); } } } virtual ~PutDeliveryChannelResponse() = default; }; class PutEvaluationsRequest : public Darabonba::Model { public: shared_ptr<string> evaluations{}; shared_ptr<string> resultToken{}; PutEvaluationsRequest() {} explicit PutEvaluationsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (evaluations) { res["Evaluations"] = boost::any(*evaluations); } if (resultToken) { res["ResultToken"] = boost::any(*resultToken); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Evaluations") != m.end() && !m["Evaluations"].empty()) { evaluations = make_shared<string>(boost::any_cast<string>(m["Evaluations"])); } if (m.find("ResultToken") != m.end() && !m["ResultToken"].empty()) { resultToken = make_shared<string>(boost::any_cast<string>(m["ResultToken"])); } } virtual ~PutEvaluationsRequest() = default; }; class PutEvaluationsResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<bool> result{}; PutEvaluationsResponseBody() {} explicit PutEvaluationsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (result) { res["Result"] = boost::any(*result); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Result") != m.end() && !m["Result"].empty()) { result = make_shared<bool>(boost::any_cast<bool>(m["Result"])); } } virtual ~PutEvaluationsResponseBody() = default; }; class PutEvaluationsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<PutEvaluationsResponseBody> body{}; PutEvaluationsResponse() {} explicit PutEvaluationsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { PutEvaluationsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<PutEvaluationsResponseBody>(model1); } } } virtual ~PutEvaluationsResponse() = default; }; class StartConfigRuleEvaluationRequest : public Darabonba::Model { public: shared_ptr<string> compliancePackId{}; shared_ptr<string> configRuleId{}; shared_ptr<bool> revertEvaluation{}; StartConfigRuleEvaluationRequest() {} explicit StartConfigRuleEvaluationRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (compliancePackId) { res["CompliancePackId"] = boost::any(*compliancePackId); } if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (revertEvaluation) { res["RevertEvaluation"] = boost::any(*revertEvaluation); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("CompliancePackId") != m.end() && !m["CompliancePackId"].empty()) { compliancePackId = make_shared<string>(boost::any_cast<string>(m["CompliancePackId"])); } if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("RevertEvaluation") != m.end() && !m["RevertEvaluation"].empty()) { revertEvaluation = make_shared<bool>(boost::any_cast<bool>(m["RevertEvaluation"])); } } virtual ~StartConfigRuleEvaluationRequest() = default; }; class StartConfigRuleEvaluationResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<bool> result{}; StartConfigRuleEvaluationResponseBody() {} explicit StartConfigRuleEvaluationResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (result) { res["Result"] = boost::any(*result); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Result") != m.end() && !m["Result"].empty()) { result = make_shared<bool>(boost::any_cast<bool>(m["Result"])); } } virtual ~StartConfigRuleEvaluationResponseBody() = default; }; class StartConfigRuleEvaluationResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<StartConfigRuleEvaluationResponseBody> body{}; StartConfigRuleEvaluationResponse() {} explicit StartConfigRuleEvaluationResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { StartConfigRuleEvaluationResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<StartConfigRuleEvaluationResponseBody>(model1); } } } virtual ~StartConfigRuleEvaluationResponse() = default; }; class StartConfigurationRecorderRequest : public Darabonba::Model { public: shared_ptr<bool> enterpriseEdition{}; StartConfigurationRecorderRequest() {} explicit StartConfigurationRecorderRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (enterpriseEdition) { res["EnterpriseEdition"] = boost::any(*enterpriseEdition); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EnterpriseEdition") != m.end() && !m["EnterpriseEdition"].empty()) { enterpriseEdition = make_shared<bool>(boost::any_cast<bool>(m["EnterpriseEdition"])); } } virtual ~StartConfigurationRecorderRequest() = default; }; class StartConfigurationRecorderResponseBodyConfigurationRecorder : public Darabonba::Model { public: shared_ptr<long> accountId{}; shared_ptr<string> configurationRecorderStatus{}; shared_ptr<string> organizationEnableStatus{}; shared_ptr<long> organizationMasterId{}; shared_ptr<vector<string>> resourceTypes{}; StartConfigurationRecorderResponseBodyConfigurationRecorder() {} explicit StartConfigurationRecorderResponseBodyConfigurationRecorder(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accountId) { res["AccountId"] = boost::any(*accountId); } if (configurationRecorderStatus) { res["ConfigurationRecorderStatus"] = boost::any(*configurationRecorderStatus); } if (organizationEnableStatus) { res["OrganizationEnableStatus"] = boost::any(*organizationEnableStatus); } if (organizationMasterId) { res["OrganizationMasterId"] = boost::any(*organizationMasterId); } if (resourceTypes) { res["ResourceTypes"] = boost::any(*resourceTypes); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccountId") != m.end() && !m["AccountId"].empty()) { accountId = make_shared<long>(boost::any_cast<long>(m["AccountId"])); } if (m.find("ConfigurationRecorderStatus") != m.end() && !m["ConfigurationRecorderStatus"].empty()) { configurationRecorderStatus = make_shared<string>(boost::any_cast<string>(m["ConfigurationRecorderStatus"])); } if (m.find("OrganizationEnableStatus") != m.end() && !m["OrganizationEnableStatus"].empty()) { organizationEnableStatus = make_shared<string>(boost::any_cast<string>(m["OrganizationEnableStatus"])); } if (m.find("OrganizationMasterId") != m.end() && !m["OrganizationMasterId"].empty()) { organizationMasterId = make_shared<long>(boost::any_cast<long>(m["OrganizationMasterId"])); } if (m.find("ResourceTypes") != m.end() && !m["ResourceTypes"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["ResourceTypes"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["ResourceTypes"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } resourceTypes = make_shared<vector<string>>(toVec1); } } virtual ~StartConfigurationRecorderResponseBodyConfigurationRecorder() = default; }; class StartConfigurationRecorderResponseBody : public Darabonba::Model { public: shared_ptr<StartConfigurationRecorderResponseBodyConfigurationRecorder> configurationRecorder{}; shared_ptr<string> requestId{}; StartConfigurationRecorderResponseBody() {} explicit StartConfigurationRecorderResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configurationRecorder) { res["ConfigurationRecorder"] = configurationRecorder ? boost::any(configurationRecorder->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigurationRecorder") != m.end() && !m["ConfigurationRecorder"].empty()) { if (typeid(map<string, boost::any>) == m["ConfigurationRecorder"].type()) { StartConfigurationRecorderResponseBodyConfigurationRecorder model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["ConfigurationRecorder"])); configurationRecorder = make_shared<StartConfigurationRecorderResponseBodyConfigurationRecorder>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~StartConfigurationRecorderResponseBody() = default; }; class StartConfigurationRecorderResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<StartConfigurationRecorderResponseBody> body{}; StartConfigurationRecorderResponse() {} explicit StartConfigurationRecorderResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { StartConfigurationRecorderResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<StartConfigurationRecorderResponseBody>(model1); } } } virtual ~StartConfigurationRecorderResponse() = default; }; class StopConfigRulesRequest : public Darabonba::Model { public: shared_ptr<string> configRuleIds{}; StopConfigRulesRequest() {} explicit StopConfigRulesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRuleIds) { res["ConfigRuleIds"] = boost::any(*configRuleIds); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRuleIds") != m.end() && !m["ConfigRuleIds"].empty()) { configRuleIds = make_shared<string>(boost::any_cast<string>(m["ConfigRuleIds"])); } } virtual ~StopConfigRulesRequest() = default; }; class StopConfigRulesResponseBodyOperateRuleResultOperateRuleItemList : public Darabonba::Model { public: shared_ptr<string> configRuleId{}; shared_ptr<string> errorCode{}; shared_ptr<bool> success{}; StopConfigRulesResponseBodyOperateRuleResultOperateRuleItemList() {} explicit StopConfigRulesResponseBodyOperateRuleResultOperateRuleItemList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (configRuleId) { res["ConfigRuleId"] = boost::any(*configRuleId); } if (errorCode) { res["ErrorCode"] = boost::any(*errorCode); } if (success) { res["Success"] = boost::any(*success); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ConfigRuleId") != m.end() && !m["ConfigRuleId"].empty()) { configRuleId = make_shared<string>(boost::any_cast<string>(m["ConfigRuleId"])); } if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) { errorCode = make_shared<string>(boost::any_cast<string>(m["ErrorCode"])); } if (m.find("Success") != m.end() && !m["Success"].empty()) { success = make_shared<bool>(boost::any_cast<bool>(m["Success"])); } } virtual ~StopConfigRulesResponseBodyOperateRuleResultOperateRuleItemList() = default; }; class StopConfigRulesResponseBodyOperateRuleResult : public Darabonba::Model { public: shared_ptr<vector<StopConfigRulesResponseBodyOperateRuleResultOperateRuleItemList>> operateRuleItemList{}; StopConfigRulesResponseBodyOperateRuleResult() {} explicit StopConfigRulesResponseBodyOperateRuleResult(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (operateRuleItemList) { vector<boost::any> temp1; for(auto item1:*operateRuleItemList){ temp1.push_back(boost::any(item1.toMap())); } res["OperateRuleItemList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OperateRuleItemList") != m.end() && !m["OperateRuleItemList"].empty()) { if (typeid(vector<boost::any>) == m["OperateRuleItemList"].type()) { vector<StopConfigRulesResponseBodyOperateRuleResultOperateRuleItemList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["OperateRuleItemList"])){ if (typeid(map<string, boost::any>) == item1.type()) { StopConfigRulesResponseBodyOperateRuleResultOperateRuleItemList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } operateRuleItemList = make_shared<vector<StopConfigRulesResponseBodyOperateRuleResultOperateRuleItemList>>(expect1); } } } virtual ~StopConfigRulesResponseBodyOperateRuleResult() = default; }; class StopConfigRulesResponseBody : public Darabonba::Model { public: shared_ptr<StopConfigRulesResponseBodyOperateRuleResult> operateRuleResult{}; shared_ptr<string> requestId{}; StopConfigRulesResponseBody() {} explicit StopConfigRulesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (operateRuleResult) { res["OperateRuleResult"] = operateRuleResult ? boost::any(operateRuleResult->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OperateRuleResult") != m.end() && !m["OperateRuleResult"].empty()) { if (typeid(map<string, boost::any>) == m["OperateRuleResult"].type()) { StopConfigRulesResponseBodyOperateRuleResult model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["OperateRuleResult"])); operateRuleResult = make_shared<StopConfigRulesResponseBodyOperateRuleResult>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~StopConfigRulesResponseBody() = default; }; class StopConfigRulesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<StopConfigRulesResponseBody> body{}; StopConfigRulesResponse() {} explicit StopConfigRulesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { StopConfigRulesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<StopConfigRulesResponseBody>(model1); } } } virtual ~StopConfigRulesResponse() = default; }; class Client : Alibabacloud_OpenApi::Client { public: explicit Client(const shared_ptr<Alibabacloud_OpenApi::Config>& config); string getEndpoint(shared_ptr<string> productId, shared_ptr<string> regionId, shared_ptr<string> endpointRule, shared_ptr<string> network, shared_ptr<string> suffix, shared_ptr<map<string, string>> endpointMap, shared_ptr<string> endpoint); ActiveConfigRulesResponse activeConfigRulesWithOptions(shared_ptr<ActiveConfigRulesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ActiveConfigRulesResponse activeConfigRules(shared_ptr<ActiveConfigRulesRequest> request); DeleteConfigRulesResponse deleteConfigRulesWithOptions(shared_ptr<DeleteConfigRulesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DeleteConfigRulesResponse deleteConfigRules(shared_ptr<DeleteConfigRulesRequest> request); DescribeComplianceResponse describeComplianceWithOptions(shared_ptr<DescribeComplianceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeComplianceResponse describeCompliance(shared_ptr<DescribeComplianceRequest> request); DescribeComplianceSummaryResponse describeComplianceSummaryWithOptions(shared_ptr<DescribeComplianceSummaryRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeComplianceSummaryResponse describeComplianceSummary(shared_ptr<DescribeComplianceSummaryRequest> request); DescribeConfigRuleResponse describeConfigRuleWithOptions(shared_ptr<DescribeConfigRuleRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeConfigRuleResponse describeConfigRule(shared_ptr<DescribeConfigRuleRequest> request); DescribeConfigurationRecorderResponse describeConfigurationRecorderWithOptions(shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeConfigurationRecorderResponse describeConfigurationRecorder(); DescribeDeliveryChannelsResponse describeDeliveryChannelsWithOptions(shared_ptr<DescribeDeliveryChannelsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDeliveryChannelsResponse describeDeliveryChannels(shared_ptr<DescribeDeliveryChannelsRequest> request); DescribeDiscoveredResourceResponse describeDiscoveredResourceWithOptions(shared_ptr<DescribeDiscoveredResourceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDiscoveredResourceResponse describeDiscoveredResource(shared_ptr<DescribeDiscoveredResourceRequest> request); DescribeEvaluationResultsResponse describeEvaluationResultsWithOptions(shared_ptr<DescribeEvaluationResultsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeEvaluationResultsResponse describeEvaluationResults(shared_ptr<DescribeEvaluationResultsRequest> request); GetAggregateDiscoveredResourceResponse getAggregateDiscoveredResourceWithOptions(shared_ptr<GetAggregateDiscoveredResourceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); GetAggregateDiscoveredResourceResponse getAggregateDiscoveredResource(shared_ptr<GetAggregateDiscoveredResourceRequest> request); GetDiscoveredResourceCountsResponse getDiscoveredResourceCountsWithOptions(shared_ptr<GetDiscoveredResourceCountsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); GetDiscoveredResourceCountsResponse getDiscoveredResourceCounts(shared_ptr<GetDiscoveredResourceCountsRequest> request); GetDiscoveredResourceSummaryResponse getDiscoveredResourceSummaryWithOptions(shared_ptr<GetDiscoveredResourceSummaryRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); GetDiscoveredResourceSummaryResponse getDiscoveredResourceSummary(shared_ptr<GetDiscoveredResourceSummaryRequest> request); GetResourceComplianceTimelineResponse getResourceComplianceTimelineWithOptions(shared_ptr<GetResourceComplianceTimelineRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); GetResourceComplianceTimelineResponse getResourceComplianceTimeline(shared_ptr<GetResourceComplianceTimelineRequest> request); GetResourceConfigurationTimelineResponse getResourceConfigurationTimelineWithOptions(shared_ptr<GetResourceConfigurationTimelineRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); GetResourceConfigurationTimelineResponse getResourceConfigurationTimeline(shared_ptr<GetResourceConfigurationTimelineRequest> request); GetSupportedResourceTypesResponse getSupportedResourceTypesWithOptions(shared_ptr<Darabonba_Util::RuntimeOptions> runtime); GetSupportedResourceTypesResponse getSupportedResourceTypes(); ListAggregateDiscoveredResourcesResponse listAggregateDiscoveredResourcesWithOptions(shared_ptr<ListAggregateDiscoveredResourcesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ListAggregateDiscoveredResourcesResponse listAggregateDiscoveredResources(shared_ptr<ListAggregateDiscoveredResourcesRequest> request); ListConfigRulesResponse listConfigRulesWithOptions(shared_ptr<ListConfigRulesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ListConfigRulesResponse listConfigRules(shared_ptr<ListConfigRulesRequest> request); ListDiscoveredResourcesResponse listDiscoveredResourcesWithOptions(shared_ptr<ListDiscoveredResourcesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ListDiscoveredResourcesResponse listDiscoveredResources(shared_ptr<ListDiscoveredResourcesRequest> request); ListRemediationTemplatesResponse listRemediationTemplatesWithOptions(shared_ptr<ListRemediationTemplatesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ListRemediationTemplatesResponse listRemediationTemplates(shared_ptr<ListRemediationTemplatesRequest> request); PutConfigRuleResponse putConfigRuleWithOptions(shared_ptr<PutConfigRuleRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); PutConfigRuleResponse putConfigRule(shared_ptr<PutConfigRuleRequest> request); PutConfigurationRecorderResponse putConfigurationRecorderWithOptions(shared_ptr<PutConfigurationRecorderRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); PutConfigurationRecorderResponse putConfigurationRecorder(shared_ptr<PutConfigurationRecorderRequest> request); PutDeliveryChannelResponse putDeliveryChannelWithOptions(shared_ptr<PutDeliveryChannelRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); PutDeliveryChannelResponse putDeliveryChannel(shared_ptr<PutDeliveryChannelRequest> request); PutEvaluationsResponse putEvaluationsWithOptions(shared_ptr<PutEvaluationsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); PutEvaluationsResponse putEvaluations(shared_ptr<PutEvaluationsRequest> request); StartConfigRuleEvaluationResponse startConfigRuleEvaluationWithOptions(shared_ptr<StartConfigRuleEvaluationRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); StartConfigRuleEvaluationResponse startConfigRuleEvaluation(shared_ptr<StartConfigRuleEvaluationRequest> request); StartConfigurationRecorderResponse startConfigurationRecorderWithOptions(shared_ptr<StartConfigurationRecorderRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); StartConfigurationRecorderResponse startConfigurationRecorder(shared_ptr<StartConfigurationRecorderRequest> request); StopConfigRulesResponse stopConfigRulesWithOptions(shared_ptr<StopConfigRulesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); StopConfigRulesResponse stopConfigRules(shared_ptr<StopConfigRulesRequest> request); virtual ~Client() = default; }; } // namespace Alibabacloud_Config20190108 #endif
wenfeifei/miniblink49
third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp
<reponame>wenfeifei/miniblink49<filename>third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp<gh_stars>1000+ /* * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2008 <NAME> <<EMAIL>> * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/inspector/InjectedScriptManager.h" #include "bindings/core/v8/ScriptValue.h" #include "core/inspector/InjectedScript.h" #include "core/inspector/InjectedScriptHost.h" #include "core/inspector/InjectedScriptNative.h" #include "core/inspector/JSONParser.h" #include "platform/JSONValues.h" #include "public/platform/Platform.h" #include "public/platform/WebData.h" #include "wtf/PassOwnPtr.h" namespace blink { PassOwnPtrWillBeRawPtr<InjectedScriptManager> InjectedScriptManager::createForPage() { return adoptPtrWillBeNoop(new InjectedScriptManager(&InjectedScriptManager::canAccessInspectedWindow)); } PassOwnPtrWillBeRawPtr<InjectedScriptManager> InjectedScriptManager::createForWorker() { return adoptPtrWillBeNoop(new InjectedScriptManager(&InjectedScriptManager::canAccessInspectedWorkerGlobalScope)); } InjectedScriptManager::InjectedScriptManager(InspectedStateAccessCheck accessCheck) : m_nextInjectedScriptId(1) , m_injectedScriptHost(InjectedScriptHost::create()) , m_inspectedStateAccessCheck(accessCheck) , m_customObjectFormatterEnabled(false) { } InjectedScriptManager::~InjectedScriptManager() { } DEFINE_TRACE(InjectedScriptManager) { visitor->trace(m_injectedScriptHost); } void InjectedScriptManager::disconnect() { m_injectedScriptHost->disconnect(); m_injectedScriptHost.clear(); } InjectedScriptHost* InjectedScriptManager::injectedScriptHost() { return m_injectedScriptHost.get(); } InjectedScript InjectedScriptManager::injectedScriptForId(int id) { IdToInjectedScriptMap::iterator it = m_idToInjectedScript.find(id); if (it != m_idToInjectedScript.end()) return it->value; for (auto& state : m_scriptStateToId) { if (state.value == id) return injectedScriptFor(state.key.get()); } return InjectedScript(); } int InjectedScriptManager::injectedScriptIdFor(ScriptState* scriptState) { ScriptStateToId::iterator it = m_scriptStateToId.find(scriptState); if (it != m_scriptStateToId.end()) return it->value; int id = m_nextInjectedScriptId++; m_scriptStateToId.set(scriptState, id); return id; } InjectedScript InjectedScriptManager::injectedScriptForObjectId(const String& objectId) { RefPtr<JSONValue> parsedObjectId = parseJSON(objectId); if (parsedObjectId && parsedObjectId->type() == JSONValue::TypeObject) { long injectedScriptId = 0; bool success = parsedObjectId->asObject()->getNumber("injectedScriptId", &injectedScriptId); if (success) return m_idToInjectedScript.get(injectedScriptId); } return InjectedScript(); } void InjectedScriptManager::discardInjectedScripts() { m_idToInjectedScript.clear(); m_scriptStateToId.clear(); } void InjectedScriptManager::discardInjectedScriptFor(ScriptState* scriptState) { ScriptStateToId::iterator it = m_scriptStateToId.find(scriptState); if (it == m_scriptStateToId.end()) return; m_idToInjectedScript.remove(it->value); m_scriptStateToId.remove(it); } bool InjectedScriptManager::canAccessInspectedWorkerGlobalScope(ScriptState*) { return true; } void InjectedScriptManager::releaseObjectGroup(const String& objectGroup) { Vector<int> keys; keys.appendRange(m_idToInjectedScript.keys().begin(), m_idToInjectedScript.keys().end()); for (auto& key : keys) { IdToInjectedScriptMap::iterator s = m_idToInjectedScript.find(key); if (s != m_idToInjectedScript.end()) s->value.releaseObjectGroup(objectGroup); // m_idToInjectedScript may change here. } } void InjectedScriptManager::setCustomObjectFormatterEnabled(bool enabled) { m_customObjectFormatterEnabled = enabled; IdToInjectedScriptMap::iterator end = m_idToInjectedScript.end(); for (IdToInjectedScriptMap::iterator it = m_idToInjectedScript.begin(); it != end; ++it) { if (!it->value.isEmpty()) it->value.setCustomObjectFormatterEnabled(enabled); } } String InjectedScriptManager::injectedScriptSource() { const WebData& injectedScriptSourceResource = Platform::current()->loadResource("InjectedScriptSource.js"); return String(injectedScriptSourceResource.data(), injectedScriptSourceResource.size()); } InjectedScript InjectedScriptManager::injectedScriptFor(ScriptState* inspectedScriptState) { ScriptStateToId::iterator it = m_scriptStateToId.find(inspectedScriptState); if (it != m_scriptStateToId.end()) { IdToInjectedScriptMap::iterator it1 = m_idToInjectedScript.find(it->value); if (it1 != m_idToInjectedScript.end()) return it1->value; } if (!m_inspectedStateAccessCheck(inspectedScriptState)) return InjectedScript(); int id = injectedScriptIdFor(inspectedScriptState); RefPtr<InjectedScriptNative> injectedScriptNative = adoptRef(new InjectedScriptNative(inspectedScriptState->isolate())); ScriptValue injectedScriptValue = createInjectedScript(injectedScriptSource(), inspectedScriptState, id, injectedScriptNative.get()); InjectedScript result(injectedScriptValue, m_inspectedStateAccessCheck, injectedScriptNative.release()); if (m_customObjectFormatterEnabled) result.setCustomObjectFormatterEnabled(m_customObjectFormatterEnabled); m_idToInjectedScript.set(id, result); return result; } } // namespace blink
neoguru/axboot-origin
ax-boot-core/src/main/java/com/chequer/axboot/core/converter/BaseConverter.java
<reponame>neoguru/axboot-origin package com.chequer.axboot.core.converter; import com.chequer.axboot.core.utils.ModelMapperUtils; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; @Component public class BaseConverter { public <T> List<T> convert(List<?> sourceList, Class<T> destinationClass) { return sourceList.stream().map(source -> convert(source, destinationClass)).collect(Collectors.toList()); } public <T> T convert(Object source, Class<T> destinationClass) { T map = ModelMapperUtils.map(source, destinationClass); return map; } }
xmar/pythran
pythran/pythonic/include/__builtin__/set/remove.hpp
#ifndef PYTHONIC_INCLUDE_BUILTIN_SET_REMOVE_HPP #define PYTHONIC_INCLUDE_BUILTIN_SET_REMOVE_HPP #include "pythonic/include/__dispatch__/remove.hpp" #include "pythonic/include/utils/functor.hpp" namespace pythonic { namespace __builtin__ { namespace set { USING_FUNCTOR(remove, pythonic::__dispatch__::functor::remove); } } } #endif
electriccitizen/mlsa-calculator
src/components/MultiStepsLayout.js
<filename>src/components/MultiStepsLayout.js import React from "react" import { Link } from "gatsby" import PropTypes from "prop-types" import { useForm } from "@formiz/core" import { PageLayout } from "../layout/PageLayout" import { Box, Grid, Button, Stack } from "@chakra-ui/react" import { CustomDrawer } from "./Utils/CustomDrawer" import { navigate } from "gatsby" import { Element, scroller } from 'react-scroll'; const propTypes = { // eslint-disable-next-line react/forbid-prop-types form: PropTypes.object, children: PropTypes.node, submitLabel: PropTypes.node, } const defaultProps = { form: null, children: "", submitLabel: "", } export const MultiStepsLayout = ({ children, submitLabel = "Submit", app, buttonTitle, ...props }) => { // const fieldRef = React.useRef<HTMLInputElement>(null); const form = useForm({ subscribe: { form: true, fields: ["TermsOfUse"] } }) const hasSteps = !!form.steps.length const handleExit = (dest) => { navigate(dest) } // Similar to componentDidMount and componentDidUpdate: // useEffect(() => { // // // Update the document title using the browser API // scroller.scrollTo('step-top-scroll', { // duration: 500, // delay: 50, // smooth: true, // // containerId: 'ContainerElementID', // offset: -100, // Scrolls to element + 50 pixels down the page // }) // }); const submitStep = async (e) => { e.preventDefault() // fieldRef.current.scrollIntoView(); // Trigger the Formiz submitStep form.submitStep() // Update the document title using the browser API scroller.scrollTo('step-top-scroll', { duration: 500, delay: 50, smooth: true, // containerId: 'ContainerElementID', offset: -100, // Scrolls to element + 50 pixels down the page }) } return ( <PageLayout {...props}> <Element name='step-top-scroll'/> <form noValidate onSubmit={hasSteps ? submitStep : form.submit}> <Stack w="100%" direction={["column", "row"]}> <Box width="100%" align="right" flex={1}> <CustomDrawer app={app} buttonTitle={buttonTitle} /> </Box> {/*<div ref={fieldRef}>scroll target</div>*/} </Stack> {children} {hasSteps && ( <Grid mt={8} templateColumns="1fr 2fr 1fr" alignItems="center"> {!form.isFirstStep && ( <Button gridColumn="1" onClick={form.prevStep}> Previous </Button> )} <Box gridColumn="2" textAlign="center" fontSize="sm" color="gray.500" > Step {form.currentStep.index + 1} / {form.steps.length} </Box> {!form.isLastStep && <Button type="submit" gridColumn="3" colorScheme="brand" isDisabled={ app === "support" && form.values && form.values.TermsOfUse !== "yes" ? true : (form.isLastStep ? !form.isValid : !form.isStepValid) && form.isStepSubmitted } > {form.isLastStep ? submitLabel : "Next"} </Button> } {form.isLastStep && app === "support" && ( <Box gridColumn="3" textAlign="right" fontSize="sm" color="gray.500" mt={2} > <Button colorScheme={"red"} onClick={() => handleExit("/")}>Exit interview</Button> </Box> )} {form.isLastStep && app === "supportIntro" && ( <Box gridColumn="3" textAlign="right" fontSize="sm" color="gray.500" mt={2} > <Button colorScheme={"brand"} onClick={() => handleExit("/child-support/calculator")}>Start interview</Button> </Box> )} {form.isLastStep && app === "restitutionIntro" && ( <Box gridColumn="3" textAlign="right" fontSize="sm" color="gray.500" mt={2} > <Button colorScheme={"brand"} onClick={() => handleExit("/restitution/worksheet")}>Start interview</Button> </Box> )} </Grid> )} {app === "supportIntro" && ( <Box mt="8" fontSize={"md"} align={"center"}> If you have used this tool before, you can{" "} <Link to={"/child-support/calculator"}>skip to the start</Link>. </Box> )} {app === "restitutionIntro" && ( <Box mt="8" fontSize={"md"} align={"center"}> If you have used this tool before, you can{" "} <Link to={"/restitution/worksheet"}>skip to the start</Link>. </Box> )} </form> </PageLayout> ) } MultiStepsLayout.propTypes = propTypes MultiStepsLayout.defaultProps = defaultProps
lee-dohm/hero-database
src/hero/characteristics-block.js
import HeroMath from './math' import Model from './model' /** * A block that represents information on the characteristics of the character. * * The characteristics are each available as a property. The list of characteristics is available in * `data/characteristics.json`. * * @hero 6E1 40 Characteristics */ export default class CharacteristicsBlock extends Model { /** * Deserializes the info block. * * @param {Object} state Serialized information * @param {HeroEnvironment} heroEnv Application environment * @return {CharacteristicsBlock} Deserialized info block */ static deserialize (state, heroEnv) { return new CharacteristicsBlock(state, heroEnv) } /** * Constructs a default set of characteristics. * * @param {Object} [state] Initial values * @param {HeroEnvironment} [heroEnv] Application environment */ constructor (state = {}, heroEnv = hero) { super(heroEnv) Object.assign(this, this.getDefaultBaseCharacteristics(), state, {heroEnv}) } /** * Serializes the info block for storage on disk. * * @return {Object} Serialized information */ serialize () { return Object.assign({}, this, {heroEnv: undefined}) } /** * Gets the cost of an individual characteristic. * * @param {String} char Name of the characteristic * @return {Number} Cost of the characteristic at its current value * @see {@link HeroMath.characteristicCost} */ getCost (char) { const info = this.heroEnv.getData('characteristics') return HeroMath.characteristicCost(this[char], info[char]) } /** * Calculates the total cost of the characteristics. * * @return {Number} Total cost of characteristics in Character Points. */ getTotalCost () { const info = this.heroEnv.getData('characteristics') let total = 0 for (let char in info) { total += this.getCost(char) } return total } getDefaultBaseCharacteristics () { const defaults = this.heroEnv.getData('characteristics') let defaultBases = {} for (let prop in defaults) { defaultBases[prop] = defaults[prop].base } return defaultBases } }