max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
312
<filename>mpp/hal/vpu/jpege/hal_jpege_vepu1_v2.c<gh_stars>100-1000 /* * Copyright 2015 Rockchip Electronics Co. LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define MODULE_TAG "hal_jpege_vepu1" #include <string.h> #include "mpp_env.h" #include "mpp_common.h" #include "mpp_mem.h" #include "mpp_platform.h" #include "mpp_enc_hal.h" #include "vcodec_service.h" #include "hal_jpege_debug.h" #include "hal_jpege_api_v2.h" #include "hal_jpege_base.h" #define VEPU_JPEGE_VEPU1_NUM_REGS 164 typedef struct jpege_vepu1_reg_set_t { RK_U32 val[VEPU_JPEGE_VEPU1_NUM_REGS]; } jpege_vepu1_reg_set; static MPP_RET hal_jpege_vepu1_init(void *hal, MppEncHalCfg *cfg) { MPP_RET ret = MPP_OK; HalJpegeCtx *ctx = (HalJpegeCtx *)hal; mpp_env_get_u32("hal_jpege_debug", &hal_jpege_debug, 0); hal_jpege_dbg_func("enter hal %p cfg %p\n", hal, cfg); /* update output to MppEnc */ cfg->type = VPU_CLIENT_VEPU1; ret = mpp_dev_init(&cfg->dev, cfg->type); if (ret) { mpp_err_f("mpp_dev_init failed. ret: %d\n", ret); return ret; } ctx->dev = cfg->dev; jpege_bits_init(&ctx->bits); mpp_assert(ctx->bits); ret = hal_jpege_vepu_init_rc(&ctx->hal_rc); if (ret) return ret; ctx->cfg = cfg->cfg; ctx->reg_size = sizeof(RK_U32) * VEPU_JPEGE_VEPU1_NUM_REGS; ctx->regs = mpp_calloc_size(void, ctx->reg_size + EXTRA_INFO_SIZE); if (NULL == ctx->regs) { mpp_err_f("failed to malloc vepu1 regs\n"); return MPP_NOK; } ctx->regs_out = mpp_calloc_size(void, ctx->reg_size + EXTRA_INFO_SIZE); if (NULL == ctx->regs_out) { mpp_err_f("failed to malloc vepu2 regs\n"); return MPP_NOK; } hal_jpege_dbg_func("leave hal %p\n", hal); return MPP_OK; } static MPP_RET hal_jpege_vepu1_deinit(void *hal) { HalJpegeCtx *ctx = (HalJpegeCtx *)hal; hal_jpege_dbg_func("enter hal %p\n", hal); if (ctx->bits) { jpege_bits_deinit(ctx->bits); ctx->bits = NULL; } if (ctx->dev) { mpp_dev_deinit(ctx->dev); ctx->dev = NULL; } hal_jpege_vepu_deinit_rc(&ctx->hal_rc); MPP_FREE(ctx->regs); MPP_FREE(ctx->regs_out); hal_jpege_dbg_func("leave hal %p\n", hal); return MPP_OK; } static MPP_RET hal_jpege_vepu1_get_task(void *hal, HalEncTask *task) { HalJpegeCtx *ctx = (HalJpegeCtx *)hal; JpegeSyntax *syntax = (JpegeSyntax *)task->syntax.data; hal_jpege_dbg_func("enter hal %p\n", hal); memcpy(&ctx->syntax, syntax, sizeof(ctx->syntax)); /* Set rc paramters */ hal_jpege_dbg_input("rc_mode %d\n", ctx->cfg->rc.rc_mode); if (ctx->cfg->rc.rc_mode != MPP_ENC_RC_MODE_FIXQP) { if (!ctx->hal_rc.q_factor) { task->rc_task->info.quality_target = syntax->q_factor ? (100 - syntax->q_factor) : 80; task->rc_task->info.quality_min = 100 - syntax->qf_max; task->rc_task->info.quality_max = 100 - syntax->qf_min; task->rc_task->frm.is_intra = 1; } else { task->rc_task->info.quality_target = ctx->hal_rc.last_quality; task->rc_task->info.quality_min = 100 - syntax->qf_max; task->rc_task->info.quality_max = 100 - syntax->qf_min; } } ctx->hal_start_pos = mpp_packet_get_length(task->packet); /* prepare for part encoding */ ctx->mcu_y = 0; ctx->mcu_h = syntax->mcu_h; ctx->sw_bit = 0; ctx->part_bytepos = 0; ctx->part_x_fill = 0; ctx->part_y_fill = 0; task->part_first = 1; task->part_last = 0; hal_jpege_dbg_func("leave hal %p\n", hal); return MPP_OK; } static MPP_RET hal_jpege_vepu1_set_extra_info(MppDev dev, JpegeSyntax *syntax, RK_U32 start_mbrow) { MppFrameFormat fmt = syntax->format; RK_U32 hor_stride = syntax->hor_stride; RK_U32 ver_stride = syntax->ver_stride; RK_U32 offset = 0; MppDevRegOffsetCfg trans_cfg; switch (fmt) { case MPP_FMT_YUV420SP : case MPP_FMT_YUV420P : { if (start_mbrow) { offset = 16 * start_mbrow * hor_stride; trans_cfg.reg_idx = 11; trans_cfg.offset = offset; mpp_dev_ioctl(dev, MPP_DEV_REG_OFFSET, &trans_cfg); } offset = hor_stride * ver_stride + hor_stride * start_mbrow * 16 / 2; if (fmt == MPP_FMT_YUV420P) offset = hor_stride * start_mbrow * 16 / 4 + hor_stride * ver_stride; trans_cfg.reg_idx = 12; trans_cfg.offset = offset; mpp_dev_ioctl(dev, MPP_DEV_REG_OFFSET, &trans_cfg); if (fmt == MPP_FMT_YUV420P) offset = hor_stride * start_mbrow * 16 / 4 + hor_stride * ver_stride * 5 / 4; trans_cfg.reg_idx = 13; trans_cfg.offset = offset; mpp_dev_ioctl(dev, MPP_DEV_REG_OFFSET, &trans_cfg); } break; default : { if (start_mbrow) { offset = start_mbrow * hor_stride; trans_cfg.reg_idx = 11; trans_cfg.offset = offset; mpp_dev_ioctl(dev, MPP_DEV_REG_OFFSET, &trans_cfg); } } break; } return MPP_OK; } static MPP_RET hal_jpege_vepu1_gen_regs(void *hal, HalEncTask *task) { HalJpegeCtx *ctx = (HalJpegeCtx *)hal; MppBuffer input = task->input; MppBuffer output = task->output; JpegeSyntax *syntax = &ctx->syntax; RK_U32 width = syntax->width; RK_U32 width_align = MPP_ALIGN(width, 16); RK_U32 height = syntax->height; MppFrameFormat fmt = syntax->format; RK_U32 hor_stride = 0; RK_U32 ver_stride = MPP_ALIGN(height, 16); JpegeBits bits = ctx->bits; RK_U32 *regs = (RK_U32 *)ctx->regs; size_t length = mpp_packet_get_length(task->packet); RK_U8 *buf = mpp_buffer_get_ptr(output); size_t size = mpp_buffer_get_size(output); const RK_U8 *qtable[2]; RK_S32 bitpos; RK_S32 bytepos; RK_U32 x_fill = 0; RK_U32 y_fill = 0; VepuFormatCfg fmt_cfg; RK_U32 rotation = 0; hal_jpege_dbg_func("enter hal %p\n", hal); if (syntax->rotation == MPP_ENC_ROT_90) rotation = 1; else if (syntax->rotation == MPP_ENC_ROT_270) rotation = 2; else if (syntax->rotation != MPP_ENC_ROT_0) mpp_err_f("Warning: only support 90 or 270 degree rotate, request rotate %d", syntax->rotation); if (rotation) { MPP_SWAP(RK_U32, width, height); MPP_SWAP(RK_U32, width_align, ver_stride); } hor_stride = get_vepu_pixel_stride(&ctx->stride_cfg, width, syntax->hor_stride, fmt); //hor_stride must be align with 8, and ver_stride mus align with 2 if ((hor_stride & 0x7) || (ver_stride & 0x1) || (hor_stride >= (1 << 15))) { mpp_err_f("illegal resolution, hor_stride %d, ver_stride %d, width %d, height %d\n", syntax->hor_stride, syntax->ver_stride, syntax->width, syntax->height); } x_fill = (width_align - width) / 4; y_fill = (ver_stride - height); mpp_assert(x_fill <= 3); mpp_assert(y_fill <= 15); ctx->part_x_fill = x_fill; ctx->part_y_fill = y_fill; /* write header to output buffer */ jpege_bits_setup(bits, buf, (RK_U32)size); /* seek length bytes data */ jpege_seek_bits(bits, length << 3); /* NOTE: write header will update qtable */ if (ctx->cfg->rc.rc_mode != MPP_ENC_RC_MODE_FIXQP) { hal_jpege_vepu_rc(ctx, task); qtable[0] = ctx->hal_rc.qtable_y; qtable[1] = ctx->hal_rc.qtable_c; } else { qtable[0] = NULL; qtable[1] = NULL; } write_jpeg_header(bits, syntax, qtable); memset(regs, 0, sizeof(RK_U32) * VEPU_JPEGE_VEPU1_NUM_REGS); regs[11] = mpp_buffer_get_fd(input); regs[12] = mpp_buffer_get_fd(input); regs[13] = regs[12]; bitpos = jpege_bits_get_bitpos(bits); bytepos = (bitpos + 7) >> 3; ctx->base = buf; ctx->size = size; ctx->sw_bit = bitpos; ctx->part_bytepos = bytepos; get_msb_lsb_at_pos(&regs[22], &regs[23], buf, bytepos); if (!get_vepu_fmt(&fmt_cfg, fmt)) { RK_U32 deflt_cfg = ((0 & (255)) << 24) | ((0 & (255)) << 16) | ((1 & (1)) << 15) | ((16 & (63)) << 8) | ((0 & (1)) << 6) | ((0 & (1)) << 5) | ((1 & (1)) << 4) | ((1 & (1)) << 3) | ((1 & (1)) << 1); regs[2] = deflt_cfg | (fmt_cfg.swap_8_in & 1) | (fmt_cfg.swap_32_in & 1) << 2 | (fmt_cfg.swap_16_in & 1) << 14; } regs[5] = mpp_buffer_get_fd(output); if (bytepos) mpp_dev_set_reg_offset(ctx->dev, 5, bytepos); regs[14] = (1 << 31) | (0 << 30) | (0 << 29) | ((width_align >> 4) << 19) | ((ver_stride >> 4) << 10) | (1 << 3) | (2 << 1); regs[15] = (0 << 29) | (0 << 26) | (hor_stride << 12) | (x_fill << 10) | (y_fill << 6) | (fmt_cfg.format << 2) | rotation; regs[24] = size - bytepos; regs[37] = ((bytepos & 7) * 8) << 23; { RK_U32 coeffA; RK_U32 coeffB; RK_U32 coeffC; RK_U32 coeffE; RK_U32 coeffF; switch (syntax->color_conversion_type) { case 0 : { /* BT.601 */ /* * Y = 0.2989 R + 0.5866 G + 0.1145 B * Cb = 0.5647 (B - Y) + 128 * Cr = 0.7132 (R - Y) + 128 */ coeffA = 19589; coeffB = 38443; coeffC = 7504; coeffE = 37008; coeffF = 46740; } break; case 1 : { /* BT.709 */ /* * Y = 0.2126 R + 0.7152 G + 0.0722 B * Cb = 0.5389 (B - Y) + 128 * Cr = 0.6350 (R - Y) + 128 */ coeffA = 13933; coeffB = 46871; coeffC = 4732; coeffE = 35317; coeffF = 41615; } break; case 2 : { coeffA = syntax->coeffA; coeffB = syntax->coeffB; coeffC = syntax->coeffC; coeffE = syntax->coeffE; coeffF = syntax->coeffF; } break; default : { mpp_err("invalid color conversion type %d\n", syntax->color_conversion_type); coeffA = 19589; coeffB = 38443; coeffC = 7504; coeffE = 37008; coeffF = 46740; } break; } regs[53] = coeffA | (coeffB << 16); regs[54] = coeffC | (coeffE << 16); regs[55] = ((fmt_cfg.b_mask & 0x1f) << 26) | ((fmt_cfg.g_mask & 0x1f) << 21) | ((fmt_cfg.r_mask & 0x1f) << 16) | coeffF; } regs[14] |= 0x001; { RK_S32 i; for (i = 0; i < 16; i++) { /* qtable need to reorder in particular order */ regs[i + 64] = qtable[0][qp_reorder_table[i * 4 + 0]] << 24 | qtable[0][qp_reorder_table[i * 4 + 1]] << 16 | qtable[0][qp_reorder_table[i * 4 + 2]] << 8 | qtable[0][qp_reorder_table[i * 4 + 3]]; } for (i = 0; i < 16; i++) { /* qtable need to reorder in particular order */ regs[i + 80] = qtable[1][qp_reorder_table[i * 4 + 0]] << 24 | qtable[1][qp_reorder_table[i * 4 + 1]] << 16 | qtable[1][qp_reorder_table[i * 4 + 2]] << 8 | qtable[1][qp_reorder_table[i * 4 + 3]]; } } hal_jpege_dbg_func("leave hal %p\n", hal); return MPP_OK; } static MPP_RET hal_jpege_vepu1_start(void *hal, HalEncTask *task) { MPP_RET ret = MPP_OK; HalJpegeCtx *ctx = (HalJpegeCtx *)hal; hal_jpege_dbg_func("enter hal %p\n", hal); hal_jpege_vepu1_set_extra_info(ctx->dev, &ctx->syntax, 0); do { MppDevRegWrCfg wr_cfg; MppDevRegRdCfg rd_cfg; RK_U32 reg_size = ctx->reg_size; wr_cfg.reg = ctx->regs; wr_cfg.size = reg_size; wr_cfg.offset = 0; ret = mpp_dev_ioctl(ctx->dev, MPP_DEV_REG_WR, &wr_cfg); if (ret) { mpp_err_f("set register write failed %d\n", ret); break; } rd_cfg.reg = ctx->regs; rd_cfg.size = reg_size; rd_cfg.offset = 0; ret = mpp_dev_ioctl(ctx->dev, MPP_DEV_REG_RD, &rd_cfg); if (ret) { mpp_err_f("set register read failed %d\n", ret); break; } ret = mpp_dev_ioctl(ctx->dev, MPP_DEV_CMD_SEND, NULL); if (ret) { mpp_err_f("send cmd failed %d\n", ret); break; } } while (0); hal_jpege_dbg_func("leave hal %p\n", hal); (void)task; return ret; } static MPP_RET hal_jpege_vepu1_wait(void *hal, HalEncTask *task) { MPP_RET ret = MPP_OK; HalJpegeCtx *ctx = (HalJpegeCtx *)hal; JpegeBits bits = ctx->bits; RK_U32 *regs = (RK_U32 *)ctx->regs; JpegeFeedback *feedback = &ctx->feedback; RK_U32 val; RK_U32 sw_bit = 0; RK_U32 hw_bit = 0; hal_jpege_dbg_func("enter hal %p\n", hal); if (ctx->dev) { ret = mpp_dev_ioctl(ctx->dev, MPP_DEV_CMD_POLL, NULL); if (ret) mpp_err_f("poll cmd failed %d\n", ret); } val = regs[1]; hal_jpege_dbg_output("hw_status %08x\n", val); feedback->hw_status = val & 0x70; val = regs[24]; sw_bit = jpege_bits_get_bitpos(bits); hw_bit = val; // NOTE: hardware will return 64 bit access byte count feedback->stream_length = ((sw_bit / 8) & (~0x7)) + hw_bit / 8; task->length = feedback->stream_length; task->hw_length = task->length - ctx->hal_start_pos; hal_jpege_dbg_output("stream bit: sw %d hw %d total %d hw_length %d\n", sw_bit, hw_bit, feedback->stream_length, task->hw_length); hal_jpege_dbg_func("leave hal %p\n", hal); return ret; } static MPP_RET hal_jpege_vepu1_part_start(void *hal, HalEncTask *task) { MPP_RET ret = MPP_OK; HalJpegeCtx *ctx = (HalJpegeCtx *)hal; JpegeSyntax *syntax = (JpegeSyntax *)task->syntax.data; RK_U32 mcu_w = syntax->mcu_w; RK_U32 mcu_h = syntax->mcu_h; RK_U32 mcu_y = ctx->mcu_y; RK_U32 part_mcu_h = syntax->part_rows; RK_U32 *regs = (RK_U32 *)ctx->regs; RK_U32 part_enc_h; RK_U32 part_enc_mcu_h; RK_U32 part_y_fill; RK_U32 part_not_end; hal_jpege_dbg_func("enter part start %p\n", hal); /* Fix register for each part encoding */ task->part_first = !mcu_y; if (mcu_y + part_mcu_h < mcu_h) { part_enc_h = part_mcu_h * 16; part_enc_mcu_h = part_mcu_h; part_y_fill = 0; part_not_end = 1; task->part_last = 0; } else { part_enc_h = syntax->height - mcu_y * 16; part_enc_mcu_h = MPP_ALIGN(part_enc_h, 16) / 16;; part_y_fill = ctx->part_y_fill; part_not_end = 0; task->part_last = 1; } hal_jpege_dbg_detail("part first %d last %d\n", task->part_first, task->part_last); get_msb_lsb_at_pos(&regs[22], &regs[23], ctx->base, ctx->part_bytepos); regs[24] = ctx->size - ctx->part_bytepos; regs[15] = (regs[15] & 0xfffffc3f) | (part_y_fill << 6); regs[37] = ((ctx->part_bytepos & 7) * 8) << 23; regs[5] = mpp_buffer_get_fd(task->output); if (ctx->part_bytepos) mpp_dev_set_reg_offset(ctx->dev, 5, ctx->part_bytepos); regs[14] = (1 << 31) | (0 << 30) | (0 << 29) | (mcu_w << 19) | (part_enc_mcu_h << 10) | (1 << 3) | (2 << 1) | 1; regs[20] = part_not_end << 24 | jpege_restart_marker[ctx->rst_marker_idx & 7]; ctx->rst_marker_idx++; hal_jpege_vepu1_set_extra_info(ctx->dev, syntax, mcu_y); ctx->mcu_y += part_enc_mcu_h; do { MppDevRegWrCfg wr_cfg; MppDevRegRdCfg rd_cfg; RK_U32 reg_size = ctx->reg_size; wr_cfg.reg = ctx->regs; wr_cfg.size = reg_size; wr_cfg.offset = 0; ret = mpp_dev_ioctl(ctx->dev, MPP_DEV_REG_WR, &wr_cfg); if (ret) { mpp_err_f("set register write failed %d\n", ret); break; } rd_cfg.reg = ctx->regs_out; rd_cfg.size = reg_size; rd_cfg.offset = 0; ret = mpp_dev_ioctl(ctx->dev, MPP_DEV_REG_RD, &rd_cfg); if (ret) { mpp_err_f("set register read failed %d\n", ret); break; } ret = mpp_dev_ioctl(ctx->dev, MPP_DEV_CMD_SEND, NULL); if (ret) { mpp_err_f("send cmd failed %d\n", ret); break; } } while (0); hal_jpege_dbg_func("leave part start %p\n", hal); (void)task; return ret; } static MPP_RET hal_jpege_vepu1_part_wait(void *hal, HalEncTask *task) { MPP_RET ret = MPP_OK; HalJpegeCtx *ctx = (HalJpegeCtx *)hal; RK_U32 *regs = ctx->regs_out; JpegeFeedback *feedback = &ctx->feedback; RK_U32 hw_bit = 0; hal_jpege_dbg_func("enter part wait %p\n", hal); if (ctx->dev) { ret = mpp_dev_ioctl(ctx->dev, MPP_DEV_CMD_POLL, NULL); if (ret) mpp_err_f("poll cmd failed %d\n", ret); } hal_jpege_dbg_detail("hw_status %08x\n", regs[1]); hw_bit = regs[24]; hal_jpege_dbg_detail("byte pos %d -> %d\n", ctx->part_bytepos, (ctx->part_bytepos & (~7)) + (hw_bit / 8)); ctx->part_bytepos = (ctx->part_bytepos & (~7)) + (hw_bit / 8); feedback->stream_length = ctx->part_bytepos; task->length = ctx->part_bytepos; task->hw_length = task->length - ctx->hal_start_pos; hal_jpege_dbg_detail("stream_length %d, hw_byte %d", feedback->stream_length, hw_bit / 8); hal_jpege_dbg_output("stream bit: sw %d hw %d total %d hw_length %d\n", ctx->sw_bit, hw_bit, feedback->stream_length, task->hw_length); hal_jpege_dbg_func("leave part wait %p\n", hal); return ret; } static MPP_RET hal_jpege_vepu1_ret_task(void *hal, HalEncTask *task) { HalJpegeCtx *ctx = (HalJpegeCtx *)hal; ctx->hal_rc.last_quality = task->rc_task->info.quality_target; task->rc_task->info.bit_real = ctx->feedback.stream_length * 8; task->hal_ret.data = &ctx->feedback; task->hal_ret.number = 1; return MPP_OK; } const MppEncHalApi hal_jpege_vepu1 = { .name = "hal_jpege_vepu1", .coding = MPP_VIDEO_CodingMJPEG, .ctx_size = sizeof(HalJpegeCtx), .flag = 0, .init = hal_jpege_vepu1_init, .deinit = hal_jpege_vepu1_deinit, .prepare = NULL, .get_task = hal_jpege_vepu1_get_task, .gen_regs = hal_jpege_vepu1_gen_regs, .start = hal_jpege_vepu1_start, .wait = hal_jpege_vepu1_wait, .part_start = hal_jpege_vepu1_part_start, .part_wait = hal_jpege_vepu1_part_wait, .ret_task = hal_jpege_vepu1_ret_task, };
10,730
807
<gh_stars>100-1000 #include "util/thread_pool.h" #include "util/task.h" #include <glog/logging.h> #include <condition_variable> #include <mutex> #include <queue> #include <thread> #include <vector> using std::chrono::duration; using std::chrono::duration_cast; using std::chrono::seconds; using std::chrono::steady_clock; using std::condition_variable; using std::function; using std::get; using std::lock_guard; using std::mutex; using std::priority_queue; using std::thread; using std::tuple; using std::unique_lock; using std::vector; namespace cert_trans { namespace { typedef tuple<steady_clock::time_point, function<void()>, util::Task*> QueueEntry; struct QueueOrdering { bool operator()(const QueueEntry& lhs, const QueueEntry& rhs) const { return get<0>(lhs) > get<0>(rhs); } }; } // namespace class ThreadPool::Impl { public: ~Impl(); void Worker(); // TODO(pphaneuf): I'd like this to be const, but it required // jumping through a few more hoops, keeping it simple for now. vector<thread> threads_; mutex queue_lock_; condition_variable queue_cond_var_; priority_queue<QueueEntry, vector<QueueEntry>, QueueOrdering> queue_; }; ThreadPool::Impl::~Impl() { // Start by sending an empty closure to every thread (and notify // them), to have them exit cleanly. { lock_guard<mutex> lock(queue_lock_); for (int i = threads_.size(); i > 0; --i) queue_.emplace( make_tuple(steady_clock::time_point(), function<void()>(), nullptr)); } // Notify all the threads *after* adding all the empty closures, to // avoid any races. queue_cond_var_.notify_all(); // Wait for the threads to exit. for (auto& thread : threads_) { thread.join(); } // Workers should've drained everything from the queue. CHECK(queue_.empty()); } void ThreadPool::Impl::Worker() { while (true) { QueueEntry entry; { unique_lock<mutex> lock(queue_lock_); while (queue_.empty() || get<0>(queue_.top()) > steady_clock::now()) { if (queue_.empty()) { // If there's nothing to do, wait until there is. queue_cond_var_.wait(lock); } else { // Otherwise, wait until the next thing we currently know about is // ready. const steady_clock::duration duration(get<0>(queue_.top()) - steady_clock::now()); queue_cond_var_.wait_for(lock, duration); } } entry = queue_.top(); queue_.pop(); // If we received an empty entry, exit cleanly. if (!get<1>(entry)) { // Anything left in the queue must be either other exit sentinels, or // future (delayed) tasks, so we'll cancel anything we find, up until // either the next exit sentinel, or the end of the queue. VLOG(1) << "Cancelling delayed tasks..."; vector<util::Task*> to_be_cancelled; while (!queue_.empty() && get<2>(queue_.top())) { to_be_cancelled.push_back(CHECK_NOTNULL(get<2>(queue_.top()))); queue_.pop(); } // Cancel the callbacks below outside of the lock to avoid deadlocking // anyone who tries to Add() more stuff when they're cancelled. // Anyone who does that is going to cause a CHECK fail in the d'tor of // the pool anyway, but at least they'll know about it that way. lock.unlock(); for (const auto& t : to_be_cancelled) { t->Return(util::Status::CANCELLED); } VLOG(1) << "Cancelled " << to_be_cancelled.size() << " delayed tasks."; return; } } // Make sure not to hold the lock while calling the closure. get<1>(entry)(); } } ThreadPool::ThreadPool() : ThreadPool(thread::hardware_concurrency() > 0 ? thread::hardware_concurrency() : 1) { } ThreadPool::ThreadPool(size_t num_threads) : impl_(new Impl) { CHECK_GT(num_threads, static_cast<size_t>(0)); LOG(INFO) << "ThreadPool starting with " << num_threads << " threads"; for (int i = 0; i < static_cast<int64_t>(num_threads); ++i) impl_->threads_.emplace_back(thread(&Impl::Worker, impl_.get())); } ThreadPool::~ThreadPool() { // Need to have this method defined where the definition of // ThreadPool::Impl is visible. } void ThreadPool::Add(const function<void()>& closure) { // Empty closures signal a thread to exit, don't allow that (also, // it doesn't make sense). if (!closure) { return; } { lock_guard<mutex> lock(impl_->queue_lock_); impl_->queue_.emplace(make_tuple(steady_clock::now(), closure, nullptr)); } impl_->queue_cond_var_.notify_one(); } void ThreadPool::Delay(const duration<double>& delay, util::Task* task) { CHECK_NOTNULL(task); { lock_guard<mutex> lock(impl_->queue_lock_); impl_->queue_.emplace(make_tuple( steady_clock::now() + duration_cast<std::chrono::microseconds>(delay), [task]() { task->Return(); }, task)); } impl_->queue_cond_var_.notify_one(); } } // namespace cert_trans
1,983
416
/* NSPropertyMapping.h Core Data Copyright (c) 2004-2017, Apple Inc. All rights reserved. */ #import <Foundation/NSArray.h> #import <Foundation/NSDictionary.h> NS_ASSUME_NONNULL_BEGIN @class NSExpression; API_AVAILABLE(macosx(10.5),ios(3.0)) @interface NSPropertyMapping : NSObject { #if (!__OBJC2__) @private void *_reserved; NSArray *_transformValidations; NSArray *_propertyTransforms; NSString *_name; NSExpression *_valueExpression; NSDictionary *_userInfo; struct __propertyMappingFlags { unsigned int _isInUse:1; unsigned int _reservedPropertyMapping:31; } _propertyMappingFlags; #endif } /* Returns/sets the name of the property in the destination entity for the mapping. */ @property (nullable, copy) NSString *name; /* Returns/sets the value expression for the property mapping. The expression is used to create the value for the destination property. */ @property (nullable, strong) NSExpression *valueExpression; /* Returns/sets the user info for the property mapping. */ @property (nullable, strong) NSDictionary *userInfo; @end NS_ASSUME_NONNULL_END
404
992
/* Copyright (c) 2006, <NAME> and <NAME> 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 Johns Hopkins University 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CORED_MESH_INCLUDED #define CORED_MESH_INCLUDED #include "Geometry.h" #include "MyMiscellany.h" template< typename Index > class CoredPointIndex { public: Index index; char inCore; bool operator == (const CoredPointIndex& cpi) const {return (index==cpi.index) && (inCore==cpi.inCore);}; bool operator != (const CoredPointIndex& cpi) const {return (index!=cpi.index) || (inCore!=cpi.inCore);}; }; template< typename Index > struct CoredEdgeIndex{ CoredPointIndex< Index > idx[2]; }; template< typename Index > struct CoredVertexIndex { Index idx; bool inCore; }; template< class Vertex , typename Index > class CoredCurveData { public: std::vector< Vertex > inCoreVertices; virtual void resetIterator( void ) = 0; virtual Index addOutOfCoreVertex ( const Vertex& v ) = 0; virtual Index addOutOfCoreVertex_s( unsigned int thread , const Vertex& v ) = 0; virtual void addEdge_s( unsigned int thread , CoredVertexIndex< Index > v1 , CoredVertexIndex< Index > v2 ) = 0; virtual void addEdge_s( unsigned int thread , Index v1 , Index v2 ) = 0; virtual Index nextOutOfCoreVertex( Vertex &v )=0; virtual Index nextEdge( CoredVertexIndex< Index >& v1 , CoredVertexIndex< Index >& v2 ) = 0; virtual size_t outOfCoreVertexNum(void)=0; virtual size_t edgeCount( void ) = 0; }; template< class Vertex , typename Index > class CoredMeshData { public: virtual ~CoredMeshData( void ){} std::vector< Vertex > inCoreVertices; virtual void resetIterator( void ) = 0; virtual Index addOutOfCoreVertex ( const Vertex &v ) = 0; virtual Index addOutOfCoreVertex_s( unsigned int thread , const Vertex &v ) = 0; virtual void addPolygon_s( unsigned int thread , const std::vector< CoredVertexIndex< Index > >& vertices ) = 0; virtual void addPolygon_s( unsigned int thread , const std::vector< Index >& vertices ) = 0; virtual Index nextOutOfCoreVertex( Vertex &v )=0; virtual Index nextPolygon( std::vector< CoredVertexIndex< Index > >& vertices ) = 0; virtual size_t outOfCoreVertexNum( void )=0; virtual size_t polygonNum( void ) = 0; }; template< class Vertex , typename Index > class CoredVectorCurveData : public CoredCurveData< Vertex , Index > { std::vector< Vertex > oocPoints; std::vector< std::pair< Index , Index > > edges; unsigned int threadIndex; Index edgeIndex; Index oocPointIndex; public: CoredVectorCurveData( void ); void resetIterator( void ); Index addOutOfCoreVertex ( const Vertex &v ); Index addOutOfCoreVertex_s( unsigned int thread , const Vertex &v ); void addEdge_s( unsigned int thread , CoredVertexIndex< Index > v1 , CoredVertexIndex< Index > v2 ); void addEdge_s( unsigned int thread , Index v1 , Index v2 ); Index nextOutOfCoreVertex( Vertex &v ); Index nextEdge( CoredVertexIndex< Index > &v1 , CoredVertexIndex< Index > &v2 ); size_t outOfCoreVertexNum( void ); size_t edgeCount( void ); }; template< class Vertex , typename Index > class CoredVectorMeshData : public CoredMeshData< Vertex , Index > { std::vector< Vertex > oocPoints; std::vector< std::vector< std::vector< Index > > > polygons; unsigned int threadIndex; Index polygonIndex; Index oocPointIndex; public: CoredVectorMeshData( void ); void resetIterator( void ); Index addOutOfCoreVertex ( const Vertex &v ); Index addOutOfCoreVertex_s( unsigned int thread , const Vertex &v ); void addPolygon_s( unsigned int thread , const std::vector< CoredVertexIndex< Index > >& vertices ); void addPolygon_s( unsigned int thread , const std::vector< Index >& vertices ); Index nextOutOfCoreVertex( Vertex &v ); Index nextPolygon( std::vector< CoredVertexIndex< Index > >& vertices ); size_t outOfCoreVertexNum( void ); size_t polygonNum( void ); }; class BufferedReadWriteFile { bool tempFile; FILE* _fp; char *_buffer , _fileName[1024]; size_t _bufferIndex , _bufferSize; public: BufferedReadWriteFile( const char* fileName=NULL , const char* fileHeader="" , unsigned int bufferSize=(1<<20) ) { _bufferIndex = 0; _bufferSize = bufferSize; if( fileName ) strcpy( _fileName , fileName ) , tempFile = false , _fp = fopen( _fileName , "w+b" ); else { if( fileHeader && strlen(fileHeader) ) sprintf( _fileName , "%sXXXXXX" , fileHeader ); else strcpy( _fileName , "XXXXXX" ); #ifdef _WIN32 _mktemp( _fileName ); _fp = fopen( _fileName , "w+b" ); #else // !_WIN32 _fp = fdopen( mkstemp( _fileName ) , "w+b" ); #endif // _WIN32 tempFile = true; } if( !_fp ) ERROR_OUT( "Failed to open file: " , _fileName ); _buffer = (char*) malloc( _bufferSize ); } ~BufferedReadWriteFile( void ) { free( _buffer ); fclose( _fp ); if( tempFile ) remove( _fileName ); } bool write( const void* data , size_t size ) { if( !size ) return true; const char* _data = (char*) data; size_t sz = _bufferSize - _bufferIndex; while( sz<=size ) { memcpy( _buffer+_bufferIndex , _data , sz ); fwrite( _buffer , 1 , _bufferSize , _fp ); _data += sz; size -= sz; _bufferIndex = 0; sz = _bufferSize; } if( size ) { memcpy( _buffer+_bufferIndex , _data , size ); _bufferIndex += size; } return true; } bool read( void* data , size_t size ) { if( !size ) return true; char *_data = (char*) data; size_t sz = _bufferSize - _bufferIndex; while( sz<=size ) { if( size && !_bufferSize ) return false; memcpy( _data , _buffer+_bufferIndex , sz ); _bufferSize = fread( _buffer , 1 , _bufferSize , _fp ); _data += sz; size -= sz; _bufferIndex = 0; if( !size ) return true; sz = _bufferSize; } if( size ) { if( !_bufferSize ) return false; memcpy( _data , _buffer+_bufferIndex , size ); _bufferIndex += size; } return true; } void reset( void ) { if( _bufferIndex ) fwrite( _buffer , 1 , _bufferIndex , _fp ); _bufferIndex = 0; fseek( _fp , 0 , SEEK_SET ); _bufferIndex = 0; _bufferSize = fread( _buffer , 1 , _bufferSize , _fp ); } }; template< class Vertex , typename Index > class CoredFileCurveData : public CoredCurveData< Vertex , Index > { BufferedReadWriteFile *oocPointFile; Index oocPoints; std::vector< BufferedReadWriteFile* > edgeFiles; unsigned int threadIndex; public: CoredFileCurveData( const char* fileHeader="" ); ~CoredFileCurveData( void ); void resetIterator( void ); Index addOutOfCoreVertex ( const Vertex &v ); Index addOutOfCoreVertex_s( unsigned int thread , const Vertex &v ); void addEdge_s( unsigned int thread , CoredVertexIndex< Index > v1 , CoredVertexIndex< Index > v2 ); void addEdge_s( unsigned int thread , Index v1 , Index v2 ); Index nextOutOfCoreVertex( Vertex &v ); Index nextEdge( CoredVertexIndex< Index > &v1 , CoredVertexIndex< Index > &v2 ); size_t outOfCoreVertexNum( void ); size_t edgeCount( void ); }; template< typename Index , typename VertexFactory > class CoredFileMeshData : public CoredMeshData< typename VertexFactory::VertexType , Index > { typedef typename VertexFactory::VertexType VertexType; BufferedReadWriteFile *_oocVertexFile; Index _oocVertexNum; std::vector< Index > _polygonNum; std::vector< BufferedReadWriteFile * > _polygonFiles; unsigned int _threadIndex; const VertexFactory &_factory; char *_buffer; public: CoredFileMeshData( const VertexFactory &vFactory , const char* fileHeader="" ); ~CoredFileMeshData( void ); void resetIterator( void ); Index addOutOfCoreVertex ( const VertexType& v ); Index addOutOfCoreVertex_s( unsigned int thread , const VertexType& v ); void addPolygon_s( unsigned int thread , const std::vector< CoredVertexIndex< Index > >& vertices ); void addPolygon_s( unsigned int thread , const std::vector< Index >& vertices ); Index nextOutOfCoreVertex( VertexType &v ); Index nextPolygon( std::vector< CoredVertexIndex< Index > >& vertices ); size_t outOfCoreVertexNum( void ); size_t polygonNum( void ); }; #include "CoredMesh.inl" #endif // CORED_MESH
3,395
348
{"nom":"Saint-Martin-de-Mâcon","circ":"3ème circonscription","dpt":"Deux-Sèvres","inscrits":264,"abs":166,"votants":98,"blancs":8,"nuls":0,"exp":90,"res":[{"nuance":"LR","nom":"<NAME>","voix":49},{"nuance":"REM","nom":"<NAME>","voix":41}]}
99
10,225
<gh_stars>1000+ package io.quarkus.elytron.security.jdbc; import java.security.Principal; import javax.annotation.security.DenyAll; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.SecurityContext; @Path("subject") public class SubjectExposingResource { @Inject Principal principal; @GET @RolesAllowed("user") @Path("secured") public String getSubjectSecured(@Context SecurityContext sec) { Principal user = sec.getUserPrincipal(); String name = user != null ? user.getName() : "anonymous"; return name; } @GET @RolesAllowed("user") @Path("principal-secured") public String getPrincipalSecured(@Context SecurityContext sec) { if (principal == null) { throw new IllegalStateException("No injected principal"); } String name = principal.getName(); return name; } @GET @Path("unsecured") @PermitAll public String getSubjectUnsecured(@Context SecurityContext sec) { Principal user = sec.getUserPrincipal(); String name = user != null ? user.getName() : "anonymous"; return name; } @DenyAll @GET @Path("denied") public String getSubjectDenied(@Context SecurityContext sec) { Principal user = sec.getUserPrincipal(); String name = user != null ? user.getName() : "anonymous"; return name; } }
620
1,585
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */ /* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2005 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2011-2012 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2014 Los Alamos National Security, LLC. All rights * reserved. * Copyright (c) 2015 Research Organization for Information Science * and Technology (RIST). All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "ompi_config.h" #include "ompi/mpi/fortran/mpif-h/bindings.h" #if OMPI_BUILD_MPI_PROFILING #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak PMPI_WIN_FLUSH_LOCAL = ompi_win_flush_local_f #pragma weak pmpi_win_flush_local = ompi_win_flush_local_f #pragma weak pmpi_win_flush_local_ = ompi_win_flush_local_f #pragma weak pmpi_win_flush_local__ = ompi_win_flush_local_f #pragma weak PMPI_Win_flush_local_f = ompi_win_flush_local_f #pragma weak PMPI_Win_flush_local_f08 = ompi_win_flush_local_f #else OMPI_GENERATE_F77_BINDINGS (PMPI_WIN_FLUSH_LOCAL, pmpi_win_flush_local, pmpi_win_flush_local_, pmpi_win_flush_local__, pompi_win_flush_local_f, (MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr), (rank, win, ierr) ) #endif #endif #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak MPI_WIN_FLUSH_LOCAL = ompi_win_flush_local_f #pragma weak mpi_win_flush_local = ompi_win_flush_local_f #pragma weak mpi_win_flush_local_ = ompi_win_flush_local_f #pragma weak mpi_win_flush_local__ = ompi_win_flush_local_f #pragma weak MPI_Win_flush_local_f = ompi_win_flush_local_f #pragma weak MPI_Win_flush_local_f08 = ompi_win_flush_local_f #else #if ! OMPI_BUILD_MPI_PROFILING OMPI_GENERATE_F77_BINDINGS (MPI_WIN_FLUSH_LOCAL, mpi_win_flush_local, mpi_win_flush_local_, mpi_win_flush_local__, ompi_win_flush_local_f, (MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr), (rank, win, ierr) ) #else #define ompi_win_flush_local_f pompi_win_flush_local_f #endif #endif void ompi_win_flush_local_f(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { int c_ierr; MPI_Win c_win = PMPI_Win_f2c(*win); c_ierr = PMPI_Win_flush_local(OMPI_FINT_2_INT(*rank), c_win); if (NULL != ierr) *ierr = OMPI_INT_2_FINT(c_ierr); }
1,600
1,473
<gh_stars>1000+ #include "build.h" #include "config.h" #include "configManager.h" namespace tools { ConfigurationManager::ConfigurationManager() : m_sessionConfig(wxT("UniversalCompiler"), wxT("RexDex"), wxT("UniversalCompiler.ini"), wxEmptyString, wxCONFIG_USE_LOCAL_FILE) {} ConfigurationManager::~ConfigurationManager() {} ConfigurationManager& ConfigurationManager::GetInstance() { static ConfigurationManager theInstance; return theInstance; } void ConfigurationManager::SaveConfig() { std::lock_guard<std::mutex> lock(m_configEntriesLock); // Dump all configuration entries for (auto* entry : m_configEntries) entry->OnSaveConfiguration(); // Flush the changes to the file m_sessionConfig.Flush(); } void ConfigurationManager::LoadConfig() { std::lock_guard<std::mutex> lock(m_configEntriesLock); // Load all configuration entries for (auto* entry : m_configEntries) entry->OnLoadConfiguration(); } void ConfigurationManager::RegisterConfigurationEntry(IConfiguration* entry) { std::lock_guard<std::mutex> lock(m_configEntriesLock); m_configEntries.push_back(entry); } void ConfigurationManager::UnregisterConfigurationEntry(IConfiguration* entry) { std::lock_guard<std::mutex> lock(m_configEntriesLock); std::remove(m_configEntries.begin(), m_configEntries.end(), entry); } } // tools
450
309
<filename>piou/formatter/__init__.py from .base import Formatter from .rich_formatter import RichFormatter
33
343
<reponame>devtayls/elixir<gh_stars>100-1000 [ { "url": "https://hexdocs.pm/elixir/Kernel.SpecialForms.html#import/2", "description": "Documentation - import" } ]
75
563
/* * Copyright 2018-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 dev.miku.r2dbc.mysql.codec; import dev.miku.r2dbc.mysql.MySqlColumnMetadata; import dev.miku.r2dbc.mysql.Parameter; import dev.miku.r2dbc.mysql.ParameterWriter; import dev.miku.r2dbc.mysql.constant.MySqlType; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import reactor.core.publisher.Mono; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; /** * Codec for {@code long}. */ final class LongCodec extends AbstractPrimitiveCodec<Long> { LongCodec(ByteBufAllocator allocator) { super(allocator, Long.TYPE, Long.class); } @Override public Long decode(ByteBuf value, MySqlColumnMetadata metadata, Class<?> target, boolean binary, CodecContext context) { MySqlType type = metadata.getType(); if (binary) { return decodeBinary(value, type); } switch (type) { case FLOAT: return (long) Float.parseFloat(value.toString(StandardCharsets.US_ASCII)); case DOUBLE: return (long) Double.parseDouble(value.toString(StandardCharsets.US_ASCII)); case DECIMAL: return decimalLong(value); default: return CodecUtils.parseLong(value); } } @Override public boolean canEncode(Object value) { return value instanceof Long; } @Override public Parameter encode(Object value, CodecContext context) { return encodeLong(allocator, (Long) value); } @Override public boolean canPrimitiveDecode(MySqlColumnMetadata metadata) { return metadata.getType().isNumeric(); } static Parameter encodeLong(ByteBufAllocator allocator, long v) { if ((byte) v == v) { return new ByteCodec.ByteParameter(allocator, (byte) v); } else if ((short) v == v) { return new ShortCodec.ShortParameter(allocator, (short) v); } else if ((int) v == v) { return new IntegerCodec.IntParameter(allocator, (int) v); } return new LongParameter(allocator, v); } private static long decodeBinary(ByteBuf buf, MySqlType type) { switch (type) { case BIGINT_UNSIGNED: case BIGINT: return buf.readLongLE(); case INT_UNSIGNED: return buf.readUnsignedIntLE(); case INT: case MEDIUMINT_UNSIGNED: case MEDIUMINT: // Note: MySQL return 32-bits two's complement for 24-bits integer return buf.readIntLE(); case SMALLINT_UNSIGNED: return buf.readUnsignedShortLE(); case SMALLINT: case YEAR: return buf.readShortLE(); case TINYINT_UNSIGNED: return buf.readUnsignedByte(); case TINYINT: return buf.readByte(); case DECIMAL: return decimalLong(buf); case FLOAT: return (long) buf.readFloatLE(); case DOUBLE: return (long) buf.readDoubleLE(); } throw new IllegalStateException("Cannot decode type " + type + " as a Long"); } private static long decimalLong(ByteBuf buf) { return new BigDecimal(buf.toString(StandardCharsets.US_ASCII)).longValue(); } private static final class LongParameter extends AbstractParameter { private final ByteBufAllocator allocator; private final long value; private LongParameter(ByteBufAllocator allocator, long value) { this.allocator = allocator; this.value = value; } @Override public Mono<ByteBuf> publishBinary() { return Mono.fromSupplier(() -> allocator.buffer(Long.BYTES).writeLongLE(value)); } @Override public Mono<Void> publishText(ParameterWriter writer) { return Mono.fromRunnable(() -> writer.writeLong(value)); } @Override public MySqlType getType() { return MySqlType.BIGINT; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof LongParameter)) { return false; } LongParameter longValue = (LongParameter) o; return value == longValue.value; } @Override public int hashCode() { return (int) (value ^ (value >>> 32)); } } }
2,289
2,338
<filename>test_inputs/codegen/cloog/lex.c for (int c0 = 0; c0 <= 10; c0 += 1) { S2(c0); S1(c0); }
57
627
/* Copyright 2017 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* I2C module driver depends on chip series for Chrome EC */ #include "common.h" #include "i2c.h" #include "i2c_chip.h" #include "registers.h" #include "util.h" /*****************************************************************************/ /* IC specific low-level driver depends on chip series */ int i2c_port_to_controller(int port) { if (port < 0 || port >= I2C_PORT_COUNT) return -1; if (port <= NPCX_I2C_PORT3_0) return port; #ifndef NPCX_PSL_MODE_SUPPORT else if (port == NPCX_I2C_PORT4_0) return 4; #endif else /* If port >= NPCX_I2C_PORT4_1 */ return 4 + ((port - NPCX_I2C_PORT4_1 + 1) / 2); } void i2c_select_port(int port) { /* Only I2C 4/5/6 have multiple ports in series npcx7 */ if (port <= NPCX_I2C_PORT3_0 || port >= NPCX_I2C_PORT7_0) return; /* Select I2C ports for the same controller */ else if (port <= NPCX_I2C_PORT4_1) { UPDATE_BIT(NPCX_GLUE_SMBSEL, NPCX_SMBSEL_SMB4SEL, (port == NPCX_I2C_PORT4_1)); } else if (port <= NPCX_I2C_PORT5_1) { UPDATE_BIT(NPCX_GLUE_SMBSEL, NPCX_SMBSEL_SMB5SEL, (port == NPCX_I2C_PORT5_1)); } else { UPDATE_BIT(NPCX_GLUE_SMBSEL, NPCX_SMBSEL_SMB6SEL, (port == NPCX_I2C_PORT6_1)); } } int i2c_is_raw_mode(int port) { int group, bit; if (port == NPCX_I2C_PORT4_1 || port == NPCX_I2C_PORT5_1 || port == NPCX_I2C_PORT6_1) { group = 6; bit = 7 - (port - NPCX_I2C_PORT4_1) / 2; } else { group = 2; if (port <= NPCX_I2C_PORT3_0) bit = 2 * port; else bit = I2C_PORT_COUNT - port; } if (IS_BIT_SET(NPCX_DEVALT(group), bit)) return 0; else return 1; }
787
10,876
<filename>ports/tmxlite/vcpkg.json { "name": "tmxlite", "version": "1.3.0", "description": "A lightweight C++14 parsing library for tmx map files created with the Tiled map editor.", "dependencies": [ { "name": "vcpkg-cmake", "host": true }, { "name": "vcpkg-cmake-config", "host": true } ] }
153
14,668
<gh_stars>1000+ // Copyright 2017 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "snapshot/linux/system_snapshot_linux.h" #include <sys/time.h> #include <unistd.h> #include <string> #include "build/build_config.h" #include "gtest/gtest.h" #include "snapshot/linux/process_reader_linux.h" #include "test/errors.h" #include "test/linux/fake_ptrace_connection.h" namespace crashpad { namespace test { namespace { TEST(SystemSnapshotLinux, Basic) { FakePtraceConnection connection; ASSERT_TRUE(connection.Initialize(getpid())); ProcessReaderLinux process_reader; ASSERT_TRUE(process_reader.Initialize(&connection)); timeval snapshot_time; ASSERT_EQ(gettimeofday(&snapshot_time, nullptr), 0) << ErrnoMessage("gettimeofday"); internal::SystemSnapshotLinux system; system.Initialize(&process_reader, &snapshot_time); EXPECT_GT(system.CPUCount(), 0u); uint64_t current_hz, max_hz; system.CPUFrequency(&current_hz, &max_hz); // For short-term loads, modern CPUs can boost single-core frequency beyond // the advertised base clock. Let's assume this is no more than a factor 2. EXPECT_GE(max_hz * 2, current_hz); int major, minor, bugfix; std::string build; system.OSVersion(&major, &minor, &bugfix, &build); EXPECT_GE(major, 3); EXPECT_GE(minor, 0); EXPECT_GE(bugfix, 0); EXPECT_FALSE(build.empty()); EXPECT_FALSE(system.OSVersionFull().empty()); // No expectations; just make sure these can be called successfully. system.CPURevision(); system.NXEnabled(); #if defined(OS_ANDROID) EXPECT_FALSE(system.MachineDescription().empty()); #else system.MachineDescription(); #endif // OS_ANDROID #if defined(ARCH_CPU_X86_FAMILY) system.CPUX86Signature(); system.CPUX86Features(); system.CPUX86ExtendedFeatures(); system.CPUX86Leaf7Features(); EXPECT_PRED1( [](std::string vendor) { return vendor == "GenuineIntel" || vendor == "AuthenticAMD" || vendor == "HygonGenuine"; }, system.CPUVendor()); EXPECT_TRUE(system.CPUX86SupportsDAZ()); #endif // ARCH_CPU_X86_FAMILY } } // namespace } // namespace test } // namespace crashpad
917
2,568
{ "Ancestry": { "domain": "ancestry.com", "url": "https://www.ancestry.com", "tfa": [ "sms", "email" ], "documentation": "https://support.ancestry.com/s/article/MFA", "notes": "SMS 2FA is currently only available for customers with a U.S. based phone number.", "keywords": [ "other" ] } }
156
3,112
// // 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PXFOUNDATION_PXSIMPLETYPES_H #define PXFOUNDATION_PXSIMPLETYPES_H /** \addtogroup foundation @{ */ // Platform specific types: // Design note: Its OK to use int for general loop variables and temps. #include "foundation/PxPreprocessor.h" #if PX_VC #pragma warning(push) #pragma warning(disable : 4668) // suppressing warning generated by Microsoft Visual Studio when including this standard // header #endif #if PX_LINUX #define __STDC_LIMIT_MACROS #endif #include <stdint.h> #if PX_VC #pragma warning(pop) #endif #if PX_VC // we could use inttypes.h starting with VC12 #define PX_PRIu64 "I64u" #else #if !PX_PS4 && !PX_APPLE_FAMILY #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #define PX_PRIu64 PRIu64 #endif namespace physx { typedef int64_t PxI64; typedef uint64_t PxU64; typedef int32_t PxI32; typedef uint32_t PxU32; typedef int16_t PxI16; typedef uint16_t PxU16; typedef int8_t PxI8; typedef uint8_t PxU8; typedef float PxF32; typedef double PxF64; typedef float PxReal; } // Type ranges // These are here because we sometimes have non-IEEE compliant platforms to deal with. // Removal is under consideration (issue GWSD-34) #define PX_MAX_F32 3.4028234663852885981170418348452e+38F // maximum possible float value #define PX_MAX_F64 DBL_MAX // maximum possible double value #define PX_EPS_F32 FLT_EPSILON // maximum relative error of float rounding #define PX_EPS_F64 DBL_EPSILON // maximum relative error of double rounding #define PX_MAX_REAL PX_MAX_F32 #define PX_EPS_REAL PX_EPS_F32 #define PX_NORMALIZATION_EPSILON float(1e-20f) // Legacy type ranges used by PhysX #define PX_MAX_I8 INT8_MAX #define PX_MIN_I8 INT8_MIN #define PX_MAX_U8 UINT8_MAX #define PX_MIN_U8 UINT8_MIN #define PX_MAX_I16 INT16_MAX #define PX_MIN_I16 INT16_MIN #define PX_MAX_U16 UINT16_MAX #define PX_MIN_U16 UINT16_MIN #define PX_MAX_I32 INT32_MAX #define PX_MIN_I32 INT32_MIN #define PX_MAX_U32 UINT32_MAX #define PX_MIN_U32 UINT32_MIN /** @} */ #endif // #ifndef PXFOUNDATION_PXSIMPLETYPES_H
1,319
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"<NAME>","circ":"5ème circonscription","dpt":"Seine-Maritime","inscrits":518,"abs":260,"votants":258,"blancs":14,"nuls":1,"exp":243,"res":[{"nuance":"SOC","nom":"<NAME>","voix":189},{"nuance":"LR","nom":"<NAME>","voix":54}]}
111
329
package com.jvms.i18neditor; /** * An enum describing the type of a {@link Resource}. * * <p>A resource type additionally holds information about the filename representation.</p> * * @author <NAME> */ public enum ResourceType { JSON(".json"), ES6(".js"), Properties(".properties"); private final String extension; /** * Gets the file extension of the resource type. * * @return the file extension. */ public String getExtension() { return extension; } private ResourceType(String extension) { this.extension = extension; } }
182
6,451
<reponame>victorcouste/great_expectations import json from great_expectations.core import ExpectationConfiguration from great_expectations.core.expectation_validation_result import ( ExpectationValidationResult, ) from great_expectations.expectations.registry import get_renderer_impl from great_expectations.render.renderer.content_block import ( ValidationResultsTableContentBlockRenderer, ) from great_expectations.render.types import ( RenderedComponentContent, RenderedStringTemplateContent, ) def test_ValidationResultsTableContentBlockRenderer_generate_expectation_row_with_errored_expectation( evr_failed_with_exception, ): result = ValidationResultsTableContentBlockRenderer.render( [evr_failed_with_exception] ).to_json_dict() print(result) expected_result = { "content_block_type": "table", "styling": { "body": {"classes": ["table"]}, "classes": ["ml-2", "mr-2", "mt-0", "mb-0", "table-responsive"], }, "table": [ [ { "content_block_type": "string_template", "string_template": { "template": "$icon", "params": {"icon": "", "markdown_status_icon": "❗"}, "styling": { "params": { "icon": { "classes": [ "fas", "fa-exclamation-triangle", "text-warning", ], "tag": "i", } } }, }, }, [ { "content_block_type": "string_template", "string_template": { "template": "$column can match any distribution.", "params": { "column": "live", "partition_object": None, "threshold": None, "result_format": "SUMMARY", "row_condition": None, "condition_parser": None, }, }, }, { "content_block_type": "string_template", "string_template": { "template": "\n\n$expectation_type raised an exception:\n$exception_message", "params": { "expectation_type": "expect_column_kl_divergence_to_be_less_than", "exception_message": "Invalid partition object.", }, "tag": "strong", "styling": { "classes": ["text-danger"], "params": { "exception_message": {"tag": "code"}, "expectation_type": { "classes": ["badge", "badge-danger", "mb-2"] }, }, }, }, }, { "content_block_type": "collapse", "collapse_toggle_link": "Show exception traceback...", "collapse": [ { "content_block_type": "string_template", "string_template": { "template": 'Traceback (most recent call last):\n File "/great_expectations/great_expectations/data_asset/data_asset.py", line 216, in wrapper\n return_obj = func(self, **evaluation_args)\n File "/great_expectations/great_expectations/dataset/dataset.py", line 106, in inner_wrapper\n evaluation_result = func(self, column, *args, **kwargs)\n File "/great_expectations/great_expectations/dataset/dataset.py", line 3381, in expect_column_kl_divergence_to_be_less_than\n raise ValueError("Invalid partition object.")\nValueError: Invalid partition object.\n', "tag": "code", }, } ], "inline_link": False, }, ], "--", ] ], "header_row": ["Status", "Expectation", "Observed Value"], "header_row_options": {"Status": {"sortable": True}}, "table_options": {"search": True, "icon-size": "sm"}, } assert result == expected_result def test_ValidationResultsTableContentBlockRenderer_render( titanic_profiled_name_column_evrs, ): validation_results_table = ValidationResultsTableContentBlockRenderer.render( titanic_profiled_name_column_evrs ) assert isinstance(validation_results_table, RenderedComponentContent) assert validation_results_table.content_block_type == "table" assert len(validation_results_table.table) == 6 assert validation_results_table.header_row == [ "Status", "Expectation", "Observed Value", ] assert validation_results_table.styling == { "body": {"classes": ["table"]}, "classes": ["ml-2", "mr-2", "mt-0", "mb-0", "table-responsive"], } assert json.dumps(validation_results_table.to_json_dict()).count("$icon") == 6 def test_ValidationResultsTableContentBlockRenderer_get_content_block_fn(evr_success): content_block_fn = ValidationResultsTableContentBlockRenderer._get_content_block_fn( "expect_table_row_count_to_be_between" ) content_block_fn_output = content_block_fn(result=evr_success) content_block_fn_expected_output = [ [ RenderedStringTemplateContent( **{ "content_block_type": "string_template", "string_template": { "template": "$icon", "params": {"icon": "", "markdown_status_icon": "✅"}, "styling": { "params": { "icon": { "classes": [ "fas", "fa-check-circle", "text-success", ], "tag": "i", } } }, }, "styling": { "parent": { "classes": ["hide-succeeded-validation-target-child"] } }, } ), RenderedStringTemplateContent( **{ "content_block_type": "string_template", "string_template": { "template": "Must have greater than or equal to $min_value rows.", "params": { "min_value": 0, "max_value": None, "result_format": "SUMMARY", "row_condition": None, "condition_parser": None, "strict_max": None, "strict_min": None, }, "styling": None, }, } ), "1,313", ] ] assert content_block_fn_output == content_block_fn_expected_output def test_ValidationResultsTableContentBlockRenderer_get_content_block_fn_with_v2_api_style_custom_rendering(): """Test backwards support for custom expectation rendering with the V2 API as described at https://docs.greatexpectations.io/en/latest/reference/spare_parts/data_docs_reference.html#customizing-data-docs. """ custom_expectation_template = "custom_expectation_template" custom_expectation_observed_value = "custom_expectation_observed_value" class ValidationResultsTableContentBlockRendererWithV2ApiStyleCustomExpectations( ValidationResultsTableContentBlockRenderer ): @classmethod def expect_custom_expectation_written_in_v2_api_style( cls, expectation, styling=None, include_column_name: bool = True ): return [ RenderedStringTemplateContent( content_block_type="string_template", string_template={ "template": custom_expectation_template, "params": expectation.kwargs, "styling": styling, }, ) ] evr = ExpectationValidationResult( success=True, result={ "observed_value": custom_expectation_observed_value, }, exception_info={ "raised_exception": False, "exception_message": None, "exception_traceback": None, }, expectation_config=ExpectationConfiguration( expectation_type="expect_custom_expectation", kwargs={"column": "a_column_name", "result_format": "SUMMARY"}, ), ) content_block_fn = ValidationResultsTableContentBlockRendererWithV2ApiStyleCustomExpectations._get_content_block_fn( "expect_custom_expectation_written_in_v2_api_style" ) content_block_fn_output = content_block_fn(result=evr) content_block_fn_expected_output = [ [ RenderedStringTemplateContent( **{ "content_block_type": "string_template", "string_template": { "template": "$icon", "params": {"icon": "", "markdown_status_icon": "✅"}, "styling": { "params": { "icon": { "classes": [ "fas", "fa-check-circle", "text-success", ], "tag": "i", } } }, }, "styling": { "parent": { "classes": ["hide-succeeded-validation-target-child"] } }, } ), RenderedStringTemplateContent( **{ "content_block_type": "string_template", "string_template": { "template": custom_expectation_template, "params": { "column": "a_column_name", "result_format": "SUMMARY", }, "styling": None, }, } ), custom_expectation_observed_value, ] ] assert content_block_fn_output == content_block_fn_expected_output def test_ValidationResultsTableContentBlockRenderer_get_observed_value(evr_success): evr_no_result_key = ExpectationValidationResult( success=True, exception_info={ "raised_exception": False, "exception_message": None, "exception_traceback": None, }, expectation_config=ExpectationConfiguration( expectation_type="expect_table_row_count_to_be_between", kwargs={"min_value": 0, "max_value": None, "result_format": "SUMMARY"}, ), ) evr_expect_column_values_to_not_be_null = ExpectationValidationResult( success=True, result={ "element_count": 1313, "unexpected_count": 1050, "unexpected_percent": 79.96953541508, "partial_unexpected_list": [], }, exception_info={ "raised_exception": False, "exception_message": None, "exception_traceback": None, }, expectation_config=ExpectationConfiguration( expectation_type="expect_column_values_to_not_be_null", kwargs={"column": "Unnamed: 0", "mostly": 0.5, "result_format": "SUMMARY"}, ), ) evr_expect_column_values_to_be_null = ExpectationValidationResult( success=True, result={ "element_count": 1313, "unexpected_count": 0, "unexpected_percent": 0.0, "partial_unexpected_list": [], }, exception_info={ "raised_exception": False, "exception_message": None, "exception_traceback": None, }, expectation_config=ExpectationConfiguration( expectation_type="expect_column_values_to_be_null", kwargs={"column": "Unnamed: 0", "mostly": 0.5, "result_format": "SUMMARY"}, ), ) evr_success_zero = ExpectationValidationResult( success=True, result={"observed_value": 0}, exception_info={ "raised_exception": False, "exception_message": None, "exception_traceback": None, }, expectation_config=ExpectationConfiguration( expectation_type="expect_table_row_count_to_be_between", kwargs={"min_value": 0, "max_value": None, "result_format": "SUMMARY"}, ), ) # test _get_observed_value when evr.result["observed_value"] exists output_1 = get_renderer_impl( object_name=evr_success.expectation_config.expectation_type, renderer_type="renderer.diagnostic.observed_value", )[1](result=evr_success) assert output_1 == "1,313" # test _get_observed_value when evr.result does not exist output_2 = get_renderer_impl( object_name=evr_no_result_key.expectation_config.expectation_type, renderer_type="renderer.diagnostic.observed_value", )[1](result=evr_no_result_key) assert output_2 == "--" # test _get_observed_value for expect_column_values_to_not_be_null expectation type output_3 = get_renderer_impl( object_name=evr_expect_column_values_to_not_be_null.expectation_config.expectation_type, renderer_type="renderer.diagnostic.observed_value", )[1](result=evr_expect_column_values_to_not_be_null) assert output_3 == "≈20.03% not null" # test _get_observed_value for expect_column_values_to_be_null expectation type output_4 = get_renderer_impl( object_name=evr_expect_column_values_to_be_null.expectation_config.expectation_type, renderer_type="renderer.diagnostic.observed_value", )[1](result=evr_expect_column_values_to_be_null) assert output_4 == "100% null" # test _get_observed_value to be 0 output_5 = get_renderer_impl( object_name=evr_success_zero.expectation_config.expectation_type, renderer_type="renderer.diagnostic.observed_value", )[1](result=evr_success_zero) assert output_5 == "0" def test_ValidationResultsTableContentBlockRenderer_get_unexpected_statement( evr_success, evr_failed ): evr_no_result = ExpectationValidationResult( success=True, exception_info={ "raised_exception": False, "exception_message": None, "exception_traceback": None, }, expectation_config=ExpectationConfiguration( expectation_type="expect_table_row_count_to_be_between", kwargs={"min_value": 0, "max_value": None, "result_format": "SUMMARY"}, ), ) evr_failed_no_unexpected_count = ExpectationValidationResult( success=False, result={ "element_count": 1313, "missing_count": 0, "missing_percent": 0.0, "unexpected_percent": 0.2284843869002285, "unexpected_percent_nonmissing": 0.2284843869002285, "partial_unexpected_list": [ "Daly, Mr <NAME> ", "Barber, Ms ", "Geiger, <NAME> ", ], "partial_unexpected_index_list": [77, 289, 303], "partial_unexpected_counts": [ {"value": "Barber, Ms ", "count": 1}, {"value": "Daly, Mr <NAME> ", "count": 1}, {"value": "<NAME> Emily ", "count": 1}, ], }, exception_info={ "raised_exception": False, "exception_message": None, "exception_traceback": None, }, expectation_config=ExpectationConfiguration( expectation_type="expect_column_values_to_not_match_regex", kwargs={ "column": "Name", "regex": "^\\s+|\\s+$", "result_format": "SUMMARY", }, ), ) # test for succeeded evr output_1 = get_renderer_impl( object_name=evr_success.expectation_config.expectation_type, renderer_type="renderer.diagnostic.unexpected_statement", )[1](result=evr_success) assert output_1 == [] # test for failed evr output_2 = get_renderer_impl( object_name=evr_failed.expectation_config.expectation_type, renderer_type="renderer.diagnostic.unexpected_statement", )[1](result=evr_failed) assert output_2 == [ RenderedStringTemplateContent( **{ "content_block_type": "string_template", "string_template": { "template": "\n\n$unexpected_count unexpected values found. $unexpected_percent of $element_count total rows.", "params": { "unexpected_count": "3", "unexpected_percent": "≈0.2285%", "element_count": "1,313", }, "tag": "strong", "styling": {"classes": ["text-danger"]}, }, } ) ] # test for evr with no "result" key output_3 = get_renderer_impl( object_name=evr_no_result.expectation_config.expectation_type, renderer_type="renderer.diagnostic.unexpected_statement", )[1](result=evr_no_result) print(json.dumps(output_3, indent=2)) assert output_3 == [] # test for evr with no unexpected count output_4 = get_renderer_impl( object_name=evr_failed_no_unexpected_count.expectation_config.expectation_type, renderer_type="renderer.diagnostic.unexpected_statement", )[1](result=evr_failed_no_unexpected_count) print(output_4) assert output_4 == [] # test for evr with exception evr_failed_exception = ExpectationValidationResult( success=False, exception_info={ "raised_exception": True, "exception_message": "Unrecognized column: not_a_real_column", "exception_traceback": "Traceback (most recent call last):\n...more_traceback...", }, expectation_config=ExpectationConfiguration( expectation_type="expect_column_values_to_not_match_regex", kwargs={ "column": "Name", "regex": "^\\s+|\\s+$", "result_format": "SUMMARY", }, ), ) output_5 = get_renderer_impl( object_name=evr_failed_exception.expectation_config.expectation_type, renderer_type="renderer.diagnostic.unexpected_statement", )[1](result=evr_failed_exception) output_5 = [content.to_json_dict() for content in output_5] expected_output_5 = [ { "content_block_type": "string_template", "string_template": { "template": "\n\n$expectation_type raised an exception:\n$exception_message", "params": { "expectation_type": "expect_column_values_to_not_match_regex", "exception_message": "Unrecognized column: not_a_real_column", }, "tag": "strong", "styling": { "classes": ["text-danger"], "params": { "exception_message": {"tag": "code"}, "expectation_type": { "classes": ["badge", "badge-danger", "mb-2"] }, }, }, }, }, { "content_block_type": "collapse", "collapse_toggle_link": "Show exception traceback...", "collapse": [ { "content_block_type": "string_template", "string_template": { "template": "Traceback (most recent call last):\n...more_traceback...", "tag": "code", }, } ], "inline_link": False, }, ] assert output_5 == expected_output_5 def test_ValidationResultsTableContentBlockRenderer_get_unexpected_table(evr_success): evr_failed_no_result = ExpectationValidationResult( success=False, exception_info={ "raised_exception": False, "exception_message": None, "exception_traceback": None, }, expectation_config=ExpectationConfiguration( expectation_type="expect_column_values_to_be_in_set", kwargs={ "column": "Unnamed: 0", "value_set": [], "result_format": "SUMMARY", }, ), ) evr_failed_no_unexpected_list_or_counts = ExpectationValidationResult( success=False, result={ "element_count": 1313, "missing_count": 0, "missing_percent": 0.0, "unexpected_count": 1313, "unexpected_percent": 100.0, "unexpected_percent_nonmissing": 100.0, }, exception_info={ "raised_exception": False, "exception_message": None, "exception_traceback": None, }, expectation_config=ExpectationConfiguration( expectation_type="expect_column_values_to_be_in_set", kwargs={ "column": "Unnamed: 0", "value_set": [], "result_format": "SUMMARY", }, ), ) evr_failed_partial_unexpected_list = ExpectationValidationResult( success=False, result={ "element_count": 1313, "missing_count": 0, "missing_percent": 0.0, "unexpected_count": 1313, "unexpected_percent": 100.0, "unexpected_percent_nonmissing": 100.0, "partial_unexpected_list": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ], }, exception_info={ "raised_exception": False, "exception_message": None, "exception_traceback": None, }, expectation_config=ExpectationConfiguration( expectation_type="expect_column_values_to_be_in_set", kwargs={ "column": "Unnamed: 0", "value_set": [], "result_format": "SUMMARY", }, ), ) evr_failed_partial_unexpected_counts = ExpectationValidationResult( success=False, result={ "element_count": 1313, "missing_count": 0, "missing_percent": 0.0, "unexpected_count": 1313, "unexpected_percent": 100.0, "unexpected_percent_nonmissing": 100.0, "partial_unexpected_list": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ], "partial_unexpected_index_list": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ], "partial_unexpected_counts": [ {"value": 1, "count": 1}, {"value": 2, "count": 1}, {"value": 3, "count": 1}, {"value": 4, "count": 1}, {"value": 5, "count": 1}, {"value": 6, "count": 1}, {"value": 7, "count": 1}, {"value": 8, "count": 1}, {"value": 9, "count": 1}, {"value": 10, "count": 1}, {"value": 11, "count": 1}, {"value": 12, "count": 1}, {"value": 13, "count": 1}, {"value": 14, "count": 1}, {"value": 15, "count": 1}, {"value": 16, "count": 1}, {"value": 17, "count": 1}, {"value": 18, "count": 1}, {"value": 19, "count": 1}, {"value": 20, "count": 1}, ], }, exception_info={ "raised_exception": False, "exception_message": None, "exception_traceback": None, }, expectation_config=ExpectationConfiguration( expectation_type="expect_column_values_to_be_in_set", kwargs={ "column": "Unnamed: 0", "value_set": [], "result_format": "SUMMARY", }, ), ) # test for succeeded evr output_1 = get_renderer_impl( object_name=evr_success.expectation_config.expectation_type, renderer_type="renderer.diagnostic.unexpected_table", )[1](result=evr_success) assert output_1 is None # test for failed evr with no "result" key output_2 = get_renderer_impl( object_name=evr_failed_no_result.expectation_config.expectation_type, renderer_type="renderer.diagnostic.unexpected_table", )[1](result=evr_failed_no_result) assert output_2 is None # test for failed evr with no unexpected list or unexpected counts output_3 = get_renderer_impl( object_name=evr_failed_no_unexpected_list_or_counts.expectation_config.expectation_type, renderer_type="renderer.diagnostic.unexpected_table", )[1](result=evr_failed_no_unexpected_list_or_counts) assert output_3 is None # test for failed evr with partial unexpected list output_4 = get_renderer_impl( object_name=evr_failed_partial_unexpected_list.expectation_config.expectation_type, renderer_type="renderer.diagnostic.unexpected_table", )[1](result=evr_failed_partial_unexpected_list) assert output_4.to_json_dict() == { "content_block_type": "table", "table": [ [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], ], "header_row": ["Sampled Unexpected Values"], "styling": {"body": {"classes": ["table-bordered", "table-sm", "mt-3"]}}, } # test for failed evr with partial unexpected counts output_5 = get_renderer_impl( object_name=evr_failed_partial_unexpected_counts.expectation_config.expectation_type, renderer_type="renderer.diagnostic.unexpected_table", )[1](result=evr_failed_partial_unexpected_counts) assert output_5.to_json_dict() == { "content_block_type": "table", "table": [ [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], ], "header_row": ["Sampled Unexpected Values"], "styling": {"body": {"classes": ["table-bordered", "table-sm", "mt-3"]}}, } def test_ValidationResultsTableContentBlockRenderer_get_status_cell( evr_failed_with_exception, evr_success, evr_failed ): # test for failed evr with exception output_1 = get_renderer_impl( object_name=evr_failed_with_exception.expectation_config.expectation_type, renderer_type="renderer.diagnostic.status_icon", )[1](result=evr_failed_with_exception) assert output_1.to_json_dict() == { "content_block_type": "string_template", "string_template": { "template": "$icon", "params": {"icon": "", "markdown_status_icon": "❗"}, "styling": { "params": { "icon": { "classes": ["fas", "fa-exclamation-triangle", "text-warning"], "tag": "i", } } }, }, } # test for succeeded evr output_2 = get_renderer_impl( object_name=evr_success.expectation_config.expectation_type, renderer_type="renderer.diagnostic.status_icon", )[1](result=evr_success) assert output_2.to_json_dict() == { "content_block_type": "string_template", "string_template": { "template": "$icon", "params": {"icon": "", "markdown_status_icon": "✅"}, "styling": { "params": { "icon": { "classes": ["fas", "fa-check-circle", "text-success"], "tag": "i", } } }, }, "styling": {"parent": {"classes": ["hide-succeeded-validation-target-child"]}}, } # test for failed evr output_3 = get_renderer_impl( object_name=evr_failed.expectation_config.expectation_type, renderer_type="renderer.diagnostic.status_icon", )[1](result=evr_failed) assert output_3.to_json_dict() == { "content_block_type": "string_template", "string_template": { "template": "$icon", "params": {"icon": "", "markdown_status_icon": "❌"}, "styling": { "params": { "icon": {"tag": "i", "classes": ["fas", "fa-times", "text-danger"]} } }, }, }
17,757
348
{"nom":"Lisle-sur-Tarn","circ":"2ème circonscription","dpt":"Tarn","inscrits":3665,"abs":1904,"votants":1761,"blancs":167,"nuls":94,"exp":1500,"res":[{"nuance":"REM","nom":"<NAME>","voix":945},{"nuance":"FN","nom":"<NAME>","voix":555}]}
96
763
package org.batfish.datamodel; import static com.google.common.base.MoreObjects.toStringHelper; import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import org.batfish.datamodel.visitors.FibActionVisitor; /** * A {@link FibAction} directing the device to ARP for a given IP on a given interface, then forward * a packet given a successful reply. */ @ParametersAreNonnullByDefault public final class FibForward implements FibAction { private final @Nonnull Ip _arpIp; private final @Nonnull String _interfaceName; public FibForward(Ip arpIp, String interfaceName) { _arpIp = arpIp; _interfaceName = interfaceName; } /** IP that a router would ARP for to send the packet */ public @Nonnull Ip getArpIp() { return _arpIp; } /** Name of the interface to be used to send the packet out */ public @Nonnull String getInterfaceName() { return _interfaceName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FibForward)) { return false; } FibForward rhs = (FibForward) o; return _arpIp.equals(rhs._arpIp) && _interfaceName.equals(rhs._interfaceName); } @Override public int hashCode() { return _arpIp.hashCode() * 31 + _interfaceName.hashCode(); } @Override public @Nonnull String toString() { return toStringHelper(FibForward.class) .add("arpIp", _arpIp) .add("interfaceName", _interfaceName) .toString(); } @Override public <T> T accept(FibActionVisitor<T> visitor) { return visitor.visitFibForward(this); } }
581
1,520
<gh_stars>1000+ package org.cnodejs.android.md.ui.view; import android.support.annotation.NonNull; public interface ICreateTopicView { void onTitleError(@NonNull String message); void onContentError(@NonNull String message); void onCreateTopicOk(@NonNull String topicId); void onCreateTopicStart(); void onCreateTopicFinish(); }
116
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/tiles/software_image_decode_cache.h" #include "base/strings/stringprintf.h" #include "cc/paint/draw_image.h" #include "cc/paint/paint_image_builder.h" #include "cc/test/fake_paint_image_generator.h" #include "cc/test/skia_common.h" #include "cc/test/test_tile_task_runner.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkRefCnt.h" namespace cc { namespace { size_t kLockedMemoryLimitBytes = 128 * 1024 * 1024; SkMatrix CreateMatrix(const SkSize& scale, bool is_decomposable) { SkMatrix matrix; matrix.setScale(scale.width(), scale.height()); if (!is_decomposable) { // Perspective is not decomposable, add it. matrix[SkMatrix::kMPersp0] = 0.1f; } return matrix; } class BaseTest : public testing::Test { public: void SetUp() override { cache_ = CreateCache(); paint_image_ = CreatePaintImage(gfx::Size(512, 512)); } void TearDown() override { paint_image_ = PaintImage(); cache_.reset(); } DrawImage CreateDrawImageForScale( float scale, const SkIRect src_rect = SkIRect::MakeEmpty()) { return DrawImage( paint_image(), src_rect.isEmpty() ? SkIRect::MakeWH(paint_image().width(), paint_image().height()) : src_rect, kMedium_SkFilterQuality, CreateMatrix(SkSize::Make(scale, scale), true), PaintImage::kDefaultFrameIndex, GetColorSpace()); } SoftwareImageDecodeCache& cache() { return *cache_; } PaintImage& paint_image() { return paint_image_; } protected: struct CacheEntryResult { bool has_task = false; bool needs_unref = false; }; virtual std::unique_ptr<SoftwareImageDecodeCache> CreateCache() = 0; virtual CacheEntryResult GenerateCacheEntry(const DrawImage& image) = 0; virtual PaintImage CreatePaintImage(const gfx::Size& size) = 0; virtual gfx::ColorSpace GetColorSpace() = 0; virtual void VerifyEntryExists(int line, const DrawImage& draw_image, const gfx::Size& expected_size) = 0; private: std::unique_ptr<SoftwareImageDecodeCache> cache_; PaintImage paint_image_; }; class N32Cache : public virtual BaseTest { protected: std::unique_ptr<SoftwareImageDecodeCache> CreateCache() override { return std::make_unique<SoftwareImageDecodeCache>(kN32_SkColorType, kLockedMemoryLimitBytes); } }; class RGBA4444Cache : public virtual BaseTest { protected: std::unique_ptr<SoftwareImageDecodeCache> CreateCache() override { return std::make_unique<SoftwareImageDecodeCache>(kARGB_4444_SkColorType, kLockedMemoryLimitBytes); } }; class AtRaster : public virtual BaseTest { protected: CacheEntryResult GenerateCacheEntry(const DrawImage& image) override { // At raster doesn't generate cache entries. return {false, false}; } void VerifyEntryExists(int line, const DrawImage& draw_image, const gfx::Size& expected_size) override { auto decoded = cache().GetDecodedImageForDraw(draw_image); SCOPED_TRACE(base::StringPrintf("Failure from line %d", line)); EXPECT_EQ(decoded.image()->width(), expected_size.width()); EXPECT_EQ(decoded.image()->height(), expected_size.height()); cache().DrawWithImageFinished(draw_image, decoded); } }; class Predecode : public virtual BaseTest { protected: CacheEntryResult GenerateCacheEntry(const DrawImage& image) override { auto task_result = cache().GetTaskForImageAndRef(image, ImageDecodeCache::TracingInfo()); CacheEntryResult result = {!!task_result.task, task_result.need_unref}; if (task_result.task) TestTileTaskRunner::ProcessTask(task_result.task.get()); return result; } void VerifyEntryExists(int line, const DrawImage& draw_image, const gfx::Size& expected_size) override { auto decoded = cache().GetDecodedImageForDraw(draw_image); SCOPED_TRACE(base::StringPrintf("Failure from line %d", line)); EXPECT_EQ(decoded.image()->width(), expected_size.width()); EXPECT_EQ(decoded.image()->height(), expected_size.height()); cache().DrawWithImageFinished(draw_image, decoded); } }; class NoDecodeToScaleSupport : public virtual BaseTest { protected: PaintImage CreatePaintImage(const gfx::Size& size) override { return CreateDiscardablePaintImage(size, GetColorSpace().ToSkColorSpace()); } }; class DefaultColorSpace : public virtual BaseTest { protected: gfx::ColorSpace GetColorSpace() override { return gfx::ColorSpace::CreateSRGB(); } }; class ExoticColorSpace : public virtual BaseTest { protected: gfx::ColorSpace GetColorSpace() override { return gfx::ColorSpace(gfx::ColorSpace::PrimaryID::XYZ_D50, gfx::ColorSpace::TransferID::IEC61966_2_1); } }; class SoftwareImageDecodeCacheTest_Typical : public N32Cache, public Predecode, public NoDecodeToScaleSupport, public DefaultColorSpace {}; TEST_F(SoftwareImageDecodeCacheTest_Typical, UseClosestAvailableDecode) { auto draw_image_50 = CreateDrawImageForScale(0.5f); auto result = GenerateCacheEntry(draw_image_50); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); // Clear the cache to eliminate the transient 1.f scale from the cache. cache().ClearCache(); VerifyEntryExists(__LINE__, draw_image_50, gfx::Size(256, 256)); EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); auto draw_image_125 = CreateDrawImageForScale(0.125f); result = GenerateCacheEntry(draw_image_125); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); VerifyEntryExists(__LINE__, draw_image_125, gfx::Size(64, 64)); // We didn't clear the cache the second time, and should only expect to find // these entries: 0.5 scale and 0.125 scale. EXPECT_EQ(2u, cache().GetNumCacheEntriesForTesting()); cache().UnrefImage(draw_image_50); cache().UnrefImage(draw_image_125); } TEST_F(SoftwareImageDecodeCacheTest_Typical, UseClosestAvailableDecodeNotSmaller) { auto draw_image_25 = CreateDrawImageForScale(0.25f); auto result = GenerateCacheEntry(draw_image_25); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); // Clear the cache to eliminate the transient 1.f scale from the cache. cache().ClearCache(); VerifyEntryExists(__LINE__, draw_image_25, gfx::Size(128, 128)); EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); auto draw_image_50 = CreateDrawImageForScale(0.5f); result = GenerateCacheEntry(draw_image_50); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); VerifyEntryExists(__LINE__, draw_image_50, gfx::Size(256, 256)); // We didn't clear the cache the second time, and should only expect to find // these entries: 1.0 scale, 0.5 scale and 0.25 scale. EXPECT_EQ(3u, cache().GetNumCacheEntriesForTesting()); cache().UnrefImage(draw_image_50); cache().UnrefImage(draw_image_25); } TEST_F(SoftwareImageDecodeCacheTest_Typical, UseClosestAvailableDecodeFirstImageSubrected) { auto draw_image_50 = CreateDrawImageForScale(0.5f, SkIRect::MakeWH(500, 500)); auto result = GenerateCacheEntry(draw_image_50); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); // Clear the cache to eliminate the transient 1.f scale from the cache. cache().ClearCache(); VerifyEntryExists(__LINE__, draw_image_50, gfx::Size(250, 250)); EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); auto draw_image_125 = CreateDrawImageForScale(0.125f); result = GenerateCacheEntry(draw_image_125); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); VerifyEntryExists(__LINE__, draw_image_125, gfx::Size(64, 64)); // We didn't clear the cache the second time, and should only expect to find // these entries: 1.0 scale, 0.5 scale subrected and 0.125 scale. EXPECT_EQ(3u, cache().GetNumCacheEntriesForTesting()); cache().UnrefImage(draw_image_50); cache().UnrefImage(draw_image_125); } TEST_F(SoftwareImageDecodeCacheTest_Typical, UseClosestAvailableDecodeSecondImageSubrected) { auto draw_image_50 = CreateDrawImageForScale(0.5f); auto result = GenerateCacheEntry(draw_image_50); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); // Clear the cache to eliminate the transient 1.f scale from the cache. cache().ClearCache(); VerifyEntryExists(__LINE__, draw_image_50, gfx::Size(256, 256)); EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); auto draw_image_125 = CreateDrawImageForScale(0.125f, SkIRect::MakeWH(400, 400)); result = GenerateCacheEntry(draw_image_125); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); VerifyEntryExists(__LINE__, draw_image_125, gfx::Size(50, 50)); // We didn't clear the cache the second time, and should only expect to find // these entries: 1.0 scale, 0.5 scale and 0.125 scale subrected. EXPECT_EQ(3u, cache().GetNumCacheEntriesForTesting()); cache().UnrefImage(draw_image_50); cache().UnrefImage(draw_image_125); } TEST_F(SoftwareImageDecodeCacheTest_Typical, UseClosestAvailableDecodeBothSubrected) { auto draw_image_50 = CreateDrawImageForScale(0.5f, SkIRect::MakeWH(400, 400)); auto result = GenerateCacheEntry(draw_image_50); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); // Clear the cache to eliminate the transient 1.f scale from the cache. cache().ClearCache(); VerifyEntryExists(__LINE__, draw_image_50, gfx::Size(200, 200)); EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); auto draw_image_125 = CreateDrawImageForScale(0.125f, SkIRect::MakeWH(400, 400)); result = GenerateCacheEntry(draw_image_125); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); VerifyEntryExists(__LINE__, draw_image_125, gfx::Size(50, 50)); // We didn't clear the cache the second time, and should only expect to find // these entries: 0.5 scale subrected and 0.125 scale subrected. EXPECT_EQ(2u, cache().GetNumCacheEntriesForTesting()); cache().UnrefImage(draw_image_50); cache().UnrefImage(draw_image_125); } TEST_F(SoftwareImageDecodeCacheTest_Typical, UseClosestAvailableDecodeBothPastPostScaleSize) { auto draw_image_50 = CreateDrawImageForScale(0.5f, SkIRect::MakeXYWH(300, 300, 52, 52)); auto result = GenerateCacheEntry(draw_image_50); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); // Clear the cache to eliminate the transient 1.f scale from the cache. cache().ClearCache(); VerifyEntryExists(__LINE__, draw_image_50, gfx::Size(26, 26)); EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); auto draw_image_25 = CreateDrawImageForScale(0.25, SkIRect::MakeXYWH(300, 300, 52, 52)); result = GenerateCacheEntry(draw_image_25); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); VerifyEntryExists(__LINE__, draw_image_25, gfx::Size(13, 13)); // We didn't clear the cache the second time, and should only expect to find // these entries: 0.5 scale subrected and 0.25 scale subrected. EXPECT_EQ(2u, cache().GetNumCacheEntriesForTesting()); cache().UnrefImage(draw_image_50); cache().UnrefImage(draw_image_25); } class SoftwareImageDecodeCacheTest_AtRaster : public N32Cache, public AtRaster, public NoDecodeToScaleSupport, public DefaultColorSpace {}; TEST_F(SoftwareImageDecodeCacheTest_AtRaster, UseClosestAvailableDecode) { auto draw_image_50 = CreateDrawImageForScale(0.5f); auto decoded = cache().GetDecodedImageForDraw(draw_image_50); { VerifyEntryExists(__LINE__, draw_image_50, gfx::Size(256, 256)); cache().ClearCache(); EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); auto draw_image_125 = CreateDrawImageForScale(0.125f); VerifyEntryExists(__LINE__, draw_image_125, gfx::Size(64, 64)); } cache().DrawWithImageFinished(draw_image_50, decoded); // We should only expect to find these entries: 0.5 scale and 0.125 scale. EXPECT_EQ(2u, cache().GetNumCacheEntriesForTesting()); } TEST_F(SoftwareImageDecodeCacheTest_AtRaster, UseClosestAvailableDecodeSubrected) { auto draw_image_50 = CreateDrawImageForScale(0.5f, SkIRect::MakeWH(500, 500)); auto decoded = cache().GetDecodedImageForDraw(draw_image_50); { VerifyEntryExists(__LINE__, draw_image_50, gfx::Size(250, 250)); cache().ClearCache(); EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); auto draw_image_125 = CreateDrawImageForScale(0.125f); VerifyEntryExists(__LINE__, draw_image_125, gfx::Size(64, 64)); } cache().DrawWithImageFinished(draw_image_50, decoded); // We should only expect to find these entries: 1.0 scale, 0.5 scale subrected // and 0.125 scale. EXPECT_EQ(3u, cache().GetNumCacheEntriesForTesting()); } class SoftwareImageDecodeCacheTest_RGBA4444 : public RGBA4444Cache, public Predecode, public NoDecodeToScaleSupport, public DefaultColorSpace {}; TEST_F(SoftwareImageDecodeCacheTest_RGBA4444, AlwaysUseOriginalDecode) { auto draw_image_50 = CreateDrawImageForScale(0.5f); auto result = GenerateCacheEntry(draw_image_50); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); cache().ClearCache(); VerifyEntryExists(__LINE__, draw_image_50, gfx::Size(512, 512)); EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); auto draw_image_125 = CreateDrawImageForScale(0.125f); result = GenerateCacheEntry(draw_image_125); EXPECT_FALSE(result.has_task); EXPECT_TRUE(result.needs_unref); VerifyEntryExists(__LINE__, draw_image_125, gfx::Size(512, 512)); // We didn't clear the cache the second time, and should only expect to find // one entry: 1.0 scale. EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); cache().UnrefImage(draw_image_50); cache().UnrefImage(draw_image_125); } TEST_F(SoftwareImageDecodeCacheTest_RGBA4444, AlwaysUseOriginalDecodeEvenSubrected) { auto draw_image_50 = CreateDrawImageForScale(0.5f, SkIRect::MakeWH(10, 10)); auto result = GenerateCacheEntry(draw_image_50); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); cache().ClearCache(); VerifyEntryExists(__LINE__, draw_image_50, gfx::Size(512, 512)); EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); auto draw_image_125 = CreateDrawImageForScale(0.125f, SkIRect::MakeWH(20, 20)); result = GenerateCacheEntry(draw_image_125); EXPECT_FALSE(result.has_task); EXPECT_TRUE(result.needs_unref); VerifyEntryExists(__LINE__, draw_image_125, gfx::Size(512, 512)); // We didn't clear the cache the second time, and should only expect to find // one entry: 1.0 scale. EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); cache().UnrefImage(draw_image_50); cache().UnrefImage(draw_image_125); } class SoftwareImageDecodeCacheTest_ExoticColorSpace : public N32Cache, public Predecode, public NoDecodeToScaleSupport, public ExoticColorSpace {}; TEST_F(SoftwareImageDecodeCacheTest_ExoticColorSpace, UseClosestAvailableDecode) { auto draw_image_50 = CreateDrawImageForScale(0.5f); auto result = GenerateCacheEntry(draw_image_50); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); // Clear the cache to eliminate the transient 1.f scale from the cache. cache().ClearCache(); VerifyEntryExists(__LINE__, draw_image_50, gfx::Size(256, 256)); EXPECT_EQ(1u, cache().GetNumCacheEntriesForTesting()); auto draw_image_125 = CreateDrawImageForScale(0.125f); result = GenerateCacheEntry(draw_image_125); EXPECT_TRUE(result.has_task); EXPECT_TRUE(result.needs_unref); VerifyEntryExists(__LINE__, draw_image_125, gfx::Size(64, 64)); // We didn't clear the cache the second time, and should only expect to find // these entries: 0.5 scale and 0.125 scale. EXPECT_EQ(2u, cache().GetNumCacheEntriesForTesting()); cache().UnrefImage(draw_image_50); cache().UnrefImage(draw_image_125); } } // namespace } // namespace cc
6,319
325
#ifndef WIZ_COMPILER_BUILTINS_H #define WIZ_COMPILER_BUILTINS_H #include <vector> #include <memory> #include <utility> #include <unordered_map> #include <wiz/compiler/instruction.h> #include <wiz/utility/int128.h> #include <wiz/utility/array_view.h> #include <wiz/utility/fwd_unique_ptr.h> namespace wiz { struct Statement; struct Definition; struct Expression; struct TypeExpression; class Platform; class StringPool; class SymbolTable; struct BuiltinModeAttribute { BuiltinModeAttribute( StringView name, std::size_t groupIndex) : name(name), groupIndex(groupIndex) {} StringView name; std::size_t groupIndex; }; class Builtins { public: enum class DefinitionType { None, Bool, U8, U16, U24, U32, U64, I8, I16, I24, I32, I64, IExpr, Let, Range, Intrinsic, TypeOf, HasDef, GetDef, }; enum class Property { None, Len, MinValue, MaxValue, Count }; enum class DeclarationAttribute { None, Irq, Nmi, Fallthrough, Align, Count }; Builtins( StringPool* stringPool, Platform* platform, std::unordered_map<StringView, FwdUniquePtr<const Expression>> defines); ~Builtins(); template <typename... Args> const InstructionOperandPattern* createInstructionOperandPattern(Args&&... args) { return addInstructionOperandPattern(makeFwdUnique<const InstructionOperandPattern>(std::forward<Args>(args)...)); } template <typename... Args> const InstructionEncoding* createInstructionEncoding(Args&&... args) { return addInstructionEncoding(makeFwdUnique<const InstructionEncoding>(std::forward<Args>(args)...)); } template <typename... Args> const Instruction* createInstruction(Args&&... args) { return addInstruction(makeFwdUnique<const Instruction>(std::forward<Args>(args)...)); } StringPool* getStringPool() const; SymbolTable* getBuiltinScope() const; const Statement* getBuiltinDeclaration() const; Definition* getDefinition(DefinitionType type) const; const Expression* getDefineExpression(StringView key) const; void addDefineInteger(StringView key, Int128 value); void addDefineBoolean(StringView key, bool value); ArrayView<FwdUniquePtr<const InstructionOperandPattern>> getInstructionOperandPatterns() const; const InstructionOperandPattern* addInstructionOperandPattern(FwdUniquePtr<const InstructionOperandPattern> uniquePattern); ArrayView<FwdUniquePtr<const InstructionEncoding>> getInstructionEncodings() const; const InstructionEncoding* addInstructionEncoding(FwdUniquePtr<const InstructionEncoding> uniqueEncoding); ArrayView<FwdUniquePtr<const Instruction>> getInstructions() const; const Instruction* addInstruction(FwdUniquePtr<const Instruction> uniqueInstruction); std::vector<const Instruction*> findAllInstructionsByType(const InstructionType& instructionType) const; std::vector<const Instruction*> findAllSpecializationsByInstruction(const Instruction* instruction) const; const Instruction* selectInstruction(const InstructionType& instructionType, std::uint32_t modeFlags, const std::vector<InstructionOperandRoot>& operandRoots) const; void addRegisterDecomposition(const Definition* reg, std::vector<Definition*> subRegisters); ArrayView<Definition*> findRegisterDecomposition(const Definition* reg) const; StringView getPropertyName(Property prop) const; Property findPropertyByName(StringView name) const; DeclarationAttribute findDeclarationAttributeByName(StringView name) const; bool isDeclarationAttributeValid(DeclarationAttribute attribute, const Statement* statement) const; std::size_t getDeclarationAttributeArgumentCount(DeclarationAttribute attribute) const; std::size_t addModeAttribute(StringView name, std::size_t groupIndex); std::size_t findModeAttributeByName(StringView name) const; const BuiltinModeAttribute* getModeAttribute(std::size_t index) const; std::size_t getModeAttributeCount() const; const TypeExpression* getUnitTuple() const; private: StringPool* stringPool = nullptr; Platform* platform = nullptr; std::unordered_map<StringView, FwdUniquePtr<const Expression>> defines; std::unique_ptr<SymbolTable> scope; FwdUniquePtr<const Statement> declaration; Definition* boolType = nullptr; Definition* u8Type = nullptr; Definition* u16Type = nullptr; Definition* u24Type = nullptr; Definition* u32Type = nullptr; Definition* u64Type = nullptr; Definition* i8Type = nullptr; Definition* i16Type = nullptr; Definition* i24Type = nullptr; Definition* i32Type = nullptr; Definition* i64Type = nullptr; Definition* iexprType = nullptr; Definition* letType = nullptr; Definition* rangeType = nullptr; Definition* intrinsicType = nullptr; Definition* typeofType = nullptr; Definition* hasDef = nullptr; Definition* getDef = nullptr; FwdUniquePtr<const TypeExpression> unitTuple; std::vector<FwdUniquePtr<const InstructionOperandPattern>> instructionOperandPatterns; std::vector<FwdUniquePtr<const InstructionEncoding>> instructionEncodings; std::vector<FwdUniquePtr<const Instruction>> instructions; std::unordered_map<InstructionType, std::vector<const Instruction*>> primaryInstructionsByInstructionTypes; std::unordered_map<const Instruction*, std::vector<const Instruction*>> specializationsByInstructions; std::unordered_map<const Definition*, std::vector<Definition*>> registerDecompositions; std::vector<std::unique_ptr<BuiltinModeAttribute>> modeAttributes; std::unordered_map<StringView, std::size_t> modeAttributesByName; }; } #endif
3,044
669
<gh_stars>100-1000 // Copyright 2019 <NAME> // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// #include "model_integrator_test.h" namespace mpcc{ int testIntegrator(const PathToJson &path){ double Ts = 0.02; const Integrator integrator = Integrator(Ts,path); // test integrator by comparing Euler forward to RK4 // 3 differnet test points, hand picked, going straight and random //Integrator integrator; ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Hand picked x and u StateVector error1; State xk1 = {0,0,0,2,0.1,-0.3,0.1,0.2,-0.1,2}; Input uk1 = {0.2,-0.1,0}; error1 = stateToVector(integrator.EF(xk1,uk1,Ts)) - stateToVector(integrator.RK4(xk1,uk1,Ts)); std::cout << "hand picked point RK4 - EF error = " << error1.norm() << std::endl; ////////////////////////////////////////////////////////////////////////////////////////////////////////// // x and u corresponding to going straight with 1m/s StateVector error2; State xk2 = {0,0,0,1,0,0,0,0,0,0}; Input uk2 ={0,0,0}; error2 = stateToVector(integrator.EF(xk2,uk2,Ts)) - stateToVector(integrator.RK4(xk2,uk2,Ts)); std::cout << "straight RK4 - EF error = " << error2.norm() << std::endl; ////////////////////////////////////////////////////////////////////////////////////////////////////////// // random x and u StateVector error3; StateVector xkr = StateVector::Random(); InputVector ukr = InputVector::Random(); State xk3 = vectorToState(xkr); Input uk3 = vectorToInput(ukr); error3 = stateToVector(integrator.EF(xk3,uk3,Ts)) - stateToVector(integrator.RK4(xk3,uk3,Ts)); std::cout << "random RK4 - EF error = " << error3.norm() << std::endl; ////////////////////////////////////////////////////////////////////////////////////////////////////////// // test how good fit is if(error1.norm()/10.0 <= 0.3 && error2.norm()/10.0 <= 0.3 && error3.norm()/10.0 <= 0.3 ){ return 1; } else{ return 0; } } int testLinModel(const PathToJson &path){ // test Liniear model by comparing it to RK4 // 3 differnet test cases, hand picked, going straight and test how good linear model generalizes double Ts = 0.02; const Integrator integrator = Integrator(0.02,path); const Model model = Model(0.02,path); ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Hand picked x and u StateVector error1; State xk1 = {0,0,0,2,0.1,-0.3,0.1,0.2,-0.1,2}; Input uk1 = {0.2,-0.1,0}; StateVector xk1_vec = stateToVector(xk1); InputVector uk1_vec = inputToVector(uk1); const LinModelMatrix lin_model_d1 = model.getLinModel(xk1,uk1); error1 = (lin_model_d1.A*xk1_vec + lin_model_d1.B*uk1_vec + lin_model_d1.g) - stateToVector(integrator.RK4(xk1,uk1,Ts)); std::cout << "hand picked point RK4 - lin error = " << error1.norm() << std::endl; ////////////////////////////////////////////////////////////////////////////////////////////////////////// // x and u corresponding to going straight with 1m/s StateVector error2; State xk2 = {0,0,0,1,0,0,0,0,0,0}; Input uk2 = {0,0,0}; StateVector xk2_vec = stateToVector(xk2); InputVector uk2_vec = inputToVector(uk2); const LinModelMatrix lin_model_d2 = model.getLinModel(xk2,uk2); error2 = (lin_model_d2.A*xk2_vec + lin_model_d2.B*uk2_vec + lin_model_d2.g) - stateToVector(integrator.RK4(xk2,uk2,Ts)); std::cout << "straight RK4 - lin error = " << error2.norm() << std::endl; ////////////////////////////////////////////////////////////////////////////////////////////////////////// // generalization test // perturbe xk1 slightly, however us the model linearized around xk1 and uk1 StateVector error3; State xk3; // xk3 is slightly perturbed version of xk1 xk3 = xk1; xk3.vx += 0.2; //vx xk3.vy += 0.05; //vy xk3.r += 0.8; //r xk3.D += 0.2; //D xk3.delta -= 0.05; //delta Input uk3; uk3 = uk1; //still linearize around xk1 and uk1 StateVector xk3_vec = stateToVector(xk3); InputVector uk3_vec = inputToVector(uk3); error3 = (lin_model_d1.A*xk3_vec + lin_model_d1.B*uk3_vec + lin_model_d1.g) - stateToVector(integrator.RK4(xk3,uk3,Ts)); // std::cout << error3 << std::endl; std::cout << "generalization test RK4 - lin error = " << error3.norm() << std::endl; if(error1.norm()/10.0 <= 0.03 && error2.norm()/10.0 <= 0.03){ return 1; } else{ return 0; } } }
1,931
2,542
// Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: cri-api.proto // Original file comments: // To regenerate api.pb.go run hack/update-generated-runtime.sh #ifndef GRPC_cri_2dapi_2eproto__INCLUDED #define GRPC_cri_2dapi_2eproto__INCLUDED #include "cri-api.pb.h" #include <grpc++/impl/codegen/async_stream.h> #include <grpc++/impl/codegen/async_unary_call.h> #include <grpc++/impl/codegen/method_handler_impl.h> #include <grpc++/impl/codegen/proto_utils.h> #include <grpc++/impl/codegen/rpc_method.h> #include <grpc++/impl/codegen/service_type.h> #include <grpc++/impl/codegen/status.h> #include <grpc++/impl/codegen/stub_options.h> #include <grpc++/impl/codegen/sync_stream.h> namespace grpc { class CompletionQueue; class Channel; class ServerCompletionQueue; class ServerContext; } // namespace grpc namespace runtime { // import "github.com/gogo/protobuf/gogoproto/gogo.proto"; // // option (gogoproto.goproto_stringer_all) = false; // option (gogoproto.stringer_all) = true; // option (gogoproto.goproto_getters_all) = true; // option (gogoproto.marshaler_all) = true; // option (gogoproto.sizer_all) = true; // option (gogoproto.unmarshaler_all) = true; // option (gogoproto.goproto_unrecognized_all) = false; // // Runtime service defines the public APIs for remote container runtimes class RuntimeService final { public: static constexpr char const* service_full_name() { return "runtime.RuntimeService"; } class StubInterface { public: virtual ~StubInterface() {} // Version returns the runtime name, runtime version, and runtime API version. virtual ::grpc::Status Version(::grpc::ClientContext* context, const ::runtime::VersionRequest& request, ::runtime::VersionResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::VersionResponse>> AsyncVersion(::grpc::ClientContext* context, const ::runtime::VersionRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::VersionResponse>>(AsyncVersionRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::VersionResponse>> PrepareAsyncVersion(::grpc::ClientContext* context, const ::runtime::VersionRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::VersionResponse>>(PrepareAsyncVersionRaw(context, request, cq)); } // RunPodSandbox creates and starts a pod-level sandbox. Runtimes must ensure // the sandbox is in the ready state on success. virtual ::grpc::Status RunPodSandbox(::grpc::ClientContext* context, const ::runtime::RunPodSandboxRequest& request, ::runtime::RunPodSandboxResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RunPodSandboxResponse>> AsyncRunPodSandbox(::grpc::ClientContext* context, const ::runtime::RunPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RunPodSandboxResponse>>(AsyncRunPodSandboxRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RunPodSandboxResponse>> PrepareAsyncRunPodSandbox(::grpc::ClientContext* context, const ::runtime::RunPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RunPodSandboxResponse>>(PrepareAsyncRunPodSandboxRaw(context, request, cq)); } // StopPodSandbox stops any running process that is part of the sandbox and // reclaims network resources (e.g., IP addresses) allocated to the sandbox. // If there are any running containers in the sandbox, they must be forcibly // terminated. // This call is idempotent, and must not return an error if all relevant // resources have already been reclaimed. kubelet will call StopPodSandbox // at least once before calling RemovePodSandbox. It will also attempt to // reclaim resources eagerly, as soon as a sandbox is not needed. Hence, // multiple StopPodSandbox calls are expected. virtual ::grpc::Status StopPodSandbox(::grpc::ClientContext* context, const ::runtime::StopPodSandboxRequest& request, ::runtime::StopPodSandboxResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopPodSandboxResponse>> AsyncStopPodSandbox(::grpc::ClientContext* context, const ::runtime::StopPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopPodSandboxResponse>>(AsyncStopPodSandboxRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopPodSandboxResponse>> PrepareAsyncStopPodSandbox(::grpc::ClientContext* context, const ::runtime::StopPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopPodSandboxResponse>>(PrepareAsyncStopPodSandboxRaw(context, request, cq)); } // RemovePodSandbox removes the sandbox. If there are any running containers // in the sandbox, they must be forcibly terminated and removed. // This call is idempotent, and must not return an error if the sandbox has // already been removed. virtual ::grpc::Status RemovePodSandbox(::grpc::ClientContext* context, const ::runtime::RemovePodSandboxRequest& request, ::runtime::RemovePodSandboxResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemovePodSandboxResponse>> AsyncRemovePodSandbox(::grpc::ClientContext* context, const ::runtime::RemovePodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemovePodSandboxResponse>>(AsyncRemovePodSandboxRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemovePodSandboxResponse>> PrepareAsyncRemovePodSandbox(::grpc::ClientContext* context, const ::runtime::RemovePodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemovePodSandboxResponse>>(PrepareAsyncRemovePodSandboxRaw(context, request, cq)); } // PodSandboxStatus returns the status of the PodSandbox. If the PodSandbox is not // present, returns an error. virtual ::grpc::Status PodSandboxStatus(::grpc::ClientContext* context, const ::runtime::PodSandboxStatusRequest& request, ::runtime::PodSandboxStatusResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PodSandboxStatusResponse>> AsyncPodSandboxStatus(::grpc::ClientContext* context, const ::runtime::PodSandboxStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PodSandboxStatusResponse>>(AsyncPodSandboxStatusRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PodSandboxStatusResponse>> PrepareAsyncPodSandboxStatus(::grpc::ClientContext* context, const ::runtime::PodSandboxStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PodSandboxStatusResponse>>(PrepareAsyncPodSandboxStatusRaw(context, request, cq)); } // ListPodSandbox returns a list of PodSandboxes. virtual ::grpc::Status ListPodSandbox(::grpc::ClientContext* context, const ::runtime::ListPodSandboxRequest& request, ::runtime::ListPodSandboxResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListPodSandboxResponse>> AsyncListPodSandbox(::grpc::ClientContext* context, const ::runtime::ListPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListPodSandboxResponse>>(AsyncListPodSandboxRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListPodSandboxResponse>> PrepareAsyncListPodSandbox(::grpc::ClientContext* context, const ::runtime::ListPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListPodSandboxResponse>>(PrepareAsyncListPodSandboxRaw(context, request, cq)); } // CreateContainer creates a new container in specified PodSandbox virtual ::grpc::Status CreateContainer(::grpc::ClientContext* context, const ::runtime::CreateContainerRequest& request, ::runtime::CreateContainerResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::CreateContainerResponse>> AsyncCreateContainer(::grpc::ClientContext* context, const ::runtime::CreateContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::CreateContainerResponse>>(AsyncCreateContainerRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::CreateContainerResponse>> PrepareAsyncCreateContainer(::grpc::ClientContext* context, const ::runtime::CreateContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::CreateContainerResponse>>(PrepareAsyncCreateContainerRaw(context, request, cq)); } // StartContainer starts the container. virtual ::grpc::Status StartContainer(::grpc::ClientContext* context, const ::runtime::StartContainerRequest& request, ::runtime::StartContainerResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StartContainerResponse>> AsyncStartContainer(::grpc::ClientContext* context, const ::runtime::StartContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StartContainerResponse>>(AsyncStartContainerRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StartContainerResponse>> PrepareAsyncStartContainer(::grpc::ClientContext* context, const ::runtime::StartContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StartContainerResponse>>(PrepareAsyncStartContainerRaw(context, request, cq)); } // StopContainer stops a running container with a grace period (i.e., timeout). // This call is idempotent, and must not return an error if the container has // already been stopped. // TODO: what must the runtime do after the grace period is reached? virtual ::grpc::Status StopContainer(::grpc::ClientContext* context, const ::runtime::StopContainerRequest& request, ::runtime::StopContainerResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopContainerResponse>> AsyncStopContainer(::grpc::ClientContext* context, const ::runtime::StopContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopContainerResponse>>(AsyncStopContainerRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopContainerResponse>> PrepareAsyncStopContainer(::grpc::ClientContext* context, const ::runtime::StopContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopContainerResponse>>(PrepareAsyncStopContainerRaw(context, request, cq)); } // RemoveContainer removes the container. If the container is running, the // container must be forcibly removed. // This call is idempotent, and must not return an error if the container has // already been removed. virtual ::grpc::Status RemoveContainer(::grpc::ClientContext* context, const ::runtime::RemoveContainerRequest& request, ::runtime::RemoveContainerResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveContainerResponse>> AsyncRemoveContainer(::grpc::ClientContext* context, const ::runtime::RemoveContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveContainerResponse>>(AsyncRemoveContainerRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveContainerResponse>> PrepareAsyncRemoveContainer(::grpc::ClientContext* context, const ::runtime::RemoveContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveContainerResponse>>(PrepareAsyncRemoveContainerRaw(context, request, cq)); } // ListContainers lists all containers by filters. virtual ::grpc::Status ListContainers(::grpc::ClientContext* context, const ::runtime::ListContainersRequest& request, ::runtime::ListContainersResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainersResponse>> AsyncListContainers(::grpc::ClientContext* context, const ::runtime::ListContainersRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainersResponse>>(AsyncListContainersRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainersResponse>> PrepareAsyncListContainers(::grpc::ClientContext* context, const ::runtime::ListContainersRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainersResponse>>(PrepareAsyncListContainersRaw(context, request, cq)); } // ContainerStatus returns status of the container. If the container is not // present, returns an error. virtual ::grpc::Status ContainerStatus(::grpc::ClientContext* context, const ::runtime::ContainerStatusRequest& request, ::runtime::ContainerStatusResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatusResponse>> AsyncContainerStatus(::grpc::ClientContext* context, const ::runtime::ContainerStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatusResponse>>(AsyncContainerStatusRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatusResponse>> PrepareAsyncContainerStatus(::grpc::ClientContext* context, const ::runtime::ContainerStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatusResponse>>(PrepareAsyncContainerStatusRaw(context, request, cq)); } // UpdateContainerResources updates ContainerConfig of the container. virtual ::grpc::Status UpdateContainerResources(::grpc::ClientContext* context, const ::runtime::UpdateContainerResourcesRequest& request, ::runtime::UpdateContainerResourcesResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateContainerResourcesResponse>> AsyncUpdateContainerResources(::grpc::ClientContext* context, const ::runtime::UpdateContainerResourcesRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateContainerResourcesResponse>>(AsyncUpdateContainerResourcesRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateContainerResourcesResponse>> PrepareAsyncUpdateContainerResources(::grpc::ClientContext* context, const ::runtime::UpdateContainerResourcesRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateContainerResourcesResponse>>(PrepareAsyncUpdateContainerResourcesRaw(context, request, cq)); } // ExecSync runs a command in a container synchronously. virtual ::grpc::Status ExecSync(::grpc::ClientContext* context, const ::runtime::ExecSyncRequest& request, ::runtime::ExecSyncResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecSyncResponse>> AsyncExecSync(::grpc::ClientContext* context, const ::runtime::ExecSyncRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecSyncResponse>>(AsyncExecSyncRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecSyncResponse>> PrepareAsyncExecSync(::grpc::ClientContext* context, const ::runtime::ExecSyncRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecSyncResponse>>(PrepareAsyncExecSyncRaw(context, request, cq)); } // Exec prepares a streaming endpoint to execute a command in the container. virtual ::grpc::Status Exec(::grpc::ClientContext* context, const ::runtime::ExecRequest& request, ::runtime::ExecResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecResponse>> AsyncExec(::grpc::ClientContext* context, const ::runtime::ExecRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecResponse>>(AsyncExecRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecResponse>> PrepareAsyncExec(::grpc::ClientContext* context, const ::runtime::ExecRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecResponse>>(PrepareAsyncExecRaw(context, request, cq)); } // Attach prepares a streaming endpoint to attach to a running container. virtual ::grpc::Status Attach(::grpc::ClientContext* context, const ::runtime::AttachRequest& request, ::runtime::AttachResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::AttachResponse>> AsyncAttach(::grpc::ClientContext* context, const ::runtime::AttachRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::AttachResponse>>(AsyncAttachRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::AttachResponse>> PrepareAsyncAttach(::grpc::ClientContext* context, const ::runtime::AttachRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::AttachResponse>>(PrepareAsyncAttachRaw(context, request, cq)); } // PortForward prepares a streaming endpoint to forward ports from a PodSandbox. virtual ::grpc::Status PortForward(::grpc::ClientContext* context, const ::runtime::PortForwardRequest& request, ::runtime::PortForwardResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PortForwardResponse>> AsyncPortForward(::grpc::ClientContext* context, const ::runtime::PortForwardRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PortForwardResponse>>(AsyncPortForwardRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PortForwardResponse>> PrepareAsyncPortForward(::grpc::ClientContext* context, const ::runtime::PortForwardRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PortForwardResponse>>(PrepareAsyncPortForwardRaw(context, request, cq)); } // ContainerStats returns stats of the container. If the container does not // exist, the call returns an error. virtual ::grpc::Status ContainerStats(::grpc::ClientContext* context, const ::runtime::ContainerStatsRequest& request, ::runtime::ContainerStatsResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatsResponse>> AsyncContainerStats(::grpc::ClientContext* context, const ::runtime::ContainerStatsRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatsResponse>>(AsyncContainerStatsRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatsResponse>> PrepareAsyncContainerStats(::grpc::ClientContext* context, const ::runtime::ContainerStatsRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatsResponse>>(PrepareAsyncContainerStatsRaw(context, request, cq)); } // ListContainerStats returns stats of all running containers. virtual ::grpc::Status ListContainerStats(::grpc::ClientContext* context, const ::runtime::ListContainerStatsRequest& request, ::runtime::ListContainerStatsResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainerStatsResponse>> AsyncListContainerStats(::grpc::ClientContext* context, const ::runtime::ListContainerStatsRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainerStatsResponse>>(AsyncListContainerStatsRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainerStatsResponse>> PrepareAsyncListContainerStats(::grpc::ClientContext* context, const ::runtime::ListContainerStatsRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainerStatsResponse>>(PrepareAsyncListContainerStatsRaw(context, request, cq)); } // UpdateRuntimeConfig updates the runtime configuration based on the given request. virtual ::grpc::Status UpdateRuntimeConfig(::grpc::ClientContext* context, const ::runtime::UpdateRuntimeConfigRequest& request, ::runtime::UpdateRuntimeConfigResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateRuntimeConfigResponse>> AsyncUpdateRuntimeConfig(::grpc::ClientContext* context, const ::runtime::UpdateRuntimeConfigRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateRuntimeConfigResponse>>(AsyncUpdateRuntimeConfigRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateRuntimeConfigResponse>> PrepareAsyncUpdateRuntimeConfig(::grpc::ClientContext* context, const ::runtime::UpdateRuntimeConfigRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateRuntimeConfigResponse>>(PrepareAsyncUpdateRuntimeConfigRaw(context, request, cq)); } // Status returns the status of the runtime. virtual ::grpc::Status Status(::grpc::ClientContext* context, const ::runtime::StatusRequest& request, ::runtime::StatusResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StatusResponse>> AsyncStatus(::grpc::ClientContext* context, const ::runtime::StatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StatusResponse>>(AsyncStatusRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StatusResponse>> PrepareAsyncStatus(::grpc::ClientContext* context, const ::runtime::StatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StatusResponse>>(PrepareAsyncStatusRaw(context, request, cq)); } private: virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::VersionResponse>* AsyncVersionRaw(::grpc::ClientContext* context, const ::runtime::VersionRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::VersionResponse>* PrepareAsyncVersionRaw(::grpc::ClientContext* context, const ::runtime::VersionRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RunPodSandboxResponse>* AsyncRunPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::RunPodSandboxRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RunPodSandboxResponse>* PrepareAsyncRunPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::RunPodSandboxRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopPodSandboxResponse>* AsyncStopPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::StopPodSandboxRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopPodSandboxResponse>* PrepareAsyncStopPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::StopPodSandboxRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemovePodSandboxResponse>* AsyncRemovePodSandboxRaw(::grpc::ClientContext* context, const ::runtime::RemovePodSandboxRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemovePodSandboxResponse>* PrepareAsyncRemovePodSandboxRaw(::grpc::ClientContext* context, const ::runtime::RemovePodSandboxRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PodSandboxStatusResponse>* AsyncPodSandboxStatusRaw(::grpc::ClientContext* context, const ::runtime::PodSandboxStatusRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PodSandboxStatusResponse>* PrepareAsyncPodSandboxStatusRaw(::grpc::ClientContext* context, const ::runtime::PodSandboxStatusRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListPodSandboxResponse>* AsyncListPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::ListPodSandboxRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListPodSandboxResponse>* PrepareAsyncListPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::ListPodSandboxRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::CreateContainerResponse>* AsyncCreateContainerRaw(::grpc::ClientContext* context, const ::runtime::CreateContainerRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::CreateContainerResponse>* PrepareAsyncCreateContainerRaw(::grpc::ClientContext* context, const ::runtime::CreateContainerRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StartContainerResponse>* AsyncStartContainerRaw(::grpc::ClientContext* context, const ::runtime::StartContainerRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StartContainerResponse>* PrepareAsyncStartContainerRaw(::grpc::ClientContext* context, const ::runtime::StartContainerRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopContainerResponse>* AsyncStopContainerRaw(::grpc::ClientContext* context, const ::runtime::StopContainerRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StopContainerResponse>* PrepareAsyncStopContainerRaw(::grpc::ClientContext* context, const ::runtime::StopContainerRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveContainerResponse>* AsyncRemoveContainerRaw(::grpc::ClientContext* context, const ::runtime::RemoveContainerRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveContainerResponse>* PrepareAsyncRemoveContainerRaw(::grpc::ClientContext* context, const ::runtime::RemoveContainerRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainersResponse>* AsyncListContainersRaw(::grpc::ClientContext* context, const ::runtime::ListContainersRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainersResponse>* PrepareAsyncListContainersRaw(::grpc::ClientContext* context, const ::runtime::ListContainersRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatusResponse>* AsyncContainerStatusRaw(::grpc::ClientContext* context, const ::runtime::ContainerStatusRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatusResponse>* PrepareAsyncContainerStatusRaw(::grpc::ClientContext* context, const ::runtime::ContainerStatusRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateContainerResourcesResponse>* AsyncUpdateContainerResourcesRaw(::grpc::ClientContext* context, const ::runtime::UpdateContainerResourcesRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateContainerResourcesResponse>* PrepareAsyncUpdateContainerResourcesRaw(::grpc::ClientContext* context, const ::runtime::UpdateContainerResourcesRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecSyncResponse>* AsyncExecSyncRaw(::grpc::ClientContext* context, const ::runtime::ExecSyncRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecSyncResponse>* PrepareAsyncExecSyncRaw(::grpc::ClientContext* context, const ::runtime::ExecSyncRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecResponse>* AsyncExecRaw(::grpc::ClientContext* context, const ::runtime::ExecRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ExecResponse>* PrepareAsyncExecRaw(::grpc::ClientContext* context, const ::runtime::ExecRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::AttachResponse>* AsyncAttachRaw(::grpc::ClientContext* context, const ::runtime::AttachRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::AttachResponse>* PrepareAsyncAttachRaw(::grpc::ClientContext* context, const ::runtime::AttachRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PortForwardResponse>* AsyncPortForwardRaw(::grpc::ClientContext* context, const ::runtime::PortForwardRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PortForwardResponse>* PrepareAsyncPortForwardRaw(::grpc::ClientContext* context, const ::runtime::PortForwardRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatsResponse>* AsyncContainerStatsRaw(::grpc::ClientContext* context, const ::runtime::ContainerStatsRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ContainerStatsResponse>* PrepareAsyncContainerStatsRaw(::grpc::ClientContext* context, const ::runtime::ContainerStatsRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainerStatsResponse>* AsyncListContainerStatsRaw(::grpc::ClientContext* context, const ::runtime::ListContainerStatsRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListContainerStatsResponse>* PrepareAsyncListContainerStatsRaw(::grpc::ClientContext* context, const ::runtime::ListContainerStatsRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateRuntimeConfigResponse>* AsyncUpdateRuntimeConfigRaw(::grpc::ClientContext* context, const ::runtime::UpdateRuntimeConfigRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::UpdateRuntimeConfigResponse>* PrepareAsyncUpdateRuntimeConfigRaw(::grpc::ClientContext* context, const ::runtime::UpdateRuntimeConfigRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StatusResponse>* AsyncStatusRaw(::grpc::ClientContext* context, const ::runtime::StatusRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::StatusResponse>* PrepareAsyncStatusRaw(::grpc::ClientContext* context, const ::runtime::StatusRequest& request, ::grpc::CompletionQueue* cq) = 0; }; class Stub final : public StubInterface { public: Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); ::grpc::Status Version(::grpc::ClientContext* context, const ::runtime::VersionRequest& request, ::runtime::VersionResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::VersionResponse>> AsyncVersion(::grpc::ClientContext* context, const ::runtime::VersionRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::VersionResponse>>(AsyncVersionRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::VersionResponse>> PrepareAsyncVersion(::grpc::ClientContext* context, const ::runtime::VersionRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::VersionResponse>>(PrepareAsyncVersionRaw(context, request, cq)); } ::grpc::Status RunPodSandbox(::grpc::ClientContext* context, const ::runtime::RunPodSandboxRequest& request, ::runtime::RunPodSandboxResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RunPodSandboxResponse>> AsyncRunPodSandbox(::grpc::ClientContext* context, const ::runtime::RunPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RunPodSandboxResponse>>(AsyncRunPodSandboxRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RunPodSandboxResponse>> PrepareAsyncRunPodSandbox(::grpc::ClientContext* context, const ::runtime::RunPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RunPodSandboxResponse>>(PrepareAsyncRunPodSandboxRaw(context, request, cq)); } ::grpc::Status StopPodSandbox(::grpc::ClientContext* context, const ::runtime::StopPodSandboxRequest& request, ::runtime::StopPodSandboxResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StopPodSandboxResponse>> AsyncStopPodSandbox(::grpc::ClientContext* context, const ::runtime::StopPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StopPodSandboxResponse>>(AsyncStopPodSandboxRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StopPodSandboxResponse>> PrepareAsyncStopPodSandbox(::grpc::ClientContext* context, const ::runtime::StopPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StopPodSandboxResponse>>(PrepareAsyncStopPodSandboxRaw(context, request, cq)); } ::grpc::Status RemovePodSandbox(::grpc::ClientContext* context, const ::runtime::RemovePodSandboxRequest& request, ::runtime::RemovePodSandboxResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemovePodSandboxResponse>> AsyncRemovePodSandbox(::grpc::ClientContext* context, const ::runtime::RemovePodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemovePodSandboxResponse>>(AsyncRemovePodSandboxRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemovePodSandboxResponse>> PrepareAsyncRemovePodSandbox(::grpc::ClientContext* context, const ::runtime::RemovePodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemovePodSandboxResponse>>(PrepareAsyncRemovePodSandboxRaw(context, request, cq)); } ::grpc::Status PodSandboxStatus(::grpc::ClientContext* context, const ::runtime::PodSandboxStatusRequest& request, ::runtime::PodSandboxStatusResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PodSandboxStatusResponse>> AsyncPodSandboxStatus(::grpc::ClientContext* context, const ::runtime::PodSandboxStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PodSandboxStatusResponse>>(AsyncPodSandboxStatusRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PodSandboxStatusResponse>> PrepareAsyncPodSandboxStatus(::grpc::ClientContext* context, const ::runtime::PodSandboxStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PodSandboxStatusResponse>>(PrepareAsyncPodSandboxStatusRaw(context, request, cq)); } ::grpc::Status ListPodSandbox(::grpc::ClientContext* context, const ::runtime::ListPodSandboxRequest& request, ::runtime::ListPodSandboxResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListPodSandboxResponse>> AsyncListPodSandbox(::grpc::ClientContext* context, const ::runtime::ListPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListPodSandboxResponse>>(AsyncListPodSandboxRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListPodSandboxResponse>> PrepareAsyncListPodSandbox(::grpc::ClientContext* context, const ::runtime::ListPodSandboxRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListPodSandboxResponse>>(PrepareAsyncListPodSandboxRaw(context, request, cq)); } ::grpc::Status CreateContainer(::grpc::ClientContext* context, const ::runtime::CreateContainerRequest& request, ::runtime::CreateContainerResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::CreateContainerResponse>> AsyncCreateContainer(::grpc::ClientContext* context, const ::runtime::CreateContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::CreateContainerResponse>>(AsyncCreateContainerRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::CreateContainerResponse>> PrepareAsyncCreateContainer(::grpc::ClientContext* context, const ::runtime::CreateContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::CreateContainerResponse>>(PrepareAsyncCreateContainerRaw(context, request, cq)); } ::grpc::Status StartContainer(::grpc::ClientContext* context, const ::runtime::StartContainerRequest& request, ::runtime::StartContainerResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StartContainerResponse>> AsyncStartContainer(::grpc::ClientContext* context, const ::runtime::StartContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StartContainerResponse>>(AsyncStartContainerRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StartContainerResponse>> PrepareAsyncStartContainer(::grpc::ClientContext* context, const ::runtime::StartContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StartContainerResponse>>(PrepareAsyncStartContainerRaw(context, request, cq)); } ::grpc::Status StopContainer(::grpc::ClientContext* context, const ::runtime::StopContainerRequest& request, ::runtime::StopContainerResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StopContainerResponse>> AsyncStopContainer(::grpc::ClientContext* context, const ::runtime::StopContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StopContainerResponse>>(AsyncStopContainerRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StopContainerResponse>> PrepareAsyncStopContainer(::grpc::ClientContext* context, const ::runtime::StopContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StopContainerResponse>>(PrepareAsyncStopContainerRaw(context, request, cq)); } ::grpc::Status RemoveContainer(::grpc::ClientContext* context, const ::runtime::RemoveContainerRequest& request, ::runtime::RemoveContainerResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemoveContainerResponse>> AsyncRemoveContainer(::grpc::ClientContext* context, const ::runtime::RemoveContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemoveContainerResponse>>(AsyncRemoveContainerRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemoveContainerResponse>> PrepareAsyncRemoveContainer(::grpc::ClientContext* context, const ::runtime::RemoveContainerRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemoveContainerResponse>>(PrepareAsyncRemoveContainerRaw(context, request, cq)); } ::grpc::Status ListContainers(::grpc::ClientContext* context, const ::runtime::ListContainersRequest& request, ::runtime::ListContainersResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListContainersResponse>> AsyncListContainers(::grpc::ClientContext* context, const ::runtime::ListContainersRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListContainersResponse>>(AsyncListContainersRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListContainersResponse>> PrepareAsyncListContainers(::grpc::ClientContext* context, const ::runtime::ListContainersRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListContainersResponse>>(PrepareAsyncListContainersRaw(context, request, cq)); } ::grpc::Status ContainerStatus(::grpc::ClientContext* context, const ::runtime::ContainerStatusRequest& request, ::runtime::ContainerStatusResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatusResponse>> AsyncContainerStatus(::grpc::ClientContext* context, const ::runtime::ContainerStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatusResponse>>(AsyncContainerStatusRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatusResponse>> PrepareAsyncContainerStatus(::grpc::ClientContext* context, const ::runtime::ContainerStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatusResponse>>(PrepareAsyncContainerStatusRaw(context, request, cq)); } ::grpc::Status UpdateContainerResources(::grpc::ClientContext* context, const ::runtime::UpdateContainerResourcesRequest& request, ::runtime::UpdateContainerResourcesResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::UpdateContainerResourcesResponse>> AsyncUpdateContainerResources(::grpc::ClientContext* context, const ::runtime::UpdateContainerResourcesRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::UpdateContainerResourcesResponse>>(AsyncUpdateContainerResourcesRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::UpdateContainerResourcesResponse>> PrepareAsyncUpdateContainerResources(::grpc::ClientContext* context, const ::runtime::UpdateContainerResourcesRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::UpdateContainerResourcesResponse>>(PrepareAsyncUpdateContainerResourcesRaw(context, request, cq)); } ::grpc::Status ExecSync(::grpc::ClientContext* context, const ::runtime::ExecSyncRequest& request, ::runtime::ExecSyncResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ExecSyncResponse>> AsyncExecSync(::grpc::ClientContext* context, const ::runtime::ExecSyncRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ExecSyncResponse>>(AsyncExecSyncRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ExecSyncResponse>> PrepareAsyncExecSync(::grpc::ClientContext* context, const ::runtime::ExecSyncRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ExecSyncResponse>>(PrepareAsyncExecSyncRaw(context, request, cq)); } ::grpc::Status Exec(::grpc::ClientContext* context, const ::runtime::ExecRequest& request, ::runtime::ExecResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ExecResponse>> AsyncExec(::grpc::ClientContext* context, const ::runtime::ExecRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ExecResponse>>(AsyncExecRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ExecResponse>> PrepareAsyncExec(::grpc::ClientContext* context, const ::runtime::ExecRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ExecResponse>>(PrepareAsyncExecRaw(context, request, cq)); } ::grpc::Status Attach(::grpc::ClientContext* context, const ::runtime::AttachRequest& request, ::runtime::AttachResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::AttachResponse>> AsyncAttach(::grpc::ClientContext* context, const ::runtime::AttachRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::AttachResponse>>(AsyncAttachRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::AttachResponse>> PrepareAsyncAttach(::grpc::ClientContext* context, const ::runtime::AttachRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::AttachResponse>>(PrepareAsyncAttachRaw(context, request, cq)); } ::grpc::Status PortForward(::grpc::ClientContext* context, const ::runtime::PortForwardRequest& request, ::runtime::PortForwardResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PortForwardResponse>> AsyncPortForward(::grpc::ClientContext* context, const ::runtime::PortForwardRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PortForwardResponse>>(AsyncPortForwardRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PortForwardResponse>> PrepareAsyncPortForward(::grpc::ClientContext* context, const ::runtime::PortForwardRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PortForwardResponse>>(PrepareAsyncPortForwardRaw(context, request, cq)); } ::grpc::Status ContainerStats(::grpc::ClientContext* context, const ::runtime::ContainerStatsRequest& request, ::runtime::ContainerStatsResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatsResponse>> AsyncContainerStats(::grpc::ClientContext* context, const ::runtime::ContainerStatsRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatsResponse>>(AsyncContainerStatsRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatsResponse>> PrepareAsyncContainerStats(::grpc::ClientContext* context, const ::runtime::ContainerStatsRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatsResponse>>(PrepareAsyncContainerStatsRaw(context, request, cq)); } ::grpc::Status ListContainerStats(::grpc::ClientContext* context, const ::runtime::ListContainerStatsRequest& request, ::runtime::ListContainerStatsResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListContainerStatsResponse>> AsyncListContainerStats(::grpc::ClientContext* context, const ::runtime::ListContainerStatsRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListContainerStatsResponse>>(AsyncListContainerStatsRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListContainerStatsResponse>> PrepareAsyncListContainerStats(::grpc::ClientContext* context, const ::runtime::ListContainerStatsRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListContainerStatsResponse>>(PrepareAsyncListContainerStatsRaw(context, request, cq)); } ::grpc::Status UpdateRuntimeConfig(::grpc::ClientContext* context, const ::runtime::UpdateRuntimeConfigRequest& request, ::runtime::UpdateRuntimeConfigResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::UpdateRuntimeConfigResponse>> AsyncUpdateRuntimeConfig(::grpc::ClientContext* context, const ::runtime::UpdateRuntimeConfigRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::UpdateRuntimeConfigResponse>>(AsyncUpdateRuntimeConfigRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::UpdateRuntimeConfigResponse>> PrepareAsyncUpdateRuntimeConfig(::grpc::ClientContext* context, const ::runtime::UpdateRuntimeConfigRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::UpdateRuntimeConfigResponse>>(PrepareAsyncUpdateRuntimeConfigRaw(context, request, cq)); } ::grpc::Status Status(::grpc::ClientContext* context, const ::runtime::StatusRequest& request, ::runtime::StatusResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StatusResponse>> AsyncStatus(::grpc::ClientContext* context, const ::runtime::StatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StatusResponse>>(AsyncStatusRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StatusResponse>> PrepareAsyncStatus(::grpc::ClientContext* context, const ::runtime::StatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::StatusResponse>>(PrepareAsyncStatusRaw(context, request, cq)); } private: std::shared_ptr< ::grpc::ChannelInterface> channel_; ::grpc::ClientAsyncResponseReader< ::runtime::VersionResponse>* AsyncVersionRaw(::grpc::ClientContext* context, const ::runtime::VersionRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::VersionResponse>* PrepareAsyncVersionRaw(::grpc::ClientContext* context, const ::runtime::VersionRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::RunPodSandboxResponse>* AsyncRunPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::RunPodSandboxRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::RunPodSandboxResponse>* PrepareAsyncRunPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::RunPodSandboxRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::StopPodSandboxResponse>* AsyncStopPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::StopPodSandboxRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::StopPodSandboxResponse>* PrepareAsyncStopPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::StopPodSandboxRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::RemovePodSandboxResponse>* AsyncRemovePodSandboxRaw(::grpc::ClientContext* context, const ::runtime::RemovePodSandboxRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::RemovePodSandboxResponse>* PrepareAsyncRemovePodSandboxRaw(::grpc::ClientContext* context, const ::runtime::RemovePodSandboxRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::PodSandboxStatusResponse>* AsyncPodSandboxStatusRaw(::grpc::ClientContext* context, const ::runtime::PodSandboxStatusRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::PodSandboxStatusResponse>* PrepareAsyncPodSandboxStatusRaw(::grpc::ClientContext* context, const ::runtime::PodSandboxStatusRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ListPodSandboxResponse>* AsyncListPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::ListPodSandboxRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ListPodSandboxResponse>* PrepareAsyncListPodSandboxRaw(::grpc::ClientContext* context, const ::runtime::ListPodSandboxRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::CreateContainerResponse>* AsyncCreateContainerRaw(::grpc::ClientContext* context, const ::runtime::CreateContainerRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::CreateContainerResponse>* PrepareAsyncCreateContainerRaw(::grpc::ClientContext* context, const ::runtime::CreateContainerRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::StartContainerResponse>* AsyncStartContainerRaw(::grpc::ClientContext* context, const ::runtime::StartContainerRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::StartContainerResponse>* PrepareAsyncStartContainerRaw(::grpc::ClientContext* context, const ::runtime::StartContainerRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::StopContainerResponse>* AsyncStopContainerRaw(::grpc::ClientContext* context, const ::runtime::StopContainerRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::StopContainerResponse>* PrepareAsyncStopContainerRaw(::grpc::ClientContext* context, const ::runtime::StopContainerRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::RemoveContainerResponse>* AsyncRemoveContainerRaw(::grpc::ClientContext* context, const ::runtime::RemoveContainerRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::RemoveContainerResponse>* PrepareAsyncRemoveContainerRaw(::grpc::ClientContext* context, const ::runtime::RemoveContainerRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ListContainersResponse>* AsyncListContainersRaw(::grpc::ClientContext* context, const ::runtime::ListContainersRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ListContainersResponse>* PrepareAsyncListContainersRaw(::grpc::ClientContext* context, const ::runtime::ListContainersRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatusResponse>* AsyncContainerStatusRaw(::grpc::ClientContext* context, const ::runtime::ContainerStatusRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatusResponse>* PrepareAsyncContainerStatusRaw(::grpc::ClientContext* context, const ::runtime::ContainerStatusRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::UpdateContainerResourcesResponse>* AsyncUpdateContainerResourcesRaw(::grpc::ClientContext* context, const ::runtime::UpdateContainerResourcesRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::UpdateContainerResourcesResponse>* PrepareAsyncUpdateContainerResourcesRaw(::grpc::ClientContext* context, const ::runtime::UpdateContainerResourcesRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ExecSyncResponse>* AsyncExecSyncRaw(::grpc::ClientContext* context, const ::runtime::ExecSyncRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ExecSyncResponse>* PrepareAsyncExecSyncRaw(::grpc::ClientContext* context, const ::runtime::ExecSyncRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ExecResponse>* AsyncExecRaw(::grpc::ClientContext* context, const ::runtime::ExecRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ExecResponse>* PrepareAsyncExecRaw(::grpc::ClientContext* context, const ::runtime::ExecRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::AttachResponse>* AsyncAttachRaw(::grpc::ClientContext* context, const ::runtime::AttachRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::AttachResponse>* PrepareAsyncAttachRaw(::grpc::ClientContext* context, const ::runtime::AttachRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::PortForwardResponse>* AsyncPortForwardRaw(::grpc::ClientContext* context, const ::runtime::PortForwardRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::PortForwardResponse>* PrepareAsyncPortForwardRaw(::grpc::ClientContext* context, const ::runtime::PortForwardRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatsResponse>* AsyncContainerStatsRaw(::grpc::ClientContext* context, const ::runtime::ContainerStatsRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ContainerStatsResponse>* PrepareAsyncContainerStatsRaw(::grpc::ClientContext* context, const ::runtime::ContainerStatsRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ListContainerStatsResponse>* AsyncListContainerStatsRaw(::grpc::ClientContext* context, const ::runtime::ListContainerStatsRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ListContainerStatsResponse>* PrepareAsyncListContainerStatsRaw(::grpc::ClientContext* context, const ::runtime::ListContainerStatsRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::UpdateRuntimeConfigResponse>* AsyncUpdateRuntimeConfigRaw(::grpc::ClientContext* context, const ::runtime::UpdateRuntimeConfigRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::UpdateRuntimeConfigResponse>* PrepareAsyncUpdateRuntimeConfigRaw(::grpc::ClientContext* context, const ::runtime::UpdateRuntimeConfigRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::StatusResponse>* AsyncStatusRaw(::grpc::ClientContext* context, const ::runtime::StatusRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::StatusResponse>* PrepareAsyncStatusRaw(::grpc::ClientContext* context, const ::runtime::StatusRequest& request, ::grpc::CompletionQueue* cq) override; const ::grpc::internal::RpcMethod rpcmethod_Version_; const ::grpc::internal::RpcMethod rpcmethod_RunPodSandbox_; const ::grpc::internal::RpcMethod rpcmethod_StopPodSandbox_; const ::grpc::internal::RpcMethod rpcmethod_RemovePodSandbox_; const ::grpc::internal::RpcMethod rpcmethod_PodSandboxStatus_; const ::grpc::internal::RpcMethod rpcmethod_ListPodSandbox_; const ::grpc::internal::RpcMethod rpcmethod_CreateContainer_; const ::grpc::internal::RpcMethod rpcmethod_StartContainer_; const ::grpc::internal::RpcMethod rpcmethod_StopContainer_; const ::grpc::internal::RpcMethod rpcmethod_RemoveContainer_; const ::grpc::internal::RpcMethod rpcmethod_ListContainers_; const ::grpc::internal::RpcMethod rpcmethod_ContainerStatus_; const ::grpc::internal::RpcMethod rpcmethod_UpdateContainerResources_; const ::grpc::internal::RpcMethod rpcmethod_ExecSync_; const ::grpc::internal::RpcMethod rpcmethod_Exec_; const ::grpc::internal::RpcMethod rpcmethod_Attach_; const ::grpc::internal::RpcMethod rpcmethod_PortForward_; const ::grpc::internal::RpcMethod rpcmethod_ContainerStats_; const ::grpc::internal::RpcMethod rpcmethod_ListContainerStats_; const ::grpc::internal::RpcMethod rpcmethod_UpdateRuntimeConfig_; const ::grpc::internal::RpcMethod rpcmethod_Status_; }; static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); class Service : public ::grpc::Service { public: Service(); virtual ~Service(); // Version returns the runtime name, runtime version, and runtime API version. virtual ::grpc::Status Version(::grpc::ServerContext* context, const ::runtime::VersionRequest* request, ::runtime::VersionResponse* response); // RunPodSandbox creates and starts a pod-level sandbox. Runtimes must ensure // the sandbox is in the ready state on success. virtual ::grpc::Status RunPodSandbox(::grpc::ServerContext* context, const ::runtime::RunPodSandboxRequest* request, ::runtime::RunPodSandboxResponse* response); // StopPodSandbox stops any running process that is part of the sandbox and // reclaims network resources (e.g., IP addresses) allocated to the sandbox. // If there are any running containers in the sandbox, they must be forcibly // terminated. // This call is idempotent, and must not return an error if all relevant // resources have already been reclaimed. kubelet will call StopPodSandbox // at least once before calling RemovePodSandbox. It will also attempt to // reclaim resources eagerly, as soon as a sandbox is not needed. Hence, // multiple StopPodSandbox calls are expected. virtual ::grpc::Status StopPodSandbox(::grpc::ServerContext* context, const ::runtime::StopPodSandboxRequest* request, ::runtime::StopPodSandboxResponse* response); // RemovePodSandbox removes the sandbox. If there are any running containers // in the sandbox, they must be forcibly terminated and removed. // This call is idempotent, and must not return an error if the sandbox has // already been removed. virtual ::grpc::Status RemovePodSandbox(::grpc::ServerContext* context, const ::runtime::RemovePodSandboxRequest* request, ::runtime::RemovePodSandboxResponse* response); // PodSandboxStatus returns the status of the PodSandbox. If the PodSandbox is not // present, returns an error. virtual ::grpc::Status PodSandboxStatus(::grpc::ServerContext* context, const ::runtime::PodSandboxStatusRequest* request, ::runtime::PodSandboxStatusResponse* response); // ListPodSandbox returns a list of PodSandboxes. virtual ::grpc::Status ListPodSandbox(::grpc::ServerContext* context, const ::runtime::ListPodSandboxRequest* request, ::runtime::ListPodSandboxResponse* response); // CreateContainer creates a new container in specified PodSandbox virtual ::grpc::Status CreateContainer(::grpc::ServerContext* context, const ::runtime::CreateContainerRequest* request, ::runtime::CreateContainerResponse* response); // StartContainer starts the container. virtual ::grpc::Status StartContainer(::grpc::ServerContext* context, const ::runtime::StartContainerRequest* request, ::runtime::StartContainerResponse* response); // StopContainer stops a running container with a grace period (i.e., timeout). // This call is idempotent, and must not return an error if the container has // already been stopped. // TODO: what must the runtime do after the grace period is reached? virtual ::grpc::Status StopContainer(::grpc::ServerContext* context, const ::runtime::StopContainerRequest* request, ::runtime::StopContainerResponse* response); // RemoveContainer removes the container. If the container is running, the // container must be forcibly removed. // This call is idempotent, and must not return an error if the container has // already been removed. virtual ::grpc::Status RemoveContainer(::grpc::ServerContext* context, const ::runtime::RemoveContainerRequest* request, ::runtime::RemoveContainerResponse* response); // ListContainers lists all containers by filters. virtual ::grpc::Status ListContainers(::grpc::ServerContext* context, const ::runtime::ListContainersRequest* request, ::runtime::ListContainersResponse* response); // ContainerStatus returns status of the container. If the container is not // present, returns an error. virtual ::grpc::Status ContainerStatus(::grpc::ServerContext* context, const ::runtime::ContainerStatusRequest* request, ::runtime::ContainerStatusResponse* response); // UpdateContainerResources updates ContainerConfig of the container. virtual ::grpc::Status UpdateContainerResources(::grpc::ServerContext* context, const ::runtime::UpdateContainerResourcesRequest* request, ::runtime::UpdateContainerResourcesResponse* response); // ExecSync runs a command in a container synchronously. virtual ::grpc::Status ExecSync(::grpc::ServerContext* context, const ::runtime::ExecSyncRequest* request, ::runtime::ExecSyncResponse* response); // Exec prepares a streaming endpoint to execute a command in the container. virtual ::grpc::Status Exec(::grpc::ServerContext* context, const ::runtime::ExecRequest* request, ::runtime::ExecResponse* response); // Attach prepares a streaming endpoint to attach to a running container. virtual ::grpc::Status Attach(::grpc::ServerContext* context, const ::runtime::AttachRequest* request, ::runtime::AttachResponse* response); // PortForward prepares a streaming endpoint to forward ports from a PodSandbox. virtual ::grpc::Status PortForward(::grpc::ServerContext* context, const ::runtime::PortForwardRequest* request, ::runtime::PortForwardResponse* response); // ContainerStats returns stats of the container. If the container does not // exist, the call returns an error. virtual ::grpc::Status ContainerStats(::grpc::ServerContext* context, const ::runtime::ContainerStatsRequest* request, ::runtime::ContainerStatsResponse* response); // ListContainerStats returns stats of all running containers. virtual ::grpc::Status ListContainerStats(::grpc::ServerContext* context, const ::runtime::ListContainerStatsRequest* request, ::runtime::ListContainerStatsResponse* response); // UpdateRuntimeConfig updates the runtime configuration based on the given request. virtual ::grpc::Status UpdateRuntimeConfig(::grpc::ServerContext* context, const ::runtime::UpdateRuntimeConfigRequest* request, ::runtime::UpdateRuntimeConfigResponse* response); // Status returns the status of the runtime. virtual ::grpc::Status Status(::grpc::ServerContext* context, const ::runtime::StatusRequest* request, ::runtime::StatusResponse* response); }; template <class BaseClass> class WithAsyncMethod_Version : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_Version() { ::grpc::Service::MarkMethodAsync(0); } ~WithAsyncMethod_Version() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Version(::grpc::ServerContext* context, const ::runtime::VersionRequest* request, ::runtime::VersionResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestVersion(::grpc::ServerContext* context, ::runtime::VersionRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::VersionResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_RunPodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_RunPodSandbox() { ::grpc::Service::MarkMethodAsync(1); } ~WithAsyncMethod_RunPodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status RunPodSandbox(::grpc::ServerContext* context, const ::runtime::RunPodSandboxRequest* request, ::runtime::RunPodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestRunPodSandbox(::grpc::ServerContext* context, ::runtime::RunPodSandboxRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::RunPodSandboxResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(1, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_StopPodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_StopPodSandbox() { ::grpc::Service::MarkMethodAsync(2); } ~WithAsyncMethod_StopPodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status StopPodSandbox(::grpc::ServerContext* context, const ::runtime::StopPodSandboxRequest* request, ::runtime::StopPodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestStopPodSandbox(::grpc::ServerContext* context, ::runtime::StopPodSandboxRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::StopPodSandboxResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(2, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_RemovePodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_RemovePodSandbox() { ::grpc::Service::MarkMethodAsync(3); } ~WithAsyncMethod_RemovePodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status RemovePodSandbox(::grpc::ServerContext* context, const ::runtime::RemovePodSandboxRequest* request, ::runtime::RemovePodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestRemovePodSandbox(::grpc::ServerContext* context, ::runtime::RemovePodSandboxRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::RemovePodSandboxResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(3, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_PodSandboxStatus : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_PodSandboxStatus() { ::grpc::Service::MarkMethodAsync(4); } ~WithAsyncMethod_PodSandboxStatus() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status PodSandboxStatus(::grpc::ServerContext* context, const ::runtime::PodSandboxStatusRequest* request, ::runtime::PodSandboxStatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestPodSandboxStatus(::grpc::ServerContext* context, ::runtime::PodSandboxStatusRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::PodSandboxStatusResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(4, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_ListPodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_ListPodSandbox() { ::grpc::Service::MarkMethodAsync(5); } ~WithAsyncMethod_ListPodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ListPodSandbox(::grpc::ServerContext* context, const ::runtime::ListPodSandboxRequest* request, ::runtime::ListPodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestListPodSandbox(::grpc::ServerContext* context, ::runtime::ListPodSandboxRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::ListPodSandboxResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(5, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_CreateContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_CreateContainer() { ::grpc::Service::MarkMethodAsync(6); } ~WithAsyncMethod_CreateContainer() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status CreateContainer(::grpc::ServerContext* context, const ::runtime::CreateContainerRequest* request, ::runtime::CreateContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestCreateContainer(::grpc::ServerContext* context, ::runtime::CreateContainerRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::CreateContainerResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(6, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_StartContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_StartContainer() { ::grpc::Service::MarkMethodAsync(7); } ~WithAsyncMethod_StartContainer() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status StartContainer(::grpc::ServerContext* context, const ::runtime::StartContainerRequest* request, ::runtime::StartContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestStartContainer(::grpc::ServerContext* context, ::runtime::StartContainerRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::StartContainerResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(7, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_StopContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_StopContainer() { ::grpc::Service::MarkMethodAsync(8); } ~WithAsyncMethod_StopContainer() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status StopContainer(::grpc::ServerContext* context, const ::runtime::StopContainerRequest* request, ::runtime::StopContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestStopContainer(::grpc::ServerContext* context, ::runtime::StopContainerRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::StopContainerResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(8, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_RemoveContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_RemoveContainer() { ::grpc::Service::MarkMethodAsync(9); } ~WithAsyncMethod_RemoveContainer() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status RemoveContainer(::grpc::ServerContext* context, const ::runtime::RemoveContainerRequest* request, ::runtime::RemoveContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestRemoveContainer(::grpc::ServerContext* context, ::runtime::RemoveContainerRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::RemoveContainerResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(9, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_ListContainers : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_ListContainers() { ::grpc::Service::MarkMethodAsync(10); } ~WithAsyncMethod_ListContainers() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ListContainers(::grpc::ServerContext* context, const ::runtime::ListContainersRequest* request, ::runtime::ListContainersResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestListContainers(::grpc::ServerContext* context, ::runtime::ListContainersRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::ListContainersResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(10, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_ContainerStatus : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_ContainerStatus() { ::grpc::Service::MarkMethodAsync(11); } ~WithAsyncMethod_ContainerStatus() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ContainerStatus(::grpc::ServerContext* context, const ::runtime::ContainerStatusRequest* request, ::runtime::ContainerStatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestContainerStatus(::grpc::ServerContext* context, ::runtime::ContainerStatusRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::ContainerStatusResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(11, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_UpdateContainerResources : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_UpdateContainerResources() { ::grpc::Service::MarkMethodAsync(12); } ~WithAsyncMethod_UpdateContainerResources() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status UpdateContainerResources(::grpc::ServerContext* context, const ::runtime::UpdateContainerResourcesRequest* request, ::runtime::UpdateContainerResourcesResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestUpdateContainerResources(::grpc::ServerContext* context, ::runtime::UpdateContainerResourcesRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::UpdateContainerResourcesResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(12, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_ExecSync : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_ExecSync() { ::grpc::Service::MarkMethodAsync(13); } ~WithAsyncMethod_ExecSync() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ExecSync(::grpc::ServerContext* context, const ::runtime::ExecSyncRequest* request, ::runtime::ExecSyncResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestExecSync(::grpc::ServerContext* context, ::runtime::ExecSyncRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::ExecSyncResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(13, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_Exec : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_Exec() { ::grpc::Service::MarkMethodAsync(14); } ~WithAsyncMethod_Exec() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Exec(::grpc::ServerContext* context, const ::runtime::ExecRequest* request, ::runtime::ExecResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestExec(::grpc::ServerContext* context, ::runtime::ExecRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::ExecResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(14, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_Attach : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_Attach() { ::grpc::Service::MarkMethodAsync(15); } ~WithAsyncMethod_Attach() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Attach(::grpc::ServerContext* context, const ::runtime::AttachRequest* request, ::runtime::AttachResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestAttach(::grpc::ServerContext* context, ::runtime::AttachRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::AttachResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(15, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_PortForward : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_PortForward() { ::grpc::Service::MarkMethodAsync(16); } ~WithAsyncMethod_PortForward() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status PortForward(::grpc::ServerContext* context, const ::runtime::PortForwardRequest* request, ::runtime::PortForwardResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestPortForward(::grpc::ServerContext* context, ::runtime::PortForwardRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::PortForwardResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(16, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_ContainerStats : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_ContainerStats() { ::grpc::Service::MarkMethodAsync(17); } ~WithAsyncMethod_ContainerStats() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ContainerStats(::grpc::ServerContext* context, const ::runtime::ContainerStatsRequest* request, ::runtime::ContainerStatsResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestContainerStats(::grpc::ServerContext* context, ::runtime::ContainerStatsRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::ContainerStatsResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(17, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_ListContainerStats : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_ListContainerStats() { ::grpc::Service::MarkMethodAsync(18); } ~WithAsyncMethod_ListContainerStats() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ListContainerStats(::grpc::ServerContext* context, const ::runtime::ListContainerStatsRequest* request, ::runtime::ListContainerStatsResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestListContainerStats(::grpc::ServerContext* context, ::runtime::ListContainerStatsRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::ListContainerStatsResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(18, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_UpdateRuntimeConfig : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_UpdateRuntimeConfig() { ::grpc::Service::MarkMethodAsync(19); } ~WithAsyncMethod_UpdateRuntimeConfig() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status UpdateRuntimeConfig(::grpc::ServerContext* context, const ::runtime::UpdateRuntimeConfigRequest* request, ::runtime::UpdateRuntimeConfigResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestUpdateRuntimeConfig(::grpc::ServerContext* context, ::runtime::UpdateRuntimeConfigRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::UpdateRuntimeConfigResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(19, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_Status : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_Status() { ::grpc::Service::MarkMethodAsync(20); } ~WithAsyncMethod_Status() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Status(::grpc::ServerContext* context, const ::runtime::StatusRequest* request, ::runtime::StatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestStatus(::grpc::ServerContext* context, ::runtime::StatusRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::StatusResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(20, context, request, response, new_call_cq, notification_cq, tag); } }; typedef WithAsyncMethod_Version<WithAsyncMethod_RunPodSandbox<WithAsyncMethod_StopPodSandbox<WithAsyncMethod_RemovePodSandbox<WithAsyncMethod_PodSandboxStatus<WithAsyncMethod_ListPodSandbox<WithAsyncMethod_CreateContainer<WithAsyncMethod_StartContainer<WithAsyncMethod_StopContainer<WithAsyncMethod_RemoveContainer<WithAsyncMethod_ListContainers<WithAsyncMethod_ContainerStatus<WithAsyncMethod_UpdateContainerResources<WithAsyncMethod_ExecSync<WithAsyncMethod_Exec<WithAsyncMethod_Attach<WithAsyncMethod_PortForward<WithAsyncMethod_ContainerStats<WithAsyncMethod_ListContainerStats<WithAsyncMethod_UpdateRuntimeConfig<WithAsyncMethod_Status<Service > > > > > > > > > > > > > > > > > > > > > AsyncService; template <class BaseClass> class WithGenericMethod_Version : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_Version() { ::grpc::Service::MarkMethodGeneric(0); } ~WithGenericMethod_Version() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Version(::grpc::ServerContext* context, const ::runtime::VersionRequest* request, ::runtime::VersionResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_RunPodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_RunPodSandbox() { ::grpc::Service::MarkMethodGeneric(1); } ~WithGenericMethod_RunPodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status RunPodSandbox(::grpc::ServerContext* context, const ::runtime::RunPodSandboxRequest* request, ::runtime::RunPodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_StopPodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_StopPodSandbox() { ::grpc::Service::MarkMethodGeneric(2); } ~WithGenericMethod_StopPodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status StopPodSandbox(::grpc::ServerContext* context, const ::runtime::StopPodSandboxRequest* request, ::runtime::StopPodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_RemovePodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_RemovePodSandbox() { ::grpc::Service::MarkMethodGeneric(3); } ~WithGenericMethod_RemovePodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status RemovePodSandbox(::grpc::ServerContext* context, const ::runtime::RemovePodSandboxRequest* request, ::runtime::RemovePodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_PodSandboxStatus : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_PodSandboxStatus() { ::grpc::Service::MarkMethodGeneric(4); } ~WithGenericMethod_PodSandboxStatus() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status PodSandboxStatus(::grpc::ServerContext* context, const ::runtime::PodSandboxStatusRequest* request, ::runtime::PodSandboxStatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_ListPodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_ListPodSandbox() { ::grpc::Service::MarkMethodGeneric(5); } ~WithGenericMethod_ListPodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ListPodSandbox(::grpc::ServerContext* context, const ::runtime::ListPodSandboxRequest* request, ::runtime::ListPodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_CreateContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_CreateContainer() { ::grpc::Service::MarkMethodGeneric(6); } ~WithGenericMethod_CreateContainer() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status CreateContainer(::grpc::ServerContext* context, const ::runtime::CreateContainerRequest* request, ::runtime::CreateContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_StartContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_StartContainer() { ::grpc::Service::MarkMethodGeneric(7); } ~WithGenericMethod_StartContainer() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status StartContainer(::grpc::ServerContext* context, const ::runtime::StartContainerRequest* request, ::runtime::StartContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_StopContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_StopContainer() { ::grpc::Service::MarkMethodGeneric(8); } ~WithGenericMethod_StopContainer() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status StopContainer(::grpc::ServerContext* context, const ::runtime::StopContainerRequest* request, ::runtime::StopContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_RemoveContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_RemoveContainer() { ::grpc::Service::MarkMethodGeneric(9); } ~WithGenericMethod_RemoveContainer() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status RemoveContainer(::grpc::ServerContext* context, const ::runtime::RemoveContainerRequest* request, ::runtime::RemoveContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_ListContainers : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_ListContainers() { ::grpc::Service::MarkMethodGeneric(10); } ~WithGenericMethod_ListContainers() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ListContainers(::grpc::ServerContext* context, const ::runtime::ListContainersRequest* request, ::runtime::ListContainersResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_ContainerStatus : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_ContainerStatus() { ::grpc::Service::MarkMethodGeneric(11); } ~WithGenericMethod_ContainerStatus() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ContainerStatus(::grpc::ServerContext* context, const ::runtime::ContainerStatusRequest* request, ::runtime::ContainerStatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_UpdateContainerResources : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_UpdateContainerResources() { ::grpc::Service::MarkMethodGeneric(12); } ~WithGenericMethod_UpdateContainerResources() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status UpdateContainerResources(::grpc::ServerContext* context, const ::runtime::UpdateContainerResourcesRequest* request, ::runtime::UpdateContainerResourcesResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_ExecSync : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_ExecSync() { ::grpc::Service::MarkMethodGeneric(13); } ~WithGenericMethod_ExecSync() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ExecSync(::grpc::ServerContext* context, const ::runtime::ExecSyncRequest* request, ::runtime::ExecSyncResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_Exec : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_Exec() { ::grpc::Service::MarkMethodGeneric(14); } ~WithGenericMethod_Exec() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Exec(::grpc::ServerContext* context, const ::runtime::ExecRequest* request, ::runtime::ExecResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_Attach : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_Attach() { ::grpc::Service::MarkMethodGeneric(15); } ~WithGenericMethod_Attach() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Attach(::grpc::ServerContext* context, const ::runtime::AttachRequest* request, ::runtime::AttachResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_PortForward : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_PortForward() { ::grpc::Service::MarkMethodGeneric(16); } ~WithGenericMethod_PortForward() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status PortForward(::grpc::ServerContext* context, const ::runtime::PortForwardRequest* request, ::runtime::PortForwardResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_ContainerStats : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_ContainerStats() { ::grpc::Service::MarkMethodGeneric(17); } ~WithGenericMethod_ContainerStats() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ContainerStats(::grpc::ServerContext* context, const ::runtime::ContainerStatsRequest* request, ::runtime::ContainerStatsResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_ListContainerStats : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_ListContainerStats() { ::grpc::Service::MarkMethodGeneric(18); } ~WithGenericMethod_ListContainerStats() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ListContainerStats(::grpc::ServerContext* context, const ::runtime::ListContainerStatsRequest* request, ::runtime::ListContainerStatsResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_UpdateRuntimeConfig : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_UpdateRuntimeConfig() { ::grpc::Service::MarkMethodGeneric(19); } ~WithGenericMethod_UpdateRuntimeConfig() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status UpdateRuntimeConfig(::grpc::ServerContext* context, const ::runtime::UpdateRuntimeConfigRequest* request, ::runtime::UpdateRuntimeConfigResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_Status : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_Status() { ::grpc::Service::MarkMethodGeneric(20); } ~WithGenericMethod_Status() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Status(::grpc::ServerContext* context, const ::runtime::StatusRequest* request, ::runtime::StatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithStreamedUnaryMethod_Version : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_Version() { ::grpc::Service::MarkMethodStreamed(0, new ::grpc::internal::StreamedUnaryHandler< ::runtime::VersionRequest, ::runtime::VersionResponse>(std::bind(&WithStreamedUnaryMethod_Version<BaseClass>::StreamedVersion, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_Version() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status Version(::grpc::ServerContext* context, const ::runtime::VersionRequest* request, ::runtime::VersionResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedVersion(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::VersionRequest,::runtime::VersionResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_RunPodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_RunPodSandbox() { ::grpc::Service::MarkMethodStreamed(1, new ::grpc::internal::StreamedUnaryHandler< ::runtime::RunPodSandboxRequest, ::runtime::RunPodSandboxResponse>(std::bind(&WithStreamedUnaryMethod_RunPodSandbox<BaseClass>::StreamedRunPodSandbox, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_RunPodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status RunPodSandbox(::grpc::ServerContext* context, const ::runtime::RunPodSandboxRequest* request, ::runtime::RunPodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedRunPodSandbox(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::RunPodSandboxRequest,::runtime::RunPodSandboxResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_StopPodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_StopPodSandbox() { ::grpc::Service::MarkMethodStreamed(2, new ::grpc::internal::StreamedUnaryHandler< ::runtime::StopPodSandboxRequest, ::runtime::StopPodSandboxResponse>(std::bind(&WithStreamedUnaryMethod_StopPodSandbox<BaseClass>::StreamedStopPodSandbox, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_StopPodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status StopPodSandbox(::grpc::ServerContext* context, const ::runtime::StopPodSandboxRequest* request, ::runtime::StopPodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedStopPodSandbox(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::StopPodSandboxRequest,::runtime::StopPodSandboxResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_RemovePodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_RemovePodSandbox() { ::grpc::Service::MarkMethodStreamed(3, new ::grpc::internal::StreamedUnaryHandler< ::runtime::RemovePodSandboxRequest, ::runtime::RemovePodSandboxResponse>(std::bind(&WithStreamedUnaryMethod_RemovePodSandbox<BaseClass>::StreamedRemovePodSandbox, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_RemovePodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status RemovePodSandbox(::grpc::ServerContext* context, const ::runtime::RemovePodSandboxRequest* request, ::runtime::RemovePodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedRemovePodSandbox(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::RemovePodSandboxRequest,::runtime::RemovePodSandboxResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_PodSandboxStatus : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_PodSandboxStatus() { ::grpc::Service::MarkMethodStreamed(4, new ::grpc::internal::StreamedUnaryHandler< ::runtime::PodSandboxStatusRequest, ::runtime::PodSandboxStatusResponse>(std::bind(&WithStreamedUnaryMethod_PodSandboxStatus<BaseClass>::StreamedPodSandboxStatus, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_PodSandboxStatus() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status PodSandboxStatus(::grpc::ServerContext* context, const ::runtime::PodSandboxStatusRequest* request, ::runtime::PodSandboxStatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedPodSandboxStatus(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::PodSandboxStatusRequest,::runtime::PodSandboxStatusResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_ListPodSandbox : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_ListPodSandbox() { ::grpc::Service::MarkMethodStreamed(5, new ::grpc::internal::StreamedUnaryHandler< ::runtime::ListPodSandboxRequest, ::runtime::ListPodSandboxResponse>(std::bind(&WithStreamedUnaryMethod_ListPodSandbox<BaseClass>::StreamedListPodSandbox, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_ListPodSandbox() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status ListPodSandbox(::grpc::ServerContext* context, const ::runtime::ListPodSandboxRequest* request, ::runtime::ListPodSandboxResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedListPodSandbox(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::ListPodSandboxRequest,::runtime::ListPodSandboxResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_CreateContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_CreateContainer() { ::grpc::Service::MarkMethodStreamed(6, new ::grpc::internal::StreamedUnaryHandler< ::runtime::CreateContainerRequest, ::runtime::CreateContainerResponse>(std::bind(&WithStreamedUnaryMethod_CreateContainer<BaseClass>::StreamedCreateContainer, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_CreateContainer() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status CreateContainer(::grpc::ServerContext* context, const ::runtime::CreateContainerRequest* request, ::runtime::CreateContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedCreateContainer(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::CreateContainerRequest,::runtime::CreateContainerResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_StartContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_StartContainer() { ::grpc::Service::MarkMethodStreamed(7, new ::grpc::internal::StreamedUnaryHandler< ::runtime::StartContainerRequest, ::runtime::StartContainerResponse>(std::bind(&WithStreamedUnaryMethod_StartContainer<BaseClass>::StreamedStartContainer, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_StartContainer() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status StartContainer(::grpc::ServerContext* context, const ::runtime::StartContainerRequest* request, ::runtime::StartContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedStartContainer(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::StartContainerRequest,::runtime::StartContainerResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_StopContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_StopContainer() { ::grpc::Service::MarkMethodStreamed(8, new ::grpc::internal::StreamedUnaryHandler< ::runtime::StopContainerRequest, ::runtime::StopContainerResponse>(std::bind(&WithStreamedUnaryMethod_StopContainer<BaseClass>::StreamedStopContainer, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_StopContainer() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status StopContainer(::grpc::ServerContext* context, const ::runtime::StopContainerRequest* request, ::runtime::StopContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedStopContainer(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::StopContainerRequest,::runtime::StopContainerResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_RemoveContainer : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_RemoveContainer() { ::grpc::Service::MarkMethodStreamed(9, new ::grpc::internal::StreamedUnaryHandler< ::runtime::RemoveContainerRequest, ::runtime::RemoveContainerResponse>(std::bind(&WithStreamedUnaryMethod_RemoveContainer<BaseClass>::StreamedRemoveContainer, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_RemoveContainer() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status RemoveContainer(::grpc::ServerContext* context, const ::runtime::RemoveContainerRequest* request, ::runtime::RemoveContainerResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedRemoveContainer(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::RemoveContainerRequest,::runtime::RemoveContainerResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_ListContainers : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_ListContainers() { ::grpc::Service::MarkMethodStreamed(10, new ::grpc::internal::StreamedUnaryHandler< ::runtime::ListContainersRequest, ::runtime::ListContainersResponse>(std::bind(&WithStreamedUnaryMethod_ListContainers<BaseClass>::StreamedListContainers, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_ListContainers() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status ListContainers(::grpc::ServerContext* context, const ::runtime::ListContainersRequest* request, ::runtime::ListContainersResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedListContainers(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::ListContainersRequest,::runtime::ListContainersResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_ContainerStatus : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_ContainerStatus() { ::grpc::Service::MarkMethodStreamed(11, new ::grpc::internal::StreamedUnaryHandler< ::runtime::ContainerStatusRequest, ::runtime::ContainerStatusResponse>(std::bind(&WithStreamedUnaryMethod_ContainerStatus<BaseClass>::StreamedContainerStatus, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_ContainerStatus() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status ContainerStatus(::grpc::ServerContext* context, const ::runtime::ContainerStatusRequest* request, ::runtime::ContainerStatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedContainerStatus(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::ContainerStatusRequest,::runtime::ContainerStatusResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_UpdateContainerResources : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_UpdateContainerResources() { ::grpc::Service::MarkMethodStreamed(12, new ::grpc::internal::StreamedUnaryHandler< ::runtime::UpdateContainerResourcesRequest, ::runtime::UpdateContainerResourcesResponse>(std::bind(&WithStreamedUnaryMethod_UpdateContainerResources<BaseClass>::StreamedUpdateContainerResources, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_UpdateContainerResources() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status UpdateContainerResources(::grpc::ServerContext* context, const ::runtime::UpdateContainerResourcesRequest* request, ::runtime::UpdateContainerResourcesResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedUpdateContainerResources(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::UpdateContainerResourcesRequest,::runtime::UpdateContainerResourcesResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_ExecSync : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_ExecSync() { ::grpc::Service::MarkMethodStreamed(13, new ::grpc::internal::StreamedUnaryHandler< ::runtime::ExecSyncRequest, ::runtime::ExecSyncResponse>(std::bind(&WithStreamedUnaryMethod_ExecSync<BaseClass>::StreamedExecSync, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_ExecSync() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status ExecSync(::grpc::ServerContext* context, const ::runtime::ExecSyncRequest* request, ::runtime::ExecSyncResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedExecSync(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::ExecSyncRequest,::runtime::ExecSyncResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_Exec : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_Exec() { ::grpc::Service::MarkMethodStreamed(14, new ::grpc::internal::StreamedUnaryHandler< ::runtime::ExecRequest, ::runtime::ExecResponse>(std::bind(&WithStreamedUnaryMethod_Exec<BaseClass>::StreamedExec, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_Exec() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status Exec(::grpc::ServerContext* context, const ::runtime::ExecRequest* request, ::runtime::ExecResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedExec(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::ExecRequest,::runtime::ExecResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_Attach : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_Attach() { ::grpc::Service::MarkMethodStreamed(15, new ::grpc::internal::StreamedUnaryHandler< ::runtime::AttachRequest, ::runtime::AttachResponse>(std::bind(&WithStreamedUnaryMethod_Attach<BaseClass>::StreamedAttach, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_Attach() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status Attach(::grpc::ServerContext* context, const ::runtime::AttachRequest* request, ::runtime::AttachResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedAttach(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::AttachRequest,::runtime::AttachResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_PortForward : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_PortForward() { ::grpc::Service::MarkMethodStreamed(16, new ::grpc::internal::StreamedUnaryHandler< ::runtime::PortForwardRequest, ::runtime::PortForwardResponse>(std::bind(&WithStreamedUnaryMethod_PortForward<BaseClass>::StreamedPortForward, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_PortForward() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status PortForward(::grpc::ServerContext* context, const ::runtime::PortForwardRequest* request, ::runtime::PortForwardResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedPortForward(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::PortForwardRequest,::runtime::PortForwardResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_ContainerStats : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_ContainerStats() { ::grpc::Service::MarkMethodStreamed(17, new ::grpc::internal::StreamedUnaryHandler< ::runtime::ContainerStatsRequest, ::runtime::ContainerStatsResponse>(std::bind(&WithStreamedUnaryMethod_ContainerStats<BaseClass>::StreamedContainerStats, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_ContainerStats() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status ContainerStats(::grpc::ServerContext* context, const ::runtime::ContainerStatsRequest* request, ::runtime::ContainerStatsResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedContainerStats(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::ContainerStatsRequest,::runtime::ContainerStatsResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_ListContainerStats : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_ListContainerStats() { ::grpc::Service::MarkMethodStreamed(18, new ::grpc::internal::StreamedUnaryHandler< ::runtime::ListContainerStatsRequest, ::runtime::ListContainerStatsResponse>(std::bind(&WithStreamedUnaryMethod_ListContainerStats<BaseClass>::StreamedListContainerStats, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_ListContainerStats() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status ListContainerStats(::grpc::ServerContext* context, const ::runtime::ListContainerStatsRequest* request, ::runtime::ListContainerStatsResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedListContainerStats(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::ListContainerStatsRequest,::runtime::ListContainerStatsResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_UpdateRuntimeConfig : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_UpdateRuntimeConfig() { ::grpc::Service::MarkMethodStreamed(19, new ::grpc::internal::StreamedUnaryHandler< ::runtime::UpdateRuntimeConfigRequest, ::runtime::UpdateRuntimeConfigResponse>(std::bind(&WithStreamedUnaryMethod_UpdateRuntimeConfig<BaseClass>::StreamedUpdateRuntimeConfig, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_UpdateRuntimeConfig() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status UpdateRuntimeConfig(::grpc::ServerContext* context, const ::runtime::UpdateRuntimeConfigRequest* request, ::runtime::UpdateRuntimeConfigResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedUpdateRuntimeConfig(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::UpdateRuntimeConfigRequest,::runtime::UpdateRuntimeConfigResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_Status : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_Status() { ::grpc::Service::MarkMethodStreamed(20, new ::grpc::internal::StreamedUnaryHandler< ::runtime::StatusRequest, ::runtime::StatusResponse>(std::bind(&WithStreamedUnaryMethod_Status<BaseClass>::StreamedStatus, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_Status() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status Status(::grpc::ServerContext* context, const ::runtime::StatusRequest* request, ::runtime::StatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedStatus(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::StatusRequest,::runtime::StatusResponse>* server_unary_streamer) = 0; }; typedef WithStreamedUnaryMethod_Version<WithStreamedUnaryMethod_RunPodSandbox<WithStreamedUnaryMethod_StopPodSandbox<WithStreamedUnaryMethod_RemovePodSandbox<WithStreamedUnaryMethod_PodSandboxStatus<WithStreamedUnaryMethod_ListPodSandbox<WithStreamedUnaryMethod_CreateContainer<WithStreamedUnaryMethod_StartContainer<WithStreamedUnaryMethod_StopContainer<WithStreamedUnaryMethod_RemoveContainer<WithStreamedUnaryMethod_ListContainers<WithStreamedUnaryMethod_ContainerStatus<WithStreamedUnaryMethod_UpdateContainerResources<WithStreamedUnaryMethod_ExecSync<WithStreamedUnaryMethod_Exec<WithStreamedUnaryMethod_Attach<WithStreamedUnaryMethod_PortForward<WithStreamedUnaryMethod_ContainerStats<WithStreamedUnaryMethod_ListContainerStats<WithStreamedUnaryMethod_UpdateRuntimeConfig<WithStreamedUnaryMethod_Status<Service > > > > > > > > > > > > > > > > > > > > > StreamedUnaryService; typedef Service SplitStreamedService; typedef WithStreamedUnaryMethod_Version<WithStreamedUnaryMethod_RunPodSandbox<WithStreamedUnaryMethod_StopPodSandbox<WithStreamedUnaryMethod_RemovePodSandbox<WithStreamedUnaryMethod_PodSandboxStatus<WithStreamedUnaryMethod_ListPodSandbox<WithStreamedUnaryMethod_CreateContainer<WithStreamedUnaryMethod_StartContainer<WithStreamedUnaryMethod_StopContainer<WithStreamedUnaryMethod_RemoveContainer<WithStreamedUnaryMethod_ListContainers<WithStreamedUnaryMethod_ContainerStatus<WithStreamedUnaryMethod_UpdateContainerResources<WithStreamedUnaryMethod_ExecSync<WithStreamedUnaryMethod_Exec<WithStreamedUnaryMethod_Attach<WithStreamedUnaryMethod_PortForward<WithStreamedUnaryMethod_ContainerStats<WithStreamedUnaryMethod_ListContainerStats<WithStreamedUnaryMethod_UpdateRuntimeConfig<WithStreamedUnaryMethod_Status<Service > > > > > > > > > > > > > > > > > > > > > StreamedService; }; // ImageService defines the public APIs for managing images. class ImageService final { public: static constexpr char const* service_full_name() { return "runtime.ImageService"; } class StubInterface { public: virtual ~StubInterface() {} // ListImages lists existing images. virtual ::grpc::Status ListImages(::grpc::ClientContext* context, const ::runtime::ListImagesRequest& request, ::runtime::ListImagesResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListImagesResponse>> AsyncListImages(::grpc::ClientContext* context, const ::runtime::ListImagesRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListImagesResponse>>(AsyncListImagesRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListImagesResponse>> PrepareAsyncListImages(::grpc::ClientContext* context, const ::runtime::ListImagesRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListImagesResponse>>(PrepareAsyncListImagesRaw(context, request, cq)); } // ImageStatus returns the status of the image. If the image is not // present, returns a response with ImageStatusResponse.Image set to // nil. virtual ::grpc::Status ImageStatus(::grpc::ClientContext* context, const ::runtime::ImageStatusRequest& request, ::runtime::ImageStatusResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageStatusResponse>> AsyncImageStatus(::grpc::ClientContext* context, const ::runtime::ImageStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageStatusResponse>>(AsyncImageStatusRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageStatusResponse>> PrepareAsyncImageStatus(::grpc::ClientContext* context, const ::runtime::ImageStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageStatusResponse>>(PrepareAsyncImageStatusRaw(context, request, cq)); } // PullImage pulls an image with authentication config. virtual ::grpc::Status PullImage(::grpc::ClientContext* context, const ::runtime::PullImageRequest& request, ::runtime::PullImageResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PullImageResponse>> AsyncPullImage(::grpc::ClientContext* context, const ::runtime::PullImageRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PullImageResponse>>(AsyncPullImageRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PullImageResponse>> PrepareAsyncPullImage(::grpc::ClientContext* context, const ::runtime::PullImageRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PullImageResponse>>(PrepareAsyncPullImageRaw(context, request, cq)); } // RemoveImage removes the image. // This call is idempotent, and must not return an error if the image has // already been removed. virtual ::grpc::Status RemoveImage(::grpc::ClientContext* context, const ::runtime::RemoveImageRequest& request, ::runtime::RemoveImageResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveImageResponse>> AsyncRemoveImage(::grpc::ClientContext* context, const ::runtime::RemoveImageRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveImageResponse>>(AsyncRemoveImageRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveImageResponse>> PrepareAsyncRemoveImage(::grpc::ClientContext* context, const ::runtime::RemoveImageRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveImageResponse>>(PrepareAsyncRemoveImageRaw(context, request, cq)); } // ImageFSInfo returns information of the filesystem that is used to store images. virtual ::grpc::Status ImageFsInfo(::grpc::ClientContext* context, const ::runtime::ImageFsInfoRequest& request, ::runtime::ImageFsInfoResponse* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageFsInfoResponse>> AsyncImageFsInfo(::grpc::ClientContext* context, const ::runtime::ImageFsInfoRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageFsInfoResponse>>(AsyncImageFsInfoRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageFsInfoResponse>> PrepareAsyncImageFsInfo(::grpc::ClientContext* context, const ::runtime::ImageFsInfoRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageFsInfoResponse>>(PrepareAsyncImageFsInfoRaw(context, request, cq)); } private: virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListImagesResponse>* AsyncListImagesRaw(::grpc::ClientContext* context, const ::runtime::ListImagesRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ListImagesResponse>* PrepareAsyncListImagesRaw(::grpc::ClientContext* context, const ::runtime::ListImagesRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageStatusResponse>* AsyncImageStatusRaw(::grpc::ClientContext* context, const ::runtime::ImageStatusRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageStatusResponse>* PrepareAsyncImageStatusRaw(::grpc::ClientContext* context, const ::runtime::ImageStatusRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PullImageResponse>* AsyncPullImageRaw(::grpc::ClientContext* context, const ::runtime::PullImageRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::PullImageResponse>* PrepareAsyncPullImageRaw(::grpc::ClientContext* context, const ::runtime::PullImageRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveImageResponse>* AsyncRemoveImageRaw(::grpc::ClientContext* context, const ::runtime::RemoveImageRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::RemoveImageResponse>* PrepareAsyncRemoveImageRaw(::grpc::ClientContext* context, const ::runtime::RemoveImageRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageFsInfoResponse>* AsyncImageFsInfoRaw(::grpc::ClientContext* context, const ::runtime::ImageFsInfoRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::runtime::ImageFsInfoResponse>* PrepareAsyncImageFsInfoRaw(::grpc::ClientContext* context, const ::runtime::ImageFsInfoRequest& request, ::grpc::CompletionQueue* cq) = 0; }; class Stub final : public StubInterface { public: Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); ::grpc::Status ListImages(::grpc::ClientContext* context, const ::runtime::ListImagesRequest& request, ::runtime::ListImagesResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListImagesResponse>> AsyncListImages(::grpc::ClientContext* context, const ::runtime::ListImagesRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListImagesResponse>>(AsyncListImagesRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListImagesResponse>> PrepareAsyncListImages(::grpc::ClientContext* context, const ::runtime::ListImagesRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ListImagesResponse>>(PrepareAsyncListImagesRaw(context, request, cq)); } ::grpc::Status ImageStatus(::grpc::ClientContext* context, const ::runtime::ImageStatusRequest& request, ::runtime::ImageStatusResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ImageStatusResponse>> AsyncImageStatus(::grpc::ClientContext* context, const ::runtime::ImageStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ImageStatusResponse>>(AsyncImageStatusRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ImageStatusResponse>> PrepareAsyncImageStatus(::grpc::ClientContext* context, const ::runtime::ImageStatusRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ImageStatusResponse>>(PrepareAsyncImageStatusRaw(context, request, cq)); } ::grpc::Status PullImage(::grpc::ClientContext* context, const ::runtime::PullImageRequest& request, ::runtime::PullImageResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PullImageResponse>> AsyncPullImage(::grpc::ClientContext* context, const ::runtime::PullImageRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PullImageResponse>>(AsyncPullImageRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PullImageResponse>> PrepareAsyncPullImage(::grpc::ClientContext* context, const ::runtime::PullImageRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::PullImageResponse>>(PrepareAsyncPullImageRaw(context, request, cq)); } ::grpc::Status RemoveImage(::grpc::ClientContext* context, const ::runtime::RemoveImageRequest& request, ::runtime::RemoveImageResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemoveImageResponse>> AsyncRemoveImage(::grpc::ClientContext* context, const ::runtime::RemoveImageRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemoveImageResponse>>(AsyncRemoveImageRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemoveImageResponse>> PrepareAsyncRemoveImage(::grpc::ClientContext* context, const ::runtime::RemoveImageRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::RemoveImageResponse>>(PrepareAsyncRemoveImageRaw(context, request, cq)); } ::grpc::Status ImageFsInfo(::grpc::ClientContext* context, const ::runtime::ImageFsInfoRequest& request, ::runtime::ImageFsInfoResponse* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ImageFsInfoResponse>> AsyncImageFsInfo(::grpc::ClientContext* context, const ::runtime::ImageFsInfoRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ImageFsInfoResponse>>(AsyncImageFsInfoRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ImageFsInfoResponse>> PrepareAsyncImageFsInfo(::grpc::ClientContext* context, const ::runtime::ImageFsInfoRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::runtime::ImageFsInfoResponse>>(PrepareAsyncImageFsInfoRaw(context, request, cq)); } private: std::shared_ptr< ::grpc::ChannelInterface> channel_; ::grpc::ClientAsyncResponseReader< ::runtime::ListImagesResponse>* AsyncListImagesRaw(::grpc::ClientContext* context, const ::runtime::ListImagesRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ListImagesResponse>* PrepareAsyncListImagesRaw(::grpc::ClientContext* context, const ::runtime::ListImagesRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ImageStatusResponse>* AsyncImageStatusRaw(::grpc::ClientContext* context, const ::runtime::ImageStatusRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ImageStatusResponse>* PrepareAsyncImageStatusRaw(::grpc::ClientContext* context, const ::runtime::ImageStatusRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::PullImageResponse>* AsyncPullImageRaw(::grpc::ClientContext* context, const ::runtime::PullImageRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::PullImageResponse>* PrepareAsyncPullImageRaw(::grpc::ClientContext* context, const ::runtime::PullImageRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::RemoveImageResponse>* AsyncRemoveImageRaw(::grpc::ClientContext* context, const ::runtime::RemoveImageRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::RemoveImageResponse>* PrepareAsyncRemoveImageRaw(::grpc::ClientContext* context, const ::runtime::RemoveImageRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ImageFsInfoResponse>* AsyncImageFsInfoRaw(::grpc::ClientContext* context, const ::runtime::ImageFsInfoRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::runtime::ImageFsInfoResponse>* PrepareAsyncImageFsInfoRaw(::grpc::ClientContext* context, const ::runtime::ImageFsInfoRequest& request, ::grpc::CompletionQueue* cq) override; const ::grpc::internal::RpcMethod rpcmethod_ListImages_; const ::grpc::internal::RpcMethod rpcmethod_ImageStatus_; const ::grpc::internal::RpcMethod rpcmethod_PullImage_; const ::grpc::internal::RpcMethod rpcmethod_RemoveImage_; const ::grpc::internal::RpcMethod rpcmethod_ImageFsInfo_; }; static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); class Service : public ::grpc::Service { public: Service(); virtual ~Service(); // ListImages lists existing images. virtual ::grpc::Status ListImages(::grpc::ServerContext* context, const ::runtime::ListImagesRequest* request, ::runtime::ListImagesResponse* response); // ImageStatus returns the status of the image. If the image is not // present, returns a response with ImageStatusResponse.Image set to // nil. virtual ::grpc::Status ImageStatus(::grpc::ServerContext* context, const ::runtime::ImageStatusRequest* request, ::runtime::ImageStatusResponse* response); // PullImage pulls an image with authentication config. virtual ::grpc::Status PullImage(::grpc::ServerContext* context, const ::runtime::PullImageRequest* request, ::runtime::PullImageResponse* response); // RemoveImage removes the image. // This call is idempotent, and must not return an error if the image has // already been removed. virtual ::grpc::Status RemoveImage(::grpc::ServerContext* context, const ::runtime::RemoveImageRequest* request, ::runtime::RemoveImageResponse* response); // ImageFSInfo returns information of the filesystem that is used to store images. virtual ::grpc::Status ImageFsInfo(::grpc::ServerContext* context, const ::runtime::ImageFsInfoRequest* request, ::runtime::ImageFsInfoResponse* response); }; template <class BaseClass> class WithAsyncMethod_ListImages : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_ListImages() { ::grpc::Service::MarkMethodAsync(0); } ~WithAsyncMethod_ListImages() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ListImages(::grpc::ServerContext* context, const ::runtime::ListImagesRequest* request, ::runtime::ListImagesResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestListImages(::grpc::ServerContext* context, ::runtime::ListImagesRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::ListImagesResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_ImageStatus : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_ImageStatus() { ::grpc::Service::MarkMethodAsync(1); } ~WithAsyncMethod_ImageStatus() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ImageStatus(::grpc::ServerContext* context, const ::runtime::ImageStatusRequest* request, ::runtime::ImageStatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestImageStatus(::grpc::ServerContext* context, ::runtime::ImageStatusRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::ImageStatusResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(1, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_PullImage : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_PullImage() { ::grpc::Service::MarkMethodAsync(2); } ~WithAsyncMethod_PullImage() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status PullImage(::grpc::ServerContext* context, const ::runtime::PullImageRequest* request, ::runtime::PullImageResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestPullImage(::grpc::ServerContext* context, ::runtime::PullImageRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::PullImageResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(2, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_RemoveImage : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_RemoveImage() { ::grpc::Service::MarkMethodAsync(3); } ~WithAsyncMethod_RemoveImage() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status RemoveImage(::grpc::ServerContext* context, const ::runtime::RemoveImageRequest* request, ::runtime::RemoveImageResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestRemoveImage(::grpc::ServerContext* context, ::runtime::RemoveImageRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::RemoveImageResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(3, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_ImageFsInfo : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_ImageFsInfo() { ::grpc::Service::MarkMethodAsync(4); } ~WithAsyncMethod_ImageFsInfo() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ImageFsInfo(::grpc::ServerContext* context, const ::runtime::ImageFsInfoRequest* request, ::runtime::ImageFsInfoResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestImageFsInfo(::grpc::ServerContext* context, ::runtime::ImageFsInfoRequest* request, ::grpc::ServerAsyncResponseWriter< ::runtime::ImageFsInfoResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(4, context, request, response, new_call_cq, notification_cq, tag); } }; typedef WithAsyncMethod_ListImages<WithAsyncMethod_ImageStatus<WithAsyncMethod_PullImage<WithAsyncMethod_RemoveImage<WithAsyncMethod_ImageFsInfo<Service > > > > > AsyncService; template <class BaseClass> class WithGenericMethod_ListImages : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_ListImages() { ::grpc::Service::MarkMethodGeneric(0); } ~WithGenericMethod_ListImages() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ListImages(::grpc::ServerContext* context, const ::runtime::ListImagesRequest* request, ::runtime::ListImagesResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_ImageStatus : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_ImageStatus() { ::grpc::Service::MarkMethodGeneric(1); } ~WithGenericMethod_ImageStatus() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ImageStatus(::grpc::ServerContext* context, const ::runtime::ImageStatusRequest* request, ::runtime::ImageStatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_PullImage : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_PullImage() { ::grpc::Service::MarkMethodGeneric(2); } ~WithGenericMethod_PullImage() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status PullImage(::grpc::ServerContext* context, const ::runtime::PullImageRequest* request, ::runtime::PullImageResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_RemoveImage : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_RemoveImage() { ::grpc::Service::MarkMethodGeneric(3); } ~WithGenericMethod_RemoveImage() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status RemoveImage(::grpc::ServerContext* context, const ::runtime::RemoveImageRequest* request, ::runtime::RemoveImageResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_ImageFsInfo : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_ImageFsInfo() { ::grpc::Service::MarkMethodGeneric(4); } ~WithGenericMethod_ImageFsInfo() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status ImageFsInfo(::grpc::ServerContext* context, const ::runtime::ImageFsInfoRequest* request, ::runtime::ImageFsInfoResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithStreamedUnaryMethod_ListImages : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_ListImages() { ::grpc::Service::MarkMethodStreamed(0, new ::grpc::internal::StreamedUnaryHandler< ::runtime::ListImagesRequest, ::runtime::ListImagesResponse>(std::bind(&WithStreamedUnaryMethod_ListImages<BaseClass>::StreamedListImages, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_ListImages() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status ListImages(::grpc::ServerContext* context, const ::runtime::ListImagesRequest* request, ::runtime::ListImagesResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedListImages(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::ListImagesRequest,::runtime::ListImagesResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_ImageStatus : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_ImageStatus() { ::grpc::Service::MarkMethodStreamed(1, new ::grpc::internal::StreamedUnaryHandler< ::runtime::ImageStatusRequest, ::runtime::ImageStatusResponse>(std::bind(&WithStreamedUnaryMethod_ImageStatus<BaseClass>::StreamedImageStatus, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_ImageStatus() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status ImageStatus(::grpc::ServerContext* context, const ::runtime::ImageStatusRequest* request, ::runtime::ImageStatusResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedImageStatus(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::ImageStatusRequest,::runtime::ImageStatusResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_PullImage : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_PullImage() { ::grpc::Service::MarkMethodStreamed(2, new ::grpc::internal::StreamedUnaryHandler< ::runtime::PullImageRequest, ::runtime::PullImageResponse>(std::bind(&WithStreamedUnaryMethod_PullImage<BaseClass>::StreamedPullImage, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_PullImage() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status PullImage(::grpc::ServerContext* context, const ::runtime::PullImageRequest* request, ::runtime::PullImageResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedPullImage(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::PullImageRequest,::runtime::PullImageResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_RemoveImage : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_RemoveImage() { ::grpc::Service::MarkMethodStreamed(3, new ::grpc::internal::StreamedUnaryHandler< ::runtime::RemoveImageRequest, ::runtime::RemoveImageResponse>(std::bind(&WithStreamedUnaryMethod_RemoveImage<BaseClass>::StreamedRemoveImage, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_RemoveImage() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status RemoveImage(::grpc::ServerContext* context, const ::runtime::RemoveImageRequest* request, ::runtime::RemoveImageResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedRemoveImage(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::RemoveImageRequest,::runtime::RemoveImageResponse>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_ImageFsInfo : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_ImageFsInfo() { ::grpc::Service::MarkMethodStreamed(4, new ::grpc::internal::StreamedUnaryHandler< ::runtime::ImageFsInfoRequest, ::runtime::ImageFsInfoResponse>(std::bind(&WithStreamedUnaryMethod_ImageFsInfo<BaseClass>::StreamedImageFsInfo, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_ImageFsInfo() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status ImageFsInfo(::grpc::ServerContext* context, const ::runtime::ImageFsInfoRequest* request, ::runtime::ImageFsInfoResponse* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedImageFsInfo(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::runtime::ImageFsInfoRequest,::runtime::ImageFsInfoResponse>* server_unary_streamer) = 0; }; typedef WithStreamedUnaryMethod_ListImages<WithStreamedUnaryMethod_ImageStatus<WithStreamedUnaryMethod_PullImage<WithStreamedUnaryMethod_RemoveImage<WithStreamedUnaryMethod_ImageFsInfo<Service > > > > > StreamedUnaryService; typedef Service SplitStreamedService; typedef WithStreamedUnaryMethod_ListImages<WithStreamedUnaryMethod_ImageStatus<WithStreamedUnaryMethod_PullImage<WithStreamedUnaryMethod_RemoveImage<WithStreamedUnaryMethod_ImageFsInfo<Service > > > > > StreamedService; }; } // namespace runtime #endif // GRPC_cri_2dapi_2eproto__INCLUDED
50,757
318
<reponame>eliseemond/elastix /*========================================================================= * * Copyright UMC Utrecht and contributors * * 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.txt * * 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. * *=========================================================================*/ // First include the header file to be tested: #include <elxElastixFilter.h> #include "elxCoreMainGTestUtilities.h" // ITK header file: #include <itkImage.h> #include <itkIndexRange.h> // GoogleTest header file: #include <gtest/gtest.h> #include <algorithm> // For transform #include <map> #include <string> #include <utility> // For pair // Using-declarations: using elx::CoreMainGTestUtilities::CheckNew; using elx::CoreMainGTestUtilities::ConvertToOffset; using elx::CoreMainGTestUtilities::CreateParameterObject; using elx::CoreMainGTestUtilities::Deref; using elx::CoreMainGTestUtilities::FillImageRegion; using elx::CoreMainGTestUtilities::GetTransformParametersFromFilter; // Tests registering two small (5x6) binary images, which are translated with respect to each other. GTEST_TEST(ElastixFilter, Translation) { constexpr auto ImageDimension = 2U; using ImageType = itk::Image<float, ImageDimension>; using SizeType = itk::Size<ImageDimension>; using IndexType = itk::Index<ImageDimension>; using OffsetType = itk::Offset<ImageDimension>; const OffsetType translationOffset{ { 1, -2 } }; const auto regionSize = SizeType::Filled(2); const SizeType imageSize{ { 5, 6 } }; const IndexType fixedImageRegionIndex{ { 1, 3 } }; const auto fixedImage = ImageType::New(); fixedImage->SetRegions(imageSize); fixedImage->Allocate(true); FillImageRegion(*fixedImage, fixedImageRegionIndex, regionSize); const auto movingImage = ImageType::New(); movingImage->SetRegions(imageSize); movingImage->Allocate(true); FillImageRegion(*movingImage, fixedImageRegionIndex + translationOffset, regionSize); const auto filter = CheckNew<elx::ElastixFilter<ImageType, ImageType>>(); filter->SetFixedImage(fixedImage); filter->SetMovingImage(movingImage); filter->SetParameterObject(CreateParameterObject({ // Parameters in alphabetic order: { "ImageSampler", "Full" }, { "MaximumNumberOfIterations", "2" }, { "Metric", "AdvancedNormalizedCorrelation" }, { "Optimizer", "AdaptiveStochasticGradientDescent" }, { "Transform", "TranslationTransform" } })); filter->Update(); const auto transformParameters = GetTransformParametersFromFilter(*filter); EXPECT_EQ(ConvertToOffset<ImageDimension>(transformParameters), translationOffset); } // Tests registering two images, having "WriteResultImage" set. GTEST_TEST(ElastixFilter, WriteResultImage) { constexpr auto ImageDimension = 2U; using ImageType = itk::Image<float, ImageDimension>; using SizeType = itk::Size<ImageDimension>; using IndexType = itk::Index<ImageDimension>; using OffsetType = itk::Offset<ImageDimension>; const OffsetType translationOffset{ { 1, -2 } }; const auto regionSize = SizeType::Filled(2); const SizeType imageSize{ { 5, 6 } }; const IndexType fixedImageRegionIndex{ { 1, 3 } }; const auto fixedImage = ImageType::New(); fixedImage->SetRegions(imageSize); fixedImage->Allocate(true); FillImageRegion(*fixedImage, fixedImageRegionIndex, regionSize); const auto movingImage = ImageType::New(); movingImage->SetRegions(imageSize); movingImage->Allocate(true); FillImageRegion(*movingImage, fixedImageRegionIndex + translationOffset, regionSize); for (const bool writeResultImage : { true, false }) { const auto filter = CheckNew<elx::ElastixFilter<ImageType, ImageType>>(); filter->SetFixedImage(fixedImage); filter->SetMovingImage(movingImage); filter->SetParameterObject( CreateParameterObject({ // Parameters in alphabetic order: { "ImageSampler", "Full" }, { "MaximumNumberOfIterations", "2" }, { "Metric", "AdvancedNormalizedCorrelation" }, { "Optimizer", "AdaptiveStochasticGradientDescent" }, { "Transform", "TranslationTransform" }, { "WriteResultImage", (writeResultImage ? "true" : "false") } })); filter->Update(); const auto & output = Deref(filter->GetOutput()); const auto & outputImageSize = output.GetBufferedRegion().GetSize(); const auto * const outputBufferPointer = output.GetBufferPointer(); if (writeResultImage) { EXPECT_EQ(outputImageSize, imageSize); ASSERT_NE(outputBufferPointer, nullptr); // When "WriteResultImage" is true, expect an output image that is very much like the fixed image. for (const auto index : itk::ZeroBasedIndexRange<ImageDimension>(imageSize)) { EXPECT_EQ(std::round(output.GetPixel(index)), std::round(fixedImage->GetPixel(index))); } } else { // When "WriteResultImage" is false, expect an empty output image. EXPECT_EQ(outputImageSize, ImageType::SizeType()); EXPECT_EQ(outputBufferPointer, nullptr); } const auto transformParameters = GetTransformParametersFromFilter(*filter); EXPECT_EQ(ConvertToOffset<ImageDimension>(transformParameters), translationOffset); } }
2,179
6,215
<gh_stars>1000+ /* * Copyright (c) 2021 Airbyte, Inc., all rights reserved. */ package io.airbyte.commons.map; import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.common.collect.ImmutableMap; import java.util.Map; import org.junit.jupiter.api.Test; class MoreMapsTest { @Test void testMerge() { final Map<String, Integer> map1 = ImmutableMap.of("a", 3, "b", 2); final Map<String, Integer> map2 = ImmutableMap.of("a", 1); assertEquals(ImmutableMap.of("a", 1, "b", 2), MoreMaps.merge(map1, map2)); } }
213
319
<gh_stars>100-1000 /** * Copyright (c) 2011, The University of Southampton and the individual contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * 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 Southampton 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 OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openimaj.experiment.gmm.retrieval; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.apache.commons.vfs2.FileSystemManager; import org.apache.commons.vfs2.VFS; import org.openimaj.data.dataset.GroupedDataset; import org.openimaj.data.dataset.ReadableGroupDataset; import org.openimaj.data.identity.Identifiable; import org.openimaj.io.ObjectReader; /** * A {@link GroupedDataset} of {@link UKBenchListDataset}s instances each of an * item in the UKBench experiment. * * UKBench can be provided in any form supported by {@link VFS} * * The UKBench files must be in one flat directory and named "ukbenchXXXXX.jpg" * * @author <NAME> (<EMAIL>) * * @param <IMAGE> * The type of IMAGE in the dataset */ public class UKBenchGroupDataset<IMAGE> extends ReadableGroupDataset<Integer, UKBenchListDataset<IMAGE>, IMAGE, FileObject> implements Identifiable { private static final int UKBENCH_OBJECTS = 2550; private Map<Integer, UKBenchListDataset<IMAGE>> ukbenchObjects; private FileObject base; /** * @param path * @param reader */ public UKBenchGroupDataset(String path, ObjectReader<IMAGE, FileObject> reader) { super(reader); this.ukbenchObjects = new HashMap<Integer, UKBenchListDataset<IMAGE>>(); FileSystemManager manager; try { manager = VFS.getManager(); this.base = manager.resolveFile(path); } catch (final FileSystemException e) { throw new RuntimeException(e); } for (int i = 0; i < UKBENCH_OBJECTS; i++) { this.ukbenchObjects.put(i, new UKBenchListDataset<IMAGE>(path, reader, i)); } } @Override public String toString() { return String.format("%s(%d groups with a total of %d instances)", this.getClass().getName(), this.size(), this.numInstances()); } @Override public String getID() { return base.getName().getBaseName(); } @Override public Set<java.util.Map.Entry<Integer, UKBenchListDataset<IMAGE>>> entrySet() { return ukbenchObjects.entrySet(); } }
1,225
7,744
<filename>examples/ASDKgram/Sample/ASCollectionSectionController.h // // ASCollectionSectionController.h // Texture // // Copyright (c) Pinterest, Inc. All rights reserved. // Licensed under Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0 // #import <IGListKit/IGListKit.h> NS_ASSUME_NONNULL_BEGIN @interface ASCollectionSectionController : IGListSectionController /** * The items managed by this section controller. */ @property (nonatomic, strong, readonly) NSArray<id<IGListDiffable>> *items; - (void)setItems:(NSArray<id<IGListDiffable>> *)newItems animated:(BOOL)animated completion:(nullable void(^)())completion; - (NSInteger)numberOfItems; @end NS_ASSUME_NONNULL_END
245
3,442
<filename>src/net/java/sip/communicator/service/protocol/event/SubscriptionAdapter.java /* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.service.protocol.event; /** * Represents a default implementation of <code>SubscriptionListener</code> * which performs no processing of the received events and allows extenders to * easily implement the interface in question by just overriding the methods * they are interested in. * * @author <NAME> */ public class SubscriptionAdapter implements SubscriptionListener { /* * Implements * SubscriptionListener#contactModified(ContactPropertyChangeEvent). Does * nothing. */ public void contactModified(ContactPropertyChangeEvent evt) { } /* * Implements SubscriptionListener#subscriptionCreated(SubscriptionEvent). * Does nothing. */ public void subscriptionCreated(SubscriptionEvent evt) { } /* * Implements SubscriptionListener#subscriptionFailed(SubscriptionEvent). * Does nothing. */ public void subscriptionFailed(SubscriptionEvent evt) { } /* * Implements SubscriptionListener#subscriptionMoved(SubscriptionMovedEvent). * Does nothing. */ public void subscriptionMoved(SubscriptionMovedEvent evt) { } /* * Implements SubscriptionListener#subscriptionRemoved(SubscriptionEvent). * Does nothing. */ public void subscriptionRemoved(SubscriptionEvent evt) { } /* * Implements SubscriptionListener#subscriptionResolved(SubscriptionEvent). * Does nothing. */ public void subscriptionResolved(SubscriptionEvent evt) { } }
722
373
<gh_stars>100-1000 /** @file Kaby Lake RVP 3 Multi-Board Initialization Pre-Memory library Copyright (c) 2017 - 2019, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PiPei.h> #include <Library/BaseLib.h> #include <Library/IoLib.h> #include <Library/BoardInitLib.h> #include <Library/MultiBoardInitSupportLib.h> #include <Library/PcdLib.h> #include <Library/DebugLib.h> #include <PlatformBoardId.h> EFI_STATUS EFIAPI KabylakeRvp3BoardDetect ( VOID ); EFI_STATUS EFIAPI KabylakeRvp3MultiBoardDetect ( VOID ); EFI_BOOT_MODE EFIAPI KabylakeRvp3BoardBootModeDetect ( VOID ); EFI_STATUS EFIAPI KabylakeRvp3BoardDebugInit ( VOID ); EFI_STATUS EFIAPI KabylakeRvp3BoardInitBeforeMemoryInit ( VOID ); BOARD_DETECT_FUNC mKabylakeRvp3BoardDetectFunc = { KabylakeRvp3MultiBoardDetect }; BOARD_PRE_MEM_INIT_FUNC mKabylakeRvp3BoardPreMemInitFunc = { KabylakeRvp3BoardDebugInit, KabylakeRvp3BoardBootModeDetect, KabylakeRvp3BoardInitBeforeMemoryInit, NULL, // BoardInitAfterMemoryInit NULL, // BoardInitBeforeTempRamExit NULL, // BoardInitAfterTempRamExit }; EFI_STATUS EFIAPI KabylakeRvp3MultiBoardDetect ( VOID ) { KabylakeRvp3BoardDetect (); if ((LibPcdGetSku () == BoardIdKabyLakeYLpddr3Rvp3) || (LibPcdGetSku () == BoardIdSkylakeRvp3)) { RegisterBoardPreMemInit (&mKabylakeRvp3BoardPreMemInitFunc); } return EFI_SUCCESS; } EFI_STATUS EFIAPI PeiKabylakeRvp3MultiBoardInitPreMemLibConstructor ( VOID ) { return RegisterBoardDetect (&mKabylakeRvp3BoardDetectFunc); }
733
2,659
<reponame>lotabout/OpenMLDB #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2021 4Paradigm # # 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. # -*- coding: utf-8 -*- from testcasebase import TestCaseBase import threading import time from libs.deco import multi_dimension from libs.logger import infoLogger import libs.ddt as ddt from libs.test_loader import load import libs.utils as utils @ddt.ddt @multi_dimension(False) class TestAddTableField(TestCaseBase): def test_add_table_field_with_columnkey(self): """ 指定时间列的schema表统计pk下的条数 :return: """ name = 'tname{}'.format(time.time()) metadata_path = '{}/metadata.txt'.format(self.testpath) table_meta = { "name": name, "ttl": 0, "column_desc":[ {"name": "card", "type": "string", "add_ts_idx": "true"}, {"name": "mcc", "type": "string", "add_ts_idx": "true"}, {"name": "amt", "type": "double", "add_ts_idx": "false"}, {"name": "ts1", "type": "int64", "add_ts_idx": "false", "is_ts_col": "true"}, {"name": "ts2", "type": "int64", "add_ts_idx": "false", "is_ts_col": "true"}, ], "column_key":[ {"index_name":"card", "ts_name":["ts1", "ts2"]}, {"index_name":"mcc", "ts_name":["ts2"]}, ] } utils.gen_table_meta_file(table_meta, metadata_path) rs = self.ns_create(self.ns_leader, metadata_path) self.assertIn('Create table ok', rs) (schema, column_key) = self.ns_showschema(self.ns_leader, name) self.assertEqual(len(schema), 5) self.assertEqual(schema[0], ['0', 'card', 'string']) self.assertEqual(schema[1], ['1', 'mcc', 'string']) self.assertEqual(schema[2], ['2', 'amt', 'double']) self.assertEqual(schema[3], ['3', 'ts1', 'int64']) self.assertEqual(schema[4], ['4', 'ts2', 'int64']) self.assertEqual(len(column_key), 3) self.assertEqual(column_key[0], ["0", "card", "card", "ts1", "0min"]) self.assertEqual(column_key[1], ["1", "card", "card", "ts2", "0min"]) self.assertEqual(column_key[2], ["2", "mcc", "mcc", "ts2", "0min"]) self.ns_add_table_field(self.ns_leader, name, 'aa', 'string'); (schema, column_key) = self.ns_showschema(self.ns_leader, name) self.assertEqual(len(schema), 6) self.assertEqual(schema[0], ['0', 'card', 'string']) self.assertEqual(schema[1], ['1', 'mcc', 'string']) self.assertEqual(schema[2], ['2', 'amt', 'double']) self.assertEqual(schema[3], ['3', 'ts1', 'int64']) self.assertEqual(schema[4], ['4', 'ts2', 'int64']) self.assertEqual(schema[5], ['5', 'aa', 'string']) self.assertEqual(len(column_key), 3) self.assertEqual(column_key[0], ["0", "card", "card", "ts1", "0min"]) self.assertEqual(column_key[1], ["1", "card", "card", "ts2", "0min"]) self.assertEqual(column_key[2], ["2", "mcc", "mcc", "ts2", "0min"]) self.ns_drop(self.ns_leader, name) def test_add_table_field_without_columnkey(self): name = 'tname{}'.format(time.time()) metadata_path = '{}/metadata.txt'.format(self.testpath) table_meta = { "name": name, "ttl": 14400, "column_desc":[ {"name": "card", "type": "string", "add_ts_idx": "true"}, {"name": "mcc", "type": "string", "add_ts_idx": "true"}, {"name": "amt", "type": "double", "add_ts_idx": "false"}, {"name": "ts1", "type": "int64", "add_ts_idx": "false"} ] } utils.gen_table_meta_file(table_meta, metadata_path) rs = self.ns_create(self.ns_leader, metadata_path) self.assertIn('Create table ok', rs) (schema, column_key) = self.ns_showschema(self.ns_leader, name) self.assertEqual(len(schema), 4) self.assertEqual(schema[0], ["0", "card", "string", "yes"]) self.assertEqual(schema[1], ["1", "mcc", "string", "yes"]) self.assertEqual(schema[2], ["2", "amt", "double", "no"]) self.assertEqual(schema[3], ["3", "ts1", "int64", "no"]) self.ns_add_table_field(self.ns_leader, name, 'aa', 'string'); (schema, column_key) = self.ns_showschema(self.ns_leader, name) self.assertEqual(len(schema), 5) self.assertEqual(schema[0], ["0", "card", "string", "yes"]) self.assertEqual(schema[1], ["1", "mcc", "string", "yes"]) self.assertEqual(schema[2], ["2", "amt", "double", "no"]) self.assertEqual(schema[3], ["3", "ts1", "int64", "no"]) self.assertEqual(schema[4], ["4", "aa", "string", "no"]) self.ns_drop(self.ns_leader, name) if __name__ == "__main__": load(TestAddTableField)
2,661
3,384
<reponame>teemobean/XVim<gh_stars>1000+ // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #pragma mark Function Pointers and Blocks typedef void (*CDUnknownFunctionPointerType)(void); // return type and parameters are unknown typedef void (^CDUnknownBlockType)(void); // return type and parameters are unknown #pragma mark Named Structures struct _NSRange { unsigned long long location; unsigned long long length; }; #pragma mark Typedef'd Structures typedef struct { unsigned long long state; id *itemsPtr; unsigned long long *mutationsPtr; unsigned long long extra[5]; } CDStruct_58648341; #pragma mark - // // File: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/MIME.framework/MIME // UUID: C969F586-B3B0-3786-9C4B-DBB9766834F0 // // Arch: x86_64 // Current version: 20.0.0 // Compatibility version: 1.0.0 // Source version: 2243.0.0.0.0 // Minimum iOS version: 8.0.0 // SDK version: 8.0.0 // // Objective-C Garbage Collection: Unsupported // @protocol MFCollectingDataConsumer <MFDataConsumer> - (NSData *)data; @end @protocol MFDataConsumer <NSObject> - (void)done; - (long long)appendData:(NSData *)arg1; @end @protocol MFFuture <NSObject> @property(readonly, getter=isCancelled) _Bool cancelled; @property(readonly, getter=isFinished) _Bool finished; - (void)addFailureBlock:(void (^)(NSError *))arg1; - (void)addSuccessBlock:(void (^)(id))arg1; - (_Bool)cancel; - (id)resultBeforeDate:(NSDate *)arg1 error:(id *)arg2; - (id)resultWithTimeout:(double)arg1 error:(id *)arg2; - (id)result:(id *)arg1; @end @protocol MFGuaranteedCollectingDataConsumer <MFCollectingDataConsumer> - (NSData *)data; @end @protocol MFLockObject - (id)initWithName:(NSString *)arg1 andDelegate:(id)arg2; - (_Bool)isLockedByMe; @end @protocol NSCopying - (id)copyWithZone:(struct _NSZone *)arg1; @end @protocol NSMutableCopying - (id)mutableCopyWithZone:(struct _NSZone *)arg1; @end @protocol NSObject @property(readonly, copy) NSString *description; @property(readonly) Class superclass; @property(readonly) unsigned long long hash; - (struct _NSZone *)zone; - (unsigned long long)retainCount; - (id)autorelease; - (oneway void)release; - (id)retain; - (_Bool)respondsToSelector:(SEL)arg1; - (_Bool)conformsToProtocol:(Protocol *)arg1; - (_Bool)isMemberOfClass:(Class)arg1; - (_Bool)isKindOfClass:(Class)arg1; - (_Bool)isProxy; - (id)performSelector:(SEL)arg1 withObject:(id)arg2 withObject:(id)arg3; - (id)performSelector:(SEL)arg1 withObject:(id)arg2; - (id)performSelector:(SEL)arg1; - (id)self; - (Class)class; - (_Bool)isEqual:(id)arg1; @optional @property(readonly, copy) NSString *debugDescription; @end @interface MFBaseFilterDataConsumer : NSObject <MFDataConsumer> { NSMutableArray *_consumers; _Bool _serialAppend; } + (id)filterWithConsumer:(id)arg1; + (id)filterWithConsumers:(id)arg1; @property(readonly, nonatomic) NSArray *consumers; // @synthesize consumers=_consumers; @property(nonatomic, getter=isSerialAppend) _Bool serialAppend; // @synthesize serialAppend=_serialAppend; - (void)dealloc; - (void)done; - (long long)appendData:(id)arg1; - (id)initWithConsumer:(id)arg1; - (id)initWithConsumers:(id)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface MFBase64Decoder : MFBaseFilterDataConsumer { NSMutableData *_leftovers; unsigned int _decodedBits; unsigned long long _validBytes; unsigned long long _equalCount; const char *_table; _Bool _bound; } + (_Bool)isValidBase64:(id)arg1; @property(nonatomic) _Bool isBound; // @synthesize isBound=_bound; @property(readonly, nonatomic) unsigned long long unconverted; // @synthesize unconverted=_validBytes; @property(nonatomic) _Bool convertCommas; - (void)dealloc; - (void)done; - (long long)appendData:(id)arg1; - (unsigned long long)_decodeBytes:(const char *)arg1 end:(const char *)arg2 into:(char *)arg3 length:(unsigned long long)arg4 startingAt:(unsigned long long)arg5 outEncodedOffset:(unsigned long long *)arg6; - (id)initWithConsumers:(id)arg1; @end @interface MFBase64Encoder : MFBaseFilterDataConsumer { const char *_table; unsigned long long _left; unsigned char _leftovers[3]; unsigned long long _line; unsigned long long _lineBreak; BOOL _padChar; } @property(nonatomic) BOOL padChar; // @synthesize padChar=_padChar; @property(nonatomic) unsigned long long lineBreak; // @synthesize lineBreak=_lineBreak; - (void)setStandardLineBreak; @property(nonatomic) _Bool allowSlash; - (void)done; - (long long)appendData:(id)arg1; - (id)initWithConsumers:(id)arg1; @end @interface MFBufferedDataConsumer : NSObject <MFGuaranteedCollectingDataConsumer> { NSMutableData *_data; int _fd; NSString *_path; } - (void)done; - (long long)appendData:(id)arg1; - (id)data; - (void)dealloc; - (id)init; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface MFByteSet : NSObject <NSCopying, NSMutableCopying> { char mySet[32]; } + (id)suspiciousCodepage1252ByteSet; + (id)nonASCIIByteSet; + (id)ASCIIByteSet; + (id)asciiWhitespaceSet; - (id)mutableCopyWithZone:(struct _NSZone *)arg1; - (id)copyWithZone:(struct _NSZone *)arg1; - (id)_initWithSet:(const char *)arg1; - (id)initWithBytes:(const void *)arg1 length:(unsigned int)arg2; - (id)initWithCString:(const char *)arg1; - (id)initWithRange:(struct _NSRange)arg1; - (id)invertedSet; - (_Bool)byteIsMember:(BOOL)arg1; @end @interface MFConditionLock : NSConditionLock <MFLockObject> { NSString *_name; id _delegate; } + (void)initialize; - (void)dealloc; - (id)description; - (void)unlockWithCondition:(long long)arg1; - (void)unlock; - (_Bool)lockWhenCondition:(long long)arg1 beforeDate:(id)arg2; - (_Bool)lockBeforeDate:(id)arg1; - (_Bool)isLockedByMe; - (id)initWithName:(id)arg1 condition:(long long)arg2 andDelegate:(id)arg3; - (id)initWithName:(id)arg1 andDelegate:(id)arg2; - (id)init; @end @interface MFNullDataConsumer : NSObject <MFDataConsumer> { } - (void)done; @property(readonly, copy) NSString *description; - (long long)appendData:(id)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface MFCountingDataConsumer : MFNullDataConsumer { unsigned long long _count; } @property(readonly, nonatomic) unsigned long long count; // @synthesize count=_count; - (long long)appendData:(id)arg1; @end @interface MFData : NSData <NSCopying, NSMutableCopying> { NSData *_internal; NSString *_path; NSData *_parent; _Bool _subdata; } + (void)setDefaultMappingThresholdInBytes:(unsigned long long)arg1; - (_Bool)mf_immutable; - (_Bool)writeToURL:(id)arg1 options:(unsigned long long)arg2 error:(id *)arg3; - (_Bool)writeToFile:(id)arg1 options:(unsigned long long)arg2 error:(id *)arg3; - (_Bool)writeToURL:(id)arg1 atomically:(_Bool)arg2; - (_Bool)writeToFile:(id)arg1 atomically:(_Bool)arg2; - (id)data; - (id)_initWithRange:(struct _NSRange)arg1 from:(id)arg2 retainingParent:(_Bool)arg3; - (id)subdataWithRange:(struct _NSRange)arg1; - (const void *)bytes; - (unsigned long long)length; - (void)dealloc; - (id)mutableCopyWithZone:(struct _NSZone *)arg1; - (id)copyWithZone:(struct _NSZone *)arg1; - (id)initWithImmutableData:(id)arg1; - (id)initWithData:(id)arg1; - (id)_initWithData:(id)arg1 maybeMutable:(_Bool)arg2; - (id)initWithContentsOfFile:(id)arg1; - (id)initWithContentsOfFile:(id)arg1 options:(unsigned long long)arg2 error:(id *)arg3; - (id)initWithContentsOfMappedFile:(id)arg1; - (id)initWithContentsOfURL:(id)arg1; - (id)initWithContentsOfURL:(id)arg1 options:(unsigned long long)arg2 error:(id *)arg3; - (id)initWithBytesNoCopy:(void *)arg1 length:(unsigned long long)arg2 freeWhenDone:(_Bool)arg3; - (id)initWithBytesNoCopy:(void *)arg1 length:(unsigned long long)arg2; - (id)initWithBytes:(const void *)arg1 length:(unsigned long long)arg2; - (id)_initWithFile:(id)arg1; - (id)init; @end @interface MFMessageStore : NSObject <NSCopying> { NSMutableSet *_uniqueStrings; MFMessageStoreObjectCaches *objectCaches; MFMessageStoreIntKeyCaches *intKeyCaches; } + (void)setDefaultMessageHeadersClass:(Class)arg1; + (Class)classForMimePart; + (Class)headersClass; @property(retain, nonatomic) MFMessageStoreIntKeyCaches *intKeyCaches; // @synthesize intKeyCaches; @property(retain, nonatomic) MFMessageStoreObjectCaches *objectCaches; // @synthesize objectCaches; - (id)additionalHeadersForForwardOfMessage:(id)arg1; - (id)additionalHeadersForReplyOfMessage:(id)arg1; - (void)setMessageClass:(Class)arg1; - (_Bool)wantsLineEndingConversionForMIMEPart:(id)arg1; - (void)setNumberOfAttachments:(unsigned int)arg1 isSigned:(_Bool)arg2 isEncrypted:(_Bool)arg3 forMessage:(id)arg4; - (_Bool)hasCompleteDataForMimePart:(id)arg1; - (id)bodyDataForMessage:(id)arg1 isComplete:(_Bool *)arg2 isPartial:(_Bool *)arg3 downloadIfNecessary:(_Bool)arg4; - (id)_fetchBodyDataForMessage:(id)arg1 andHeaderDataIfReadilyAvailable:(id *)arg2 downloadIfNecessary:(_Bool)arg3 partial:(_Bool *)arg4; - (void)_flushAllCaches; - (id)_cachedBodyDataContainerForMessage:(id)arg1 valueIfNotPresent:(id)arg2; - (id)_cachedHeadersForMessage:(id)arg1 valueIfNotPresent:(id)arg2; - (id)_cachedBodyForMessage:(id)arg1 valueIfNotPresent:(id)arg2; - (id)_cachedBodyDataForMessage:(id)arg1 valueIfNotPresent:(id)arg2; - (id)_cachedHeaderDataForMessage:(id)arg1 valueIfNotPresent:(id)arg2; - (id)bestAlternativeForPart:(id)arg1; - (id)defaultAlternativeForPart:(id)arg1; - (id)decryptedTopLevelPartForPart:(id)arg1; - (_Bool)dataForMimePart:(id)arg1 inRange:(struct _NSRange)arg2 withConsumer:(id)arg3 downloadIfNecessary:(_Bool)arg4; - (_Bool)dataForMimePart:(id)arg1 inRange:(struct _NSRange)arg2 isComplete:(_Bool *)arg3 withConsumer:(id)arg4 downloadIfNecessary:(_Bool)arg5 didDownload:(_Bool *)arg6; - (id)dataForMimePart:(id)arg1 inRange:(struct _NSRange)arg2 isComplete:(_Bool *)arg3 downloadIfNecessary:(_Bool)arg4 didDownload:(_Bool *)arg5; - (id)uniquedString:(id)arg1; - (id)fullBodyDataForMessage:(id)arg1 andHeaderDataIfReadilyAvailable:(id *)arg2 isComplete:(_Bool *)arg3 downloadIfNecessary:(_Bool)arg4 didDownload:(_Bool *)arg5; - (id)bodyForMessage:(id)arg1 fetchIfNotAvailable:(_Bool)arg2 updateFlags:(_Bool)arg3; - (id)_bodyForMessage:(id)arg1 fetchIfNotAvailable:(_Bool)arg2 updateFlags:(_Bool)arg3; - (_Bool)bodyFetchRequiresNetworkActivity; @property(copy, nonatomic) NSString *storagePath; - (id)_setOrGetBody:(id)arg1 forMessage:(id)arg2 updateFlags:(_Bool)arg3; - (id)headersForMessage:(id)arg1 fetchIfNotAvailable:(_Bool)arg2; - (id)headerDataForMessage:(id)arg1 downloadIfNecessary:(_Bool)arg2; - (id)copyWithZone:(struct _NSZone *)arg1; - (void)_flushAllMessageData; - (void)dealloc; - (id)init; @end @interface MFDataMessageStore : MFMessageStore { NSData *_data; Class _messageClass; NSString *_storagePath; } - (id)mailboxUid; - (id)storeData:(id)arg1 forMimePart:(id)arg2 isComplete:(_Bool)arg3; - (id)_cachedBodyDataForMessage:(id)arg1 valueIfNotPresent:(id)arg2; - (id)_cachedHeadersForMessage:(id)arg1 valueIfNotPresent:(id)arg2; - (id)_cachedBodyForMessage:(id)arg1 valueIfNotPresent:(id)arg2; - (id)bodyDataForMessage:(id)arg1 isComplete:(_Bool *)arg2 isPartial:(_Bool *)arg3 downloadIfNecessary:(_Bool)arg4; - (_Bool)bodyFetchRequiresNetworkActivity; - (id)headerDataForMessage:(id)arg1 downloadIfNecessary:(_Bool)arg2; - (id)account; - (id)message; - (void)setMessageClass:(Class)arg1; - (void)writeUpdatedMessageDataToDisk; - (void)setStoragePath:(id)arg1; - (id)storagePath; - (id)storePath; - (void)dealloc; - (id)initWithData:(id)arg1; @end @interface MFEmailSet : NSMutableSet { struct __CFSet *_set; } + (id)set; - (void)setSet:(id)arg1; - (void)intersectSet:(id)arg1; - (void)minusSet:(id)arg1; - (void)unionSet:(id)arg1; - (void)removeAllObjects; - (void)removeObject:(id)arg1; - (void)addObject:(id)arg1; - (unsigned long long)countByEnumeratingWithState:(CDStruct_58648341 *)arg1 objects:(id *)arg2 count:(unsigned long long)arg3; - (id)objectEnumerator; - (id)allObjects; - (id)allCommentedAddresses; - (id)_generateAllObjectsFromSelector:(SEL)arg1; - (_Bool)isEqualToSet:(id)arg1; - (_Bool)isSubsetOfSet:(id)arg1; - (_Bool)intersectsSet:(id)arg1; - (id)member:(id)arg1; - (unsigned long long)count; - (id)copyWithZone:(struct _NSZone *)arg1; - (id)mutableCopyWithZone:(struct _NSZone *)arg1; - (void)dealloc; - (void)_setupSetWithCapacity:(unsigned long long)arg1; - (id)initWithCapacity:(unsigned long long)arg1; - (id)init; @end @interface MFFuture : NSObject <MFFuture> { NSConditionLock *_stateLock; id _result; NSError *_error; NSMutableArray *_completionBlocks; } + (id)future; - (void)_flushCompletionBlocks; - (void)_addCompletionBlock:(CDUnknownBlockType)arg1; - (void)addFailureBlock:(CDUnknownBlockType)arg1; - (void)addSuccessBlock:(CDUnknownBlockType)arg1; - (_Bool)_nts_isFinished; - (_Bool)finishWithError:(id)arg1; - (_Bool)finishWithResult:(id)arg1; - (_Bool)finishWithResult:(id)arg1 error:(id)arg2; - (void)didCancel; - (_Bool)cancel; @property(readonly, getter=isCancelled) _Bool cancelled; @property(readonly, getter=isFinished) _Bool finished; - (id)resultBeforeDate:(id)arg1 error:(id *)arg2; - (id)resultWithTimeout:(double)arg1 error:(id *)arg2; - (id)result:(id *)arg1; - (void)dealloc; - (id)init; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface MFHTMLParser : NSObject { } + (id)plainTextFromHTMLSnippet:(id)arg1; + (id)plainTextFromHTML:(id)arg1; + (id)plainTextFromHTML:(id)arg1 limit:(unsigned long long)arg2; + (id)plainTextFromHTML:(id)arg1 limit:(unsigned long long)arg2 preserveNewlines:(_Bool)arg3; @end @interface MFLineEndingConverterFilter : MFBaseFilterDataConsumer { _Bool _lastCR; } - (void)done; - (long long)appendData:(id)arg1; @end @interface MFLock : NSLock <MFLockObject> { NSString *_name; id _delegate; } + (void)initialize; - (void)dealloc; - (id)description; - (void)unlock; - (_Bool)lockBeforeDate:(id)arg1; - (_Bool)tryLock; - (void)lock; - (_Bool)isLockedByMe; - (id)initWithName:(id)arg1 andDelegate:(id)arg2; - (id)init; @end @interface MFMessage : NSObject <NSCopying> { MFMessageStore *_store; unsigned int _preferredEncoding; NSString *_senderAddressComment; unsigned int _dateSentInterval; unsigned int _dateReceivedInterval; unsigned long long _generationNumber; NSString *_subject; NSArray *_to; NSArray *_cc; NSArray *_bcc; NSArray *_sender; NSString *_contentType; long long _messageIDHeaderHash; long long _conversationID; NSString *_summary; NSString *_externalID; MFMimePart *_parentPart; NSURL *_messageURL; NSString *_cachedMessageIDHeader; unsigned int _calculatedAttachmentInfo:1; unsigned short _numberOfAttachments; } + (void)setMessageClassForStore:(id)arg1; + (id)messageWithRFC822Data:(id)arg1 withParentPart:(id)arg2; + (id)messageWithRFC822Data:(id)arg1; + (Class)dataMessageStoreToUse; @property(retain, nonatomic) MFMimePart *parentPart; // @synthesize parentPart=_parentPart; - (id)additionalHeadersForForward; - (id)additionalHeadersForReply; - (_Bool)isLibraryMessage; - (_Bool)canBeDeleted; - (id)bestAlternativeInPart:(id)arg1; - (id)defaultAlternativeInPart:(id)arg1; - (long long)generationCompare:(id)arg1; - (unsigned long long)generationNumber; - (void)setGenerationNumber:(unsigned long long)arg1; - (void)setNumberOfAttachments:(unsigned int)arg1; - (void)setNumberOfAttachments:(unsigned int)arg1 isSigned:(_Bool)arg2 isEncrypted:(_Bool)arg3; - (void)calculateAttachmentInfoFromBody:(id)arg1; - (void)_calculateAttachmentInfoFromBody:(id)arg1; - (id)dataPathForMimePart:(id)arg1; - (_Bool)fetchDataForMimePart:(id)arg1 inRange:(struct _NSRange)arg2 withConsumer:(id)arg3 isComplete:(_Bool *)arg4 downloadIfNecessary:(_Bool)arg5; - (id)dataForMimePart:(id)arg1 inRange:(struct _NSRange)arg2 isComplete:(_Bool *)arg3 downloadIfNecessary:(_Bool)arg4 didDownload:(_Bool *)arg5; - (id)dataForMimePart:(id)arg1 inRange:(struct _NSRange)arg2 isComplete:(_Bool *)arg3; - (id)dataForMimePart:(id)arg1; - (id)headerDataDownloadIfNecessary:(_Bool)arg1; - (id)headerData; - (id)bodyDataIsComplete:(_Bool *)arg1 isPartial:(_Bool *)arg2 downloadIfNecessary:(_Bool)arg3; - (id)bodyDataIsComplete:(_Bool *)arg1 isPartial:(_Bool *)arg2; - (id)bodyDataIsComplete:(_Bool *)arg1; - (id)bodyData; - (id)persistentID; - (id)attachmentStorageLocation; - (id)path; - (unsigned int)uid; - (id)remoteID; - (void)setMessageInfoFromMessage:(id)arg1; - (void)setSubject:(id)arg1 to:(id)arg2 cc:(id)arg3 bcc:(id)arg4 sender:(id)arg5 dateReceived:(double)arg6 dateSent:(double)arg7 messageIDHash:(long long)arg8 conversationIDHash:(long long)arg9 summary:(id)arg10 withOptions:(unsigned int)arg11; - (void)setMessageInfo:(id)arg1 to:(id)arg2 cc:(id)arg3 bcc:(id)arg4 sender:(id)arg5 dateReceivedTimeIntervalSince1970:(double)arg6 dateSentTimeIntervalSince1970:(double)arg7 messageIDHash:(long long)arg8 conversationID:(long long)arg9 summary:(id)arg10; - (id)uniqueArray:(id)arg1 withStore:(id)arg2; - (id)summary; - (void)setExternalID:(id)arg1; - (id)externalID; - (void)setConversationID:(long long)arg1; - (void)setMessageIDHash:(long long)arg1; - (long long)conversationID; - (void)setBcc:(id)arg1; - (id)bccIfCached; - (id)bcc; - (void)setCc:(id)arg1; - (id)ccIfCached; - (id)cc; - (void)setTo:(id)arg1; - (id)toIfCached; - (id)to; - (id)senderAddressComment; - (void)setSender:(id)arg1; - (id)firstSender; - (id)sendersIfCached; - (id)senders; - (void)setContentType:(id)arg1; - (id)contentType; - (void)setDateSentTimeIntervalSince1970:(double)arg1; - (double)dateSentAsTimeIntervalSince1970; - (_Bool)needsDateReceived; - (double)dateReceivedAsTimeIntervalSince1970; - (void)setDateReceivedTimeIntervalSince1970:(double)arg1; - (id)dateSent; - (id)dateReceived; - (void)setSubject:(id)arg1; - (id)subjectIfCached; - (id)subject; - (void)loadCachedHeaderValuesFromHeaders:(id)arg1; - (void)_setDateSentFromHeaders:(id)arg1; - (void)_setDateReceivedFromHeaders:(id)arg1; - (id)_copyDateFromDateHeaderInHeaders:(id)arg1; - (id)_copyDateFromReceivedHeadersInHeaders:(id)arg1; - (_Bool)_doesDateAppearToBeSane:(id)arg1; - (void)setPreferredEncoding:(unsigned int)arg1; - (unsigned int)preferredEncoding; - (_Bool)calculatedNumberOfAttachments; - (unsigned short)numberOfAttachments; - (_Bool)isMessageContentsLocallyAvailable; - (long long)_messageIDHeaderHashIvar; - (id)messageIDHeaderInFortyBytesOrLess; - (void)setMessageIDHeader:(id)arg1; - (id)messageIDHeader; - (long long)messageIDHash; - (id)messageURL; - (void)setMessageURL:(id)arg1; - (id)messageID; - (id)preferredEmailAddressToReplyWith; - (unsigned long long)messageSize; - (void)dealloc; - (id)dataConsumerForMimePart:(id)arg1; - (void)setMessageData:(id)arg1 isPartial:(_Bool)arg2; - (id)messageData; - (id)messageDataIsComplete:(_Bool *)arg1 downloadIfNecessary:(_Bool)arg2; - (_Bool)messageData:(id *)arg1 messageSize:(unsigned long long *)arg2 isComplete:(_Bool *)arg3 downloadIfNecessary:(_Bool)arg4; - (id)messageBodyIfAvailableUpdatingFlags:(_Bool)arg1; - (id)messageBodyUpdatingFlags:(_Bool)arg1; - (id)messageBodyIfAvailable; - (id)messageBody; - (id)headersIfAvailable; - (id)headers; - (void)setMessageStore:(id)arg1; - (id)messageStore; - (id)copyWithZone:(struct _NSZone *)arg1; - (id)init; @end @interface MFMessageBody : NSObject { MFMessage *_message; } - (void)dealloc; - (id)textHtmlPart; - (id)attachmentURLs; - (id)attachments; - (unsigned int)numberOfAttachmentsSigned:(_Bool *)arg1 encrypted:(_Bool *)arg2; - (id)message; - (void)setMessage:(id)arg1; - (_Bool)isRich; - (_Bool)isHTML; - (id)htmlContent; - (id)contentToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 asHTML:(_Bool)arg3 isComplete:(_Bool *)arg4; - (id)htmlContentToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2; - (id)contentToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 asHTML:(_Bool)arg3; - (id)rawData; @end @interface MFMessageDataContainer : NSObject { NSData *_data; _Bool _partial; _Bool _incomplete; } - (void)dealloc; - (id)data; - (id)initWithData:(id)arg1; - (id)initWithData:(id)arg1 partial:(_Bool)arg2 incomplete:(_Bool)arg3; @end @interface MFMessageFileWrapper : NSObject { NSString *_path; NSString *_filename; NSString *_preferredFilename; NSData *_data; NSMutableDictionary *_attributes; NSString *_linkDestination; NSString *_url; int _type; } - (id)description; - (void)dealloc; - (id)fileAttributes; - (void)setFileAttributes:(id)arg1; - (id)regularFileContents; - (id)symbolicLinkDestination; - (id)fileWrappers; - (_Bool)isDirectory; - (_Bool)isRegularFile; - (_Bool)isSymbolicLink; - (id)filename; - (void)setFilename:(id)arg1; - (id)preferredFilename; - (void)setPreferredFilename:(id)arg1; - (id)initSymbolicLinkWithDestination:(id)arg1; - (id)initRegularFileWithContents:(id)arg1; - (void)setURL:(id)arg1; - (id)URL; - (_Bool)isPlaceholder; - (void)setPath:(id)arg1; - (id)path; - (id)initWithPath:(id)arg1; - (_Bool)isUnzippableFile; - (_Bool)isPDFFile; - (_Bool)isImageFile; - (void)_isImage:(_Bool *)arg1 orPDFFile:(_Bool *)arg2; - (id)fileProtection; - (void)setFileProtection:(id)arg1; - (id)icsRepresentation; - (void)setICSRepresentation:(id)arg1; - (id)meetingStorePersistentID; - (void)setMeetingStorePersistentID:(id)arg1; - (id)eventUniqueID; - (void)setEventUniqueID:(id)arg1; - (id)messageID; - (void)setMessageID:(id)arg1; - (id)contentID; - (void)setContentID:(id)arg1; - (id)inferredMimeType; - (id)mimeType; - (void)setMimeType:(id)arg1; - (unsigned short)finderFlags; - (void)setFinderFlags:(unsigned short)arg1; - (unsigned int)creator; - (void)setCreator:(unsigned int)arg1; - (unsigned int)type; - (void)setType:(unsigned int)arg1; @end @interface MFMessageHeaders : NSObject <NSCopying> { NSData *_data; unsigned int _preferredEncoding; } + (id)uniqueHeaderKeyStringForString:(id)arg1; + (id)encodedDataForAddressList:(id)arg1 splittingAtLength:(unsigned long long)arg2 firstLineBuffer:(unsigned long long)arg3; + (id)addressListFromEncodedString:(id)arg1; + (id)copyAddressListFromEncodedData:(id)arg1 encoding:(unsigned int)arg2; + (_Bool)shouldDecodeHeaderForKey:(id)arg1; + (_Bool)isStructuredHeaderKey:(id)arg1; + (id)basicHeaders; - (id)description; - (void)appendHeaderData:(id)arg1 andRecipients:(id)arg2; - (id)encodedHeaders; - (_Bool)messageIsFromEntourage; - (id)_decodeHeaderKeysFromData:(id)arg1; - (id)copyFirstStringValueForKey:(id)arg1; - (id)copyFirstNonDecodedHeaderForKey:(id)arg1; - (id)copyFirstHeaderForKey:(id)arg1; - (id)firstHeaderForKey:(id)arg1; - (id)references; - (id)copyAddressListForReplyTo; - (id)copyAddressListForResentFrom; - (id)copyAddressListForBcc; - (id)copyAddressListForCc; - (id)copyAddressListForTo; - (id)firstSenderAddress; - (id)copyAddressListForSender; - (id)_copyAddressListForKey:(id)arg1; - (id)headersForKey:(id)arg1; - (id)copyHeadersForKey:(id)arg1; - (_Bool)hasHeaderForKey:(id)arg1; - (id)_headerValueForKey:(id)arg1; - (id)_copyHeaderValueForKey:(id)arg1; - (id)_headerValueForKey:(id)arg1 offset:(unsigned long long *)arg2; - (id)_copyHeaderValueForKey:(id)arg1 offset:(unsigned long long *)arg2 decoded:(_Bool)arg3; - (id)copyDecodedStringFromHeaderData:(id)arg1 withRange:(struct _NSRange)arg2; - (unsigned int)_contentTypeEncoding; - (id)_capitalizedKeyForKey:(id)arg1; - (void)_setCapitalizedKey:(id)arg1 forKey:(id)arg2; - (id)allHeaderKeys; - (_Bool)_isStructuredHeaderKey:(id)arg1; - (void)setPreferredEncoding:(unsigned int)arg1; - (unsigned int)preferredEncoding; - (id)headerData; - (id)mutableCopy; - (void)dealloc; - (id)copyWithZone:(struct _NSZone *)arg1; - (id)initWithHeaderData:(id)arg1 encoding:(unsigned int)arg2; - (id)init; @end @interface MFMessageStoreIntKeyCaches : NSObject { NSMapTable *headerDataCache; NSMapTable *headerCache; NSMapTable *bodyDataCache; NSMapTable *bodyCache; } @property(retain, nonatomic) NSMapTable *bodyCache; // @synthesize bodyCache; @property(retain, nonatomic) NSMapTable *bodyDataCache; // @synthesize bodyDataCache; @property(retain, nonatomic) NSMapTable *headerCache; // @synthesize headerCache; @property(retain, nonatomic) NSMapTable *headerDataCache; // @synthesize headerDataCache; - (void)dealloc; - (void)flush; - (void)setCache:(id)arg1 forType:(unsigned long long)arg2; - (id)copyCacheForType:(unsigned long long)arg1; @end @interface MFMessageStoreObjectCaches : NSObject { NSMutableArray *headerDataCache; NSMutableArray *headerCache; NSMutableArray *bodyDataCache; NSMutableArray *bodyCache; } @property(retain, nonatomic) NSMutableArray *bodyCache; // @synthesize bodyCache; @property(retain, nonatomic) NSMutableArray *bodyDataCache; // @synthesize bodyDataCache; @property(retain, nonatomic) NSMutableArray *headerCache; // @synthesize headerCache; @property(retain, nonatomic) NSMutableArray *headerDataCache; // @synthesize headerDataCache; - (void)dealloc; - (void)flush; - (void)setCache:(id)arg1 forType:(unsigned long long)arg2; - (id)copyCacheForType:(unsigned long long)arg1; @end @interface MFMessageTextAttachment : NSObject { NSMutableDictionary *_cache; } + (unsigned long long)precedenceLevel; - (id)persistentUniqueIdentifier; - (id)fileWrapperForcingDownload:(_Bool)arg1; - (void)inlineDisplayData:(id *)arg1 mimeType:(id *)arg2; - (_Bool)isPlaceholder; - (void)download; - (_Bool)needsRedownload; - (_Bool)hasBeenDownloaded; - (unsigned int)approximateSize; @property(retain, nonatomic) MFMessageFileWrapper *fileWrapper; - (void)setCachedValue:(id)arg1 forKey:(id)arg2; - (id)cachedValueForKey:(id)arg1; - (id)description; - (void)dealloc; - (id)initWithWrapper:(id)arg1; - (id)init; - (void)setMimePart:(id)arg1; - (id)mimePart; - (id)textEncodingNameForData:(id)arg1 mimeType:(id)arg2; - (id)textEncodingGuess; - (_Bool)shouldDownloadAttachmentOnDisplay; @end @interface MFMimeBody : MFMessageBody { MFMimePart *_topLevelPart; unsigned int _preferredAlternative:16; unsigned int _numAlternatives:16; } + (id)copyNewMimeBoundary; + (id)versionString; - (id)textHtmlPart; - (id)preferredBodyPart; - (long long)preferredAlternative; - (void)setPreferredAlternative:(long long)arg1; - (long long)numberOfAlternatives; - (unsigned long long)totalTextSize; - (id)contentToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 asHTML:(_Bool)arg3 isComplete:(_Bool *)arg4; - (_Bool)isRich; - (_Bool)isHTML; - (id)attachmentURLs; - (id)attachments; - (unsigned int)numberOfAttachmentsSigned:(_Bool *)arg1 encrypted:(_Bool *)arg2; - (id)firstPartPassingTest:(CDUnknownBlockType)arg1; - (id)partWithNumber:(id)arg1; - (id)mimeSubtype; - (id)mimeType; - (void)setTopLevelPart:(id)arg1; - (id)topLevelPart; - (void)dealloc; - (id)init; @end @interface MFMimeCharset : NSObject { unsigned int _encoding; NSString *_primaryLanguage; NSString *_charsetName; unsigned int _coversLargeUnicodeSubset:1; unsigned int _useBase64InHeaders:1; unsigned int _canBeUsedForOutgoingMessages:1; } + (id)preferredMimeCharset; + (id)charsetForEncoding:(unsigned int)arg1; + (id)allMimeCharsets; + (id)allMimeCharsets:(_Bool)arg1; - (id)description; - (id)primaryLanguage; - (id)displayName; - (_Bool)useBase64InHeaders; - (_Bool)coversLargeUnicodeSubset; - (_Bool)canBeUsedForOutgoingMessages; - (id)charsetName; - (unsigned int)encoding; - (void)dealloc; - (void)_setPrimaryLanguage:(id)arg1; - (id)initWithEncoding:(unsigned int)arg1; @end @interface MFMimePart : NSObject { NSString *_type; NSString *_subtype; NSMutableDictionary *_bodyParameters; NSString *_contentTransferEncoding; NSMutableDictionary *_otherIvars; struct _NSRange _range; MFWeakReferenceHolder *_parent; MFWeakReferenceHolder *_body; MFMimePart *_nextPart; NSURL *_partURL; NSURL *_parentPartURL; MFPartialNetworkDataConsumer *_partialDataConsumer; NSData *_fullData; MFWeakReferenceHolder *_decodedData; } + (_Bool)isRecognizedClassForContent:(id)arg1; + (Class)attachmentClass; + (_Bool)parseContentTypeHeader:(id)arg1 type:(id *)arg2 subtype:(id *)arg3; + (_Bool)parseContentTypeHeader:(id)arg1 type:(id *)arg2 subtype:(id *)arg3 info:(id *)arg4; + (void)initialize; - (void)setIsGenerated:(_Bool)arg1; - (_Bool)isGenerated; - (id)chosenAlternativePart; - (id)partURL; - (id)attachmentURLs; - (id)attachments; - (void)getNumberOfAttachments:(unsigned int *)arg1 isSigned:(_Bool *)arg2 isEncrypted:(_Bool *)arg3; - (unsigned int)numberOfAttachments; - (id)contentToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 downloadIfNecessary:(_Bool)arg3 asHTML:(_Bool)arg4; - (id)contentToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 asHTML:(_Bool)arg3; - (id)contentToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 downloadIfNecessary:(_Bool)arg3 asHTML:(_Bool)arg4 isComplete:(_Bool *)arg5; - (_Bool)_shouldContinueDecodingProcess; - (id)bodyDataForcingDownload:(_Bool)arg1; - (id)bodyDataToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 downloadIfNecessary:(_Bool)arg3; - (id)copyBodyDataToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 downloadIfNecessary:(_Bool)arg3; - (id)copyBodyDataToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2; - (id)copyBodyDataToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 downloadIfNecessary:(_Bool)arg3 isComplete:(_Bool *)arg4; - (void)_ensureBodyDataToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 downloadIfNecessary:(_Bool)arg3 isComplete:(_Bool *)arg4 decoded:(id *)arg5; - (_Bool)_hasCompleteBodyDataToOffset:(unsigned long long)arg1; - (id)storeData:(id)arg1 inMessage:(id)arg2 isComplete:(_Bool)arg3; - (id)fileWrapper; - (id)fileWrapperForcingDownload:(_Bool)arg1; - (void)download; - (void)configureFileWrapper:(id)arg1; - (id)fileWrapperForDecodedObject:(id)arg1 withFileData:(id *)arg2; - (void)clearCachedDescryptedMessageBody; - (id)decryptedMessageBodyIsEncrypted:(_Bool *)arg1 isSigned:(_Bool *)arg2; - (id)textHtmlPart; - (id)signedData; - (id)alternativeAtIndex:(long long)arg1; - (long long)numberOfAlternatives; - (id)startPart; - (unsigned long long)totalTextSize; - (void)_setDecryptedMessageBody:(id)arg1 isEncrypted:(_Bool)arg2 isSigned:(_Bool)arg3; - (void)_setRFC822DecodedMessageBody:(id)arg1; - (id)rfc822DecodedMessageBody; - (_Bool)usesKnownSignatureProtocol; - (_Bool)isHTML; - (_Bool)isRich; - (_Bool)isAttachment; - (_Bool)shouldConsiderInlineOverridingExchangeServer; - (id)_partThatIsAttachment; - (_Bool)isReadableText; - (unsigned int)approximateRawSize; - (unsigned int)textEncoding; - (id)attachmentFilename; - (id)description; - (void)setMimeBody:(id)arg1; - (id)mimeBody; - (id)decodedDataForData:(id)arg1; - (void)setRange:(struct _NSRange)arg1; - (struct _NSRange)range; - (void)addSubpart:(id)arg1; - (void)setSubparts:(id)arg1; - (id)subpartAtIndex:(long long)arg1; - (id)subparts; - (id)nextSiblingPart; - (id)firstChildPart; - (id)parentPart; - (void)setLanguages:(id)arg1; - (id)languages; - (void)setContentLocation:(id)arg1; - (id)contentLocation; - (void)setContentID:(id)arg1; - (id)contentID; - (void)setContentDescription:(id)arg1; - (id)contentDescription; - (id)dispositionParameterKeys; - (void)setDispositionParameter:(id)arg1 forKey:(id)arg2; - (id)dispositionParameterForKey:(id)arg1; - (void)setDisposition:(id)arg1; - (id)disposition; - (void)setContentTransferEncoding:(id)arg1; - (id)contentTransferEncoding; - (id)preservedHeaderValueForKey:(id)arg1; - (id)bodyParameterKeys; - (void)setBodyParameter:(id)arg1 forKey:(id)arg2; - (id)bodyParameterForKey:(id)arg1; - (void)setSubtype:(id)arg1; - (id)subtype; - (void)setType:(id)arg1; - (id)type; - (id)init; - (void)dealloc; - (_Bool)parseMimeBodyDownloadIfNecessary:(_Bool)arg1; - (_Bool)parseMimeBody; - (id)partNumber; - (_Bool)parseIMAPPropertyList:(id)arg1; - (void)decodeIfNecessary; - (id)bodyData; - (id)bodyDataToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2; - (id)contentsForTextSystem; - (id)contentsForTextSystemForcingDownload:(_Bool)arg1; - (id)contentsForTextSystemToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2; - (id)contentsForTextSystemToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 downloadIfNecessary:(_Bool)arg3; - (id)contentsForTextSystemToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 downloadIfNecessary:(_Bool)arg3 asHTML:(_Bool)arg4; - (_Bool)hasContents; - (id)contentsForTextSystemToOffset:(unsigned long long)arg1 resultOffset:(unsigned long long *)arg2 downloadIfNecessary:(_Bool)arg3 asHTML:(_Bool)arg4 isComplete:(_Bool *)arg5; - (void)_contents:(id *)arg1 toOffset:(unsigned long long)arg2 resultOffset:(unsigned long long *)arg3 downloadIfNecessary:(_Bool)arg4 asHTML:(_Bool)arg5 isComplete:(_Bool *)arg6; - (id)decodeText; - (id)_fullMimeTypeEvenInsideAppleDouble; - (id)decodeApplicationOctet_stream; - (id)decodeApplicationZip; - (id)decodeMultipart; - (id)decodeMultipartAlternative; - (id)decodeMultipartRelated; @end @interface MFMimeTextAttachment : MFMessageTextAttachment { } - (id)persistentUniqueIdentifier; - (unsigned int)approximateSize; - (_Bool)hasBeenDownloaded; - (void)download; - (id)_displayedMimePart; - (id)initWithMimePart:(id)arg1; @end @interface MFMutableByteSet : MFByteSet { } - (void)invert; - (void)removeBytesInRange:(struct _NSRange)arg1; - (void)addBytesInRange:(struct _NSRange)arg1; @end @interface MFMutableData : NSMutableData <NSCopying, NSMutableCopying> { void *_bytes; unsigned long long _length; unsigned long long _mappedLength; unsigned long long _capacity; unsigned long long _threshold; char *_path; int _fd; unsigned long long _flushFrom; _Bool _flush; _Bool _immutable; _Bool _vm; } - (_Bool)mf_immutable; - (void)_mapMutableData:(_Bool)arg1; - (void)_flushToDisk:(unsigned long long)arg1 capacity:(unsigned long long)arg2; - (_Bool)writeToURL:(id)arg1 options:(unsigned long long)arg2 error:(id *)arg3; - (_Bool)writeToFile:(id)arg1 options:(unsigned long long)arg2 error:(id *)arg3; - (_Bool)writeToURL:(id)arg1 atomically:(_Bool)arg2; - (_Bool)writeToFile:(id)arg1 atomically:(_Bool)arg2; - (void)mf_makeImmutable; - (void)setMappingThreshold:(unsigned int)arg1; - (void)setLength:(unsigned long long)arg1; - (id)subdataWithRange:(struct _NSRange)arg1; - (void)appendData:(id)arg1; - (void)appendBytes:(const void *)arg1 length:(unsigned long long)arg2; - (void *)mutableBytes; - (const void *)bytes; - (unsigned long long)length; - (void)dealloc; - (id)mutableCopyWithZone:(struct _NSZone *)arg1; - (id)copyWithZone:(struct _NSZone *)arg1; - (id)initWithLength:(unsigned long long)arg1; - (id)initWithCapacity:(unsigned long long)arg1; - (id)initWithData:(id)arg1; - (id)initWithContentsOfFile:(id)arg1; - (id)initWithContentsOfFile:(id)arg1 options:(unsigned long long)arg2 error:(id *)arg3; - (id)initWithContentsOfMappedFile:(id)arg1; - (id)initWithContentsOfURL:(id)arg1; - (id)initWithContentsOfURL:(id)arg1 options:(unsigned long long)arg2 error:(id *)arg3; - (id)initWithBytesNoCopy:(void *)arg1 length:(unsigned long long)arg2 freeWhenDone:(_Bool)arg3; - (id)initWithBytesNoCopy:(void *)arg1 length:(unsigned long long)arg2; - (id)_initWithFd:(int)arg1 path:(id)arg2 mutable:(_Bool)arg3; - (id)initWithBytes:(const void *)arg1 length:(unsigned long long)arg2; - (id)init; @end @interface MFMutableFilterDataConsumer : MFBaseFilterDataConsumer <MFGuaranteedCollectingDataConsumer> { id <MFGuaranteedCollectingDataConsumer> _mainConsumer; MFLock *_consumerLock; _Bool _isDone; } - (void)done; - (id)data; - (long long)appendData:(id)arg1; - (void)addDataConsumer:(id)arg1; - (void)dealloc; - (id)initWithMainConsumer:(id)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface MFMutableMessageHeaders : MFMessageHeaders { NSMutableDictionary *_headersAdded; NSMutableArray *_headersRemoved; } - (id)description; - (void)stripInternalHeaders; - (void)setReferences:(id)arg1; - (void)setAddressListForBcc:(id)arg1; - (void)setAddressListForCc:(id)arg1; - (void)setAddressListForTo:(id)arg1; - (void)setAddressListForSender:(id)arg1; - (void)setAddressList:(id)arg1 forKey:(id)arg2; - (id)encodedHeaders; - (id)_copyHeaderValueForKey:(id)arg1 offset:(unsigned long long *)arg2 decoded:(_Bool)arg3; - (id)_copyHeaderValueForKey:(id)arg1; - (void)_appendAddedHeaderKey:(id)arg1 value:(id)arg2 toData:(id)arg3; - (void)_appendHeaderKey:(id)arg1 value:(id)arg2 toData:(id)arg3; - (void)mergeHeaders:(id)arg1; - (void)setHeader:(id)arg1 forKey:(id)arg2; - (void)removeHeaderForKey:(id)arg1; - (id)firstHeaderForKey:(id)arg1; - (id)_headerValueForKey:(id)arg1; - (_Bool)hasHeaderForKey:(id)arg1; - (id)allHeaderKeys; - (void)dealloc; - (id)mutableCopy; @end @interface MFPartialNetworkDataConsumer : NSObject <MFDataConsumer> { id <MFGuaranteedCollectingDataConsumer> _rawDataConsumer; NSData *_strippedData; unsigned long long _length; unsigned int _seenNetworkLineEndings:1; } - (void)purge; - (id)copyDataWithUnixLineEndings; - (id)data; - (unsigned long long)length; - (void)done; - (long long)appendData:(id)arg1; - (void)dealloc; - (id)init; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface MFPlaceholderFileWrapper : MFMessageFileWrapper { } - (_Bool)isPlaceholder; @end @interface MFPriorityDesignator : NSObject { int _priority; } + (id)currentDesignator; - (void)setPriority:(int)arg1; - (int)priority; @end @interface MFProgressFilterDataConsumer : MFBaseFilterDataConsumer { unsigned long long _expectedSize; unsigned long long _currentBytes; CDUnknownBlockType _progressBlock; } @property(readonly) unsigned long long expectedSize; // @synthesize expectedSize=_expectedSize; @property(copy, nonatomic) CDUnknownBlockType progressBlock; // @synthesize progressBlock=_progressBlock; - (long long)appendData:(id)arg1; - (void)dealloc; - (id)initWithConsumers:(id)arg1 expectedSize:(unsigned long long)arg2; - (id)initWithConsumer:(id)arg1 expectedSize:(unsigned long long)arg2; @end @interface MFQuotedPrintableDecoder : MFBaseFilterDataConsumer { unsigned char _lastEncoded; unsigned long long _required; _Bool _forTextPart; _Bool _badlyEncoded; } @property(nonatomic) _Bool forTextPart; // @synthesize forTextPart=_forTextPart; - (void)done; - (long long)appendData:(id)arg1; @end @interface MFQuotedPrintableEncoder : MFBaseFilterDataConsumer { unsigned long long _line; unsigned long long _matchedFrom; unsigned char _lastHorizontalWhitespace; _Bool _forTextPart; _Bool _lastWasNewLine; _Bool _forHeader; } + (unsigned long long)requiredSizeToEncodeHeaderBytes:(const char *)arg1 length:(unsigned long long)arg2; @property(nonatomic) _Bool forHeader; // @synthesize forHeader=_forHeader; @property(nonatomic) _Bool forTextPart; // @synthesize forTextPart=_forTextPart; - (void)done; - (long long)appendData:(id)arg1; @end @interface MFRangedDataFilter : MFBaseFilterDataConsumer { struct _NSRange _range; unsigned long long _consumedLength; } + (id)rangedFilterWithConsumer:(id)arg1 range:(struct _NSRange)arg2; + (id)rangedFilterWithConsumers:(id)arg1 range:(struct _NSRange)arg2; @property(nonatomic) struct _NSRange range; // @synthesize range=_range; - (long long)appendData:(id)arg1; @end @interface MFRecursiveLock : NSRecursiveLock <MFLockObject> { NSString *_name; id _delegate; } + (void)initialize; - (void)dealloc; - (id)description; - (void)unlock; - (_Bool)lockBeforeDate:(id)arg1; - (_Bool)tryLock; - (void)lock; - (_Bool)isLockedByMe; - (id)initWithName:(id)arg1 andDelegate:(id)arg2; - (id)init; @end @interface MFUUDecoder : MFBaseFilterDataConsumer { unsigned long long _begin; unsigned long long _end; unsigned long long _length; unsigned long long _readBytes; unsigned char _encoded[4]; _Bool _beginComplete; _Bool _dataComplete; _Bool _validLength; _Bool _lineComplete; _Bool _passthrough; } - (void)done; - (long long)appendData:(id)arg1; @end @interface MFWeakDictionary : NSMutableDictionary { unsigned long long _gen; NSLock *_lock; NSMutableDictionary *_dictionary; } - (id)_copyDictionary; - (void)enumerateKeysAndObjectsUsingBlock:(CDUnknownBlockType)arg1; - (void)enumerateKeysAndObjectsWithOptions:(unsigned long long)arg1 usingBlock:(CDUnknownBlockType)arg2; - (unsigned long long)countByEnumeratingWithState:(CDStruct_58648341 *)arg1 objects:(id *)arg2 count:(unsigned long long)arg3; - (void)removeAllObjects; - (void)removeObjectForKey:(id)arg1; - (void)setObject:(id)arg1 forKey:(id)arg2; - (id)objectForKey:(id)arg1; - (id)allValues; - (id)allKeys; - (unsigned long long)count; - (void)dealloc; - (id)initWithCapacity:(unsigned long long)arg1; @end @interface MFWeakReferenceHolder : NSObject { id <NSObject> _reference; } + (id)weakReferenceWithObject:(id)arg1; - (id)reference; - (id)retainedReference; - (void)dealloc; - (id)_initWithObject:(id)arg1; - (id)init; @end @interface MFWeakSet : NSMutableSet { NSLock *_lock; unsigned long long _gen; struct __CFDictionary *_objects; } + (id)setWithCapacity:(unsigned long long)arg1; + (id)setWithArray:(id)arg1; + (id)setWithSet:(id)arg1; + (id)setWithObjects:(id)arg1; + (id)setWithObjects:(const id *)arg1 count:(unsigned long long)arg2; + (id)setWithObject:(id)arg1; + (id)set; - (void)setSet:(id)arg1; - (void)unionSet:(id)arg1; - (void)removeAllObjects; - (void)minusSet:(id)arg1; - (void)intersectSet:(id)arg1; - (void)addObjectsFromArray:(id)arg1; - (void)removeObject:(id)arg1; - (void)addObject:(id)arg1; - (void)dealloc; - (id)init; - (id)initWithCapacity:(unsigned long long)arg1; - (id)initWithArray:(id)arg1; - (id)initWithSet:(id)arg1 copyItems:(_Bool)arg2; - (id)initWithSet:(id)arg1; - (id)initWithObjects:(id)arg1; - (id)initWithObjects:(const id *)arg1 count:(unsigned long long)arg2; - (id)objectsWithOptions:(unsigned long long)arg1 passingTest:(CDUnknownBlockType)arg2; - (id)objectsPassingTest:(CDUnknownBlockType)arg1; - (void)enumerateObjectsWithOptions:(unsigned long long)arg1 usingBlock:(CDUnknownBlockType)arg2; - (void)enumerateObjectsUsingBlock:(CDUnknownBlockType)arg1; - (id)setByAddingObjectsFromArray:(id)arg1; - (id)setByAddingObjectsFromSet:(id)arg1; - (id)setByAddingObject:(id)arg1; - (void)makeObjectsPerformSelector:(SEL)arg1 withObject:(id)arg2; - (void)makeObjectsPerformSelector:(SEL)arg1; - (_Bool)isSubsetOfSet:(id)arg1; - (_Bool)isEqualToSet:(id)arg1; - (_Bool)intersectsSet:(id)arg1; - (id)initWithCoder:(id)arg1; - (void)encodeWithCoder:(id)arg1; - (id)descriptionWithLocale:(id)arg1; - (id)description; - (_Bool)containsObject:(id)arg1; - (id)anyObject; - (id)mutableCopyWithZone:(struct _NSZone *)arg1; - (id)copyWithZone:(struct _NSZone *)arg1; - (id)allObjects; - (id)_copyAllItems; - (unsigned long long)countByEnumeratingWithState:(CDStruct_58648341 *)arg1 objects:(id *)arg2 count:(unsigned long long)arg3; - (id)objectEnumerator; - (id)member:(id)arg1; - (unsigned long long)count; @end @interface NSArray (DerivedArray) - (id)mf_objectsPassingTest:(CDUnknownBlockType)arg1; - (id)mf_indicesOfStringsWithPrefix:(id)arg1; @end @interface NSArray (Functional) - (id)mf_reduce:(CDUnknownBlockType)arg1; - (id)mf_map:(CDUnknownBlockType)arg1; - (id)mf_uniquifyWithComparator:(CDUnknownBlockType)arg1; - (id)mf_flatten; - (id)mf_firstObjectPassingTest:(CDUnknownBlockType)arg1; - (id)mf_filter:(CDUnknownBlockType)arg1; - (_Bool)mf_any:(CDUnknownBlockType)arg1; - (_Bool)mf_all:(CDUnknownBlockType)arg1; @end @interface NSArray (MessagesFromMixedStoresConvenience) - (id)mf_dictionaryWithMessagesSortedByStore; @end @interface NSArray (NSEmailAddressArray) - (id)mf_uncommentedAddressList; @end @interface NSArray (SortedArrayExtensions) - (unsigned long long)mf_indexWhereObjectWouldBeInserted:(id)arg1 usingSortFunction:(CDUnknownFunctionPointerType)arg2 context:(void *)arg3; - (unsigned long long)mf_indexWhereObjectWouldBeInserted:(id)arg1 usingComparator:(CDUnknownBlockType)arg2; - (id)mf_objectEquivalentTo:(id)arg1 usingSortFunction:(CDUnknownFunctionPointerType)arg2 context:(void *)arg3; - (id)mf_objectEquivalentTo:(id)arg1 usingComparator:(CDUnknownBlockType)arg2; - (unsigned long long)mf_indexOfObject:(id)arg1 usingSortFunction:(CDUnknownFunctionPointerType)arg2 context:(void *)arg3; - (unsigned long long)mf_indexOfObject:(id)arg1 usingComparator:(CDUnknownBlockType)arg2; @end @interface NSData (DigestUtilities) - (id)mf_MD5Digest; @end @interface NSData (MimeDataEncoding) - (id)mf_encodeBase64HeaderData; - (id)mf_encodeModifiedBase64; - (id)mf_encodeBase64; - (id)mf_encodeBase64WithoutLineBreaks; - (id)mf_decodeModifiedBase64; - (id)mf_decodeBase64InRange:(struct _NSRange *)arg1; - (id)mf_decodeBase64; - (id)mf_decodeUuencoded; - (id)mf_decodeQuotedPrintableForText:(_Bool)arg1; @end @interface NSData (NSDataExtensions) - (_Bool)mf_immutable; - (id)mf_subdataWithRange:(struct _NSRange)arg1; @end @interface NSData (NSDataUtils) - (id)mf_copyHexString; - (id)mf_dataByConvertingUnixNewlinesToNetwork; - (id)mf_locationsOfUnixNewlinesNeedingConversion; - (struct _NSRange)mf_rangeOfCString:(const char *)arg1 options:(unsigned long long)arg2 range:(struct _NSRange)arg3; - (struct _NSRange)mf_rangeOfCString:(const char *)arg1 options:(unsigned long long)arg2; - (struct _NSRange)mf_rangeOfCString:(const char *)arg1; - (struct _NSRange)mf_rangeOfByteFromSet:(id)arg1; - (struct _NSRange)mf_rangeOfByteFromSet:(id)arg1 range:(struct _NSRange)arg2; - (struct _NSRange)mf_rangeOfData:(id)arg1 options:(unsigned long long)arg2 range:(struct _NSRange)arg3; - (id)mf_subdataFromIndex:(unsigned long long)arg1; - (id)mf_subdataToIndex:(unsigned long long)arg1; - (struct _NSRange)mf_rangeOfRFC822HeaderData; @end @interface NSDate (MFDateUtils) + (id)mf_copyDateInCommonFormatsWithString:(id)arg1; @end @interface NSDate (MFDateUtils_Private) + (id)mf_copyLenientDateInCommonFormatsWithString:(id)arg1; @end @interface NSError (MIME) + (id)mf_timeoutError; - (_Bool)mf_isTimeoutError; - (_Bool)mf_isCancelledError; @end @interface NSFileManager (NSFileManagerAdditions) - (_Bool)mf_setValue:(id)arg1 forExtendedAttribute:(id)arg2 ofItemAtPath:(id)arg3 error:(id *)arg4; - (_Bool)mf_setValue:(id)arg1 forAttribute:(id)arg2 ofItemAtPath:(id)arg3 error:(id *)arg4; - (_Bool)mf_protectFileAtPath:(id)arg1 withClass:(int)arg2 error:(id *)arg3; - (void)mf_deleteFilesInSortedArray:(id)arg1 matchingPrefix:(id)arg2 fromDirectory:(id)arg3; - (id)mf_pathsAtDirectory:(id)arg1 beginningWithString:(id)arg2; - (id)mf_fileModificationDateAtPath:(id)arg1 traverseLink:(_Bool)arg2; - (_Bool)mf_canWriteToDirectoryAtPath:(id)arg1; - (_Bool)mf_makeCompletePath:(id)arg1 mode:(int)arg2; - (id)mf_makeUniqueFileInDirectory:(id)arg1; @end @interface NSLock (MessageAdditions) - (void)mf_waitForLock; @end @interface NSMutableArray (Convenience) - (void)mf_moveObjectAtIndex:(unsigned long long)arg1 toIndex:(unsigned long long)arg2; - (void)mf_addObject:(id)arg1 orPlaceholder:(id)arg2; - (_Bool)mf_addObjectIfAbsentAccordingToEquals:(id)arg1; - (_Bool)mf_addObjectIfAbsent:(id)arg1; @end @interface NSMutableArray (SortedArrayExtensions) - (unsigned long long)mf_removeObject:(id)arg1 usingSortFunction:(CDUnknownFunctionPointerType)arg2 context:(void *)arg3; - (unsigned long long)mf_insertObject:(id)arg1 usingSortFunction:(CDUnknownFunctionPointerType)arg2 context:(void *)arg3 allowDuplicates:(_Bool)arg4; - (unsigned long long)mf_removeObject:(id)arg1 usingComparator:(CDUnknownBlockType)arg2; - (unsigned long long)mf_insertObject:(id)arg1 usingComparator:(CDUnknownBlockType)arg2 allowDuplicates:(_Bool)arg3; @end @interface NSMutableData (NSDataUtils) - (void)mf_makeImmutable; - (void)mf_convertNetworkLineEndingsToUnix; - (void)mf_convertNetworkLineEndingsToUnixInRange:(struct _NSRange)arg1; - (void)mf_appendCString:(const char *)arg1; @end @interface NSMutableData (RFC2231Support) - (void)mf_appendRFC2231CompliantValue:(id)arg1 forKey:(id)arg2; @end @interface NSMutableDictionary (RFC2231Support) - (void)mf_fixupRFC2231Values; @end @interface NSMutableSet (MFMessageAdditions) - (id)mf_uniquedObject:(id)arg1; @end @interface NSObject (LockingAdditions) + (void)mf_clearLocks; - (id)mf_exclusiveLocks; - (id)mf_lockOrdering; - (id)mf_strictLockOrdering; - (_Bool)_mf_ntsIsLocked; - (void)mf_unlock; - (_Bool)mf_tryLockWithPriority; - (void)mf_lockWithPriority; - (_Bool)mf_tryLock; - (void)mf_lock; - (void)_mf_checkToAllowLock:(id)arg1; - (void)_mf_checkToAllowExclusiveLocksWithLock:(id)arg1; - (void)_mf_checkToAllowStrictProgressionWithLock:(id)arg1; - (void)_mf_checkToAllowOrderingWithLock:(id)arg1; - (void)_mf_dumpLockCallStacks:(unsigned long long)arg1 ordering:(id)arg2; - (id)_mf_lockOrderingForType:(int)arg1; @end @interface NSScanner (NSScannerUtils) - (_Bool)mf_scanUpAndOverString:(id)arg1; - (id)mf_nextTokenWithPunctuation:(struct __CFCharacterSet *)arg1; @end @interface NSString (MFStringUtils) + (id)mf_stringWithData:(id)arg1 encoding:(unsigned long long)arg2; - (id)mf_copyStringByEncodingIDNA; - (id)mf_copyStringByDecodingIDNA; - (id)mf_copyStringByEncodingIDNAInRange:(struct _NSRange)arg1; - (id)mf_copyStringByDecodingIDNAInRange:(struct _NSRange)arg1; - (id)mf_messageIDSubstring; - (id)mf_MD5Digest; - (id)mf_dataUsingEncoding:(unsigned long long)arg1 allowLossyConversion:(_Bool)arg2; - (id)mf_dataUsingEncoding:(unsigned long long)arg1; - (long long)mf_caseInsensitiveCompareExcludingXDash:(id)arg1; - (const void *)mf_lossyDefaultCStringBytes; @end @interface NSString (MimeCharsetSupport) - (id)mf_bestMimeCharsetForMessageDeliveryUsingSubtype:(id)arg1; - (id)mf_bestMimeCharsetUsingHint:(unsigned int)arg1; - (id)_mf_bestMimeCharset:(id)arg1; - (id)mf_bestMimeCharset; @end @interface NSString (MimeHeaderEncoding) - (id)mf_decodeMimeHeaderValueWithCharsetHint:(id)arg1; - (id)mf_decodeMimeHeaderValueWithEncodingHint:(unsigned int)arg1; - (id)mf_encodedHeaderDataWithEncodingHint:(unsigned int)arg1; @end @interface NSString (NSEmailAddressString) + (id)mf_partialSurnames; + (id)mf_nameExtensions; + (id)mf_formattedAddressWithName:(id)arg1 email:(id)arg2 useQuotes:(_Bool)arg3; - (id)mf_trimCommasSpacesQuotes; - (_Bool)mf_appearsToBeAnInitial; - (_Bool)mf_hasSameNamesAs:(id)arg1; - (void)mf_firstName:(id *)arg1 middleName:(id *)arg2 lastName:(id *)arg3 extension:(id *)arg4; - (void)mf_addressCommentFirstName:(id *)arg1 middleName:(id *)arg2 lastName:(id *)arg3 extension:(id *)arg4; - (id)mf_copyIDNAEncodedEmailAddress; - (id)mf_copyIDNADecodedEmailAddress; - (_Bool)mf_isEqualToAddress:(id)arg1; - (id)mf_addressDomain; - (struct _NSRange)mf_rangeOfAddressDomain; - (_Bool)mf_isLegalEmailAddress; - (_Bool)mf_isLegalCommentedEmailAddress; - (id)mf_copyAddressComment; - (id)mf_addressComment; - (id)mf_uncommentedAddressRespectingGroups; - (id)mf_uncommentedAddress; - (id)mf_copyUncommentedAddress; @end @interface _MFEmailSetEmail : NSObject { unsigned long long _hash; NSString *_encodedAddress; NSString *_comment; } @property(readonly, nonatomic) NSString *commentedAddress; @property(retain, nonatomic) NSString *address; - (_Bool)isEqualToEmail:(id)arg1; @property(readonly, nonatomic) unsigned long long hash; - (id)description; - (void)dealloc; - (id)initWithAddress:(id)arg1; @end @interface _MFEmailSetEnumerator : NSEnumerator { MFEmailSet *_set; CDStruct_58648341 _state; } - (id)nextObject; - (unsigned long long)countByEnumeratingWithState:(CDStruct_58648341 *)arg1 objects:(id *)arg2 count:(unsigned long long)arg3; - (void)dealloc; - (id)initWithSet:(id)arg1; @end
20,561
2,151
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_PUBLIC_RENDERER_URL_LOADER_THROTTLE_PROVIDER_H_ #define CONTENT_PUBLIC_RENDERER_URL_LOADER_THROTTLE_PROVIDER_H_ #include <memory> #include <vector> #include "content/common/content_export.h" #include "content/public/common/resource_type.h" #include "content/public/common/url_loader_throttle.h" #include "third_party/blink/public/platform/web_url_request.h" namespace content { enum class URLLoaderThrottleProviderType { // Used for requests from frames. Please note that the requests could be // frame or subresource requests. kFrame, // Used for requests from workers, including dedicated, shared and service // workers. kWorker }; class CONTENT_EXPORT URLLoaderThrottleProvider { public: virtual ~URLLoaderThrottleProvider() {} // Used to copy a URLLoaderThrottleProvider between worker threads. virtual std::unique_ptr<URLLoaderThrottleProvider> Clone() = 0; // For requests from frames and dedicated workers, |render_frame_id| should be // set to the corresponding frame. For requests from shared or // service workers, |render_frame_id| should be set to MSG_ROUTING_NONE. virtual std::vector<std::unique_ptr<URLLoaderThrottle>> CreateThrottles( int render_frame_id, const blink::WebURLRequest& request, ResourceType resource_type) = 0; }; } // namespace content #endif // CONTENT_PUBLIC_RENDERER_URL_LOADER_THROTTLE_PROVIDER_H_
512
430
from colorama import init, deinit, Fore, Back, Style class PrettyPrinter(object): def __enter__(self): pass def __exit__(self): pass def op(self, op): suffix = '' if op.result is not None and op.result != '?': suffix = "%s = " % self.var(op.result) descr = op.descr if descr is None: descr = '' else: descr = ', @' + self.descr(descr) args = [self.var(arg) for arg in op.args] return '%s%s(%s%s)' % (suffix, self.opname(op.opname), ', '.join(args), descr) def trace(self, fd, trace): for name, stage in trace.stages.items(): fd.write(self.stage_name(stage)) fd.write("\n") for op in stage.getoperations(): fd.write(' ' + self.op(op) + '\n') def var(self, var): return var def descr(self, descr): return descr def opname(self, opname): return opname def stage_name(self, stage): return str(stage) class ColoredPrettyPrinter(PrettyPrinter): def __enter__(self): init() return self def __exit__(self, a, b, c): deinit() def opname(self, opname): return Fore.CYAN + opname + Style.RESET_ALL def var(self, var): if len(var) > 0: if var[0] == 'i': return Fore.BLUE + var + Style.RESET_ALL if var[0] == 'p' or var[0] == 'r': return Fore.GREEN + var + Style.RESET_ALL if var[0] == 'f': return Fore.BLUE + var + Style.RESET_ALL return Fore.RED + var + Style.RESET_ALL
866
8,498
<filename>cim-common/src/main/java/com/crossoverjie/cim/common/util/RouteInfoParseUtil.java package com.crossoverjie.cim.common.util; import com.crossoverjie.cim.common.exception.CIMException; import com.crossoverjie.cim.common.pojo.RouteInfo; import static com.crossoverjie.cim.common.enums.StatusEnum.VALIDATION_FAIL; /** * Function: * * @author crossoverJie * Date: 2020-04-12 20:42 * @since JDK 1.8 */ public class RouteInfoParseUtil { public static RouteInfo parse(String info){ try { String[] serverInfo = info.split(":"); RouteInfo routeInfo = new RouteInfo(serverInfo[0], Integer.parseInt(serverInfo[1]),Integer.parseInt(serverInfo[2])) ; return routeInfo ; }catch (Exception e){ throw new CIMException(VALIDATION_FAIL) ; } } }
341
3,976
<filename>Drake-Z/0013/0013.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- '第 0013 题: 用 Python 写一个爬图片的程序,爬(http://tieba.baidu.com/p/2166231880)图片 :-)' __author__ = 'Drake-Z' import os import re import urllib from urllib import request from urllib.request import urlopen def read_url(yuanshiurl): req = request.Request(yuanshiurl) req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; InfoPath.2; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; 360SE /360/ /chrome/ig)') with request.urlopen(req) as f: Imageurl(f.read().decode('utf-8')) #输出Data return 0 def Imageurl(data): re_Imageurl = re.compile(r'src="(http://imgsrc.baidu.com/forum/.*?)"') data = re_Imageurl.findall(data) #输出图片链接 downloadImage(data) def downloadImage(pic_url): dirct = '0013' try: if not os.path.exists(dirct): #创建存放目录 os.mkdir(dirct) except: print('Failed to create directory in %s' % dirct) exit() for i in pic_url: data = urllib.request.urlopen(i).read() i = re.split('/', i)[-1] print(i) path = dirct + '/' +i f = open(path, 'wb') f.write(data) f.close() print('Done !') url = 'http://tieba.baidu.com/p/2166231880' read_url(url)
777
32,544
package com.baeldung.quarkus; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.h2.H2DatabaseTestResource; import io.quarkus.test.junit.NativeImageTest; @NativeImageTest @QuarkusTestResource(H2DatabaseTestResource.class) class NativeLibraryResourceIT extends LibraryHttpEndpointIntegrationTest { }
107
2,793
#include "ruby.h" #include "rubyspec.h" #ifdef __cplusplus extern "C" { #endif #ifdef HAVE_RB_COMPLEX static VALUE complex_spec_rb_Complex(VALUE self, VALUE num, VALUE den) { return rb_Complex(num, den); } #endif #ifdef HAVE_RB_COMPLEX1 static VALUE complex_spec_rb_Complex1(VALUE self, VALUE num) { return rb_Complex1(num); } #endif #ifdef HAVE_RB_COMPLEX2 static VALUE complex_spec_rb_Complex2(VALUE self, VALUE num, VALUE den) { return rb_Complex2(num, den); } #endif #ifdef HAVE_RB_COMPLEX_NEW static VALUE complex_spec_rb_complex_new(VALUE self, VALUE num, VALUE den) { return rb_complex_new(num, den); } #endif #ifdef HAVE_RB_COMPLEX_NEW1 static VALUE complex_spec_rb_complex_new1(VALUE self, VALUE num) { return rb_complex_new1(num); } #endif #ifdef HAVE_RB_COMPLEX_NEW2 static VALUE complex_spec_rb_complex_new2(VALUE self, VALUE num, VALUE den) { return rb_complex_new2(num, den); } #endif void Init_complex_spec(void) { VALUE cls; cls = rb_define_class("CApiComplexSpecs", rb_cObject); #ifdef HAVE_RB_COMPLEX rb_define_method(cls, "rb_Complex", complex_spec_rb_Complex, 2); #endif #ifdef HAVE_RB_COMPLEX1 rb_define_method(cls, "rb_Complex1", complex_spec_rb_Complex1, 1); #endif #ifdef HAVE_RB_COMPLEX2 rb_define_method(cls, "rb_Complex2", complex_spec_rb_Complex2, 2); #endif #ifdef HAVE_RB_COMPLEX_NEW rb_define_method(cls, "rb_complex_new", complex_spec_rb_complex_new, 2); #endif #ifdef HAVE_RB_COMPLEX_NEW1 rb_define_method(cls, "rb_complex_new1", complex_spec_rb_complex_new1, 1); #endif #ifdef HAVE_RB_COMPLEX_NEW2 rb_define_method(cls, "rb_complex_new2", complex_spec_rb_complex_new2, 2); #endif } #ifdef __cplusplus } #endif
715
937
""" 缺省函数,就是参数可以有默认值,跟kotlin一样 返回值也可以简写,省略 -> int: """ def print_info(name, age=20): print("姓名:%s, 年龄:%s" % (name, age)) print_info("张三", 28) print_info("李四") """ 元组[]不定长参数,参数的数量不确定, 调用类似于位置参数 参数名之前加上*表示这个星号表明参数的类型为元祖,但是传入实参的时候不需要中括号[] """ def my_func01(*args): print(type(args)) print(args[0]) my_func01(1, 3, 5) my_func01(1, 3, 5, 7) """ 字典类型{}的不定长参数, 调用类似于关键字参数name=的形式 参数名前面加上**两个星号,表明这个参数为一个字典,传入的时候不需要写{},但是只能传入一个字典 """ def my_func02(**kwargs): print(type(kwargs)) print(kwargs["name"]) print(kwargs["age"]) my_func02(name="小明", age=12) """ 一个函数的包含多return个 """ def my_func03(score: int) -> str: if score >= 70: return "优秀" elif score >= 30: return "中性" else: return "差" print(my_func03(50)) """ 处理多个返回值的方式 1- return ["小明", 28] 2- return {"name":"小明","age":28] 2- return 返回值1, 返回值2 """ def my_func04(name, age): return name, age print(my_func04("张三",28)[0]) print(my_func04("张三",28)[1]) """ python中的拆包(列表,字典,多个返回值): 一次性初始化多个变量的值 如果返回值是列表,字典,或者多个返回值,可以直接用来赋值多个变量的方式就叫做拆包,简化代码量 """ num01, num02, num03, num04 = 1, 3.14, True, "Hello World" num05, num06, num07, num08 = [1, 3.14, True, "Hello World"] name, age = my_func04("李四", 28) print(name, "-->", age) """ 拆包中python快速交换两个变量的值, 免去了temp中间值 """ a, b = 4, 5 a, b = b, a # b的引用给a, a的引用给b,快速交换值
1,219
421
<gh_stars>100-1000 import requests # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''HPE Smart Update Manager - Remote Unauthorized Access''', "description": '''A security vulnerability in HPE Smart Update Manager (SUM) prior to version 8.5.6 could allow remote unauthorized access. Hewlett Packard Enterprise has provided a software update to resolve this vulnerability in HPE Smart Update Manager (SUM) prior to 8.5.6. Please visit the HPE Support Center at https://support.hpe.com/hpesc/public/home to download the latest version of HPE Smart Update Manager (SUM). Download the latest version of HPE Smart Update Manager (SUM) or download the latest Service Pack For ProLiant (SPP).''', "severity": "critical", "references": [ "https://www.tenable.com/security/research/tra-2020-02", "https://support.hpe.com/hpesc/public/docDisplay?docLocale=en_US&docId=emr_na-hpesbmu03997en_us", "https://nvd.nist.gov/vuln/detail/CVE-2020-7136" ], "classification": { "cvss-metrics": "CVSS:3.1/AV:A/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "cvss-score": "", "cve-id": "CVE-2020-7136", "cwe-id": "CWE-288" }, "metadata":{ "vuln-target": "", }, "tags": ["cve", "cve2020", "hp", "auth-bypass", "hpe"], } # Vender Fingerprint def fingerprint(url): return True # Proof of Concept def poc(url): result = {} try: url = format_url(url) path = """/session/create""" method = "POST" data = {"hapi":{"username":"Administrator","password":"<PASSWORD>","language":"en","mode":"gui", "usesshkey":true, "privatekey":"any_privateky", "passphrase":"<PASSWORD>","settings":{"output_filter":"passed","port_number":"444"}}} headers = {'Accept': '*/*', 'Content-Type': 'application/json'} resp0 = requests.request(method=method,url=url+path,json=data,headers=headers,timeout=10,verify=False,allow_redirects=False) path = """/session/{{sessionid}}/node/index""" method = "GET" headers = {} resp1 = requests.request(method=method,url=url+path,headers=headers,timeout=10,verify=False,allow_redirects=False) if ("""hmessage""" in resp1.text and """Command completed successfully.""" in resp1.text and """node_name""" in resp1.text): result["success"] = True result["info"] = info() result["payload"] = url+path except: result["success"] = False return result # Exploit, can be same with poc() def exp(url): return poc(url) # Utils def format_url(url): url = url.strip() if not ( url.startswith('http://') or url.startswith('https://') ): url = 'http://' + url url = url.rstrip('/') return url
1,203
4,857
/** * 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.hbase.testing; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import java.io.IOException; import java.util.List; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.RegionInfoBuilder; import org.apache.hadoop.hbase.client.RegionLocator; import org.apache.hadoop.hbase.client.TableDescriptorBuilder; import org.apache.hadoop.hbase.regionserver.OnlineRegions; import org.apache.hadoop.hbase.regionserver.Region; import org.apache.hadoop.hbase.testclassification.LargeTests; import org.apache.hadoop.hbase.testclassification.MiscTests; import org.apache.hadoop.hbase.util.Bytes; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.hbase.thirdparty.com.google.common.io.Closeables; @Category({ MiscTests.class, LargeTests.class }) public class TestTestingHBaseClusterImplForCPs { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestTestingHBaseClusterImplForCPs.class); private static TestingHBaseCluster CLUSTER; private static TableName NAME = TableName.valueOf("test"); private static byte[] CF = Bytes.toBytes("cf"); private static Connection CONN; private static Admin ADMIN; @BeforeClass public static void setUpBeforeClass() throws Exception { CLUSTER = TestingHBaseCluster.create(TestingHBaseClusterOption.builder().numMasters(2) .numRegionServers(3).numDataNodes(3).build()); CLUSTER.start(); CONN = ConnectionFactory.createConnection(CLUSTER.getConf()); ADMIN = CONN.getAdmin(); ADMIN.createTable(TableDescriptorBuilder.newBuilder(NAME) .setColumnFamily(ColumnFamilyDescriptorBuilder.of(CF)).build()); ADMIN.balancerSwitch(false, true); } @AfterClass public static void tearDownAfterClass() throws Exception { Closeables.close(ADMIN, true); Closeables.close(CONN, true); if (CLUSTER.isClusterRunning()) { CLUSTER.stop(); } } @Test public void testGetRegion() throws IOException { List<RegionInfo> infos = ADMIN.getRegions(NAME); assertEquals(1, infos.size()); RegionInfo info = infos.get(0); Region region = CLUSTER.getRegion(info).get(); ServerName loc; try (RegionLocator locator = CONN.getRegionLocator(NAME)) { loc = locator.getRegionLocation(info.getStartKey()).getServerName(); } OnlineRegions onlineRegionsInterface = CLUSTER.getOnlineRegionsInterface(loc).get(); List<? extends Region> regions = onlineRegionsInterface.getRegions(NAME); assertEquals(1, regions.size()); assertSame(region, regions.get(0)); assertFalse(CLUSTER .getRegion(RegionInfoBuilder.newBuilder(TableName.valueOf("whatever")).build()).isPresent()); assertFalse(CLUSTER.getOnlineRegionsInterface(ServerName.valueOf("whatever,1,1")).isPresent()); } }
1,354
1,670
import sys import argparse import web3 from autobahn import xbr from test_accounts import hl def main (accounts): print('\nTest accounts:') for acct in accounts: balance_eth = w3.eth.getBalance(acct) balance_xbr = xbr.xbrtoken.functions.balanceOf(acct).call() print(' balances of {}: {:>30} ETH, {:>30} XBR'.format(hl(acct), balance_eth, balance_xbr)) print('\nXBR contracts:') for acct in [xbr.xbrtoken.address, xbr.xbrnetwork.address]: balance_eth = w3.eth.getBalance(acct) balance_xbr = xbr.xbrtoken.functions.balanceOf(acct).call() print(' balances of {}: {:>30} ETH, {:>30} XBR'.format(hl(acct), balance_eth, balance_xbr)) print() if __name__ == '__main__': print('using web3.py v{}'.format(web3.__version__)) parser = argparse.ArgumentParser() parser.add_argument('--gateway', dest='gateway', type=str, default=None, help='Ethereum HTTP gateway URL or None for auto-select (default: -, means let web3 auto-select).') args = parser.parse_args() if args.gateway: w3 = web3.Web3(web3.Web3.HTTPProvider(args.gateway)) else: # using automatic provider detection: from web3.auto import w3 # check we are connected, and check network ID if not w3.isConnected(): print('could not connect to Web3/Ethereum at: {}'.format(args.gateway or 'auto')) sys.exit(1) else: print('connected via provider "{}"'.format(args.gateway or 'auto')) # set new provider on XBR library xbr.setProvider(w3) # now enter main .. main(w3.eth.accounts)
751
6,009
/* * Copyright (c) 2016-present 贵州纳雍穿青人李裕江<<EMAIL>> * * The software is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR * PURPOSE. * See the Mulan PSL v2 for more details. */ package com.github.gzuliyujiang.calendarpicker.core; import android.graphics.Color; import androidx.annotation.ColorInt; import java.io.Serializable; /** * @author 贵州山野羡民(<EMAIL>) * @since 2021/9/17 12:28 */ public class ColorScheme implements Serializable { private int weekTextColor = 0xFF343434; private int weekBackgroundColor = Color.TRANSPARENT; private int monthTitleTextColor = 0xFF343434; private int monthTitleBackgroundColor = Color.TRANSPARENT; private int monthBackgroundColor = Color.TRANSPARENT; private int monthDividerColor = Color.TRANSPARENT; private int dayNormalTextColor = 0xFF343434; private int dayInvalidTextColor = 0xFFCCCCCC; private int dayStressTextColor = 0xFFFF6600; private int daySelectTextColor = 0xFFFFFFFF; private int dayNormalBackgroundColor = Color.TRANSPARENT; private int dayInvalidBackgroundColor = Color.TRANSPARENT; private int daySelectBackgroundColor = 0xFFE75051; public ColorScheme weekTextColor(@ColorInt int color) { this.weekTextColor = color; return this; } @ColorInt public int weekTextColor() { return weekTextColor; } public ColorScheme weekBackgroundColor(@ColorInt int color) { this.weekBackgroundColor = color; return this; } @ColorInt public int weekBackgroundColor() { return weekBackgroundColor; } public ColorScheme monthTitleTextColor(@ColorInt int color) { this.monthTitleTextColor = color; return this; } @ColorInt public int monthTitleTextColor() { return monthTitleTextColor; } public ColorScheme monthTitleBackgroundColor(@ColorInt int color) { this.monthTitleBackgroundColor = color; return this; } @ColorInt public int monthTitleBackgroundColor() { return monthTitleBackgroundColor; } public ColorScheme monthBackgroundColor(@ColorInt int color) { this.monthBackgroundColor = color; return this; } @ColorInt public int monthBackgroundColor() { return monthBackgroundColor; } public ColorScheme monthDividerColor(@ColorInt int color) { this.monthDividerColor = color; return this; } @ColorInt public int monthDividerColor() { return monthDividerColor; } public ColorScheme dayNormalTextColor(@ColorInt int color) { this.dayNormalTextColor = color; return this; } @ColorInt public int dayNormalTextColor() { return dayNormalTextColor; } public ColorScheme dayInvalidTextColor(@ColorInt int color) { this.dayInvalidTextColor = color; return this; } @ColorInt public int dayInvalidTextColor() { return dayInvalidTextColor; } public ColorScheme dayStressTextColor(@ColorInt int color) { this.dayStressTextColor = color; return this; } @ColorInt public int dayStressTextColor() { return dayStressTextColor; } public ColorScheme daySelectTextColor(@ColorInt int color) { this.daySelectTextColor = color; return this; } @ColorInt public int daySelectTextColor() { return daySelectTextColor; } public ColorScheme dayNormalBackgroundColor(@ColorInt int color) { this.dayNormalBackgroundColor = color; return this; } @ColorInt public int dayNormalBackgroundColor() { return dayNormalBackgroundColor; } public ColorScheme dayInvalidBackgroundColor(@ColorInt int color) { this.dayInvalidBackgroundColor = color; return this; } @ColorInt public int dayInvalidBackgroundColor() { return dayInvalidBackgroundColor; } public ColorScheme daySelectBackgroundColor(@ColorInt int color) { this.daySelectBackgroundColor = color; return this; } @ColorInt public int daySelectBackgroundColor() { return daySelectBackgroundColor; } }
1,691
1,625
import matplotlib import numpy as np import matplotlib.pyplot as plt import math from sklearn.linear_model import Ridge from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline from sklearn.kernel_ridge import KernelRidge matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.family'] = 'STIXGeneral' matplotlib.rcParams.update({'font.size': 25}) def f(x): """ function to approximate by polynomial interpolation""" return x * (x) # generate points used to plot x_plot = np.linspace(-5, 2, 100) # generate points and keep a subset of them x = np.linspace(-5, 2, 100) rng = np.random.RandomState(0) rng.shuffle(x) x = np.sort(x[:50]) noize = [(-5 + np.random.random()*5) for i in range(len(x))] y = f(x) + noize # create matrix versions of these arrays X = x[:, np.newaxis] X_plot = x_plot[:, np.newaxis] colors = ['red', 'blue', 'orange'] lw = 2 def kernel(x1, x2, b = 2): z = (x1 - x2) / b return (1/math.sqrt(2 * 3.14)) * np.exp(-z**2/2) fit = ["fit", "small overfit", "big overfit"] for count, degree in enumerate([0.1, 0.5, 3]): plt.figure(count) axes = plt.gca() axes.set_xlim([-5,2]) axes.set_ylim([-10,30]) plt.scatter(x, y, color='navy', s=30, marker='o', label="training examples") model = KernelRidge(alpha=0.01, kernel=kernel, kernel_params = {'b':degree}) model.fit(X, y) y_plot = model.predict(X_plot) plt.plot(x_plot, y_plot, color=colors[count], linewidth=lw, label="b = " + str(degree)) plt.legend(loc='upper right') fig1 = plt.gcf() fig1.subplots_adjust(top = 0.98, bottom = 0.1, right = 0.98, left = 0.08, hspace = 0, wspace = 0) fig1.savefig('../../Illustrations/kernel-regression-' + str(count) + '.eps', format='eps', dpi=1000, bbox_inches = 'tight', pad_inches = 0) fig1.savefig('../../Illustrations/kernel-regression-' + str(count) + '.pdf', format='pdf', dpi=1000, bbox_inches = 'tight', pad_inches = 0) fig1.savefig('../../Illustrations/kernel-regression-' + str(count) + '.png', dpi=1000, bbox_inches = 'tight', pad_inches = 0) plt.show()
872
12,252
package org.keycloak.protocol.saml.mappers; import org.keycloak.dom.saml.v2.metadata.EntityDescriptorType; import org.keycloak.models.IdentityProviderMapperModel; public interface SamlMetadataDescriptorUpdater { void updateMetadata(IdentityProviderMapperModel mapperModel, EntityDescriptorType descriptor); }
102
852
import FWCore.ParameterSet.Config as cms L1MuGMTParametersKeysOnlineProd = cms.ESProducer("L1MuGMTParametersKeysOnlineProd", onlineAuthentication = cms.string('.'), subsystemLabel = cms.string('GMT'), onlineDB = cms.string('oracle://CMS_OMDS_LB/CMS_TRG_R') )
156
862
/* * (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.sweep.queue.config; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.palantir.atlasdb.AtlasDbConstants; import com.palantir.atlasdb.sweep.queue.SweepQueueUtils; import com.palantir.logsafe.Preconditions; import com.palantir.logsafe.SafeArg; import java.time.Duration; import org.immutables.value.Value; import org.immutables.value.Value.Default; @JsonDeserialize(as = ImmutableTargetedSweepRuntimeConfig.class) @JsonSerialize(as = ImmutableTargetedSweepRuntimeConfig.class) @JsonIgnoreProperties("batchShardIterations") @Value.Immutable public abstract class TargetedSweepRuntimeConfig { /** * If true, targeted sweep will be performed in the background. Setting this to false will cause the background * threads to skip running sweeps, effectively pausing targeted sweep. */ @Value.Default public boolean enabled() { return AtlasDbConstants.DEFAULT_ENABLE_TARGETED_SWEEP; } /** * The number of shards to be used for persisting targeted sweep information. Once the number of shards is increased * it cannot be reduced again, and setting the configuration to a lower value will have no effect. The maximum * allowed value is 256. */ @Value.Default public int shards() { return AtlasDbConstants.DEFAULT_TARGETED_SWEEP_SHARDS; } /** * Specifies the maximum number of (fine) partitions over which targeted sweep attempts to read sweep queue * information before executing deletes. Only partitions which actually contain information about writes will count * towards this limit. Targeted sweep may, of course, read fewer partitions. Legacy behaviour prior to the * introduction of this feature is consistent with a value of 1. * * This is expected to improve the throughput of targeted sweep, at the expense of more uneven sweeping across * different shards. */ @Value.Default public int maximumPartitionsToBatchInSingleRead() { return 1; } @Value.Check void checkPartitionsToBatch() { Preconditions.checkArgument( maximumPartitionsToBatchInSingleRead() > 0, "Number of partitions to read in a batch must be positive.", SafeArg.of("partitions to batch", maximumPartitionsToBatchInSingleRead())); } @Value.Check void checkShardSize() { Preconditions.checkArgument( shards() >= 1 && shards() <= 256, "Shard number must be between 1 and 256 inclusive.", SafeArg.of("shards", shards())); } /** * Hint for the duration of pause between iterations of targeted sweep. Must not be longer than a day. */ @Value.Default public long pauseMillis() { return 500L; } /** * If enabled, the {@link #maximumPartitionsToBatchInSingleRead()} parameter will be ignored. Instead, sweep will * read across as many fine partitions as necessary to try assemble a single full batch of entries to sweep. * * Targeted sweep will adjust the pause between iterations depending on results of previous iterations using * {@link #pauseMillis()} as a baseline. */ @Value.Default public boolean enableAutoTuning() { return true; } /** * This parameter can be set to set the batch size threshold that an iteration of targeted sweep will try not to * exceed. This value must not exceed {@link SweepQueueUtils#MAX_CELLS_DEDICATED}. * * Must be less than or equal to {@link com.palantir.atlasdb.sweep.queue.SweepQueueUtils#SWEEP_BATCH_SIZE} */ @Default public int batchCellThreshold() { return SweepQueueUtils.SWEEP_BATCH_SIZE; } @Value.Check public void checkPauseDuration() { Preconditions.checkArgument( pauseMillis() <= Duration.ofDays(1).toMillis(), "The pause between iterations of targeted sweep must not be greater than 1 day.", SafeArg.of("pauseMillis", pauseMillis())); } @Value.Check public void checkBatchCellThreshold() { Preconditions.checkArgument( batchCellThreshold() <= SweepQueueUtils.MAX_CELLS_DEDICATED, "This configuration cannot be set to exceed the maximum number of cells in a dedicated row.", SafeArg.of("config batch size", batchCellThreshold()), SafeArg.of("max cells in a dedicated row", SweepQueueUtils.MAX_CELLS_DEDICATED)); } public static TargetedSweepRuntimeConfig defaultTargetedSweepRuntimeConfig() { return ImmutableTargetedSweepRuntimeConfig.builder().build(); } public static TargetedSweepRuntimeConfig disabled() { return ImmutableTargetedSweepRuntimeConfig.builder().enabled(false).build(); } }
1,914
19,529
<filename>vnpy/app/data_recorder/__init__.py import sys import vnpy_datarecorder sys.modules[__name__] = vnpy_datarecorder
53
956
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2018 Intel Corporation */ #ifndef EAL_ALARM_PRIVATE_H #define EAL_ALARM_PRIVATE_H #include <inttypes.h> /* * FreeBSD needs a back-channel communication mechanism between interrupt and * alarm thread, because on FreeBSD, timer period is set up inside the interrupt * API and not inside alarm API like on Linux. */ int eal_alarm_get_timeout_ns(uint64_t *val); #endif // EAL_ALARM_PRIVATE_H
154
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.containerservice.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for WorkloadRuntime. */ public final class WorkloadRuntime extends ExpandableStringEnum<WorkloadRuntime> { /** Static value OCIContainer for WorkloadRuntime. */ public static final WorkloadRuntime OCICONTAINER = fromString("OCIContainer"); /** Static value WasmWasi for WorkloadRuntime. */ public static final WorkloadRuntime WASM_WASI = fromString("WasmWasi"); /** * Creates or finds a WorkloadRuntime from its string representation. * * @param name a name to look for. * @return the corresponding WorkloadRuntime. */ @JsonCreator public static WorkloadRuntime fromString(String name) { return fromString(name, WorkloadRuntime.class); } /** @return known WorkloadRuntime values. */ public static Collection<WorkloadRuntime> values() { return values(WorkloadRuntime.class); } }
381
4,339
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache; import java.util.Random; import javax.cache.CacheException; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.cache.query.FieldsQueryCursor; import org.apache.ignite.cache.query.SqlFieldsQuery; import org.apache.ignite.internal.util.typedef.G; import org.junit.Test; /** * Tests SQL queries in read-only cluster mode. */ public class ClusterReadOnlyModeSqlTest extends ClusterReadOnlyModeAbstractTest { /** * */ @Test public void testSqlReadOnly() { assertSqlReadOnlyMode(false); changeClusterReadOnlyMode(true); assertSqlReadOnlyMode(true); changeClusterReadOnlyMode(false); assertSqlReadOnlyMode(false); } /** * @param readOnly If {@code true} then data modification SQL queries must fail, else succeed. */ private void assertSqlReadOnlyMode(boolean readOnly) { Random rnd = new Random(); for (Ignite ignite : G.allGrids()) { for (String cacheName : CACHE_NAMES) { IgniteCache<Integer, Integer> cache = ignite.cache(cacheName); try (FieldsQueryCursor<?> cur = cache.query(new SqlFieldsQuery("SELECT * FROM Integer"))) { cur.getAll(); } boolean failed = false; try (FieldsQueryCursor<?> cur = cache.query(new SqlFieldsQuery("DELETE FROM Integer"))) { cur.getAll(); } catch (CacheException ex) { if (!readOnly) log.error("Failed to delete data", ex); failed = true; } if (failed != readOnly) fail("SQL delete from " + cacheName + " must " + (readOnly ? "fail" : "succeed")); failed = false; try (FieldsQueryCursor<?> cur = cache.query(new SqlFieldsQuery( "INSERT INTO Integer(_KEY, _VAL) VALUES (?, ?)").setArgs(rnd.nextInt(1000), rnd.nextInt()))) { cur.getAll(); } catch (CacheException ex) { if (!readOnly) log.error("Failed to insert data", ex); failed = true; } if (failed != readOnly) fail("SQL insert into " + cacheName + " must " + (readOnly ? "fail" : "succeed")); } } } }
1,406
709
<reponame>StanHardy/GpuRamDrive #pragma once #define GPU_API_CUDA 1 #if GPU_API == GPU_API_CUDA #include <map> #include <mutex> #include <cuda.h> #include "DebugTools.h" class CudaHandler { private: static CudaHandler* pinstance_; static std::mutex mutex_; std::map<CUdevice, CUcontext> contexts; std::map<CUdevice, int> contextsMux; DebugTools debugTools; protected: CudaHandler(); ~CudaHandler(); public: CudaHandler(CudaHandler& other) = delete; void operator=(const CudaHandler&) = delete; static CudaHandler* GetInstance(); CUcontext getContext(cl_device_id clDeviceId); void removeContext(cl_device_id clDeviceId); }; #endif
244
892
<reponame>westonsteimel/advisory-database-github<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-4rcm-jqm5-f725", "modified": "2022-05-01T01:46:59Z", "published": "2022-05-01T01:46:59Z", "aliases": [ "CVE-2005-0082" ], "details": "The sapdbwa_GetUserData function in MySQL MaxDB 7.5.0.0, and other versions before 172.16.58.3, allows remote attackers to cause a denial of service (crash) via invalid parameters to the WebDAV handler code, which triggers a null dereference that causes the SAP DB Web Agent to crash.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2005-0082" }, { "type": "WEB", "url": "http://www.idefense.com/application/poi/display?id=187&type=vulnerabilities" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
402
2,151
<reponame>zipated/src // Copyright (c) 2009-2017 The OTS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "os2.h" #include "head.h" // OS/2 - OS/2 and Windows Metrics // http://www.microsoft.com/typography/otspec/os2.htm namespace ots { bool OpenTypeOS2::Parse(const uint8_t *data, size_t length) { Buffer table(data, length); if (!table.ReadU16(&this->table.version) || !table.ReadS16(&this->table.avg_char_width) || !table.ReadU16(&this->table.weight_class) || !table.ReadU16(&this->table.width_class) || !table.ReadU16(&this->table.type) || !table.ReadS16(&this->table.subscript_x_size) || !table.ReadS16(&this->table.subscript_y_size) || !table.ReadS16(&this->table.subscript_x_offset) || !table.ReadS16(&this->table.subscript_y_offset) || !table.ReadS16(&this->table.superscript_x_size) || !table.ReadS16(&this->table.superscript_y_size) || !table.ReadS16(&this->table.superscript_x_offset) || !table.ReadS16(&this->table.superscript_y_offset) || !table.ReadS16(&this->table.strikeout_size) || !table.ReadS16(&this->table.strikeout_position) || !table.ReadS16(&this->table.family_class)) { return Error("Error reading basic table elements"); } if (this->table.version > 5) { return Error("Unsupported table version: %u", this->table.version); } // Follow WPF Font Selection Model's advice. if (1 <= this->table.weight_class && this->table.weight_class <= 9) { Warning("Bad usWeightClass: %u, changing it to %u", this->table.weight_class, this->table.weight_class * 100); this->table.weight_class *= 100; } // Ditto. if (this->table.weight_class > 999) { Warning("Bad usWeightClass: %u, changing it to %d", this->table.weight_class, 999); this->table.weight_class = 999; } if (this->table.width_class < 1) { Warning("Bad usWidthClass: %u, changing it to %d", this->table.width_class, 1); this->table.width_class = 1; } else if (this->table.width_class > 9) { Warning("Bad usWidthClass: %u, changing it to %d", this->table.width_class, 9); this->table.width_class = 9; } // lowest 3 bits of fsType are exclusive. if (this->table.type & 0x2) { // mask bits 2 & 3. this->table.type &= 0xfff3u; } else if (this->table.type & 0x4) { // mask bits 1 & 3. this->table.type &= 0xfff4u; } else if (this->table.type & 0x8) { // mask bits 1 & 2. this->table.type &= 0xfff9u; } // mask reserved bits. use only 0..3, 8, 9 bits. this->table.type &= 0x30f; #define SET_TO_ZERO(a, b) \ if (this->table.b < 0) { \ Warning("Bad " a ": %d, setting it to zero", this->table.b); \ this->table.b = 0; \ } SET_TO_ZERO("ySubscriptXSize", subscript_x_size); SET_TO_ZERO("ySubscriptYSize", subscript_y_size); SET_TO_ZERO("ySuperscriptXSize", superscript_x_size); SET_TO_ZERO("ySuperscriptYSize", superscript_y_size); SET_TO_ZERO("yStrikeoutSize", strikeout_size); #undef SET_TO_ZERO static std::string panose_strings[10] = { "bFamilyType", "bSerifStyle", "bWeight", "bProportion", "bContrast", "bStrokeVariation", "bArmStyle", "bLetterform", "bMidline", "bXHeight", }; for (unsigned i = 0; i < 10; ++i) { if (!table.ReadU8(&this->table.panose[i])) { return Error("Failed to read PANOSE %s", panose_strings[i].c_str()); } } if (!table.ReadU32(&this->table.unicode_range_1) || !table.ReadU32(&this->table.unicode_range_2) || !table.ReadU32(&this->table.unicode_range_3) || !table.ReadU32(&this->table.unicode_range_4) || !table.ReadU32(&this->table.vendor_id) || !table.ReadU16(&this->table.selection) || !table.ReadU16(&this->table.first_char_index) || !table.ReadU16(&this->table.last_char_index) || !table.ReadS16(&this->table.typo_ascender) || !table.ReadS16(&this->table.typo_descender) || !table.ReadS16(&this->table.typo_linegap) || !table.ReadU16(&this->table.win_ascent) || !table.ReadU16(&this->table.win_descent)) { return Error("Error reading more basic table fields"); } // If bit 6 is set, then bits 0 and 5 must be clear. if (this->table.selection & 0x40) { this->table.selection &= 0xffdeu; } // the settings of bits 0 and 1 must be reflected in the macStyle bits // in the 'head' table. OpenTypeHEAD *head = static_cast<OpenTypeHEAD*>( GetFont()->GetTypedTable(OTS_TAG_HEAD)); if ((this->table.selection & 0x1) && head && !(head->mac_style & 0x2)) { Warning("Adjusting head.macStyle (italic) to match fsSelection"); head->mac_style |= 0x2; } if ((this->table.selection & 0x2) && head && !(head->mac_style & 0x4)) { Warning("Adjusting head.macStyle (underscore) to match fsSelection"); head->mac_style |= 0x4; } // While bit 6 on implies that bits 0 and 1 of macStyle are clear, // the reverse is not true. if ((this->table.selection & 0x40) && head && (head->mac_style & 0x3)) { Warning("Adjusting head.macStyle (regular) to match fsSelection"); head->mac_style &= 0xfffcu; } if ((this->table.version < 4) && (this->table.selection & 0x300)) { // bit 8 and 9 must be unset in OS/2 table versions less than 4. return Error("fSelection bits 8 and 9 must be unset for table version %d", this->table.version); } // mask reserved bits. use only 0..9 bits. this->table.selection &= 0x3ff; if (this->table.first_char_index > this->table.last_char_index) { return Error("usFirstCharIndex %d > usLastCharIndex %d", this->table.first_char_index, this->table.last_char_index); } if (this->table.typo_linegap < 0) { Warning("Bad sTypoLineGap, setting it to 0: %d", this->table.typo_linegap); this->table.typo_linegap = 0; } if (this->table.version < 1) { // http://www.microsoft.com/typography/otspec/os2ver0.htm return true; } if (length < offsetof(OS2Data, code_page_range_2)) { Warning("Bad version number, setting it to 0: %u", this->table.version); // Some fonts (e.g., kredit1.ttf and quinquef.ttf) have weird version // numbers. Fix them. this->table.version = 0; return true; } if (!table.ReadU32(&this->table.code_page_range_1) || !table.ReadU32(&this->table.code_page_range_2)) { return Error("Failed to read ulCodePageRange1 or ulCodePageRange2"); } if (this->table.version < 2) { // http://www.microsoft.com/typography/otspec/os2ver1.htm return true; } if (length < offsetof(OS2Data, max_context)) { Warning("Bad version number, setting it to 1: %u", this->table.version); // some Japanese fonts (e.g., mona.ttf) have weird version number. // fix them. this->table.version = 1; return true; } if (!table.ReadS16(&this->table.x_height) || !table.ReadS16(&this->table.cap_height) || !table.ReadU16(&this->table.default_char) || !table.ReadU16(&this->table.break_char) || !table.ReadU16(&this->table.max_context)) { return Error("Failed to read version 2-specific fields"); } if (this->table.x_height < 0) { Warning("Bad sxHeight settig it to 0: %d", this->table.x_height); this->table.x_height = 0; } if (this->table.cap_height < 0) { Warning("Bad sCapHeight setting it to 0: %d", this->table.cap_height); this->table.cap_height = 0; } if (this->table.version < 5) { // http://www.microsoft.com/typography/otspec/os2ver4.htm return true; } if (!table.ReadU16(&this->table.lower_optical_pointsize) || !table.ReadU16(&this->table.upper_optical_pointsize)) { return Error("Failed to read version 5-specific fields"); } if (this->table.lower_optical_pointsize > 0xFFFE) { Warning("usLowerOpticalPointSize is bigger than 0xFFFE: %d", this->table.lower_optical_pointsize); this->table.lower_optical_pointsize = 0xFFFE; } if (this->table.upper_optical_pointsize < 2) { Warning("usUpperOpticalPointSize is lower than 2: %d", this->table.upper_optical_pointsize); this->table.upper_optical_pointsize = 2; } return true; } bool OpenTypeOS2::Serialize(OTSStream *out) { if (!out->WriteU16(this->table.version) || !out->WriteS16(this->table.avg_char_width) || !out->WriteU16(this->table.weight_class) || !out->WriteU16(this->table.width_class) || !out->WriteU16(this->table.type) || !out->WriteS16(this->table.subscript_x_size) || !out->WriteS16(this->table.subscript_y_size) || !out->WriteS16(this->table.subscript_x_offset) || !out->WriteS16(this->table.subscript_y_offset) || !out->WriteS16(this->table.superscript_x_size) || !out->WriteS16(this->table.superscript_y_size) || !out->WriteS16(this->table.superscript_x_offset) || !out->WriteS16(this->table.superscript_y_offset) || !out->WriteS16(this->table.strikeout_size) || !out->WriteS16(this->table.strikeout_position) || !out->WriteS16(this->table.family_class)) { return Error("Failed to write basic table data"); } for (unsigned i = 0; i < 10; ++i) { if (!out->Write(&this->table.panose[i], 1)) { return Error("Failed to write PANOSE data"); } } if (!out->WriteU32(this->table.unicode_range_1) || !out->WriteU32(this->table.unicode_range_2) || !out->WriteU32(this->table.unicode_range_3) || !out->WriteU32(this->table.unicode_range_4) || !out->WriteU32(this->table.vendor_id) || !out->WriteU16(this->table.selection) || !out->WriteU16(this->table.first_char_index) || !out->WriteU16(this->table.last_char_index) || !out->WriteS16(this->table.typo_ascender) || !out->WriteS16(this->table.typo_descender) || !out->WriteS16(this->table.typo_linegap) || !out->WriteU16(this->table.win_ascent) || !out->WriteU16(this->table.win_descent)) { return Error("Failed to write version 1-specific fields"); } if (this->table.version < 1) { return true; } if (!out->WriteU32(this->table.code_page_range_1) || !out->WriteU32(this->table.code_page_range_2)) { return Error("Failed to write codepage ranges"); } if (this->table.version < 2) { return true; } if (!out->WriteS16(this->table.x_height) || !out->WriteS16(this->table.cap_height) || !out->WriteU16(this->table.default_char) || !out->WriteU16(this->table.break_char) || !out->WriteU16(this->table.max_context)) { return Error("Failed to write version 2-specific fields"); } if (this->table.version < 5) { return true; } if (!out->WriteU16(this->table.lower_optical_pointsize) || !out->WriteU16(this->table.upper_optical_pointsize)) { return Error("Failed to write version 5-specific fields"); } return true; } } // namespace ots
4,705
324
{"nodes":[{"address":"10.1.1.1","port":80,"condition":"ENABLED","weight":3},{"address":"10.1.1.2","port":80,"condition":"ENABLED","type":"SECONDARY","weight":8},{"address":"10.1.1.3","port":80,"condition":"DISABLED","weight":12}]}
83
1,338
/* * Copyright 2001-2011, Haiku. * Distributed under the terms of the MIT License. * * Authors: * Pahtz <<EMAIL>> * <NAME> * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> */ /*! Class for low-overhead port-based messaging */ #include <LinkReceiver.h> #include <stdlib.h> #include <string.h> #include <new> #include <ServerProtocol.h> #include <String.h> #include <Region.h> #include <GradientLinear.h> #include <GradientRadial.h> #include <GradientRadialFocus.h> #include <GradientDiamond.h> #include <GradientConic.h> #include "link_message.h" //#define DEBUG_BPORTLINK #ifdef DEBUG_BPORTLINK # include <stdio.h> # define STRACE(x) printf x #else # define STRACE(x) ; #endif //#define TRACE_LINK_RECEIVER_GRADIENTS #ifdef TRACE_LINK_RECEIVER_GRADIENTS # include <OS.h> # define GTRACE(x) debug_printf x #else # define GTRACE(x) ; #endif namespace BPrivate { LinkReceiver::LinkReceiver(port_id port) : fReceivePort(port), fRecvBuffer(NULL), fRecvPosition(0), fRecvStart(0), fRecvBufferSize(0), fDataSize(0), fReplySize(0), fReadError(B_OK) { } LinkReceiver::~LinkReceiver() { free(fRecvBuffer); } void LinkReceiver::SetPort(port_id port) { fReceivePort = port; } status_t LinkReceiver::GetNextMessage(int32 &code, bigtime_t timeout) { fReadError = B_OK; int32 remaining = fDataSize - (fRecvStart + fReplySize); STRACE(("info: LinkReceiver GetNextReply() reports %ld bytes remaining in buffer.\n", remaining)); // find the position of the next message header in the buffer message_header *header; if (remaining <= 0) { status_t err = ReadFromPort(timeout); if (err < B_OK) return err; remaining = fDataSize; header = (message_header *)fRecvBuffer; } else { fRecvStart += fReplySize; // start of the next message fRecvPosition = fRecvStart; header = (message_header *)(fRecvBuffer + fRecvStart); } // check we have a well-formed message if (remaining < (int32)sizeof(message_header)) { // we don't have enough data for a complete header STRACE(("error info: LinkReceiver remaining %ld bytes is less than header size.\n", remaining)); ResetBuffer(); return B_ERROR; } fReplySize = header->size; if (fReplySize > remaining || fReplySize < (int32)sizeof(message_header)) { STRACE(("error info: LinkReceiver message size of %ld bytes smaller than header size.\n", fReplySize)); ResetBuffer(); return B_ERROR; } code = header->code; fRecvPosition += sizeof(message_header); STRACE(("info: LinkReceiver got header %ld [%ld %ld %ld] from port %ld.\n", header->code, fReplySize, header->code, header->flags, fReceivePort)); return B_OK; } bool LinkReceiver::HasMessages() const { return fDataSize - (fRecvStart + fReplySize) > 0 || port_count(fReceivePort) > 0; } bool LinkReceiver::NeedsReply() const { if (fReplySize == 0) return false; message_header *header = (message_header *)(fRecvBuffer + fRecvStart); return (header->flags & kNeedsReply) != 0; } int32 LinkReceiver::Code() const { if (fReplySize == 0) return B_ERROR; message_header *header = (message_header *)(fRecvBuffer + fRecvStart); return header->code; } void LinkReceiver::ResetBuffer() { fRecvPosition = 0; fRecvStart = 0; fDataSize = 0; fReplySize = 0; } status_t LinkReceiver::AdjustReplyBuffer(bigtime_t timeout) { // Here we take advantage of the compiler's dead-code elimination if (kInitialBufferSize == kMaxBufferSize) { // fixed buffer size if (fRecvBuffer != NULL) return B_OK; fRecvBuffer = (char *)malloc(kInitialBufferSize); if (fRecvBuffer == NULL) return B_NO_MEMORY; fRecvBufferSize = kInitialBufferSize; } else { STRACE(("info: LinkReceiver getting port_buffer_size().\n")); ssize_t bufferSize; do { bufferSize = port_buffer_size_etc(fReceivePort, timeout == B_INFINITE_TIMEOUT ? 0 : B_RELATIVE_TIMEOUT, timeout); } while (bufferSize == B_INTERRUPTED); STRACE(("info: LinkReceiver got port_buffer_size() = %ld.\n", bufferSize)); if (bufferSize < 0) return (status_t)bufferSize; // make sure our receive buffer is large enough if (bufferSize > fRecvBufferSize) { if (bufferSize <= (ssize_t)kInitialBufferSize) bufferSize = (ssize_t)kInitialBufferSize; else bufferSize = (bufferSize + B_PAGE_SIZE - 1) & ~(B_PAGE_SIZE - 1); if (bufferSize > (ssize_t)kMaxBufferSize) return B_ERROR; // we can't continue STRACE(("info: LinkReceiver setting receive buffersize to %ld.\n", bufferSize)); char *buffer = (char *)malloc(bufferSize); if (buffer == NULL) return B_NO_MEMORY; free(fRecvBuffer); fRecvBuffer = buffer; fRecvBufferSize = bufferSize; } } return B_OK; } status_t LinkReceiver::ReadFromPort(bigtime_t timeout) { // we are here so it means we finished reading the buffer contents ResetBuffer(); status_t err = AdjustReplyBuffer(timeout); if (err < B_OK) return err; int32 code; ssize_t bytesRead; STRACE(("info: LinkReceiver reading port %ld.\n", fReceivePort)); while (true) { if (timeout != B_INFINITE_TIMEOUT) { do { bytesRead = read_port_etc(fReceivePort, &code, fRecvBuffer, fRecvBufferSize, B_TIMEOUT, timeout); } while (bytesRead == B_INTERRUPTED); } else { do { bytesRead = read_port(fReceivePort, &code, fRecvBuffer, fRecvBufferSize); } while (bytesRead == B_INTERRUPTED); } STRACE(("info: LinkReceiver read %ld bytes.\n", bytesRead)); if (bytesRead < B_OK) return bytesRead; // we just ignore incorrect messages, and don't bother our caller if (code != kLinkCode) { STRACE(("wrong port message %lx received.\n", code)); continue; } // port read seems to be valid break; } fDataSize = bytesRead; return B_OK; } status_t LinkReceiver::Read(void *data, ssize_t passedSize) { // STRACE(("info: LinkReceiver Read()ing %ld bytes...\n", size)); ssize_t size = passedSize; if (fReadError < B_OK) return fReadError; if (data == NULL || size < 1) { fReadError = B_BAD_VALUE; return B_BAD_VALUE; } if (fDataSize == 0 || fReplySize == 0) return B_NO_INIT; // need to call GetNextReply() first bool useArea = false; if ((size_t)size >= kMaxBufferSize) { useArea = true; size = sizeof(area_id); } if (fRecvPosition + size > fRecvStart + fReplySize) { // reading past the end of current message fReadError = B_BAD_VALUE; return B_BAD_VALUE; } if (useArea) { area_id sourceArea; memcpy((void*)&sourceArea, fRecvBuffer + fRecvPosition, size); area_info areaInfo; if (get_area_info(sourceArea, &areaInfo) < B_OK) fReadError = B_BAD_VALUE; if (fReadError >= B_OK) { void* areaAddress = areaInfo.address; if (areaAddress && sourceArea >= B_OK) { memcpy(data, areaAddress, passedSize); delete_area(sourceArea); } } } else { memcpy(data, fRecvBuffer + fRecvPosition, size); } fRecvPosition += size; return fReadError; } status_t LinkReceiver::ReadString(char** _string, size_t* _length) { int32 length = 0; status_t status = Read<int32>(&length); if (status < B_OK) return status; char *string; if (length < 0) { status = B_ERROR; goto err; } string = (char *)malloc(length + 1); if (string == NULL) { status = B_NO_MEMORY; goto err; } if (length > 0) { status = Read(string, length); if (status < B_OK) { free(string); return status; } } // make sure the string is null terminated string[length] = '\0'; if (_length) *_length = length; *_string = string; return B_OK; err: fRecvPosition -= sizeof(int32); // rewind the transaction return status; } status_t LinkReceiver::ReadString(BString &string, size_t* _length) { int32 length = 0; status_t status = Read<int32>(&length); if (status < B_OK) return status; if (length < 0) { status = B_ERROR; goto err; } if (length > 0) { char* buffer = string.LockBuffer(length + 1); if (buffer == NULL) { status = B_NO_MEMORY; goto err; } status = Read(buffer, length); if (status < B_OK) { string.UnlockBuffer(); goto err; } // make sure the string is null terminated buffer[length] = '\0'; string.UnlockBuffer(length); } else string = ""; if (_length) *_length = length; return B_OK; err: fRecvPosition -= sizeof(int32); // rewind the transaction return status; } status_t LinkReceiver::ReadString(char *buffer, size_t bufferLength) { int32 length = 0; status_t status = Read<int32>(&length); if (status < B_OK) return status; if (length >= (int32)bufferLength) { status = B_BUFFER_OVERFLOW; goto err; } if (length < 0) { status = B_ERROR; goto err; } if (length > 0) { status = Read(buffer, length); if (status < B_OK) goto err; } // make sure the string is null terminated buffer[length] = '\0'; return B_OK; err: fRecvPosition -= sizeof(int32); // rewind the transaction return status; } status_t LinkReceiver::ReadRegion(BRegion* region) { status_t status = Read(&region->fCount, sizeof(int32)); if (status >= B_OK) status = Read(&region->fBounds, sizeof(clipping_rect)); if (status >= B_OK) { if (!region->_SetSize(region->fCount)) status = B_NO_MEMORY; else { status = Read(region->fData, region->fCount * sizeof(clipping_rect)); } if (status < B_OK) region->MakeEmpty(); } return status; } static BGradient* gradient_for_type(BGradient::Type type) { switch (type) { case BGradient::TYPE_LINEAR: return new (std::nothrow) BGradientLinear(); case BGradient::TYPE_RADIAL: return new (std::nothrow) BGradientRadial(); case BGradient::TYPE_RADIAL_FOCUS: return new (std::nothrow) BGradientRadialFocus(); case BGradient::TYPE_DIAMOND: return new (std::nothrow) BGradientDiamond(); case BGradient::TYPE_CONIC: return new (std::nothrow) BGradientConic(); case BGradient::TYPE_NONE: return new (std::nothrow) BGradient(); } return NULL; } status_t LinkReceiver::ReadGradient(BGradient** _gradient) { GTRACE(("LinkReceiver::ReadGradient\n")); BGradient::Type gradientType; int32 colorsCount; Read(&gradientType, sizeof(BGradient::Type)); status_t status = Read(&colorsCount, sizeof(int32)); if (status != B_OK) return status; BGradient* gradient = gradient_for_type(gradientType); if (!gradient) return B_NO_MEMORY; *_gradient = gradient; if (colorsCount > 0) { BGradient::ColorStop stop; for (int i = 0; i < colorsCount; i++) { if ((status = Read(&stop, sizeof(BGradient::ColorStop))) != B_OK) return status; if (!gradient->AddColorStop(stop, i)) return B_NO_MEMORY; } } switch (gradientType) { case BGradient::TYPE_LINEAR: { GTRACE(("LinkReceiver::ReadGradient> type == TYPE_LINEAR\n")); BGradientLinear* linear = (BGradientLinear*)gradient; BPoint start; BPoint end; Read(&start, sizeof(BPoint)); if ((status = Read(&end, sizeof(BPoint))) != B_OK) return status; linear->SetStart(start); linear->SetEnd(end); return B_OK; } case BGradient::TYPE_RADIAL: { GTRACE(("LinkReceiver::ReadGradient> type == TYPE_RADIAL\n")); BGradientRadial* radial = (BGradientRadial*)gradient; BPoint center; float radius; Read(&center, sizeof(BPoint)); if ((status = Read(&radius, sizeof(float))) != B_OK) return status; radial->SetCenter(center); radial->SetRadius(radius); return B_OK; } case BGradient::TYPE_RADIAL_FOCUS: { GTRACE(("LinkReceiver::ReadGradient> type == TYPE_RADIAL_FOCUS\n")); BGradientRadialFocus* radialFocus = (BGradientRadialFocus*)gradient; BPoint center; BPoint focal; float radius; Read(&center, sizeof(BPoint)); Read(&focal, sizeof(BPoint)); if ((status = Read(&radius, sizeof(float))) != B_OK) return status; radialFocus->SetCenter(center); radialFocus->SetFocal(focal); radialFocus->SetRadius(radius); return B_OK; } case BGradient::TYPE_DIAMOND: { GTRACE(("LinkReceiver::ReadGradient> type == TYPE_DIAMOND\n")); BGradientDiamond* diamond = (BGradientDiamond*)gradient; BPoint center; if ((status = Read(&center, sizeof(BPoint))) != B_OK) return status; diamond->SetCenter(center); return B_OK; } case BGradient::TYPE_CONIC: { GTRACE(("LinkReceiver::ReadGradient> type == TYPE_CONIC\n")); BGradientConic* conic = (BGradientConic*)gradient; BPoint center; float angle; Read(&center, sizeof(BPoint)); if ((status = Read(&angle, sizeof(float))) != B_OK) return status; conic->SetCenter(center); conic->SetAngle(angle); return B_OK; } case BGradient::TYPE_NONE: { GTRACE(("LinkReceiver::ReadGradient> type == TYPE_NONE\n")); break; } } return B_ERROR; } } // namespace BPrivate
5,082
335
{ "word": "Bacteriostat", "definitions": [ "A substance that prevents the multiplying of bacteria without destroying them." ], "parts-of-speech": "Noun" }
67
7,482
/* * Copyright (c) 2006-2021, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * */ #ifndef __BOARD_H__ #define __BOARD_H__ // <o> Internal SRAM memory size[Kbytes] <16 or 32> // <i>Default: 16 #define NRF_SRAM_BEGIN (0x20000000) #define NRF_SRAM_SIZE (16 * 1024) #define NRF_SRAM_END (NRF_SRAM_BEGIN + NRF_SRAM_SIZE) //#endif void rt_hw_board_init(void); #endif
177
34,359
/*++ Copyright (c) Microsoft Corporation. Licensed under the MIT license. Module Name: ConsoleInputReader.h Abstract: This file contains a class whose sole purpose is to abstract away a bunch of details you usually need to know to read VT from a console input handle. --*/ class ConsoleInputReader { public: explicit ConsoleInputReader(HANDLE handle); void SetWindowSizeChangedCallback(std::function<void()> callback); std::optional<std::wstring_view> Read(); private: static constexpr size_t BufferSize{ 128 }; HANDLE _handle; std::wstring _convertedString; std::vector<INPUT_RECORD> _buffer; std::optional<wchar_t> _highSurrogate; std::function<void()> _windowSizeChangedCallback; };
279
883
<reponame>linuxonly801/awesome-DeepLearning # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import numpy as np import paddle from paddle.hapi.model import _all_gather from paddlevideo.utils import get_logger from .registry import METRIC from .base import BaseMetric logger = get_logger("paddlevideo") """ An example for metrics class. MultiCropMetric for slowfast. """ @METRIC.register class MultiCropMetric(BaseMetric): def __init__(self, data_size, batch_size, num_ensemble_views, num_spatial_crops, num_classes, log_interval=1): """prepare for metrics """ super().__init__(data_size, batch_size, log_interval) self.num_ensemble_views = num_ensemble_views self.num_spatial_crops = num_spatial_crops self.num_classes = num_classes self.num_clips = self.num_ensemble_views * self.num_spatial_crops num_videos = self.data_size // self.num_clips self.video_preds = np.zeros((num_videos, self.num_classes)) self.video_labels = np.zeros((num_videos, 1), dtype="int64") self.clip_count = {} def update(self, batch_id, data, outputs): """update metrics during each iter """ labels = data[2] clip_ids = data[3] # gather mulit card, results of following process in each card is the same. if self.world_size > 1: outputs = _all_gather(outputs, self.world_size) labels = _all_gather(labels, self.world_size) clip_ids = _all_gather(clip_ids, self.world_size) # to numpy preds = outputs.numpy() labels = labels.numpy().astype("int64") clip_ids = clip_ids.numpy() # preds ensemble for ind in range(preds.shape[0]): vid_id = int(clip_ids[ind]) // self.num_clips ts_idx = int(clip_ids[ind]) % self.num_clips if vid_id not in self.clip_count: self.clip_count[vid_id] = [] if ts_idx in self.clip_count[vid_id]: logger.info( "[TEST] Passed!! read video {} clip index {} / {} repeatedly." .format(vid_id, ts_idx, clip_ids[ind])) else: self.clip_count[vid_id].append(ts_idx) self.video_preds[vid_id] += preds[ind] # ensemble method: sum if self.video_labels[vid_id].sum() > 0: assert self.video_labels[vid_id] == labels[ind] self.video_labels[vid_id] = labels[ind] if batch_id % self.log_interval == 0: logger.info("[TEST] Processing batch {}/{} ...".format( batch_id, self.data_size // (self.batch_size * self.world_size))) def accumulate(self): """accumulate metrics when finished all iters. """ # check clip index of each video for key in self.clip_count.keys(): if len(self.clip_count[key]) != self.num_clips or sum( self.clip_count[key]) != self.num_clips * (self.num_clips - 1) / 2: logger.info( "[TEST] Count Error!! video [{}] clip count [{}] not match number clips {}" .format(key, self.clip_count[key], self.num_clips)) video_preds = paddle.to_tensor(self.video_preds) video_labels = paddle.to_tensor(self.video_labels) acc_top1 = paddle.metric.accuracy(input=video_preds, label=video_labels, k=1) acc_top5 = paddle.metric.accuracy(input=video_preds, label=video_labels, k=5) logger.info('[TEST] finished, avg_acc1= {}, avg_acc5= {} '.format( acc_top1.numpy(), acc_top5.numpy()))
2,174
2,671
<reponame>timmartin/skulpt<gh_stars>1000+ import unittest import string class ModuleTest(unittest.TestCase): def test_attrs(self): # While the exact order of the items in these attributes is not # technically part of the "language spec", in practice there is almost # certainly user code that depends on the order, so de-facto it *is* # part of the spec. # self.assertEqual(string.whitespace, ' \t\n\r\x0b\x0c') self.assertEqual(string.ascii_lowercase, 'abcdefghijklmnopqrstuvwxyz') self.assertEqual(string.ascii_uppercase, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') self.assertEqual(string.ascii_letters, string.ascii_lowercase + string.ascii_uppercase) self.assertEqual(string.digits, '0123456789') self.assertEqual(string.hexdigits, string.digits + 'abcdefABCDEF') self.assertEqual(string.octdigits, '01234567') self.assertEqual(string.punctuation, '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~') # self.assertEqual(string.printable, string.digits + string.ascii_lowercase + string.ascii_uppercase + string.punctuation + string.whitespace) def test_capwords(self): self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi') # self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi') # self.assertEqual(string.capwords('abc\t def \nghi'), 'Abc Def Ghi') self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi') self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi') self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi') # self.assertEqual(string.capwords(' aBc DeF '), 'Abc Def') # self.assertEqual(string.capwords('\taBc\tDeF\t'), 'Abc Def') # self.assertEqual(string.capwords('\taBc\tDeF\t', '\t'), '\tAbc\tDef\t') if __name__ == '__main__': unittest.main()
851
575
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // A helper class for loading resources out of portable executable files. #ifndef CHROME_INSTALLER_TEST_RESOURCE_LOADER_H_ #define CHROME_INSTALLER_TEST_RESOURCE_LOADER_H_ #include <windows.h> #include <stdint.h> #include <string> #include <utility> #include "base/macros.h" namespace base { class FilePath; } namespace upgrade_test { // Loads resources in a PE image file. class ResourceLoader { public: ResourceLoader(); ~ResourceLoader(); // Loads |pe_image_path| in preparation for loading its resources. bool Initialize(const base::FilePath& pe_image_path); // Places the address and size of the resource |name| of |type| into // |resource_data|, returning true on success. The address of the resource is // valid only until this instance is destroyed. bool Load(const std::wstring& name, const std::wstring& type, std::pair<const uint8_t*, DWORD>* resource_data); // Places the address and size of the resource |id| of |type| into // |resource_data|, returning true on success. The address of the resource is // valid only until this instance is destroyed. bool Load(WORD id, WORD type, std::pair<const uint8_t*, DWORD>* resource_data); private: HMODULE module_; DISALLOW_COPY_AND_ASSIGN(ResourceLoader); }; // class ResourceLoader } // namespace upgrade_test #endif // CHROME_INSTALLER_TEST_RESOURCE_LOADER_H_
527
1,082
package com.jzy.game.cluster.tcp.server; import java.util.Map; import com.jzy.game.message.Mid.MID; import com.jzy.game.message.ServerMessage; import com.jzy.game.message.ServerMessage.ServerListRequest; import com.jzy.game.message.ServerMessage.ServerListResponse; import com.jzy.game.cluster.manager.ServerManager; import com.jzy.game.engine.handler.HandlerEntity; import com.jzy.game.engine.handler.TcpHandler; import com.jzy.game.engine.server.ServerInfo; import com.jzy.game.engine.server.ServerType; /** * 获取服务器列表信息 * * @author JiangZhiYong * @QQ 359135103 2017年6月29日 上午11:39:55 */ @HandlerEntity(mid = MID.ServerListReq_VALUE, msg = ServerListRequest.class) public class ServerListHandler extends TcpHandler { @Override public void run() { ServerListRequest req = getMsg(); if (req.getServerType() != ServerType.GAME.getType()) { Map<Integer, ServerInfo> servers = ServerManager.getInstance() .getServers(ServerType.valueof(req.getServerType())); if (servers != null) { ServerListResponse.Builder builder = ServerListResponse.newBuilder(); ServerMessage.ServerInfo.Builder infoBuilder = ServerMessage.ServerInfo.newBuilder(); servers.forEach((id, info) -> { if (info != null && info.getSession() != null && info.getSession().isConnected()) { builder.addServerInfo(buildServerInfo(info, infoBuilder)); } }); getSession().write(builder.build()); } } else { // 只获取游戏服务器,大厅服(网关服需要获取大厅+所有游戏服务器信息) ServerListResponse.Builder builder = ServerListResponse.newBuilder(); ServerMessage.ServerInfo.Builder infoBuilder = ServerMessage.ServerInfo.newBuilder(); ServerManager.getInstance().getServers().forEach((serverType, s) -> { if (serverType.getType() > 100 || serverType == ServerType.HALL) { s.forEach((id, server) -> { if (server != null && server.getSession() != null && server.getSession().isConnected()) { builder.addServerInfo(buildServerInfo(server, infoBuilder)); } }); } }); getSession().write(builder.build()); } } /** * 服务器信息 * * @param info * @param builder * @return */ private ServerMessage.ServerInfo buildServerInfo(ServerInfo serverInfo, ServerMessage.ServerInfo.Builder infoBuilder) { infoBuilder.clear(); infoBuilder.setId(serverInfo.getId()); infoBuilder.setHttpport(serverInfo.getHttpPort()); infoBuilder.setIp(serverInfo.getIp()); infoBuilder.setMaxUserCount(serverInfo.getMaxUserCount()); infoBuilder.setName(serverInfo.getName()); infoBuilder.setOnline(serverInfo.getOnline()); infoBuilder.setPort(serverInfo.getPort()); infoBuilder.setState(serverInfo.getState()); infoBuilder.setType(serverInfo.getType()); infoBuilder.setWwwip(serverInfo.getWwwip()); return infoBuilder.build(); } }
1,163
1,408
/* * Copyright (C) 2018 Marvell International Ltd. * Copyright (C) 2021 Semihalf. * * SPDX-License-Identifier: BSD-3-Clause * https://spdx.org/licenses */ #include <armada_common.h> #include <mvebu_def.h> /* * If bootrom is currently at BLE there's no need to include the memory * maps structure at this point */ #ifndef IMAGE_BLE /***************************************************************************** * AMB Configuration ***************************************************************************** */ struct addr_map_win amb_memory_map_cp0[] = { /* CP0 SPI1 CS0 Direct Mode access */ {0xef00, 0x1000000, AMB_SPI1_CS0_ID}, }; struct addr_map_win amb_memory_map_cp1[] = { /* CP1 SPI1 CS0 Direct Mode access */ {0xe800, 0x1000000, AMB_SPI1_CS0_ID}, }; int marvell_get_amb_memory_map(struct addr_map_win **win, uint32_t *size, uintptr_t base) { switch (base) { case MVEBU_CP_REGS_BASE(0): *win = amb_memory_map_cp0; *size = ARRAY_SIZE(amb_memory_map_cp0); return 0; case MVEBU_CP_REGS_BASE(1): *win = amb_memory_map_cp1; *size = ARRAY_SIZE(amb_memory_map_cp1); return 0; case MVEBU_CP_REGS_BASE(2): default: *size = 0; *win = 0; return 1; } } #endif /***************************************************************************** * IO WIN Configuration ***************************************************************************** */ struct addr_map_win io_win_memory_map[] = { #if (CP_COUNT > 1) /* SB (MCi0) internal regs */ {0x00000000f4000000, 0x2000000, MCI_0_TID}, /* SB (MCi0) PCIe0-2 on CP1 */ {0x00000000e2000000, 0x7000000, MCI_0_TID}, /* * Due to lack of sufficient number of IO windows registers, * below CP1 PCIE configuration must be performed in the * later firmware stages. It should replace the MCI 0 indirect * window, which becomes no longer needed. */ /* {0x0000000890000000, 0x30000000, MCI_0_TID}, */ #if (CP_COUNT > 2) /* SB (MCi1) internal regs */ {0x00000000f6000000, 0x2000000, MCI_1_TID}, /* SB (MCi1) PCIe0-2 on CP2 */ {0x00000000e9000000, 0x6000000, MCI_1_TID}, /* * Due to lack of sufficient number of IO windows registers, * below CP2 PCIE configuration must be performed in the * later firmware stages. It should replace the MCI 1 indirect * window, which becomes no longer needed. */ /* {0x00000008c0000000, 0x30000000, MCI_1_TID}, */ #endif #endif #ifndef IMAGE_BLE /* MCI 0 indirect window */ {MVEBU_MCI_REG_BASE_REMAP(0), 0x100000, MCI_0_TID}, /* MCI 1 indirect window */ {MVEBU_MCI_REG_BASE_REMAP(1), 0x100000, MCI_1_TID}, #endif }; /* Global Control Register - window default target */ uint32_t marvell_get_io_win_gcr_target(int ap_index) { /* * PIDI == iMCIP AP to SB internal MoChi connection. * In other words CP0 */ return PIDI_TID; } int marvell_get_io_win_memory_map(int ap_index, struct addr_map_win **win, uint32_t *size) { *win = io_win_memory_map; if (*win == NULL) *size = 0; else *size = ARRAY_SIZE(io_win_memory_map); return 0; } #ifndef IMAGE_BLE /***************************************************************************** * IOB Configuration ***************************************************************************** */ struct addr_map_win iob_memory_map_cp0[] = { /* SPI1_CS0 (RUNIT) window */ {0x00000000ef000000, 0x1000000, RUNIT_TID}, /* PEX2_X1 window */ {0x00000000e1000000, 0x1000000, PEX2_TID}, /* PEX1_X1 window */ {0x00000000e0000000, 0x1000000, PEX1_TID}, /* PEX0_X4 window */ {0x00000000c0000000, 0x20000000, PEX0_TID}, {0x0000000800000000, 0x90000000, PEX0_TID}, }; struct addr_map_win iob_memory_map_cp1[] = { /* SPI1_CS0 (RUNIT) window */ {0x00000000e8000000, 0x1000000, RUNIT_TID}, /* PEX2_X1 window */ {0x00000000e6000000, 0x2000000, PEX2_TID}, {0x00000008b0000000, 0x10000000, PEX2_TID}, /* PEX1_X1 window */ {0x00000000e4000000, 0x2000000, PEX1_TID}, {0x00000008a0000000, 0x10000000, PEX1_TID}, /* PEX0_X2 window */ {0x00000000e2000000, 0x2000000, PEX0_TID}, {0x0000000890000000, 0x10000000, PEX0_TID}, }; struct addr_map_win iob_memory_map_cp2[] = { /* PEX2_X1 window */ {0x00000000ed000000, 0x2000000, PEX2_TID}, {0x00000008e0000000, 0x10000000, PEX2_TID}, /* PEX1_X1 window */ {0x00000000eb000000, 0x2000000, PEX1_TID}, {0x00000008d0000000, 0x10000000, PEX1_TID}, /* PEX0_X1 window */ {0x00000000e9000000, 0x2000000, PEX0_TID}, {0x00000008c0000000, 0x10000000, PEX0_TID}, }; int marvell_get_iob_memory_map(struct addr_map_win **win, uint32_t *size, uintptr_t base) { switch (base) { case MVEBU_CP_REGS_BASE(0): *win = iob_memory_map_cp0; *size = ARRAY_SIZE(iob_memory_map_cp0); return 0; case MVEBU_CP_REGS_BASE(1): *win = iob_memory_map_cp1; *size = ARRAY_SIZE(iob_memory_map_cp1); return 0; case MVEBU_CP_REGS_BASE(2): *win = iob_memory_map_cp2; *size = ARRAY_SIZE(iob_memory_map_cp2); return 0; default: *size = 0; *win = 0; return 1; } } #endif /***************************************************************************** * CCU Configuration ***************************************************************************** */ struct addr_map_win ccu_memory_map[] = { /* IO window */ #ifdef IMAGE_BLE {0x00000000f2000000, 0x6000000, IO_0_TID}, /* IO window */ #else #if LLC_SRAM {PLAT_MARVELL_LLC_SRAM_BASE, PLAT_MARVELL_LLC_SRAM_SIZE, DRAM_0_TID}, #endif {0x00000000f2000000, 0xe000000, IO_0_TID}, /* IO window */ {0x00000000c0000000, 0x30000000, IO_0_TID}, /* IO window */ {0x0000000800000000, 0x100000000, IO_0_TID}, /* IO window */ {0x0000002000000000, 0x70e000000, IO_0_TID}, /* IO for CV-OS */ #endif }; uint32_t marvell_get_ccu_gcr_target(int ap) { return DRAM_0_TID; } int marvell_get_ccu_memory_map(int ap_index, struct addr_map_win **win, uint32_t *size) { *win = ccu_memory_map; *size = ARRAY_SIZE(ccu_memory_map); return 0; } #ifdef IMAGE_BLE /***************************************************************************** * SKIP IMAGE Configuration ***************************************************************************** */ void *plat_get_skip_image_data(void) { /* No recovery button on CN-9130 board? */ return NULL; } #endif
2,528
2,151
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/cast_channel/cast_message_util.h" #include <memory> #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "build/build_config.h" #include "components/cast_channel/cast_auth_util.h" #include "components/cast_channel/proto/cast_channel.pb.h" using base::Value; namespace cast_channel { namespace { // Reserved message namespaces for internal messages. constexpr char kCastInternalNamespacePrefix[] = "urn:x-cast:com.google.cast."; constexpr char kAuthNamespace[] = "urn:x-cast:com.google.cast.tp.deviceauth"; constexpr char kHeartbeatNamespace[] = "urn:x-cast:com.google.cast.tp.heartbeat"; constexpr char kConnectionNamespace[] = "urn:x-cast:com.google.cast.tp.connection"; constexpr char kReceiverNamespace[] = "urn:x-cast:com.google.cast.receiver"; constexpr char kBroadcastNamespace[] = "urn:x-cast:com.google.cast.broadcast"; // Text payload keys. constexpr char kTypeNodeId[] = "type"; constexpr char kRequestIdNodeId[] = "requestId"; // Cast application protocol message types. constexpr char kKeepAlivePingType[] = "PING"; constexpr char kKeepAlivePongType[] = "PONG"; constexpr char kGetAppAvailabilityRequestType[] = "GET_APP_AVAILABILITY"; constexpr char kConnectionRequestType[] = "CONNECT"; constexpr char kBroadcastRequestType[] = "APPLICATION_BROADCAST"; constexpr char kLaunchRequestType[] = "LAUNCH"; constexpr char kReceiverStatusType[] = "RECEIVER_STATUS"; constexpr char kLaunchErrorType[] = "LAUNCH_ERROR"; // The value used for "sdkType" in a virtual connect request. Historically, this // value is used in the Media Router extension, but here it is reused in Chrome. constexpr int kVirtualConnectSdkType = 2; // The value used for "connectionType" in a virtual connect request. This value // stands for CONNECTION_TYPE_LOCAL, which is the only type used in Chrome. constexpr int kVirtualConnectTypeLocal = 1; void FillCommonCastMessageFields(CastMessage* message, const std::string& source_id, const std::string& destination_id, const std::string& message_namespace) { message->set_protocol_version(CastMessage::CASTV2_1_0); message->set_source_id(source_id); message->set_destination_id(destination_id); message->set_namespace_(message_namespace); } CastMessage CreateKeepAliveMessage(const char* keep_alive_type) { base::DictionaryValue type_dict; type_dict.SetString(kTypeNodeId, keep_alive_type); return CreateCastMessage(kHeartbeatNamespace, type_dict, kPlatformSenderId, kPlatformReceiverId); } // Returns the value to be set as the "platform" value in a virtual connect // request. The value is platform-dependent and is taken from the Platform enum // defined in third_party/metrics_proto/cast_logs.proto. int GetVirtualConnectPlatformValue() { #if defined(OS_WIN) return 3; #elif defined(OS_MACOSX) return 4; #elif defined(OS_CHROMEOS) return 5; #elif defined(OS_LINUX) return 6; #else return 0; #endif } } // namespace bool IsCastMessageValid(const CastMessage& message_proto) { if (!message_proto.IsInitialized()) return false; if (message_proto.namespace_().empty() || message_proto.source_id().empty() || message_proto.destination_id().empty()) { return false; } return (message_proto.payload_type() == CastMessage_PayloadType_STRING && message_proto.has_payload_utf8()) || (message_proto.payload_type() == CastMessage_PayloadType_BINARY && message_proto.has_payload_binary()); } std::unique_ptr<base::DictionaryValue> GetDictionaryFromCastMessage( const CastMessage& message) { if (!message.has_payload_utf8()) return nullptr; return base::DictionaryValue::From( base::JSONReader::Read(message.payload_utf8())); } bool IsCastInternalNamespace(const std::string& message_namespace) { // Note: any namespace with the prefix is assumed to be reserved for internal // messages. return base::StartsWith(message_namespace, kCastInternalNamespacePrefix, base::CompareCase::SENSITIVE); } CastMessageType ParseMessageType(const CastMessage& message) { std::unique_ptr<base::DictionaryValue> dictionary = GetDictionaryFromCastMessage(message); return dictionary ? ParseMessageTypeFromPayload(*dictionary) : CastMessageType::kOther; } CastMessageType ParseMessageTypeFromPayload(const base::Value& payload) { const Value* type_string = payload.FindKeyOfType(kTypeNodeId, Value::Type::STRING); return type_string ? CastMessageTypeFromString(type_string->GetString()) : CastMessageType::kOther; } const char* CastMessageTypeToString(CastMessageType message_type) { switch (message_type) { case CastMessageType::kPing: return kKeepAlivePingType; case CastMessageType::kPong: return kKeepAlivePongType; case CastMessageType::kGetAppAvailability: return kGetAppAvailabilityRequestType; case CastMessageType::kConnect: return kConnectionRequestType; case CastMessageType::kBroadcast: return kBroadcastRequestType; case CastMessageType::kLaunch: return kLaunchRequestType; case CastMessageType::kReceiverStatus: return kReceiverStatusType; case CastMessageType::kLaunchError: return kLaunchErrorType; case CastMessageType::kOther: return ""; } NOTREACHED(); return ""; } CastMessageType CastMessageTypeFromString(const std::string& type) { if (type == kKeepAlivePingType) return CastMessageType::kPing; if (type == kKeepAlivePongType) return CastMessageType::kPong; if (type == kGetAppAvailabilityRequestType) return CastMessageType::kGetAppAvailability; if (type == kConnectionRequestType) return CastMessageType::kConnect; if (type == kBroadcastRequestType) return CastMessageType::kBroadcast; if (type == kLaunchRequestType) return CastMessageType::kLaunch; if (type == kReceiverStatusType) return CastMessageType::kReceiverStatus; if (type == kLaunchErrorType) return CastMessageType::kLaunchError; DVLOG(1) << "Unknown message type: " << type; return CastMessageType::kOther; } std::string CastMessageToString(const CastMessage& message_proto) { std::string out("{"); out += "namespace = " + message_proto.namespace_(); out += ", sourceId = " + message_proto.source_id(); out += ", destId = " + message_proto.destination_id(); out += ", type = " + base::IntToString(message_proto.payload_type()); out += ", str = \"" + message_proto.payload_utf8() + "\"}"; return out; } std::string AuthMessageToString(const DeviceAuthMessage& message) { std::string out("{"); if (message.has_challenge()) { out += "challenge: {}, "; } if (message.has_response()) { out += "response: {signature: ("; out += base::NumberToString(message.response().signature().length()); out += " bytes), certificate: ("; out += base::NumberToString( message.response().client_auth_certificate().length()); out += " bytes)}"; } if (message.has_error()) { out += ", error: {"; out += base::IntToString(message.error().error_type()); out += "}"; } out += "}"; return out; } void CreateAuthChallengeMessage(CastMessage* message_proto, const AuthContext& auth_context) { CHECK(message_proto); DeviceAuthMessage auth_message; AuthChallenge* challenge = auth_message.mutable_challenge(); DCHECK(challenge); challenge->set_sender_nonce(auth_context.nonce()); challenge->set_hash_algorithm(SHA256); std::string auth_message_string; auth_message.SerializeToString(&auth_message_string); FillCommonCastMessageFields(message_proto, kPlatformSenderId, kPlatformReceiverId, kAuthNamespace); message_proto->set_payload_type(CastMessage_PayloadType_BINARY); message_proto->set_payload_binary(auth_message_string); } bool IsAuthMessage(const CastMessage& message) { return message.namespace_() == kAuthNamespace; } bool IsReceiverMessage(const CastMessage& message) { return message.namespace_() == kReceiverNamespace; } bool IsPlatformSenderMessage(const CastMessage& message) { return message.destination_id() != cast_channel::kPlatformSenderId; } CastMessage CreateKeepAlivePingMessage() { return CreateKeepAliveMessage(kKeepAlivePingType); } CastMessage CreateKeepAlivePongMessage() { return CreateKeepAliveMessage(kKeepAlivePongType); } CastMessage CreateVirtualConnectionRequest( const std::string& source_id, const std::string& destination_id, VirtualConnectionType connection_type, const std::string& user_agent, const std::string& browser_version) { DCHECK(destination_id != kPlatformReceiverId || connection_type == kStrong); // Parse system_version from user agent string. It contains platform, OS and // CPU info and is contained in the first set of parentheses of the user // agent string (e.g., X11; Linux x86_64). std::string system_version; size_t start_index = user_agent.find('('); if (start_index != std::string::npos) { size_t end_index = user_agent.find(')', start_index + 1); if (end_index != std::string::npos) { system_version = user_agent.substr(start_index + 1, end_index - start_index - 1); } } Value dict(Value::Type::DICTIONARY); dict.SetKey(kTypeNodeId, Value(kConnectionRequestType)); dict.SetKey("userAgent", Value(user_agent)); dict.SetKey("connType", Value(connection_type)); dict.SetKey("origin", Value(Value::Type::DICTIONARY)); Value sender_info(Value::Type::DICTIONARY); sender_info.SetKey("sdkType", Value(kVirtualConnectSdkType)); sender_info.SetKey("version", Value(browser_version)); sender_info.SetKey("browserVersion", Value(browser_version)); sender_info.SetKey("platform", Value(GetVirtualConnectPlatformValue())); sender_info.SetKey("connectionType", Value(kVirtualConnectTypeLocal)); if (!system_version.empty()) sender_info.SetKey("systemVersion", Value(system_version)); dict.SetKey("senderInfo", std::move(sender_info)); return CreateCastMessage(kConnectionNamespace, dict, source_id, destination_id); } CastMessage CreateGetAppAvailabilityRequest(const std::string& source_id, int request_id, const std::string& app_id) { Value dict(Value::Type::DICTIONARY); dict.SetKey(kTypeNodeId, Value(kGetAppAvailabilityRequestType)); Value app_id_value(Value::Type::LIST); app_id_value.GetList().push_back(Value(app_id)); dict.SetKey("appId", std::move(app_id_value)); dict.SetKey(kRequestIdNodeId, Value(request_id)); return CreateCastMessage(kReceiverNamespace, dict, source_id, kPlatformReceiverId); } BroadcastRequest::BroadcastRequest(const std::string& broadcast_namespace, const std::string& message) : broadcast_namespace(broadcast_namespace), message(message) {} BroadcastRequest::~BroadcastRequest() = default; bool BroadcastRequest::operator==(const BroadcastRequest& other) const { return broadcast_namespace == other.broadcast_namespace && message == other.message; } CastMessage CreateBroadcastRequest(const std::string& source_id, int request_id, const std::vector<std::string>& app_ids, const BroadcastRequest& request) { Value dict(Value::Type::DICTIONARY); dict.SetKey(kTypeNodeId, Value(kBroadcastRequestType)); std::vector<Value> app_ids_value; for (const std::string& app_id : app_ids) app_ids_value.push_back(Value(app_id)); dict.SetKey("appIds", Value(std::move(app_ids_value))); dict.SetKey("namespace", Value(request.broadcast_namespace)); dict.SetKey("message", Value(request.message)); return CreateCastMessage(kBroadcastNamespace, dict, source_id, kPlatformReceiverId); } CastMessage CreateLaunchRequest(const std::string& source_id, int request_id, const std::string& app_id, const std::string& locale) { Value dict(Value::Type::DICTIONARY); dict.SetKey(kTypeNodeId, Value(kLaunchRequestType)); dict.SetKey(kRequestIdNodeId, Value(request_id)); dict.SetKey("appId", Value(app_id)); dict.SetKey("language", Value(locale)); return CreateCastMessage(kReceiverNamespace, dict, source_id, kPlatformReceiverId); } CastMessage CreateCastMessage(const std::string& message_namespace, const base::Value& message, const std::string& source_id, const std::string& destination_id) { CastMessage output; FillCommonCastMessageFields(&output, source_id, destination_id, message_namespace); output.set_payload_type( CastMessage::PayloadType::CastMessage_PayloadType_STRING); CHECK(base::JSONWriter::Write(message, output.mutable_payload_utf8())); return output; } const char* GetAppAvailabilityResultToString(GetAppAvailabilityResult result) { switch (result) { case GetAppAvailabilityResult::kAvailable: return "available"; case GetAppAvailabilityResult::kUnavailable: return "unavailable"; case GetAppAvailabilityResult::kUnknown: return "unknown"; } } bool GetRequestIdFromResponse(const Value& payload, int* request_id) { DCHECK(request_id); DCHECK(payload.is_dict()); const Value* request_id_value = payload.FindKeyOfType(kRequestIdNodeId, Value::Type::INTEGER); if (!request_id_value) return false; *request_id = request_id_value->GetInt(); return true; } GetAppAvailabilityResult GetAppAvailabilityResultFromResponse( const Value& payload, const std::string& app_id) { DCHECK(payload.is_dict()); const Value* availability_value = payload.FindPathOfType({"availability", app_id}, Value::Type::STRING); if (!availability_value) return GetAppAvailabilityResult::kUnknown; if (availability_value->GetString() == "APP_AVAILABLE") return GetAppAvailabilityResult::kAvailable; if (availability_value->GetString() == "APP_UNAVAILABLE") return GetAppAvailabilityResult::kUnavailable; return GetAppAvailabilityResult::kUnknown; } LaunchSessionResponse::LaunchSessionResponse() {} LaunchSessionResponse::LaunchSessionResponse(LaunchSessionResponse&& other) = default; LaunchSessionResponse::~LaunchSessionResponse() = default; LaunchSessionResponse GetLaunchSessionResponse( const base::DictionaryValue& payload) { const Value* type_value = payload.FindKeyOfType(kTypeNodeId, Value::Type::STRING); if (!type_value) return LaunchSessionResponse(); if (type_value->GetString() != kReceiverStatusType && type_value->GetString() != kLaunchErrorType) return LaunchSessionResponse(); LaunchSessionResponse response; if (type_value->GetString() == kLaunchErrorType) { response.result = LaunchSessionResponse::Result::kError; return response; } const Value* receiver_status = payload.FindKeyOfType("status", Value::Type::DICTIONARY); if (!receiver_status) return LaunchSessionResponse(); response.result = LaunchSessionResponse::Result::kOk; response.receiver_status = receiver_status->Clone(); return response; } } // namespace cast_channel
5,702
3,200
/** * Copyright 2019 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TESTS_UT_PARALLEL_TENSOR_LAYOUT_UT_UTIL_LAYOUT_GEN_H_ #define TESTS_UT_PARALLEL_TENSOR_LAYOUT_UT_UTIL_LAYOUT_GEN_H_ #include <map> #include <tuple> #include <vector> #include "frontend/parallel/tensor_layout/tensor_layout.h" #include "frontend/parallel/step_parallel.h" namespace mindspore { namespace parallel { std::vector<Shape> combine(const Shape &in, int64_t target); void GenerateValidShapeBySizeAndDim(int64_t pow_size, int64_t dim, std::vector<Shape> *out); void GenerateValidShapeBySize(int64_t pow_size, std::vector<Shape> *out); TensorMap GenerateTensorMap(const int64_t &map_size, const Shape &pos_index, const Shape &pos_value); void GenerateValidTensorMap(const DeviceArrangement &device_arrangement, const TensorMap &tensor_shape, std::vector<TensorMap> *tensor_map_list); void GenerateValidLayoutByDeviceSizeAndTensorSize( int64_t device_pow_size, int64_t tensor_pow_size, int64_t max_device_dim, int64_t max_shape_dim, std::vector<std::tuple<DeviceArrangement, TensorMap, TensorShape>> *layout_list); size_t ComputeNoneNumber(const TensorMap &tensor_map); bool ShapeIsDividedByDevice(const DeviceArrangement &device_arrangement, const TensorMap &tensor_map, const TensorShape &tensor_shape); bool CheckLayoutValid(const DeviceArrangement &device_arrangement, const TensorMap &tensor_map, const TensorShape &tensor_shape); void ComputeAccumDeviceTOAccumShapeMap(const DeviceArrangement &device_arrangement, const TensorMap &tensor_map, const TensorShape &tensor_shape, std::map<int64_t, int64_t> *accum_device_to_accum_shape_map); void LayoutTransferValidLayoutChangeCheck(const DeviceArrangement &in_device_arrangement, const TensorMap &in_tensor_map, const TensorShape &in_tensor_shape, const DeviceArrangement &out_device_arrangement, const TensorMap &out_tensor_map, const TensorShape &out_tensor_shape); void ValidLayoutChangeCheck(const DeviceArrangement &in_device_arrangement, const TensorMap &in_tensor_map, const TensorShape &in_tensor_shape, const DeviceArrangement &out_device_arrangement, const TensorMap &out_tensor_map, const TensorShape &out_tensor_shape); } // namespace parallel } // namespace mindspore #endif // TESTS_UT_PARALLEL_TENSOR_LAYOUT_UT_UTIL_LAYOUT_GEN_H_
1,287
348
{"nom":"Amange","circ":"3ème circonscription","dpt":"Jura","inscrits":277,"abs":134,"votants":143,"blancs":11,"nuls":4,"exp":128,"res":[{"nuance":"LR","nom":"<NAME>","voix":71},{"nuance":"MDM","nom":"<NAME>","voix":57}]}
89
507
<filename>terrascript/provider/mumoshu/helmfile.py<gh_stars>100-1000 # terrascript/provider/mumoshu/helmfile.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:18:32 UTC) import terrascript class helmfile(terrascript.Provider): """Deploy Helmfile releases from Terraform""" __description__ = "Deploy Helmfile releases from Terraform" __namespace__ = "mumoshu" __name__ = "helmfile" __source__ = "https://github.com/mumoshu/terraform-provider-helmfile" __version__ = "0.14.1" __published__ = "2021-09-16T23:43:58Z" __tier__ = "community" __all__ = ["helmfile"]
234
416
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.tencentcloudapi.tiw.v20190919.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeVideoGenerationTaskResponse extends AbstractModel{ /** * 任务对应的群组Id */ @SerializedName("GroupId") @Expose private String GroupId; /** * 任务对应的房间号 */ @SerializedName("RoomId") @Expose private Long RoomId; /** * 任务的Id */ @SerializedName("TaskId") @Expose private String TaskId; /** * 已废弃 */ @SerializedName("Progress") @Expose private Long Progress; /** * 录制视频生成任务状态 - QUEUED: 正在排队 - PROCESSING: 正在生成视频 - FINISHED: 生成视频结束(成功完成或失败结束,可以通过错误码和错误信息进一步判断) */ @SerializedName("Status") @Expose private String Status; /** * 回放视频总时长,单位:毫秒 */ @SerializedName("TotalTime") @Expose private Long TotalTime; /** * 已废弃,请使用`VideoInfoList`参数 */ @SerializedName("VideoInfos") @Expose private VideoInfo VideoInfos; /** * 录制视频生成视频列表 */ @SerializedName("VideoInfoList") @Expose private VideoInfo [] VideoInfoList; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ @SerializedName("RequestId") @Expose private String RequestId; /** * Get 任务对应的群组Id * @return GroupId 任务对应的群组Id */ public String getGroupId() { return this.GroupId; } /** * Set 任务对应的群组Id * @param GroupId 任务对应的群组Id */ public void setGroupId(String GroupId) { this.GroupId = GroupId; } /** * Get 任务对应的房间号 * @return RoomId 任务对应的房间号 */ public Long getRoomId() { return this.RoomId; } /** * Set 任务对应的房间号 * @param RoomId 任务对应的房间号 */ public void setRoomId(Long RoomId) { this.RoomId = RoomId; } /** * Get 任务的Id * @return TaskId 任务的Id */ public String getTaskId() { return this.TaskId; } /** * Set 任务的Id * @param TaskId 任务的Id */ public void setTaskId(String TaskId) { this.TaskId = TaskId; } /** * Get 已废弃 * @return Progress 已废弃 */ public Long getProgress() { return this.Progress; } /** * Set 已废弃 * @param Progress 已废弃 */ public void setProgress(Long Progress) { this.Progress = Progress; } /** * Get 录制视频生成任务状态 - QUEUED: 正在排队 - PROCESSING: 正在生成视频 - FINISHED: 生成视频结束(成功完成或失败结束,可以通过错误码和错误信息进一步判断) * @return Status 录制视频生成任务状态 - QUEUED: 正在排队 - PROCESSING: 正在生成视频 - FINISHED: 生成视频结束(成功完成或失败结束,可以通过错误码和错误信息进一步判断) */ public String getStatus() { return this.Status; } /** * Set 录制视频生成任务状态 - QUEUED: 正在排队 - PROCESSING: 正在生成视频 - FINISHED: 生成视频结束(成功完成或失败结束,可以通过错误码和错误信息进一步判断) * @param Status 录制视频生成任务状态 - QUEUED: 正在排队 - PROCESSING: 正在生成视频 - FINISHED: 生成视频结束(成功完成或失败结束,可以通过错误码和错误信息进一步判断) */ public void setStatus(String Status) { this.Status = Status; } /** * Get 回放视频总时长,单位:毫秒 * @return TotalTime 回放视频总时长,单位:毫秒 */ public Long getTotalTime() { return this.TotalTime; } /** * Set 回放视频总时长,单位:毫秒 * @param TotalTime 回放视频总时长,单位:毫秒 */ public void setTotalTime(Long TotalTime) { this.TotalTime = TotalTime; } /** * Get 已废弃,请使用`VideoInfoList`参数 * @return VideoInfos 已废弃,请使用`VideoInfoList`参数 */ public VideoInfo getVideoInfos() { return this.VideoInfos; } /** * Set 已废弃,请使用`VideoInfoList`参数 * @param VideoInfos 已废弃,请使用`VideoInfoList`参数 */ public void setVideoInfos(VideoInfo VideoInfos) { this.VideoInfos = VideoInfos; } /** * Get 录制视频生成视频列表 * @return VideoInfoList 录制视频生成视频列表 */ public VideoInfo [] getVideoInfoList() { return this.VideoInfoList; } /** * Set 录制视频生成视频列表 * @param VideoInfoList 录制视频生成视频列表 */ public void setVideoInfoList(VideoInfo [] VideoInfoList) { this.VideoInfoList = VideoInfoList; } /** * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public String getRequestId() { return this.RequestId; } /** * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public void setRequestId(String RequestId) { this.RequestId = RequestId; } public DescribeVideoGenerationTaskResponse() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public DescribeVideoGenerationTaskResponse(DescribeVideoGenerationTaskResponse source) { if (source.GroupId != null) { this.GroupId = new String(source.GroupId); } if (source.RoomId != null) { this.RoomId = new Long(source.RoomId); } if (source.TaskId != null) { this.TaskId = new String(source.TaskId); } if (source.Progress != null) { this.Progress = new Long(source.Progress); } if (source.Status != null) { this.Status = new String(source.Status); } if (source.TotalTime != null) { this.TotalTime = new Long(source.TotalTime); } if (source.VideoInfos != null) { this.VideoInfos = new VideoInfo(source.VideoInfos); } if (source.VideoInfoList != null) { this.VideoInfoList = new VideoInfo[source.VideoInfoList.length]; for (int i = 0; i < source.VideoInfoList.length; i++) { this.VideoInfoList[i] = new VideoInfo(source.VideoInfoList[i]); } } if (source.RequestId != null) { this.RequestId = new String(source.RequestId); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "GroupId", this.GroupId); this.setParamSimple(map, prefix + "RoomId", this.RoomId); this.setParamSimple(map, prefix + "TaskId", this.TaskId); this.setParamSimple(map, prefix + "Progress", this.Progress); this.setParamSimple(map, prefix + "Status", this.Status); this.setParamSimple(map, prefix + "TotalTime", this.TotalTime); this.setParamObj(map, prefix + "VideoInfos.", this.VideoInfos); this.setParamArrayObj(map, prefix + "VideoInfoList.", this.VideoInfoList); this.setParamSimple(map, prefix + "RequestId", this.RequestId); } }
4,474
335
<reponame>draker94/vividus /* * Copyright 2019-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vividus.bdd.steps.mongodb; import static java.util.function.Function.identity; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import org.apache.commons.lang3.Validate; import org.bson.conversions.Bson; import org.jbehave.core.annotations.When; import org.vividus.bdd.context.IBddVariableContext; import org.vividus.bdd.steps.mongodb.command.CommandType; import org.vividus.bdd.steps.mongodb.command.MongoCommand; import org.vividus.bdd.steps.mongodb.command.MongoCommandEntry; import org.vividus.bdd.variable.VariableScope; import org.vividus.util.json.JsonUtils; public class MongoDbSteps { private final Map<String, String> connections; private final JsonUtils jsonUtils; private final IBddVariableContext bddVariableContext; public MongoDbSteps(Map<String, String> connections, JsonUtils jsonUtils, IBddVariableContext bddVariableContext) { this.connections = connections; this.jsonUtils = jsonUtils; this.bddVariableContext = bddVariableContext; } /** * Actions performed in the step: * <ul> * <li>executes provided <b>command</b> against MongoDB instance by the provided <b>instanceKey</b></li> * <li>saves the command execution result into <b>variableName</b> variable in JSON format</li> * </ul> * * @param command command to perform e.g. <i>{ listCollections: 1, nameOnly: true }</i> * @param dbName database name e.g. <i>users</i> * @param instanceKey key of particular connection under <b>mongodb.connection.</b> prefix * @param scopes The set (comma separated list of scopes e.g.: STORY, NEXT_BATCHES) of variable's scope<br> * <i>Available scopes:</i> * <ul> * <li><b>STEP</b> - the variable will be available only within the step, * <li><b>SCENARIO</b> - the variable will be available only within the scenario, * <li><b>STORY</b> - the variable will be available within the whole story, * <li><b>NEXT_BATCHES</b> - the variable will be available starting from next batch * </ul> * @param variableName A name of variable to assign the values from command execution result * @see <a href="https://docs.mongodb.com/manual/reference/command/">Database commands</a> */ @When("I execute command `$command` against `$dbName` database on `$instanceKey` MongoDB instance and save result " + "to $scopes variable `$variableName`") public void executeCommand(Bson command, String dbName, String instanceKey, Set<VariableScope> scopes, String variableName) { executeInDatabase(instanceKey, dbName, db -> db.runCommand(command).entrySet().stream() .peek(e -> e.setValue(jsonUtils.toJson(e.getValue()))) .collect(Collectors.collectingAndThen(Collectors.toMap(Entry::getKey, Entry::getValue), putVariable(scopes, variableName)))); } /** * Actions performed in the step: * <ul> * <li>verifies the sequence of provided <b>commands</b> (see rules below)</li> * <li>executes provided <b>commands</b> against MongoDB instance by the provided <b>instanceKey</b></li> * <li>saves the commands execution result into <b>variableName</b> variable in JSON format</li> * </ul> * Commands * <table border="1"> * <caption>A table of commands</caption> * <tr> * <th>Name</th> * <th>Type</th> * <th>Description</th> * <th>Example</th> * </tr> * <tr> * <td>find</td> * <td>source</td> * <td>selects documents in a collection, takes JSON as an argument</td> * <td>{ age: { $gte: 20 }, city: "minsk" }</td> * </tr> * <tr> * <td>projection</td> * <td>intermediate</td> * <td>determine which fields to include in the returned documents, takes JSON as an argument</td> * <td>{ age: 1, city: 1, name: 0 }</td> * </tr> * <tr> * <td>count</td> * <td>terminal</td> * <td>counts the number of documents in a collection, takes no arguments</td> * <td></td> * </tr> * <tr> * <td>collect</td> * <td>terminal</td> * <td>collects previously found documents into JSON format, takes no arguments</td> * <td></td> * </tr> * </table> * Command sequence rules * <ul> * <li>commands sequence must start with one of the <b>source</b> operations</li> * <li>commands sequence is allowed to have only <b>intermediate</b> operations between the first and last * commands</li> * <li>commands sequence must end with one of the <b>terminal</b> operations</li> * </ul> * @param commands sequence of commands to execute * @param collectionName collection name to retrieve documents from e.g. <i>phone_book</i> * @param dbName database name e.g. <i>users</i> * @param instanceKey key of particular connection under <b>mongodb.connection.</b> prefix * @param scopes The set (comma separated list of scopes e.g.: STORY, NEXT_BATCHES) of variable's scope<br> * <i>Available scopes:</i> * <ul> * <li><b>STEP</b> - the variable will be available only within the step, * <li><b>SCENARIO</b> - the variable will be available only within the scenario, * <li><b>STORY</b> - the variable will be available within the whole story, * <li><b>NEXT_BATCHES</b> - the variable will be available starting from next batch * </ul> * @param variableName A name of variable to assign the values from command execution result */ @When("I execute commands $commands in `$collectionName` collection against `$dbName` database on `$instanceKey` " + "MongoDB instance and save result to $scopes variable `$variableName`") public void executeCommands(List<MongoCommandEntry> commands, String collectionName, String dbName, String instanceKey, Set<VariableScope> scopes, String variableName) { verify(commands); executeInDatabase(instanceKey, dbName, db -> commands.stream() .reduce(identity(), (f, c) -> c.getCommand().apply(f, c.getArgument()), (l, r) -> l) .andThen(jsonUtils::toJson) .andThen(putVariable(scopes, variableName)) .apply(db.getCollection(collectionName))); } private <T> UnaryOperator<T> putVariable(Set<VariableScope> scopes, String variableName) { return r -> { bddVariableContext.putVariable(scopes, variableName, r); return r; }; } private static void verify(List<MongoCommandEntry> commands) { Validate.notEmpty(commands, "Command sequence must not be empty"); List<String> errors = new ArrayList<>(); boolean checkStart = !commands.get(0).getCommand().getCommandType().equals(CommandType.SOURCE); appendIf(checkStart, () -> "Command sequence must start with one of the source commands: " + MongoCommand.findByCommandType(CommandType.SOURCE), errors); boolean checkEnd = !commands.get(commands.size() - 1).getCommand().getCommandType() .equals(CommandType.TERMINAL); appendIf(checkEnd, () -> "Command sequence must end with one of the terminal commands: " + MongoCommand.findByCommandType(CommandType.TERMINAL), errors); boolean checkIntermediate = commands.size() > 2 && !commands.subList(1, commands.size() - 1).stream() .map(MongoCommandEntry::getCommand) .map(MongoCommand::getCommandType) .allMatch(CommandType.INTERMEDIATE::equals); appendIf(checkIntermediate, () -> "Only the following commands are allowed between the first and the last ones: " + MongoCommand.findByCommandType(CommandType.INTERMEDIATE), errors); Validate.isTrue(errors.isEmpty(), "%n%s", errors.stream().map(e -> " - " + e).collect(Collectors.joining(System.lineSeparator()))); } private static void appendIf(boolean condition, Supplier<String> error, List<String> errors) { if (condition) { errors.add(error.get()); } } private void executeInDatabase(String connectionKey, String dbKey, Consumer<MongoDatabase> databaseConsumer) { String connection = connections.get(connectionKey); Validate.validState(connection != null, "Connection with key '%s' does not exist", connectionKey); try (MongoClient client = MongoClients.create(connection)) { MongoDatabase database = client.getDatabase(dbKey); databaseConsumer.accept(database); } } }
3,680
348
{"nom":"Forcelles-sous-Gugney","dpt":"Meurthe-et-Moselle","inscrits":87,"abs":14,"votants":73,"blancs":16,"nuls":4,"exp":53,"res":[{"panneau":"2","voix":33},{"panneau":"1","voix":20}]}
82
2,674
<gh_stars>1000+ # Copyright (c) 2019 Microsoft Corporation # Distributed under the MIT software license import sys from interpret.ext.extension_utils import load_class_extensions from interpret.ext.extension import PROVIDER_EXTENSION_KEY, _is_valid_provider load_class_extensions(sys.modules[__name__], PROVIDER_EXTENSION_KEY, _is_valid_provider)
106
1,540
<filename>testng-core-api/src/main/java/org/testng/internal/annotations/DisabledRetryAnalyzer.java package org.testng.internal.annotations; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.annotations.Test; /** * A No operation retry analyzer that exists just to let us use proper types in @{@link * Test#retryAnalyzer()} */ public class DisabledRetryAnalyzer implements IRetryAnalyzer { @Override public boolean retry(ITestResult result) { return false; } }
165
2,603
<filename>FreeRTOS/Demo/CORTEX_A5_SAMA5D3x_Xplained_IAR/AtmelFiles/libchip_sama5d3x/include/instance/instance_can1.h /* ---------------------------------------------------------------------------- * SAM Software Package License * ---------------------------------------------------------------------------- * Copyright (c) 2012, Atmel Corporation * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following condition is met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the disclaimer below. * * Atmel's name may not be used to endorse or promote products derived from * this software without specific prior written permission. * * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ---------------------------------------------------------------------------- */ #ifndef _SAMA5_CAN1_INSTANCE_ #define _SAMA5_CAN1_INSTANCE_ /* ========== Register definition for CAN1 peripheral ========== */ #if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) #define REG_CAN1_MR (0xF8010000U) /**< \brief (CAN1) Mode Register */ #define REG_CAN1_IER (0xF8010004U) /**< \brief (CAN1) Interrupt Enable Register */ #define REG_CAN1_IDR (0xF8010008U) /**< \brief (CAN1) Interrupt Disable Register */ #define REG_CAN1_IMR (0xF801000CU) /**< \brief (CAN1) Interrupt Mask Register */ #define REG_CAN1_SR (0xF8010010U) /**< \brief (CAN1) Status Register */ #define REG_CAN1_BR (0xF8010014U) /**< \brief (CAN1) Baudrate Register */ #define REG_CAN1_TIM (0xF8010018U) /**< \brief (CAN1) Timer Register */ #define REG_CAN1_TIMESTP (0xF801001CU) /**< \brief (CAN1) Timestamp Register */ #define REG_CAN1_ECR (0xF8010020U) /**< \brief (CAN1) Error Counter Register */ #define REG_CAN1_TCR (0xF8010024U) /**< \brief (CAN1) Transfer Command Register */ #define REG_CAN1_ACR (0xF8010028U) /**< \brief (CAN1) Abort Command Register */ #define REG_CAN1_WPMR (0xF80100E4U) /**< \brief (CAN1) Write Protect Mode Register */ #define REG_CAN1_WPSR (0xF80100E8U) /**< \brief (CAN1) Write Protect Status Register */ #define REG_CAN1_MMR0 (0xF8010200U) /**< \brief (CAN1) Mailbox Mode Register (MB = 0) */ #define REG_CAN1_MAM0 (0xF8010204U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 0) */ #define REG_CAN1_MID0 (0xF8010208U) /**< \brief (CAN1) Mailbox ID Register (MB = 0) */ #define REG_CAN1_MFID0 (0xF801020CU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 0) */ #define REG_CAN1_MSR0 (0xF8010210U) /**< \brief (CAN1) Mailbox Status Register (MB = 0) */ #define REG_CAN1_MDL0 (0xF8010214U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 0) */ #define REG_CAN1_MDH0 (0xF8010218U) /**< \brief (CAN1) Mailbox Data High Register (MB = 0) */ #define REG_CAN1_MCR0 (0xF801021CU) /**< \brief (CAN1) Mailbox Control Register (MB = 0) */ #define REG_CAN1_MMR1 (0xF8010220U) /**< \brief (CAN1) Mailbox Mode Register (MB = 1) */ #define REG_CAN1_MAM1 (0xF8010224U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 1) */ #define REG_CAN1_MID1 (0xF8010228U) /**< \brief (CAN1) Mailbox ID Register (MB = 1) */ #define REG_CAN1_MFID1 (0xF801022CU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 1) */ #define REG_CAN1_MSR1 (0xF8010230U) /**< \brief (CAN1) Mailbox Status Register (MB = 1) */ #define REG_CAN1_MDL1 (0xF8010234U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 1) */ #define REG_CAN1_MDH1 (0xF8010238U) /**< \brief (CAN1) Mailbox Data High Register (MB = 1) */ #define REG_CAN1_MCR1 (0xF801023CU) /**< \brief (CAN1) Mailbox Control Register (MB = 1) */ #define REG_CAN1_MMR2 (0xF8010240U) /**< \brief (CAN1) Mailbox Mode Register (MB = 2) */ #define REG_CAN1_MAM2 (0xF8010244U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 2) */ #define REG_CAN1_MID2 (0xF8010248U) /**< \brief (CAN1) Mailbox ID Register (MB = 2) */ #define REG_CAN1_MFID2 (0xF801024CU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 2) */ #define REG_CAN1_MSR2 (0xF8010250U) /**< \brief (CAN1) Mailbox Status Register (MB = 2) */ #define REG_CAN1_MDL2 (0xF8010254U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 2) */ #define REG_CAN1_MDH2 (0xF8010258U) /**< \brief (CAN1) Mailbox Data High Register (MB = 2) */ #define REG_CAN1_MCR2 (0xF801025CU) /**< \brief (CAN1) Mailbox Control Register (MB = 2) */ #define REG_CAN1_MMR3 (0xF8010260U) /**< \brief (CAN1) Mailbox Mode Register (MB = 3) */ #define REG_CAN1_MAM3 (0xF8010264U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 3) */ #define REG_CAN1_MID3 (0xF8010268U) /**< \brief (CAN1) Mailbox ID Register (MB = 3) */ #define REG_CAN1_MFID3 (0xF801026CU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 3) */ #define REG_CAN1_MSR3 (0xF8010270U) /**< \brief (CAN1) Mailbox Status Register (MB = 3) */ #define REG_CAN1_MDL3 (0xF8010274U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 3) */ #define REG_CAN1_MDH3 (0xF8010278U) /**< \brief (CAN1) Mailbox Data High Register (MB = 3) */ #define REG_CAN1_MCR3 (0xF801027CU) /**< \brief (CAN1) Mailbox Control Register (MB = 3) */ #define REG_CAN1_MMR4 (0xF8010280U) /**< \brief (CAN1) Mailbox Mode Register (MB = 4) */ #define REG_CAN1_MAM4 (0xF8010284U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 4) */ #define REG_CAN1_MID4 (0xF8010288U) /**< \brief (CAN1) Mailbox ID Register (MB = 4) */ #define REG_CAN1_MFID4 (0xF801028CU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 4) */ #define REG_CAN1_MSR4 (0xF8010290U) /**< \brief (CAN1) Mailbox Status Register (MB = 4) */ #define REG_CAN1_MDL4 (0xF8010294U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 4) */ #define REG_CAN1_MDH4 (0xF8010298U) /**< \brief (CAN1) Mailbox Data High Register (MB = 4) */ #define REG_CAN1_MCR4 (0xF801029CU) /**< \brief (CAN1) Mailbox Control Register (MB = 4) */ #define REG_CAN1_MMR5 (0xF80102A0U) /**< \brief (CAN1) Mailbox Mode Register (MB = 5) */ #define REG_CAN1_MAM5 (0xF80102A4U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 5) */ #define REG_CAN1_MID5 (0xF80102A8U) /**< \brief (CAN1) Mailbox ID Register (MB = 5) */ #define REG_CAN1_MFID5 (0xF80102ACU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 5) */ #define REG_CAN1_MSR5 (0xF80102B0U) /**< \brief (CAN1) Mailbox Status Register (MB = 5) */ #define REG_CAN1_MDL5 (0xF80102B4U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 5) */ #define REG_CAN1_MDH5 (0xF80102B8U) /**< \brief (CAN1) Mailbox Data High Register (MB = 5) */ #define REG_CAN1_MCR5 (0xF80102BCU) /**< \brief (CAN1) Mailbox Control Register (MB = 5) */ #define REG_CAN1_MMR6 (0xF80102C0U) /**< \brief (CAN1) Mailbox Mode Register (MB = 6) */ #define REG_CAN1_MAM6 (0xF80102C4U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 6) */ #define REG_CAN1_MID6 (0xF80102C8U) /**< \brief (CAN1) Mailbox ID Register (MB = 6) */ #define REG_CAN1_MFID6 (0xF80102CCU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 6) */ #define REG_CAN1_MSR6 (0xF80102D0U) /**< \brief (CAN1) Mailbox Status Register (MB = 6) */ #define REG_CAN1_MDL6 (0xF80102D4U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 6) */ #define REG_CAN1_MDH6 (0xF80102D8U) /**< \brief (CAN1) Mailbox Data High Register (MB = 6) */ #define REG_CAN1_MCR6 (0xF80102DCU) /**< \brief (CAN1) Mailbox Control Register (MB = 6) */ #define REG_CAN1_MMR7 (0xF80102E0U) /**< \brief (CAN1) Mailbox Mode Register (MB = 7) */ #define REG_CAN1_MAM7 (0xF80102E4U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 7) */ #define REG_CAN1_MID7 (0xF80102E8U) /**< \brief (CAN1) Mailbox ID Register (MB = 7) */ #define REG_CAN1_MFID7 (0xF80102ECU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 7) */ #define REG_CAN1_MSR7 (0xF80102F0U) /**< \brief (CAN1) Mailbox Status Register (MB = 7) */ #define REG_CAN1_MDL7 (0xF80102F4U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 7) */ #define REG_CAN1_MDH7 (0xF80102F8U) /**< \brief (CAN1) Mailbox Data High Register (MB = 7) */ #define REG_CAN1_MCR7 (0xF80102FCU) /**< \brief (CAN1) Mailbox Control Register (MB = 7) */ #else #define REG_CAN1_MR (*(RwReg*)0xF8010000U) /**< \brief (CAN1) Mode Register */ #define REG_CAN1_IER (*(WoReg*)0xF8010004U) /**< \brief (CAN1) Interrupt Enable Register */ #define REG_CAN1_IDR (*(WoReg*)0xF8010008U) /**< \brief (CAN1) Interrupt Disable Register */ #define REG_CAN1_IMR (*(RoReg*)0xF801000CU) /**< \brief (CAN1) Interrupt Mask Register */ #define REG_CAN1_SR (*(RoReg*)0xF8010010U) /**< \brief (CAN1) Status Register */ #define REG_CAN1_BR (*(RwReg*)0xF8010014U) /**< \brief (CAN1) Baudrate Register */ #define REG_CAN1_TIM (*(RoReg*)0xF8010018U) /**< \brief (CAN1) Timer Register */ #define REG_CAN1_TIMESTP (*(RoReg*)0xF801001CU) /**< \brief (CAN1) Timestamp Register */ #define REG_CAN1_ECR (*(RoReg*)0xF8010020U) /**< \brief (CAN1) Error Counter Register */ #define REG_CAN1_TCR (*(WoReg*)0xF8010024U) /**< \brief (CAN1) Transfer Command Register */ #define REG_CAN1_ACR (*(WoReg*)0xF8010028U) /**< \brief (CAN1) Abort Command Register */ #define REG_CAN1_WPMR (*(RwReg*)0xF80100E4U) /**< \brief (CAN1) Write Protect Mode Register */ #define REG_CAN1_WPSR (*(RoReg*)0xF80100E8U) /**< \brief (CAN1) Write Protect Status Register */ #define REG_CAN1_MMR0 (*(RwReg*)0xF8010200U) /**< \brief (CAN1) Mailbox Mode Register (MB = 0) */ #define REG_CAN1_MAM0 (*(RwReg*)0xF8010204U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 0) */ #define REG_CAN1_MID0 (*(RwReg*)0xF8010208U) /**< \brief (CAN1) Mailbox ID Register (MB = 0) */ #define REG_CAN1_MFID0 (*(RoReg*)0xF801020CU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 0) */ #define REG_CAN1_MSR0 (*(RoReg*)0xF8010210U) /**< \brief (CAN1) Mailbox Status Register (MB = 0) */ #define REG_CAN1_MDL0 (*(RwReg*)0xF8010214U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 0) */ #define REG_CAN1_MDH0 (*(RwReg*)0xF8010218U) /**< \brief (CAN1) Mailbox Data High Register (MB = 0) */ #define REG_CAN1_MCR0 (*(WoReg*)0xF801021CU) /**< \brief (CAN1) Mailbox Control Register (MB = 0) */ #define REG_CAN1_MMR1 (*(RwReg*)0xF8010220U) /**< \brief (CAN1) Mailbox Mode Register (MB = 1) */ #define REG_CAN1_MAM1 (*(RwReg*)0xF8010224U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 1) */ #define REG_CAN1_MID1 (*(RwReg*)0xF8010228U) /**< \brief (CAN1) Mailbox ID Register (MB = 1) */ #define REG_CAN1_MFID1 (*(RoReg*)0xF801022CU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 1) */ #define REG_CAN1_MSR1 (*(RoReg*)0xF8010230U) /**< \brief (CAN1) Mailbox Status Register (MB = 1) */ #define REG_CAN1_MDL1 (*(RwReg*)0xF8010234U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 1) */ #define REG_CAN1_MDH1 (*(RwReg*)0xF8010238U) /**< \brief (CAN1) Mailbox Data High Register (MB = 1) */ #define REG_CAN1_MCR1 (*(WoReg*)0xF801023CU) /**< \brief (CAN1) Mailbox Control Register (MB = 1) */ #define REG_CAN1_MMR2 (*(RwReg*)0xF8010240U) /**< \brief (CAN1) Mailbox Mode Register (MB = 2) */ #define REG_CAN1_MAM2 (*(RwReg*)0xF8010244U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 2) */ #define REG_CAN1_MID2 (*(RwReg*)0xF8010248U) /**< \brief (CAN1) Mailbox ID Register (MB = 2) */ #define REG_CAN1_MFID2 (*(RoReg*)0xF801024CU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 2) */ #define REG_CAN1_MSR2 (*(RoReg*)0xF8010250U) /**< \brief (CAN1) Mailbox Status Register (MB = 2) */ #define REG_CAN1_MDL2 (*(RwReg*)0xF8010254U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 2) */ #define REG_CAN1_MDH2 (*(RwReg*)0xF8010258U) /**< \brief (CAN1) Mailbox Data High Register (MB = 2) */ #define REG_CAN1_MCR2 (*(WoReg*)0xF801025CU) /**< \brief (CAN1) Mailbox Control Register (MB = 2) */ #define REG_CAN1_MMR3 (*(RwReg*)0xF8010260U) /**< \brief (CAN1) Mailbox Mode Register (MB = 3) */ #define REG_CAN1_MAM3 (*(RwReg*)0xF8010264U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 3) */ #define REG_CAN1_MID3 (*(RwReg*)0xF8010268U) /**< \brief (CAN1) Mailbox ID Register (MB = 3) */ #define REG_CAN1_MFID3 (*(RoReg*)0xF801026CU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 3) */ #define REG_CAN1_MSR3 (*(RoReg*)0xF8010270U) /**< \brief (CAN1) Mailbox Status Register (MB = 3) */ #define REG_CAN1_MDL3 (*(RwReg*)0xF8010274U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 3) */ #define REG_CAN1_MDH3 (*(RwReg*)0xF8010278U) /**< \brief (CAN1) Mailbox Data High Register (MB = 3) */ #define REG_CAN1_MCR3 (*(WoReg*)0xF801027CU) /**< \brief (CAN1) Mailbox Control Register (MB = 3) */ #define REG_CAN1_MMR4 (*(RwReg*)0xF8010280U) /**< \brief (CAN1) Mailbox Mode Register (MB = 4) */ #define REG_CAN1_MAM4 (*(RwReg*)0xF8010284U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 4) */ #define REG_CAN1_MID4 (*(RwReg*)0xF8010288U) /**< \brief (CAN1) Mailbox ID Register (MB = 4) */ #define REG_CAN1_MFID4 (*(RoReg*)0xF801028CU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 4) */ #define REG_CAN1_MSR4 (*(RoReg*)0xF8010290U) /**< \brief (CAN1) Mailbox Status Register (MB = 4) */ #define REG_CAN1_MDL4 (*(RwReg*)0xF8010294U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 4) */ #define REG_CAN1_MDH4 (*(RwReg*)0xF8010298U) /**< \brief (CAN1) Mailbox Data High Register (MB = 4) */ #define REG_CAN1_MCR4 (*(WoReg*)0xF801029CU) /**< \brief (CAN1) Mailbox Control Register (MB = 4) */ #define REG_CAN1_MMR5 (*(RwReg*)0xF80102A0U) /**< \brief (CAN1) Mailbox Mode Register (MB = 5) */ #define REG_CAN1_MAM5 (*(RwReg*)0xF80102A4U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 5) */ #define REG_CAN1_MID5 (*(RwReg*)0xF80102A8U) /**< \brief (CAN1) Mailbox ID Register (MB = 5) */ #define REG_CAN1_MFID5 (*(RoReg*)0xF80102ACU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 5) */ #define REG_CAN1_MSR5 (*(RoReg*)0xF80102B0U) /**< \brief (CAN1) Mailbox Status Register (MB = 5) */ #define REG_CAN1_MDL5 (*(RwReg*)0xF80102B4U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 5) */ #define REG_CAN1_MDH5 (*(RwReg*)0xF80102B8U) /**< \brief (CAN1) Mailbox Data High Register (MB = 5) */ #define REG_CAN1_MCR5 (*(WoReg*)0xF80102BCU) /**< \brief (CAN1) Mailbox Control Register (MB = 5) */ #define REG_CAN1_MMR6 (*(RwReg*)0xF80102C0U) /**< \brief (CAN1) Mailbox Mode Register (MB = 6) */ #define REG_CAN1_MAM6 (*(RwReg*)0xF80102C4U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 6) */ #define REG_CAN1_MID6 (*(RwReg*)0xF80102C8U) /**< \brief (CAN1) Mailbox ID Register (MB = 6) */ #define REG_CAN1_MFID6 (*(RoReg*)0xF80102CCU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 6) */ #define REG_CAN1_MSR6 (*(RoReg*)0xF80102D0U) /**< \brief (CAN1) Mailbox Status Register (MB = 6) */ #define REG_CAN1_MDL6 (*(RwReg*)0xF80102D4U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 6) */ #define REG_CAN1_MDH6 (*(RwReg*)0xF80102D8U) /**< \brief (CAN1) Mailbox Data High Register (MB = 6) */ #define REG_CAN1_MCR6 (*(WoReg*)0xF80102DCU) /**< \brief (CAN1) Mailbox Control Register (MB = 6) */ #define REG_CAN1_MMR7 (*(RwReg*)0xF80102E0U) /**< \brief (CAN1) Mailbox Mode Register (MB = 7) */ #define REG_CAN1_MAM7 (*(RwReg*)0xF80102E4U) /**< \brief (CAN1) Mailbox Acceptance Mask Register (MB = 7) */ #define REG_CAN1_MID7 (*(RwReg*)0xF80102E8U) /**< \brief (CAN1) Mailbox ID Register (MB = 7) */ #define REG_CAN1_MFID7 (*(RoReg*)0xF80102ECU) /**< \brief (CAN1) Mailbox Family ID Register (MB = 7) */ #define REG_CAN1_MSR7 (*(RoReg*)0xF80102F0U) /**< \brief (CAN1) Mailbox Status Register (MB = 7) */ #define REG_CAN1_MDL7 (*(RwReg*)0xF80102F4U) /**< \brief (CAN1) Mailbox Data Low Register (MB = 7) */ #define REG_CAN1_MDH7 (*(RwReg*)0xF80102F8U) /**< \brief (CAN1) Mailbox Data High Register (MB = 7) */ #define REG_CAN1_MCR7 (*(WoReg*)0xF80102FCU) /**< \brief (CAN1) Mailbox Control Register (MB = 7) */ #endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ #endif /* _SAMA5_CAN1_INSTANCE_ */
8,209
4,388
<reponame>automaton123456/nanodet<gh_stars>1000+ import pytest import torch from nanodet.model.fpn.tan import TAN def test_tan(): """Tests TAN.""" s = 64 in_channels = [8, 16, 32] feat_sizes = [s // 2 ** i for i in range(3)] # [64, 32, 16] out_channels = 8 with pytest.raises(AssertionError): TAN( in_channels=[8, 16, 32, 64], out_channels=[8, 16, 32, 64], feature_hw=[32, 32], num_heads=4, num_encoders=1, mlp_ratio=2, dropout_ratio=0.9, ) pan_model = TAN( in_channels=in_channels, out_channels=out_channels, feature_hw=[32, 32], num_heads=4, num_encoders=1, mlp_ratio=2, dropout_ratio=0.9, ) # TAN expects a multiple levels of features per image feats = [ torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) for i in range(len(in_channels)) ] outs = pan_model(feats) assert len(outs) == 3 for i in range(3): assert outs[i].shape[1] == out_channels assert outs[i].shape[2] == outs[i].shape[3] == s // (2 ** i)
618
1,040
// ============================================================== // XRSoundEngine class that is bound to an Orbiter module (i.e., to a unique ID); this file is not distributed with XRSound. // The code for this exists in XRSound.dll. // // Copyright (c) 2018-2021 <NAME> // Licensed under the MIT License // ============================================================== #pragma once #include "XRSoundEngine.h" class ModuleXRSoundEngine : public XRSoundEngine { public: static ModuleXRSoundEngine *CreateInstance(const char *pUniqueModuleName); const CString &GetModuleName() const { return m_csModuleName; } virtual EngineType GetEngineType() override { return EngineType::Module; } virtual const char *GetLogID() override { return GetModuleName(); } virtual bool SetDefaultSoundEnabled(const XRSound::DefaultSoundID soundID, const bool bEnabled) override; virtual bool GetDefaultSoundEnabled(const XRSound::DefaultSoundID soundID) override; virtual bool SetDefaultSoundGroupFolder(const XRSound::DefaultSoundID groupSoundID, const char *pSubfolderPath) override; virtual const char *GetDefaultSoundGroupFolder(const XRSound::DefaultSoundID groupSoundID) const override; protected: CString m_csModuleName; // unique module ID virtual void FreeResources() override; virtual void UpdateSoundState(WavContext &context) override; private: // these are private to prevent incorrect creation or deletion outside of our static CreateInstance and DestroyInstance methods ModuleXRSoundEngine(const char *pUniqueModuleName); virtual ~ModuleXRSoundEngine() override; };
435
5,964
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FilterDisplayItem_h #define FilterDisplayItem_h #include "platform/geometry/FloatRect.h" #include "platform/graphics/paint/DisplayItem.h" #include "public/platform/WebFilterOperations.h" #include "wtf/PassOwnPtr.h" #include "wtf/PassRefPtr.h" #ifndef NDEBUG #include "wtf/text/WTFString.h" #endif namespace blink { class PLATFORM_EXPORT BeginFilterDisplayItem : public PairedBeginDisplayItem { public: BeginFilterDisplayItem(const DisplayItemClientWrapper& client, PassRefPtr<SkImageFilter> imageFilter, const FloatRect& bounds, PassOwnPtr<WebFilterOperations> filterOperations = nullptr) : PairedBeginDisplayItem(client, BeginFilter) , m_imageFilter(imageFilter) , m_webFilterOperations(filterOperations) , m_bounds(bounds) { } void replay(GraphicsContext&) override; void appendToWebDisplayItemList(WebDisplayItemList*) const override; bool drawsContent() const override; private: #ifndef NDEBUG void dumpPropertiesAsDebugString(WTF::StringBuilder&) const override; #endif // FIXME: m_imageFilter should be replaced with m_webFilterOperations when copying data to the compositor. RefPtr<SkImageFilter> m_imageFilter; OwnPtr<WebFilterOperations> m_webFilterOperations; const FloatRect m_bounds; }; class PLATFORM_EXPORT EndFilterDisplayItem : public PairedEndDisplayItem { public: EndFilterDisplayItem(const DisplayItemClientWrapper& client) : PairedEndDisplayItem(client, EndFilter) { } void replay(GraphicsContext&) override; void appendToWebDisplayItemList(WebDisplayItemList*) const override; private: #if ENABLE(ASSERT) bool isEndAndPairedWith(DisplayItem::Type otherType) const final { return otherType == BeginFilter; } #endif }; } #endif // FilterDisplayItem_h
633
4,566
<gh_stars>1000+ # -*- coding: utf-8 -*- import sublime import sublime_plugin import functools NO_SELECTION = -1 PREFERENCES = 'Preferences.sublime-settings' THEMES = [ 'ayu-light', 'ayu-mirage', 'ayu-dark' ] def get_color_scheme(): return sublime.load_settings(PREFERENCES).get('color_scheme', '') def set_color_scheme(path): return sublime.load_settings(PREFERENCES).set('color_scheme', path) def preview_color_scheme(path): set_color_scheme(path) def activate_color_scheme(path): set_color_scheme(path) commit() def revert_color_scheme(path): set_color_scheme(path) def get_ui_theme(): return sublime.load_settings(PREFERENCES).get('theme', '') def set_ui_theme(path): return sublime.load_settings(PREFERENCES).set('theme', path) def preview_ui_theme(path): set_ui_theme(path) def activate_ui_theme(path): set_ui_theme(path) commit() def revert_ui_theme(path): set_ui_theme(path) def commit(): return sublime.save_settings(PREFERENCES) class AyuActivateCommand(sublime_plugin.WindowCommand): def display_list(self, themes): self.themes = themes self.initial_color_scheme = get_color_scheme() self.initial_ui_theme = get_ui_theme() quick_list = [theme.replace("-", " ") for theme in self.themes] self.quick_list = quick_list self.window.show_quick_panel(quick_list, self.on_done, on_highlight=self.on_highlighted) def on_highlighted(self, index): preview_color_scheme(self._quick_list_to_scheme(index)) preview_ui_theme(self._quick_list_to_theme(index)) def on_done(self, index): if index is NO_SELECTION: revert_color_scheme(self.initial_color_scheme) revert_ui_theme(self.initial_ui_theme) return color_scheme = self._quick_list_to_scheme(index) activate_color_scheme(color_scheme) ui_theme = self._quick_list_to_theme(index) activate_ui_theme(ui_theme) def _quick_list_to_scheme(self, index): return 'Packages/ayu/%s.sublime-color-scheme' % THEMES[index] def _quick_list_to_theme(self, index): return '%s.sublime-theme' % THEMES[index] def run(self): self.display_list(THEMES)
832
2,279
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import division import copy import tensorflow as tf from functools import wraps from zhusuan.framework.utils import Context __all__ = [ 'MetaBayesianNet', 'meta_bayesian_net', ] class Local(Context): def __getattr__(self, item): return self.__dict__.get(item, None) def __setattr__(self, key, value): self.__dict__[key] = value class MetaBayesianNet(object): """ A lazy-constructed :class:`~zhusuan.framework.bn.BayesianNet`. Conceptually it's better to view :class:`MetaBayesianNet` rather than :class:`~zhusuan.framework.bn.BayesianNet` as the model because it can accept different observations through the :meth:`observe` method. The suggested usage is through the :func:`meta_bayesian_net` decorator. .. seealso:: For more information, please refer to :doc:`/tutorials/concepts`. :param f: A function that constructs and returns a :class:`~zhusuan.framework.bn.BayesianNet`. :param args: A list. Ordered arguments that will be passed into `f`. :param kwargs: A dictionary. Named arguments that will be passed into `f`. :param scope: A string. The scope name passed to tensorflow `variable_scope() <https://www.tensorflow.org/api_docs/python/tf/variable_scope>`_. :param reuse_variables: A bool. Whether to reuse tensorflow `Variables <https://www.tensorflow.org/api_docs/python/tf/Variable>`_ in repeated calls of :meth:`observe`. """ def __init__(self, f, args=None, kwargs=None, scope=None, reuse_variables=False): if (scope is not None) and reuse_variables: self._f = tf.make_template(scope, f) elif reuse_variables: raise ValueError("Cannot reuse tensorflow Variables when `scope` " "is not provided.") else: self._f = f self._args = copy.copy(args) self._kwargs = copy.copy(kwargs) self._scope = scope self._reuse_variables = reuse_variables self._log_joint = None @property def log_joint(self): """ The log joint function of this model. Can be overwritten as:: meta_bn = build_model(...) def log_joint(bn): return ... meta_bn.log_joint = log_joint """ return self._log_joint @log_joint.setter def log_joint(self, value): self._log_joint = value def _run_with_observations(self, func, observations): with Local() as local_cxt: local_cxt.observations = observations local_cxt.meta_bn = self return func(*self._args, **self._kwargs) def observe(self, **kwargs): """ Construct a :class:`~zhusuan.framework.bn.BayesianNet` given observations. :param kwargs: A dictionary that maps from node names to their observed values. :return: A :class:`~zhusuan.framework.bn.BayesianNet` instance. """ if (self._scope is not None) and (not self._reuse_variables): with tf.variable_scope(self._scope): return self._run_with_observations(self._f, kwargs) else: return self._run_with_observations(self._f, kwargs) def meta_bayesian_net(scope=None, reuse_variables=False): """ Transform a function that builds a :class:`~zhusuan.framework.bn.BayesianNet` into returning :class:`~zhusuan.framework.meta_bn.MetaBayesianNet`. The suggested usage is as a decorator:: @meta_bayesian_net(scope=..., reuse_variables=True) def build_model(...): bn = zs.BayesianNet() ... return bn The decorated function will return a :class:`MetaBayesianNet` instance instead of a :class:`BayesianNet` instance. .. seealso:: For more details and examples, please refer to :doc:`/tutorials/concepts`. :param scope: A string. The scope name passed to tensorflow `variable_scope() <https://www.tensorflow.org/api_docs/python/tf/variable_scope>`_. :param reuse_variables: A bool. Whether to reuse tensorflow `Variables <https://www.tensorflow.org/api_docs/python/tf/Variable>`_ in repeated calls of :meth:`MetaBayesianNet.observe`. :return: The transformed function. """ def wrapper(f): @wraps(f) def _wrapped(*args, **kwargs): meta_bn = MetaBayesianNet( f, args=args, kwargs=kwargs, scope=scope, reuse_variables=reuse_variables) return meta_bn return _wrapped return wrapper
2,033
3,986
/* * Copyright (C) 2019 xuexiangjys(<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.xuexiang.xuidemo.fragment.expands; import android.view.View; import com.xuexiang.xpage.annotation.Page; import com.xuexiang.xpage.core.PageOption; import com.xuexiang.xui.widget.actionbar.TitleBar; import com.xuexiang.xuidemo.R; import com.xuexiang.xuidemo.base.BaseSimpleListFragment; import com.xuexiang.xuidemo.fragment.expands.iconfont.SimpleIconFontFragment; import com.xuexiang.xuidemo.fragment.expands.iconfont.XUIIconFontDisplayFragment; import com.xuexiang.xuidemo.utils.Utils; import com.xuexiang.xuidemo.widget.iconfont.IconFontActivity; import java.util.List; /** * @author xuexiang * @since 2019-10-13 16:59 */ @Page(name = "字体图标库", extra = R.drawable.ic_expand_iconfont) public class IconFontFragment extends BaseSimpleListFragment { @Override protected List<String> initSimpleData(List<String> lists) { lists.add("字体图标库的用法展示"); lists.add("自定义字体图标库XUIIconFont展示"); return lists; } @Override protected void onItemClick(int position) { switch(position) { case 0: PageOption.to(SimpleIconFontFragment.class) .setNewActivity(true, IconFontActivity.class) .open(this); break; case 1: openPage(XUIIconFontDisplayFragment.class); break; default: break; } } @Override protected TitleBar initTitle() { TitleBar titleBar = super.initTitle(); titleBar.addAction(new TitleBar.TextAction("图标库") { @Override public void performAction(View view) { Utils.goWeb(getContext(), "https://www.iconfont.cn/"); } }); titleBar.addAction(new TitleBar.TextAction("Github") { @Override public void performAction(View view) { Utils.goWeb(getContext(), "https://github.com/mikepenz/Android-Iconics"); } }); return titleBar; } }
1,158
2,151
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.vr_shell.util; import static org.chromium.chrome.browser.vr_shell.VrTestFramework.POLL_TIMEOUT_LONG_MS; import org.junit.Assert; import org.chromium.chrome.browser.vr_shell.TestVrShellDelegate; import org.chromium.chrome.browser.vr_shell.VrTestFramework; import org.chromium.content_public.browser.WebContents; /** * Class containing utility functions for transitioning between different * states in VR, such as fullscreen, WebVR presentation, and the VR browser. * * All the transitions in this class are performed directly through Chrome, * as opposed to NFC tag simulation which involves receiving an intent from * an outside application (VR Services). */ public class VrTransitionUtils extends TransitionUtils { /** * Sends a click event directly to the WebGL canvas then waits for WebVR to * think that it is presenting, failing if this does not occur within the * allotted time. * * @param cvc The ContentViewCore for the tab the canvas is in. */ public static void enterPresentationOrFail(WebContents webContents) { enterPresentation(webContents); Assert.assertTrue(VrTestFramework.pollJavaScriptBoolean( "vrDisplay.isPresenting", POLL_TIMEOUT_LONG_MS, webContents)); Assert.assertTrue(TestVrShellDelegate.getVrShellForTesting().getWebVrModeEnabled()); } }
483
9,778
/* * qsort_arg.c: qsort with a passthrough "void *" argument */ #include "c.h" #define ST_SORT qsort_arg #define ST_ELEMENT_TYPE_VOID #define ST_COMPARATOR_TYPE_NAME qsort_arg_comparator #define ST_COMPARE_RUNTIME_POINTER #define ST_COMPARE_ARG_TYPE void #define ST_SCOPE #define ST_DEFINE #include "lib/sort_template.h"
135
13,162
#include <eosio/chain/apply_context.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/backing_store/db_key_value_any_lookup.hpp> #include <eosio/chain/backing_store/db_key_value_format.hpp> #include <eosio/chain/backing_store/db_context.hpp> #include <eosio/chain/backing_store/chain_kv_payer.hpp> #include <eosio/chain/combined_database.hpp> namespace eosio { namespace chain { namespace backing_store { eosio::session::shared_bytes make_useless_value() { const char null = '\0'; return eosio::session::shared_bytes {&null, 1}; } const eosio::session::shared_bytes db_key_value_any_lookup::useless_value = make_useless_value(); void db_key_value_any_lookup::add_table_if_needed(const shared_bytes& key, account_name payer) { auto table_key = db_key_value_format::create_full_key_prefix(key, end_of_prefix::pre_type); auto session_iter = current_session.lower_bound(table_key); if (!match_prefix(table_key, session_iter)) { // need to add the key_type::table to the end table_key = db_key_value_format::create_table_key(table_key); const auto legacy_key = db_key_value_format::extract_legacy_key(table_key); const auto extracted_data = db_key_value_format::get_prefix_thru_key_type(legacy_key); std::string event_id; apply_context& context = parent.context; const auto& scope = std::get<0>(extracted_data); const auto& table = std::get<1>(extracted_data); auto dm_logger = context.control.get_deep_mind_logger(); if (dm_logger != nullptr) { event_id = db_context::table_event(parent.receiver, scope, table); } context.update_db_usage(payer, table_overhead, db_context::add_table_trace(context.get_action_id(), std::move(event_id))); payer_payload pp(payer, nullptr, 0); current_session.write(table_key, pp.as_payload()); if (dm_logger != nullptr) { db_context::log_insert_table(*dm_logger, context.get_action_id(), parent.receiver, scope, table, payer); } } } void db_key_value_any_lookup::remove_table_if_empty(const shared_bytes& key) { // look for any other entries in the table auto entire_table_prefix_key = db_key_value_format::create_full_key_prefix(key, end_of_prefix::pre_type); // since this prefix key is just scope and table, it will include all primary, secondary, and table keys auto session_itr = current_session.lower_bound(entire_table_prefix_key); EOS_ASSERT( session_itr != current_session.end(), db_rocksdb_invalid_operation_exception, "invariant failure in remove_table_if_empty, iter store found and removed, but no table entry was found"); auto key_value = *session_itr; EOS_ASSERT( match_prefix(entire_table_prefix_key, key_value.first), db_rocksdb_invalid_operation_exception, "invariant failure in remove_table_if_empty, iter store found and removed, but no table entry was found"); // check if the only entry for this contract/scope/table is the table entry auto legacy_key = db_key_value_format::extract_legacy_key(key_value.first); if (db_key_value_format::extract_key_type(legacy_key) != backing_store::db_key_value_format::key_type::table) { return; } const auto extracted_data = db_key_value_format::get_prefix_thru_key_type(legacy_key); const auto& scope = std::get<0>(extracted_data); const auto& table = std::get<1>(extracted_data); const name payer = payer_payload{*key_value.second}.payer; std::string event_id; apply_context& context = parent.context; auto dm_logger = context.control.get_deep_mind_logger(); if (dm_logger != nullptr) { event_id = db_context::table_event(parent.receiver, scope, table); } context.update_db_usage(payer, - table_overhead, db_context::rem_table_trace(context.get_action_id(), std::move(event_id)) ); if (dm_logger != nullptr) { db_context::log_remove_table(*dm_logger, context.get_action_id(), parent.receiver, scope, table, payer); } current_session.erase(key_value.first); } key_bundle db_key_value_any_lookup::get_slice(name code, name scope, name table) { bytes prefix_key = db_key_value_format::create_prefix_key(scope, table); return { prefix_key, code }; } key_bundle db_key_value_any_lookup::get_table_end_slice(name code, name scope, name table) { bytes table_key = db_key_value_format::create_table_key(scope, table); return { table_key, code }; } bool db_key_value_any_lookup::match_prefix(const shared_bytes& shorter, const shared_bytes& longer) { if (shorter.size() > longer.size()) { return false; } return memcmp(shorter.data(), longer.data(), shorter.size()) == 0; } bool db_key_value_any_lookup::match_prefix(const shared_bytes& shorter, const session_variant_type::iterator& iter) { if (iter == current_session.end()) { return false; } return match_prefix(shorter, (*iter).first); } bool db_key_value_any_lookup::match(const shared_bytes& lhs, const shared_bytes& rhs) { return lhs.size() == rhs.size() && memcmp(lhs.data(), rhs.data(), lhs.size()) == 0; } bool db_key_value_any_lookup::match(const shared_bytes& lhs, const session_variant_type::iterator& iter) { if (iter == current_session.end()) { return false; } return match(lhs, (*iter).first); } key_bundle::key_bundle(const b1::chain_kv::bytes& composite_key, name code) : full_key(db_key_value_format::create_full_key(composite_key, code)){ } prefix_bundle::prefix_bundle(const b1::chain_kv::bytes& composite_key, end_of_prefix prefix_end, name code) : full_key(db_key_value_format::create_full_key(composite_key, code)), prefix_key(db_key_value_format::create_full_key_prefix(full_key, prefix_end)) { } }}} // namespace eosio::chain::backing_store
2,426
577
package org.python.util.install; import java.io.File; import org.python.util.install.Installation.JavaVersionInfo; import junit.framework.TestCase; public class InstallationTest extends TestCase { public void testGetExternalJavaVersion() { JavaHomeHandler javaHomeHandler = new JavaHomeHandler(); JavaVersionInfo versionInfo = Installation.getExternalJavaVersion(javaHomeHandler); assertEquals(Installation.NORMAL_RETURN, versionInfo.getErrorCode()); assertEquals("", versionInfo.getReason()); assertTrue(versionInfo.getVersion().length() > 0); assertTrue(versionInfo.getSpecificationVersion().length() > 0); assertTrue(versionInfo.getVersion().startsWith(versionInfo.getSpecificationVersion())); assertNotNull(versionInfo.getVendor()); assertNotSame("", versionInfo.getVendor()); } public void testGetExternalJavaVersionWithError() { JavaHomeHandler javaHomeHandler = new JavaHomeHandler("non_existing/home"); JavaVersionInfo versionInfo = Installation.getExternalJavaVersion(javaHomeHandler); assertEquals(Installation.ERROR_RETURN, versionInfo.getErrorCode()); String reason = versionInfo.getReason(); assertTrue(reason.indexOf("invalid") >= 0); } public void testGetExternalJavaVersionNoBinDirectory() { File wrongHome = new File(System.getProperty("user.home")); JavaHomeHandler javaHomeHandler = new JavaHomeHandler(wrongHome.getAbsolutePath()); JavaVersionInfo versionInfo = Installation.getExternalJavaVersion(javaHomeHandler); assertEquals(Installation.ERROR_RETURN, versionInfo.getErrorCode()); String reason = versionInfo.getReason(); assertTrue(reason.indexOf("invalid") >= 0); } public void testGetExternalJavaVersionNoJavaInBinDirectory() { File wrongHome = new File(System.getProperty("user.home")); File binDir = new File(wrongHome, "bin"); assertFalse(binDir.exists()); try { assertTrue(binDir.mkdirs()); JavaHomeHandler javaHomeHandler = new JavaHomeHandler(wrongHome.getAbsolutePath()); JavaVersionInfo versionInfo = Installation.getExternalJavaVersion(javaHomeHandler); assertEquals(Installation.ERROR_RETURN, versionInfo.getErrorCode()); assertTrue(versionInfo.getReason().indexOf("invalid") >= 0); } finally { if (binDir.exists()) { binDir.delete(); } } } public void testIsValidJavaVersion() { JavaVersionInfo javaVersionInfo = new JavaVersionInfo(); javaVersionInfo.setSpecificationVersion("1.1.9"); assertFalse(Installation.isValidJava(javaVersionInfo)); javaVersionInfo.setSpecificationVersion("1.2"); assertFalse(Installation.isValidJava(javaVersionInfo)); javaVersionInfo.setSpecificationVersion("1.3"); assertFalse(Installation.isValidJava(javaVersionInfo)); javaVersionInfo.setSpecificationVersion("1.4"); assertFalse(Installation.isValidJava(javaVersionInfo)); javaVersionInfo.setSpecificationVersion("1.5"); assertTrue(Installation.isValidJava(javaVersionInfo)); javaVersionInfo.setSpecificationVersion("1.6"); assertTrue(Installation.isValidJava(javaVersionInfo)); javaVersionInfo.setSpecificationVersion("1.7"); assertTrue(Installation.isValidJava(javaVersionInfo)); } public void testGetJavaSpecificationVersion() { String specificationVersion = "1.4.2"; assertEquals(14, Installation.getJavaSpecificationVersion(specificationVersion)); specificationVersion = "1.5.0"; assertEquals(15, Installation.getJavaSpecificationVersion(specificationVersion)); specificationVersion = "1.6.0"; assertEquals(16, Installation.getJavaSpecificationVersion(specificationVersion)); } public void testIsGNUJava() { assertFalse(Installation.isGNUJava()); String originalVmName = System.getProperty(Installation.JAVA_VM_NAME); try { // fake GNU java System.setProperty(Installation.JAVA_VM_NAME, "GNU libgcj"); assertTrue(Installation.isGNUJava()); } finally { System.setProperty(Installation.JAVA_VM_NAME, originalVmName); assertFalse(Installation.isGNUJava()); } } public void testGetDefaultJavaVersion() { JavaVersionInfo info = Installation.getDefaultJavaVersion(); assertNotNull(info); assertEquals(Installation.NORMAL_RETURN, info.getErrorCode()); String specVersion = info.getSpecificationVersion(); assertNotNull(specVersion); assertTrue(specVersion.length() >= 3); } }
1,743
2,177
<reponame>denghuafeng/nutz package org.nutz.dao.test.meta.nutzcn; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.Name; import org.nutz.dao.entity.annotation.One; import org.nutz.dao.entity.annotation.Table; @Table("t_abc_user") public class AbcUser { @Id private long id; @Name private String name; private int age; @One(key="userId", field="id") private AbcPet pet; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public AbcPet getPet() { return pet; } public void setPet(AbcPet pet) { this.pet = pet; } }
433
1,244
/****************************************************************************** * * Module Name: asllisting - Listing file generation * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2014, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * *****************************************************************************/ #include "aslcompiler.h" #include "aslcompiler.y.h" #include "amlcode.h" #include "acparser.h" #include "acnamesp.h" #define _COMPONENT ACPI_COMPILER ACPI_MODULE_NAME ("asllisting") /* Local prototypes */ static void LsGenerateListing ( UINT32 FileId); static ACPI_STATUS LsAmlListingWalk ( ACPI_PARSE_OBJECT *Op, UINT32 Level, void *Context); static ACPI_STATUS LsTreeWriteWalk ( ACPI_PARSE_OBJECT *Op, UINT32 Level, void *Context); static void LsWriteNodeToListing ( ACPI_PARSE_OBJECT *Op, UINT32 FileId); static void LsFinishSourceListing ( UINT32 FileId); /******************************************************************************* * * FUNCTION: LsDoListings * * PARAMETERS: None. Examines the various output file global flags. * * RETURN: None * * DESCRIPTION: Generate all requested listing files. * ******************************************************************************/ void LsDoListings ( void) { if (Gbl_C_OutputFlag) { LsGenerateListing (ASL_FILE_C_SOURCE_OUTPUT); } if (Gbl_ListingFlag) { LsGenerateListing (ASL_FILE_LISTING_OUTPUT); } if (Gbl_AsmOutputFlag) { LsGenerateListing (ASL_FILE_ASM_SOURCE_OUTPUT); } if (Gbl_C_IncludeOutputFlag) { LsGenerateListing (ASL_FILE_C_INCLUDE_OUTPUT); } if (Gbl_AsmIncludeOutputFlag) { LsGenerateListing (ASL_FILE_ASM_INCLUDE_OUTPUT); } if (Gbl_C_OffsetTableFlag) { LsGenerateListing (ASL_FILE_C_OFFSET_OUTPUT); } } /******************************************************************************* * * FUNCTION: LsGenerateListing * * PARAMETERS: FileId - ID of listing file * * RETURN: None * * DESCRIPTION: Generate a listing file. This can be one of the several types * of "listings" supported. * ******************************************************************************/ static void LsGenerateListing ( UINT32 FileId) { /* Start at the beginning of both the source and AML files */ FlSeekFile (ASL_FILE_SOURCE_OUTPUT, 0); FlSeekFile (ASL_FILE_AML_OUTPUT, 0); Gbl_SourceLine = 0; Gbl_CurrentHexColumn = 0; LsPushNode (Gbl_Files[ASL_FILE_INPUT].Filename); if (FileId == ASL_FILE_C_OFFSET_OUTPUT) { Gbl_CurrentAmlOffset = 0; /* Offset table file has a special header and footer */ LsDoOffsetTableHeader (FileId); TrWalkParseTree (RootNode, ASL_WALK_VISIT_DOWNWARD, LsAmlOffsetWalk, NULL, (void *) ACPI_TO_POINTER (FileId)); LsDoOffsetTableFooter (FileId); return; } /* Process all parse nodes */ TrWalkParseTree (RootNode, ASL_WALK_VISIT_DOWNWARD, LsAmlListingWalk, NULL, (void *) ACPI_TO_POINTER (FileId)); /* Final processing */ LsFinishSourceListing (FileId); } /******************************************************************************* * * FUNCTION: LsAmlListingWalk * * PARAMETERS: ASL_WALK_CALLBACK * * RETURN: Status * * DESCRIPTION: Process one node during a listing file generation. * ******************************************************************************/ static ACPI_STATUS LsAmlListingWalk ( ACPI_PARSE_OBJECT *Op, UINT32 Level, void *Context) { UINT8 FileByte; UINT32 i; UINT32 FileId = (UINT32) ACPI_TO_INTEGER (Context); LsWriteNodeToListing (Op, FileId); if (Op->Asl.CompileFlags & NODE_IS_RESOURCE_DATA) { /* Buffer is a resource template, don't dump the data all at once */ return (AE_OK); } /* Write the hex bytes to the listing file(s) (if requested) */ for (i = 0; i < Op->Asl.FinalAmlLength; i++) { if (ACPI_FAILURE (FlReadFile (ASL_FILE_AML_OUTPUT, &FileByte, 1))) { FlFileError (ASL_FILE_AML_OUTPUT, ASL_MSG_READ); AslAbort (); } LsWriteListingHexBytes (&FileByte, 1, FileId); } return (AE_OK); } /******************************************************************************* * * FUNCTION: LsDumpParseTree, LsTreeWriteWalk * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Dump entire parse tree, for compiler debug only * ******************************************************************************/ void LsDumpParseTree ( void) { if (!Gbl_DebugFlag) { return; } DbgPrint (ASL_TREE_OUTPUT, "\nOriginal parse tree from parser:\n\n"); TrWalkParseTree (RootNode, ASL_WALK_VISIT_DOWNWARD, LsTreeWriteWalk, NULL, NULL); } static ACPI_STATUS LsTreeWriteWalk ( ACPI_PARSE_OBJECT *Op, UINT32 Level, void *Context) { /* Debug output */ DbgPrint (ASL_TREE_OUTPUT, "%5.5d [%2d]", Op->Asl.LogicalLineNumber, Level); UtPrintFormattedName (Op->Asl.ParseOpcode, Level); DbgPrint (ASL_TREE_OUTPUT, " (%.4X)\n", Op->Asl.ParseOpcode); return (AE_OK); } /******************************************************************************* * * FUNCTION: LsWriteNodeToListing * * PARAMETERS: Op - Parse node to write to the listing file. * FileId - ID of current listing file * * RETURN: None. * * DESCRIPTION: Write "a node" to the listing file. This means to * 1) Write out all of the source text associated with the node * 2) Write out all of the AML bytes associated with the node * 3) Write any compiler exceptions associated with the node * ******************************************************************************/ static void LsWriteNodeToListing ( ACPI_PARSE_OBJECT *Op, UINT32 FileId) { const ACPI_OPCODE_INFO *OpInfo; UINT32 OpClass; char *Pathname; UINT32 Length; UINT32 i; OpInfo = AcpiPsGetOpcodeInfo (Op->Asl.AmlOpcode); OpClass = OpInfo->Class; /* TBD: clean this up with a single flag that says: * I start a named output block */ if (FileId == ASL_FILE_C_SOURCE_OUTPUT) { switch (Op->Asl.ParseOpcode) { case PARSEOP_DEFINITIONBLOCK: case PARSEOP_METHODCALL: case PARSEOP_INCLUDE: case PARSEOP_INCLUDE_END: case PARSEOP_DEFAULT_ARG: break; default: switch (OpClass) { case AML_CLASS_NAMED_OBJECT: switch (Op->Asl.AmlOpcode) { case AML_SCOPE_OP: case AML_ALIAS_OP: break; default: if (Op->Asl.ExternalName) { LsFlushListingBuffer (FileId); FlPrintFile (FileId, " };\n"); } break; } break; default: /* Don't care about other objects */ break; } break; } } /* These cases do not have a corresponding AML opcode */ switch (Op->Asl.ParseOpcode) { case PARSEOP_DEFINITIONBLOCK: LsWriteSourceLines (Op->Asl.EndLine, Op->Asl.EndLogicalLine, FileId); /* Use the table Signature and TableId to build a unique name */ if (FileId == ASL_FILE_ASM_SOURCE_OUTPUT) { FlPrintFile (FileId, "%s_%s_Header \\\n", Gbl_TableSignature, Gbl_TableId); } if (FileId == ASL_FILE_C_SOURCE_OUTPUT) { FlPrintFile (FileId, " unsigned char %s_%s_Header [] =\n {\n", Gbl_TableSignature, Gbl_TableId); } if (FileId == ASL_FILE_ASM_INCLUDE_OUTPUT) { FlPrintFile (FileId, "extrn %s_%s_Header : byte\n", Gbl_TableSignature, Gbl_TableId); } if (FileId == ASL_FILE_C_INCLUDE_OUTPUT) { FlPrintFile (FileId, "extern unsigned char %s_%s_Header [];\n", Gbl_TableSignature, Gbl_TableId); } return; case PARSEOP_METHODCALL: LsWriteSourceLines (Op->Asl.LineNumber, Op->Asl.LogicalLineNumber, FileId); return; case PARSEOP_INCLUDE: /* Flush everything up to and including the include source line */ LsWriteSourceLines (Op->Asl.LineNumber, Op->Asl.LogicalLineNumber, FileId); /* Create a new listing node and push it */ LsPushNode (Op->Asl.Child->Asl.Value.String); return; case PARSEOP_INCLUDE_END: /* Flush out the rest of the include file */ LsWriteSourceLines (Op->Asl.LineNumber, Op->Asl.LogicalLineNumber, FileId); /* Pop off this listing node and go back to the parent file */ (void) LsPopNode (); return; case PARSEOP_DEFAULT_ARG: if (Op->Asl.CompileFlags & NODE_IS_RESOURCE_DESC) { LsWriteSourceLines (Op->Asl.LineNumber, Op->Asl.EndLogicalLine, FileId); } return; default: /* All other opcodes have an AML opcode */ break; } /* * Otherwise, we look at the AML opcode because we can * switch on the opcode type, getting an entire class * at once */ switch (OpClass) { case AML_CLASS_ARGUMENT: /* argument type only */ case AML_CLASS_INTERNAL: break; case AML_CLASS_NAMED_OBJECT: switch (Op->Asl.AmlOpcode) { case AML_FIELD_OP: case AML_INDEX_FIELD_OP: case AML_BANK_FIELD_OP: /* * For fields, we want to dump all the AML after the * entire definition */ LsWriteSourceLines (Op->Asl.EndLine, Op->Asl.EndLogicalLine, FileId); break; case AML_NAME_OP: if (Op->Asl.CompileFlags & NODE_IS_RESOURCE_DESC) { LsWriteSourceLines (Op->Asl.LineNumber, Op->Asl.LogicalLineNumber, FileId); } else { /* * For fields, we want to dump all the AML after the * entire definition */ LsWriteSourceLines (Op->Asl.EndLine, Op->Asl.EndLogicalLine, FileId); } break; default: LsWriteSourceLines (Op->Asl.LineNumber, Op->Asl.LogicalLineNumber, FileId); break; } switch (Op->Asl.AmlOpcode) { case AML_SCOPE_OP: case AML_ALIAS_OP: /* These opcodes do not declare a new object, ignore them */ break; default: /* All other named object opcodes come here */ switch (FileId) { case ASL_FILE_ASM_SOURCE_OUTPUT: case ASL_FILE_C_SOURCE_OUTPUT: case ASL_FILE_ASM_INCLUDE_OUTPUT: case ASL_FILE_C_INCLUDE_OUTPUT: /* * For named objects, we will create a valid symbol so that the * AML code can be referenced from C or ASM */ if (Op->Asl.ExternalName) { /* Get the full pathname associated with this node */ Pathname = AcpiNsGetExternalPathname (Op->Asl.Node); Length = strlen (Pathname); if (Length >= 4) { /* Convert all dots in the path to underscores */ for (i = 0; i < Length; i++) { if (Pathname[i] == '.') { Pathname[i] = '_'; } } /* Create the appropriate symbol in the output file */ if (FileId == ASL_FILE_ASM_SOURCE_OUTPUT) { FlPrintFile (FileId, "%s_%s_%s \\\n", Gbl_TableSignature, Gbl_TableId, &Pathname[1]); } if (FileId == ASL_FILE_C_SOURCE_OUTPUT) { FlPrintFile (FileId, " unsigned char %s_%s_%s [] =\n {\n", Gbl_TableSignature, Gbl_TableId, &Pathname[1]); } if (FileId == ASL_FILE_ASM_INCLUDE_OUTPUT) { FlPrintFile (FileId, "extrn %s_%s_%s : byte\n", Gbl_TableSignature, Gbl_TableId, &Pathname[1]); } if (FileId == ASL_FILE_C_INCLUDE_OUTPUT) { FlPrintFile (FileId, "extern unsigned char %s_%s_%s [];\n", Gbl_TableSignature, Gbl_TableId, &Pathname[1]); } } ACPI_FREE (Pathname); } break; default: /* Nothing to do for listing file */ break; } } break; case AML_CLASS_EXECUTE: case AML_CLASS_CREATE: default: if ((Op->Asl.ParseOpcode == PARSEOP_BUFFER) && (Op->Asl.CompileFlags & NODE_IS_RESOURCE_DESC)) { return; } LsWriteSourceLines (Op->Asl.LineNumber, Op->Asl.LogicalLineNumber, FileId); break; case AML_CLASS_UNKNOWN: break; } } /******************************************************************************* * * FUNCTION: LsFinishSourceListing * * PARAMETERS: FileId - ID of current listing file. * * RETURN: None * * DESCRIPTION: Cleanup routine for the listing file. Flush the hex AML * listing buffer, and flush out any remaining lines in the * source input file. * ******************************************************************************/ static void LsFinishSourceListing ( UINT32 FileId) { if ((FileId == ASL_FILE_ASM_INCLUDE_OUTPUT) || (FileId == ASL_FILE_C_INCLUDE_OUTPUT)) { return; } LsFlushListingBuffer (FileId); Gbl_CurrentAmlOffset = 0; /* Flush any remaining text in the source file */ if (FileId == ASL_FILE_C_SOURCE_OUTPUT) { FlPrintFile (FileId, " /*\n"); } while (LsWriteOneSourceLine (FileId)) { ; } if (FileId == ASL_FILE_C_SOURCE_OUTPUT) { FlPrintFile (FileId, "\n */\n };\n"); } FlPrintFile (FileId, "\n"); if (FileId == ASL_FILE_LISTING_OUTPUT) { /* Print a summary of the compile exceptions */ FlPrintFile (FileId, "\n\nSummary of errors and warnings\n\n"); AePrintErrorLog (FileId); FlPrintFile (FileId, "\n"); UtDisplaySummary (FileId); FlPrintFile (FileId, "\n"); } }
9,656
427
//===-- ExceptionRecord.h ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef liblldb_Plugins_Process_Windows_ExceptionRecord_H_ #define liblldb_Plugins_Process_Windows_ExceptionRecord_H_ #include "lldb/Host/windows/windows.h" #include "lldb/lldb-forward.h" #include <dbghelp.h> #include <memory> #include <vector> namespace lldb_private { //---------------------------------------------------------------------- // ExceptionRecord // // ExceptionRecord defines an interface which allows implementors to receive // notification of events that happen in a debugged process. //---------------------------------------------------------------------- class ExceptionRecord { public: ExceptionRecord(const EXCEPTION_RECORD &record, lldb::tid_t thread_id) { m_code = record.ExceptionCode; m_continuable = (record.ExceptionFlags == 0); if (record.ExceptionRecord) m_next_exception.reset( new ExceptionRecord(*record.ExceptionRecord, thread_id)); m_exception_addr = reinterpret_cast<lldb::addr_t>(record.ExceptionAddress); m_thread_id = thread_id; m_arguments.assign(record.ExceptionInformation, record.ExceptionInformation + record.NumberParameters); } // MINIDUMP_EXCEPTIONs are almost identical to EXCEPTION_RECORDs. ExceptionRecord(const MINIDUMP_EXCEPTION &record, lldb::tid_t thread_id) : m_code(record.ExceptionCode), m_continuable(record.ExceptionFlags == 0), m_next_exception(nullptr), m_exception_addr(static_cast<lldb::addr_t>(record.ExceptionAddress)), m_thread_id(thread_id), m_arguments(record.ExceptionInformation, record.ExceptionInformation + record.NumberParameters) { // Set up link to nested exception. if (record.ExceptionRecord) { m_next_exception.reset(new ExceptionRecord( *reinterpret_cast<const MINIDUMP_EXCEPTION *>(record.ExceptionRecord), thread_id)); } } virtual ~ExceptionRecord() {} DWORD GetExceptionCode() const { return m_code; } bool IsContinuable() const { return m_continuable; } const ExceptionRecord *GetNextException() const { return m_next_exception.get(); } lldb::addr_t GetExceptionAddress() const { return m_exception_addr; } lldb::tid_t GetThreadID() const { return m_thread_id; } private: DWORD m_code; bool m_continuable; std::shared_ptr<ExceptionRecord> m_next_exception; lldb::addr_t m_exception_addr; lldb::tid_t m_thread_id; std::vector<ULONG_PTR> m_arguments; }; } #endif
939
786
#!/usr/bin/env python """ :mod:`disco.worker` -- Python Worker Interface ============================================== In Disco, :term:`workers <worker>` do the brunt of the data processing work. When a :class:`disco.job.Job` is created, it gets passed a :class:`Worker` instance, which is responsible for defining the fields used by the :class:`disco.job.JobPack`. In most cases, you don't need to define your own Worker subclass in order to run a job. The Worker classes defined in :mod:`disco` will take care of the details of creating the fields necessary for the :class:`disco.job.JobPack`, and when executed on the nodes, will handle the implementation of the :ref:`worker_protocol`. There is perhaps a subtle, but important, distinction between a :term:`worker` and a :class:`Worker`. The former refers to any binary that gets executed on the nodes, specified by :attr:`jobdict.worker`. The latter is a Python class, which handles details of submitting the job on the client side, as well as controlling the execution of user-defined code on the nodes. A :class:`Worker` can be subclassed trivially to create a new :term:`worker`, without having to worry about fulfilling many of the requirements for a well-behaving worker. In short, a :class:`Worker` provides Python library support for a Disco :term:`worker`. Those wishing to write a worker in a language besides Python may make use of the Worker class for submitting jobs to the master, but generally need to handle the :ref:`worker_protocol` in the language used for the worker executable. The :class:`Classic Worker <disco.worker.classic.worker.Worker>` is a subclass of :class:`Worker`, which implements the classic Disco :term:`mapreduce` interface. The following steps illustrate the sequence of events for running a :term:`job` using a standard :class:`Worker`: #. (client) instantiate a :class:`disco.job.Job` #. if a worker is supplied, use that worker #. otherwise, create a worker using :attr:`disco.job.Job.Worker` (the default is :class:`disco.worker.classic.worker.Worker`) #. (client) call :meth:`disco.job.Job.run` #. create a :class:`disco.job.JobPack` using: :meth:`Worker.jobdict`, :meth:`Worker.jobenvs`, :meth:`Worker.jobhome`, :meth:`disco.task.jobdata` #. submit the :class:`disco.job.JobPack` to the master #. (node) master unpacks the :term:`job home` #. (node) master executes the :attr:`jobdict.worker` with current working directory set to the :term:`job home` and environment variables set from :ref:`jobenvs` #. (node) worker requests the :class:`disco.task.Task` from the master #. (node) worker runs the :term:`task` and reports the output to the master """ import os, sys, time, traceback, random from disco.compat import basestring, force_utf8 from disco.error import DataError from disco.fileutils import DiscoOutput, NonBlockingInput, Wait, AtomicFile from disco.comm import open_url # Maximum amount of time a task might take to finish. DISCO_WORKER_MAX_TIME = 24 * 60 * 60 # Use active_task as a global variable. # I will set this when a task is running, and then access it from utilities that # need task data like ddfs directory, etc. active_task = None class MessageWriter(object): def __init__(self, worker): self.worker = worker def write(self, string): string = string.strip() if string: self.worker.send('MSG', force_utf8(string)) def isatty(self): return False def flush(self): pass class Worker(dict): """ A :class:`Worker` is a :class:`dict` subclass, with special methods defined for serializing itself, and possibly reinstantiating itself on the nodes where :term:`tasks <task>` are run. .. note:: The base worker tries to guess which modules are needed automatically, for all of the :term:`job functions` specified below, if the *required_modules* parameter is not specified. It sends any local dependencies (i.e. modules not included in the Python standard library) to nodes by default. If guessing fails, or you have other requirements, see :mod:`disco.worker.modutil` for options. The :class:`Worker` base class defines the following parameters: :type save_results: bool :param save_results: whether or not to save the output to :ref:`DDFS`. :type save_info: string :param save_info: the information about saving into a DFS. :type profile: bool :param profile: determines whether :meth:`run` will be profiled. :type required_files: list of paths or dict :param required_files: additional files that are required by the worker. Either a list of paths to files to include, or a dictionary which contains items of the form ``(filename, filecontents)``. .. versionchanged:: 0.4 The worker includes *required_files* in :meth:`jobzip`, so they are available relative to the working directory of the worker. :type required_modules: see :ref:`modspec` :param required_modules: required modules to send with the worker. """ stderr = sys.stderr def __init__(self, **kwargs): super(Worker, self).__init__(self.defaults()) self.update(kwargs) self.outputs = {} @property def bin(self): """ The path to the :term:`worker` binary, relative to the :term:`job home`. Used to set :attr:`jobdict.worker` in :meth:`jobdict`. """ from inspect import getsourcefile, getmodule return getsourcefile(getmodule(self)).strip('/') def defaults(self): """ :return: dict of default values for the :class:`Worker`. """ return {'save_results': False, 'profile': False, 'required_files': {}, 'required_modules': None} def getitem(self, key, job, jobargs, default=None): """ Resolves ``key`` in the following order: #. ``jobargs`` (parameters passed in during :meth:`disco.job.Job.run`) #. ``job`` (attributes of the :class:`disco.job.Job`) #. ``self`` (items in the :class:`Worker` dict itself) #. ``default`` """ if key in jobargs: return jobargs[key] elif hasattr(job, key): return getattr(job, key) return self.get(key, default) def get_modules(self, job, **jobargs): from disco.worker.modutil import find_modules from disco.util import iterify def get(key): return self.getitem(key, job, jobargs) from inspect import getsourcefile, getmodule job_path = getsourcefile(getmodule(job)) return find_modules([obj for key in self for obj in iterify(get(key)) if callable(obj)], job_path=job_path, exclude=['Task']) def jobdict(self, job, **jobargs): """ Creates a basic :ref:`jobdict` for the :class:`Worker`. Makes use of the following parameters: :type name: string :param name: directly sets :attr:`jobdict.prefix`. :type owner: string :param owner: directly sets :attr:`jobdict.owner`. If not specified, uses :envvar:`DISCO_JOB_OWNER`. :return: :ref:`jobdict` dict. """ return {'prefix': self.getitem('name', job, jobargs), 'save_results': self.getitem('save_results', job, jobargs, False), 'save_info': self.getitem('save_info', job, jobargs, "ddfs"), 'scheduler': self.getitem('scheduler', job, jobargs, {}), 'owner': self.getitem('owner', job, jobargs, job.settings['DISCO_JOB_OWNER'])} def jobenvs(self, job, **jobargs): """ :return: :ref:`jobenvs` dict. """ envs = {'PYTHONPATH': ':'.join([path.strip('/') for path in sys.path])} envs['LD_LIBRARY_PATH'] = 'lib' envs['PYTHONPATH'] = ':'.join(('lib', envs.get('PYTHONPATH', ''))) return envs def jobhome(self, job, **jobargs): """ :return: the :term:`job home` (serialized). Calls :meth:`jobzip` to create the :class:`disco.fileutils.DiscoZipFile`. """ jobzip = self.jobzip(job, **jobargs) jobzip.close() return jobzip.dumps() def jobzip(self, job, **jobargs): """ A hook provided by the :class:`Worker` for creating the :term:`job home` zip. The base implementation creates a minimal zip file containing the Disco standard library, and any user-specified required files and modules. :return: a :class:`disco.fileutils.DiscoZipFile`. """ # First, add the disco standard library. from clx import __file__ as clxpath from disco import __file__ as discopath from disco.fileutils import DiscoZipFile jobzip = DiscoZipFile() jobzip.writepath(os.path.dirname(clxpath), exclude=('.pyc', '__pycache__')) jobzip.writepath(os.path.dirname(discopath), exclude=('.pyc', '__pycache__')) jobzip.writesource(job) jobzip.writesource(self) # Then, add any user-specified required files. from disco.util import iskv def get(key): return self.getitem(key, job, jobargs) if isinstance(get('required_files'), dict): for path, bytes in get('required_files').items(): jobzip.writestr(path, bytes) else: for path in get('required_files'): jobzip.write(path, os.path.join('lib', os.path.basename(path))) if get('required_modules') is None: self['required_modules'] = self.get_modules(job, **jobargs) for mod in get('required_modules'): if iskv(mod): jobzip.writepath(mod[1]) # Done with basic minimal zip. return jobzip def input(self, task, merged=False, **kwds): """ :type task: :class:`disco.task.Task` :param task: the task for which to retrieve input. :type merged: bool :param merged: if specified, returns a :class:`MergedInput`. :type kwds: dict :param kwds: additional keyword arguments for the :class:`Input`. :return: an :class:`Input` to iterate over the inputs from the master. """ if merged: return MergedInput(self.get_inputs(), task=task, **kwds) return SerialInput(self.get_inputs(), task=task, **kwds) def output(self, task, label=None, **kwds): """ :type task: :class:`disco.task.Task` :param task: the task for which to create output. :type label: int or None :param label: the label of the output partition to get. :type kwds: dict :param kwds: additional keyword arguments for the :class:`Output`. :return: the previously opened :class:`Output` for *label*, or if necessary, a newly opened one. """ if label not in self.outputs: self.outputs[label] = Output(task.output(label=label), **kwds) return self.outputs[label] def start(self, task, job, **jobargs): from disco.sysutil import set_mem_limit set_mem_limit(job.settings['DISCO_WORKER_MAX_MEM']) task.makedirs() if self.getitem('profile', job, jobargs): from cProfile import runctx name = 'profile-{0}'.format(task.uid) path = task.path(name) runctx('self.run(task, job, **jobargs)', globals(), locals(), path) task.put(name, open(path, 'rb').read()) else: self.run(task, job, **jobargs) self.end(task, job, **jobargs) def run(self, task, job, **jobargs): """ Called to do the actual work of processing the :class:`disco.task.Task`. This method runs in the Disco cluster, on a server that is executing one of the tasks in a job submitted by a client. """ self.getitem(task.stage, job, jobargs)(task, job, **jobargs) def end(self, task, job, **jobargs): self.send_outputs() self.send('MSG', "Results sent to master") @classmethod def main(cls): """ The main method used to bootstrap the :class:`Worker` when it is being executed. It is enough for the module to define:: if __name__ == '__main__': Worker.main() .. note:: It is critical that subclasses check if they are executing in the ``__main__`` module, before running :meth:`main`, as the worker module is also generally imported on the client side. """ try: sys.stdin = NonBlockingInput(sys.stdin, timeout=3 * DISCO_WORKER_MAX_TIME) sys.stdout = sys.stderr = MessageWriter(cls) cls.send('WORKER', {'pid': os.getpid(), 'version': "1.1"}) task = cls.get_task() job, jobargs = task.jobobjs job.worker.start(task, job, **jobargs) cls.send('DONE') except (DataError, EnvironmentError, MemoryError) as e: # check the number of open file descriptors (under proc), warn if close to max # http://stackoverflow.com/questions/899038/getting-the-highest-allocated-file-descriptor # also check for other known reasons for error, such as if disk is full cls.send('ERROR', traceback.format_exc()) raise except Exception as e: cls.send('FATAL', force_utf8(traceback.format_exc())) raise @classmethod def send(cls, type, payload=''): from json import dumps, loads body = dumps(payload) cls.stderr.write('{0} {1} {2}\n'.format(type, len(body), body)) cls.stderr.flush() spent, rtype = sys.stdin.t_read_until(' ') spent, rsize = sys.stdin.t_read_until(' ', spent=spent) spent, rbody = sys.stdin.t_read(int(rsize) + 1, spent=spent) if type == 'ERROR': raise ValueError(loads(rbody[:-1])) return loads(rbody[:-1]) @classmethod def get_input(cls, id): done, inputs = cls.send('INPUT', ['include', [id]]) _id, status, _label, replicas = inputs[0] if status == 'busy': raise Wait if status == 'failed': raise DataError("Can't handle broken input", id) return [(id, str(url)) for id, url in replicas] @classmethod def get_inputs(cls, done=False, exclude=[]): while done != "done": done, inputs = cls.send('INPUT', ['exclude', exclude]) for id, _status, label, _replicas in inputs: if id not in exclude: label = label if label == 'all' else int(label) yield IDedInput((cls, id, label)) exclude.append(id) @classmethod def labelled_input_map(cls, task, inputs): from disco.util import ispartitioned, read_index from collections import defaultdict def update_label_map(lm, i): reps = [url for rid, url in i.replicas] if ispartitioned(reps): for l, url, size in read_index(reps[0]): if i.label in ('all', l): lm[l].append([url]) else: lm[i.label].append(reps) label_map = defaultdict(list) for i in inputs: update_label_map(label_map, i) return label_map @classmethod def concat_input(cls, task, output_label, replicas): output = AtomicFile(task.output_path(output_label)) BUFFER_SIZE = 1024*1024 for reps in replicas: # Use only the first replica for now, since a set of one # is the most common case. # TODO: handle falling back to alternative replicas. inp = open_url(reps[0]) buf = inp.read(BUFFER_SIZE) while (len(buf) > 0): output.write(buf) buf = inp.read(BUFFER_SIZE) inp.close() output.close() return output.path, output.size() @classmethod def get_task(cls): from disco.task import Task return Task(**dict((str(k), v) for k, v in cls.send('TASK').items())) def send_outputs(self): for output in self.outputs.values(): output.close() self.send('OUTPUT', [output.label, output.path, output.size()]) class Params(object): """ Classic parameter container for tasks. This object provides a way to contain custom parameters, or state, in your tasks. You can specify any number of ``key, value`` pairs to the :class:`Params`. The pairs will be available to task functions through the *params* argument. Each task receives its own copy of the initial params object. *key* must be a valid Python identifier. *value* can be any Python object. """ def __init__(self, **kwargs): self.__dict__.update(kwargs) class IDedInput(tuple): @property def worker(self): return self[0] @property def id(self): return self[1] @property def label(self): return self[2] @property def replicas(self): return self.worker.get_input(self.id) @property def isindex(self): from disco.util import ispartitioned return ispartitioned(self.locations) @property def locations(self): return [r for rid, r in self.replicas] def unavailable(self, tried): return self.worker.send('INPUT_ERR', [self.id, list(tried)]) def __str__(self): return '{0}'.format([url for rid, url in self.replicas]) class ReplicaIter(object): def __init__(self, input): self.input, self.used = input, set() self.checked_local = False def __iter__(self): return self def next(self): from disco.util import urlsplit replicas = dict(self.input.replicas) repl_ids = list(set(replicas) - self.used) if not self.checked_local and active_task: # Try to favor opening a local file self.checked_local = True for repl_id in repl_ids: replica = replicas[repl_id] scheme, netloc, rest = urlsplit(replica, localhost=active_task.host, ddfs_data=active_task.ddfs_data, disco_data=active_task.disco_data) if scheme == 'file': self.used.add(repl_id) if os.path.exists(rest): # file might not exist due to replica rebalancing return replica repl_ids.remove(repl_id) if repl_ids: repl_id = random.choice(repl_ids) self.used.add(repl_id) return replicas[repl_id] self.input.unavailable(self.used) raise StopIteration def __next__(self): return self.next() class InputIter(object): def __init__(self, input, task=None, open=None, start=0): self.input = input if isinstance(input, IDedInput): self.urls = ReplicaIter(input) elif isinstance(input, basestring): self.urls = iter([input]) else: self.urls = iter(input) self.last = start - 1 self.open = open if open else Input.default_opener(task=task) self.swap() def __iter__(self): return self def next(self): try: self.last, item = next(self.iter) return item except DataError: self.swap(traceback.format_exc()) raise Wait(0) def __next__(self): return self.next() def swap(self, error=None): try: def skip(iter, N): from itertools import dropwhile return dropwhile(lambda n_rec: n_rec[0] < N, enumerate(iter)) self.iter = skip(self.open(next(self.urls)), self.last + 1) except DataError: self.swap(traceback.format_exc()) except StopIteration: if error: raise DataError("Exhausted all available replicas, " "last error was:\n\n{0}".format(error), self.input) raise DataError("Exhausted all available replicas", self.input) class Input(object): """ An iterable over one or more :class:`Worker` inputs, which can gracefully handle corrupted replicas or otherwise failed inputs. :type open: function :param open: a function with the following signature:: def open(url): ... return file used to open input files. """ def __init__(self, input, task=None, **kwds): self.input, self.task, self.kwds = input, task, kwds def __iter__(self): iter = self.input_iter(self.input) while iter: try: for item in iter: yield item iter = None except Wait as w: time.sleep(w.retry_after) def input_iter(self, input): return InputIter(self.input, task=self.task, **self.kwds) @classmethod def default_opener(cls, task): from disco import schemes def open(url): return schemes.open(url, task=task) return open class BaseOutput(object): def __init__(self, path_type_label): self.path, self.type, label = path_type_label self.label = 0 if label is None else int(label) def size(self): return os.path.getsize(self.path) def close(self): pass class Output(BaseOutput): """ A container for outputs from :class:`workers <Worker>`. :type open: function :param open: a function with the following signature:: def open(url): ... return file used to open new output files. .. attribute:: path The path to the underlying output file. .. attribute:: type The type of output. .. attribute:: label The label for the output (or None). .. attribute:: file The underlying output file handle. """ def __init__(self, path_type_label, open=None): super(Output, self).__init__(path_type_label) self.open = open or DiscoOutput self.file = self.open(self.path) def close(self): self.file.close() class SerialInput(Input): """ Produces an iterator over the records in a list of sequential inputs. """ def __iter__(self): for input in self.input: for record in Input(input, task=self.task, **self.kwds): yield record class ParallelInput(Input): """ Produces an iterator over the unordered records in a set of inputs. Usually require the full set of inputs (i.e. will block with streaming). """ BUSY_TIMEOUT = 1 def __iter__(self): iters = [self.input_iter(input) for input in self.input] while iters: iter = iters.pop() try: for item in iter: yield item except Wait as w: if not iters: time.sleep(w.retry_after) iters.insert(0, iter) def couple(self, iters, heads, n): while True: if heads[n] is Wait: self.fill(iters, heads, n=n) head = heads[n] heads[n] = Wait yield head def fetch(self, iters, heads, stop=all): busy = 0 for n, head in enumerate(heads): if head is Wait: try: heads[n] = next(iters[n]) except Wait: if stop in (all, n): busy += 1 except StopIteration: if stop in (all, n): raise return busy def fill(self, iters, heads, n=all, busy=True): while busy: busy = self.fetch(iters, heads, stop=n) if busy: time.sleep(self.BUSY_TIMEOUT) return heads class MergedInput(ParallelInput): """ Produces an iterator over the minimal head elements of the inputs. """ def __iter__(self): from heapq import merge iters = [self.input_iter(input) for input in self.input] heads = [Wait] * len(iters) return merge(*(self.couple(iters, heads, n) for n in range(len(iters)))) if __name__ == '__main__': Worker.main()
11,384
437
# Random Quote Desktop Notification # Author: <NAME> # Date: 1st October 2020 # --------------------------------- # Imports import requests from plyer import notification from apscheduler.schedulers.blocking import BlockingScheduler # Sub-Routines def fetch(): # This gets the quote from the API and turns it into the quote to be displayed quoteSite = requests.get("http://api.quotable.io/random") quoteJson = quoteSite.json() quote = quoteJson["content"] + "\n- " + quoteJson["author"] if len(quote) > 256: fetch() else: return quote def display(quote): # Uses the plyer module to display the quote notification.notify( title="Random Quote", message=quote, app_name="Random Quote", app_icon="icon.ico", timeout=10, toast=False, ) # Main Program def task(): # This puts it all together quote = fetch() display(quote) if __name__ == "__main__": task() # So that it prints a quote without waiting for the interval scheduler = BlockingScheduler() # Creates a scheduler scheduler.add_job( task, "interval", hours=1 ) # Sets the interval, you may change this to your preferences scheduler.start() # Starts scheduler
440
370
package com.vitco.app.core.data; import com.vitco.app.core.data.container.Voxel; import org.junit.Before; import org.junit.Test; import java.awt.*; import java.math.BigInteger; import java.util.ArrayList; import java.util.Random; /** * Extensive test for voxel data. */ @SuppressWarnings("ConstantConditions") public class VoxelDataTest { private final Data data = new Data(); @Before public void setUp() throws Exception { // all tests expect an empty data container while (data.getLayers().length > 0) { data.deleteLayer(data.getLayers()[0]); } data.clearHistoryV(); } // tests for voxels @Test public void testAddDeleteVoxel() throws Exception { assert -1 == data.addVoxel(Color.RED, null, new int[]{0,0,0}); int lid1 = data.createLayer("layer1"); assert -1 == data.addVoxel(Color.RED, null, new int[]{0,0,0}); data.selectLayer(lid1); int id1 = data.addVoxel(Color.RED, null, new int[]{0,0,0}); assert id1 > -1; assert -1 == data.addVoxel(Color.RED, null, new int[]{0,0,0}); assert data.removeVoxel(id1); assert data.getVoxel(id1) == null; data.undoV(); assert data.getVoxel(id1).id == id1; int lid2 = data.createLayer("layer2"); data.deleteLayer(lid1); assert data.getVoxel(id1) == null; data.undoV(); assert data.getVoxel(id1).id == id1; assert data.addVoxel(Color.RED, null, new int[]{0,0,0}) == -1; data.selectLayer(lid2); int id2 = data.addVoxel(Color.RED, null, new int[]{0,0,0}); assert id2 > -1; assert data.getVoxel(id2).id == id2; int id3 = data.addVoxel(Color.GREEN, null, new int[]{5,0,0}); data.deleteLayer(lid2); assert data.getVoxel(id3) == null; data.undoV(); assert data.getVoxel(id3).id == id3; } @Test public void testMoveVoxel() throws Exception { int lid1 = data.createLayer("layer1"); data.createLayer("layer2"); data.selectLayer(lid1); int id1 = data.addVoxel(Color.RED, null, new int[]{5,6,7}); int id2 = data.addVoxel(Color.RED, null, new int[]{7,8,9}); data.moveVoxel(id2, new int[]{5,6,7}); assert data.getVoxel(id1) == null; data.undoV(); assert data.getVoxel(id1) != null; data.undoV(); boolean moved = data.moveVoxel(id1, new int[]{3,1,2}); assert moved; assert data.getVoxel(id1).x == 3; data.undoV(); assert data.getVoxel(id1).x == 5; data.redoV(); assert data.getVoxel(id1).z == 2; } @Test public void testColorVoxel() throws Exception { int lid1 = data.createLayer("layer1"); data.selectLayer(lid1); int id1 = data.addVoxel(Color.RED, null, new int[] {0,0,0}); assert data.getColor(id1) == Color.RED; data.setColor(id1, Color.GREEN); assert data.getColor(id1) == Color.GREEN; data.undoV(); assert data.getColor(id1) == Color.RED; data.redoV(); assert data.getColor(id1) == Color.GREEN; } @Test public void testAlphaVoxel() throws Exception { int lid1 = data.createLayer("layer1"); data.selectLayer(lid1); int id1 = data.addVoxel(Color.RED, null, new int[] {0,0,0}); assert data.getAlpha(id1) == -1; data.setAlpha(id1, 10); assert data.getAlpha(id1) == 10; data.undoV(); assert data.getAlpha(id1) == -1; data.redoV(); assert data.getAlpha(id1) == 10; } @Test public void testClear() throws Exception { int lid1 = data.createLayer("layer1"); data.selectLayer(lid1); data.addVoxel(Color.RED, null, new int[] {0,0,0}); assert data.getLayerVoxels(lid1).length == 1; data.undoV(); assert data.getLayerVoxels(lid1).length == 0; data.redoV(); data.clearV(lid1); assert data.getLayerVoxels(lid1).length == 0; data.undoV(); assert data.getLayerVoxels(lid1).length == 1; data.undoV(); assert data.getLayerVoxels(lid1).length == 0; data.redoV(); data.redoV(); assert data.getLayerVoxels(lid1).length == 0; data.undoV(); assert data.getLayerVoxels(lid1).length == 1; } @Test public void testMergeLayers() throws Exception { int lid1 = data.createLayer("layer1"); int lid2 = data.createLayer("layer2"); data.selectLayer(lid1); int id1 = data.addVoxel(Color.RED, null, new int[] {1,1,1}); int id2 = data.addVoxel(Color.GREEN, null, new int[] {1,1,2}); data.selectLayer(lid2); int id3 = data.addVoxel(Color.ORANGE, null, new int[] {1,1,1}); data.mergeVisibleLayers(); assert data.getLayers().length == 1; assert data.getVoxel(id1) == null; assert data.getVoxel(id2) == null; assert data.getVoxel(id3) == null; Voxel[] voxel = data.getLayerVoxels(data.getSelectedLayer()); assert voxel.length == 2; assert (voxel[1].z == 2 && voxel[1].getColor() == Color.GREEN); } @Test public void testGetVoxelSlice() throws Exception { int lid1 = data.createLayer("layer1"); data.selectLayer(lid1); assert !data.mergeVisibleLayers(); data.addVoxel(Color.RED, null, new int[] {0,0,0}); data.addVoxel(Color.RED, null, new int[] {5,2,0}); data.addVoxel(Color.RED, null, new int[] {4,-10,0}); data.addVoxel(Color.RED, null, new int[] {4,-10,2}); assert data.getVoxelsXY(0).length == 3; assert data.getVoxelsXY(1).length == 0; assert data.getVoxelsXY(2).length == 1; } // tests for layers @Test public void testCreateDeleteLayer() throws Exception { int lid1 =data.createLayer("hello"); assert data.getLayers().length == 1; data.undoV(); assert data.getLayers().length == 0; data.redoV(); assert data.getLayers().length == 1; data.deleteLayer(data.getLayers()[0]); assert data.getLayers().length == 0; data.undoV(); assert data.getLayers().length == 1; data.undoV(); assert data.getLayers().length == 0; data.redoV(); data.redoV(); assert data.getLayers().length == 0; data.undoV(); assert data.getLayers().length == 1; assert data.getLayerNames()[0].equals(data.getLayerName(lid1)); assert data.getLayerNames()[0].equals("hello"); int lid2 = data.createLayer("hallo2"); data.deleteLayer(lid1); data.deleteLayer(lid2); assert data.getLayers().length == 0; data.undoV(); assert data.getLayers().length == 1; data.undoV(); assert data.getLayers().length == 2; data.undoV(); assert data.getLayers().length == 1; data.redoV(); assert data.getLayers().length == 2; data.createLayer("tt1"); data.createLayer("tt2"); data.createLayer("tt3"); assert data.getLayers().length == 5; data.undoV(); data.undoV(); assert data.getLayers().length == 3; data.undoV(); data.undoV(); data.undoV(); assert data.getLayers().length == 0; while (data.canRedoV()) { data.redoV(); } assert data.getLayers().length == 5; data.deleteLayer(lid1); data.deleteLayer(lid2); assert data.getLayers().length == 3; } @Test public void testRenameLayer() throws Exception { int lid1 = data.createLayer("layer1"); data.createLayer("layer2"); data.renameLayer(lid1, "newName"); assert data.getLayerName(lid1).equals("newName"); data.undoV(); assert data.getLayerName(lid1).equals("layer1"); data.undoV(); data.undoV(); assert data.getLayerName(lid1) == null; data.redoV(); data.redoV(); data.redoV(); assert data.getLayerName(lid1).equals("newName"); data.undoV(); assert data.getLayerName(lid1).equals("layer1"); data.undoV(); assert data.getLayerName(lid1).equals("layer1"); } @Test public void testSelectLayer() throws Exception { int lid1 = data.createLayer("layer1"); int lid2 = data.createLayer("layer2"); assert data.getSelectedLayer() == -1; data.selectLayer(lid1); assert data.getSelectedLayer() == lid1; data.selectLayer(lid2); assert data.getSelectedLayer() == lid2; data.selectLayer(-1); assert data.getSelectedLayer() == -1; data.undoV(); assert data.getSelectedLayer() == lid2; data.undoV(); assert data.getSelectedLayer() == lid1; data.undoV(); assert data.getSelectedLayer() == -1; data.redoV(); assert data.getSelectedLayer() == lid1; data.redoV(); assert data.getSelectedLayer() == lid2; } @Test public void canUndoRedo() { assert !data.canRedoV(); assert !data.canUndoV(); int lid1 = data.createLayer("layer1"); assert !data.canRedoV(); assert data.canUndoV(); data.undoV(); assert data.canRedoV(); assert !data.canUndoV(); data.redoV(); assert !data.canRedoV(); assert data.canUndoV(); data.deleteLayer(lid1); assert !data.canRedoV(); assert data.canUndoV(); data.undoV(); assert data.canRedoV(); assert data.canUndoV(); data.undoV(); assert data.canRedoV(); assert !data.canUndoV(); } @Test public void testGetLayers() throws Exception { int lid1 = data.createLayer("layer1"); int lid2 = data.createLayer("layer2"); Integer[] layers = data.getLayers(); assert lid1 == layers[1]; assert lid2 == layers[0]; data.undoV(); layers = data.getLayers(); assert layers[0] == lid1; data.undoV(); assert data.getLayers().length == 0; data.redoV(); layers = data.getLayers(); assert layers[0] == lid1; data.redoV(); layers = data.getLayers(); assert lid1 == layers[1]; assert lid2 == layers[0]; data.undoV(); data.undoV(); assert data.getLayers().length == 0; } @Test public void testSetVisible() throws Exception { int lid1 = data.createLayer("layer1"); assert data.getLayerVisible(lid1); data.setVisible(lid1, false); assert !data.getLayerVisible(lid1); data.setVisible(lid1, true); assert data.getLayerVisible(lid1); data.undoV(); assert !data.getLayerVisible(lid1); data.undoV(); assert data.getLayerVisible(lid1); data.redoV(); assert !data.getLayerVisible(lid1); data.redoV(); assert data.getLayerVisible(lid1); data.setVisible(lid1, true); // this does not create a history entry data.undoV(); assert !data.getLayerVisible(lid1); } @Test public void testMoveLayerUpDownAndCanMoveLayerUpDown() throws Exception { int lid1 = data.createLayer("layer1"); int lid2 = data.createLayer("layer2"); int lid3 = data.createLayer("layer3"); assert data.canMoveLayerUp(lid1); assert data.canMoveLayerUp(lid2); assert !data.canMoveLayerUp(lid3); assert data.canMoveLayerDown(lid3); assert data.canMoveLayerDown(lid2); assert !data.canMoveLayerDown(lid1); data.moveLayerDown(lid1); data.undoV(); assert data.getLayerName(lid3) == null; data.redoV(); data.moveLayerUp(lid1); assert data.getLayerNames()[0].equals("layer3"); assert data.getLayerNames()[1].equals("layer1"); assert data.getLayerNames()[2].equals("layer2"); assert data.canMoveLayerUp(lid2); assert data.canMoveLayerUp(lid1); assert !data.canMoveLayerUp(lid3); assert data.canMoveLayerDown(lid3); assert data.canMoveLayerDown(lid1); assert !data.canMoveLayerDown(lid2); data.moveLayerUp(lid1); assert data.getLayerNames()[0].equals("layer1"); assert data.getLayerNames()[1].equals("layer3"); assert data.getLayerNames()[2].equals("layer2"); assert data.canMoveLayerUp(lid2); assert !data.canMoveLayerUp(lid1); assert data.canMoveLayerUp(lid3); assert data.canMoveLayerDown(lid3); assert data.canMoveLayerDown(lid1); assert !data.canMoveLayerDown(lid2); data.deleteLayer(lid1); data.undoV(); data.undoV(); assert data.getLayerNames()[0].equals("layer3"); assert data.getLayerNames()[1].equals("layer1"); assert data.getLayerNames()[2].equals("layer2"); assert data.canMoveLayerUp(lid2); assert data.canMoveLayerUp(lid1); assert !data.canMoveLayerUp(lid3); assert data.canMoveLayerDown(lid3); assert data.canMoveLayerDown(lid1); assert !data.canMoveLayerDown(lid2); data.undoV(); assert data.canMoveLayerUp(lid1); assert data.canMoveLayerUp(lid2); assert !data.canMoveLayerUp(lid3); assert data.canMoveLayerDown(lid3); assert data.canMoveLayerDown(lid2); assert !data.canMoveLayerDown(lid1); data.redoV(); data.redoV(); assert data.getLayerNames()[0].equals("layer1"); assert data.getLayerNames()[1].equals("layer3"); assert data.getLayerNames()[2].equals("layer2"); assert data.canMoveLayerUp(lid2); assert !data.canMoveLayerUp(lid1); assert data.canMoveLayerUp(lid3); assert data.canMoveLayerDown(lid3); assert data.canMoveLayerDown(lid1); assert !data.canMoveLayerDown(lid2); } @Test public void testMigrateSelection() throws Exception { int lid1 = data.createLayer("layer1"); int lid2 = data.createLayer("layer2"); int lid3 = data.createLayer("layer2"); data.selectLayer(lid1); int id1 = data.addVoxel(Color.BLACK, null, new int[]{1,2,3}); int id2 = data.addVoxel(Color.GREEN, null, new int[]{1,2,4}); data.selectLayer(lid2); int id3 = data.addVoxel(Color.ORANGE, null, new int[]{1,1,3}); int id4 = data.addVoxel(Color.WHITE, null, new int[]{1,2,4}); data.selectLayer(lid2); data.addVoxel(Color.BLUE, null, new int[]{1,1,3}); data.addVoxel(Color.GRAY, null, new int[]{1,2,4}); data.massSetVoxelSelected(new Integer[]{id1, id2, id3, id4}, true); data.setVisible(lid3, false); data.migrateVoxels(data.getSelectedVoxels()); assert data.searchVoxel(new int[]{1,2,3}, true).getColor().equals(Color.BLACK); assert data.searchVoxel(new int[]{1,1,3}, true).getColor().equals(Color.ORANGE); assert data.searchVoxel(new int[]{1,2,4}, true).getColor().equals(Color.WHITE); // todo test undo/redo of this } // big final test @Test public void randomeMess() throws Exception { class Util { private final Random rand; public Util(int seed) { rand = new Random(seed); } public float getFloat() { return rand.nextFloat(); } public int getInt(int range) { return rand.nextInt(range); } public int[] randPos() { return new int[]{rand.nextInt()%20, rand.nextInt()%20, rand.nextInt()%20}; } public Color randCol() { return new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)); } // XXXXXXXXXXXXXXXXXX public void createLayer() { int layercount = data.getLayers().length; data.createLayer(new BigInteger(130, rand).toString(32)); assert layercount+1 == data.getLayers().length; } public void deleteLayer() { Integer[] layers = data.getLayers(); if (layers.length > 0) { int rem = rand.nextInt(layers.length); int layercount = data.getLayers().length; data.deleteLayer(layers[rem]); assert layercount-1 == data.getLayers().length; } } public void renameLayer() { Integer[] layers = data.getLayers(); if (layers.length > 0) { int rem = rand.nextInt(layers.length); String name = data.getLayerName(layers[rem]); data.renameLayer(layers[rem], new BigInteger(130, rand).toString(32)); assert !name.equals(data.getLayerName(layers[rem])); // very unlikely that this fails! } } public void selectLayer() { Integer[] layers = data.getLayers(); if (layers.length > 0) { int rem = rand.nextInt(layers.length); data.selectLayer(layers[rem]); assert ((Integer)data.getSelectedLayer()).equals(layers[rem]); } } public void setVisible() { Integer[] layers = data.getLayers(); if (layers.length > 0) { int rem = rand.nextInt(layers.length); boolean vis = rand.nextBoolean(); data.setVisible(layers[rem], vis); assert data.getLayerVisible(layers[rem]) == vis; } } public void moveLayerUp() { Integer[] layers = data.getLayers(); if (layers.length > 0) { int rem = rand.nextInt(layers.length); Integer[] layersIds = data.getLayers(); boolean moved = data.moveLayerUp(layers[rem]); if (moved) { assert data.getLayers() != layersIds; } } } public void moveLayerDown() { Integer[] layers = data.getLayers(); if (layers.length > 0) { int rem = rand.nextInt(layers.length); Integer[] layersIds = data.getLayers(); boolean moved = data.moveLayerDown(layers[rem]); if (moved) { assert data.getLayers() != layersIds; } } } public void addVoxel() { if (data.getSelectedLayer() != -1) { int voxCount = data.getLayerVoxels(data.getSelectedLayer()).length; int id1 = data.addVoxel(randCol(), null, randPos()); if (id1 != -1) { assert voxCount+1 == data.getLayerVoxels(data.getSelectedLayer()).length; } } } public void deleteVoxel() { if ( data.getSelectedLayer() != -1) { Voxel[] voxels = data.getLayerVoxels(data.getSelectedLayer()); if (voxels.length > 0) { int voxCount = data.getLayerVoxels(data.getSelectedLayer()).length; int rem = rand.nextInt(voxels.length); data.removeVoxel(voxels[rem].id); assert voxCount-1 == data.getLayerVoxels(data.getSelectedLayer()).length; } } } public void moveVoxel() { if ( data.getSelectedLayer() != -1) { Voxel[] voxels = data.getLayerVoxels(data.getSelectedLayer()); if (voxels.length > 0) { int rem = rand.nextInt(voxels.length); int[] newPos = randPos(); if (data.moveVoxel(voxels[rem].id, newPos)) { assert data.getVoxel(voxels[rem].id).z == newPos[2]; } } } } public void colorVoxel() { if ( data.getSelectedLayer() != -1) { Voxel[] voxels = data.getLayerVoxels(data.getSelectedLayer()); if (voxels.length > 0) { int rem = rand.nextInt(voxels.length); Color col = randCol(); data.setColor(voxels[rem].id, col); assert data.getVoxel(voxels[rem].id).getColor() == col; } } } public void alphaVoxel() { if ( data.getSelectedLayer() != -1) { Voxel[] voxels = data.getLayerVoxels(data.getSelectedLayer()); if (voxels.length > 0) { int rem = rand.nextInt(voxels.length); int alpha = rand.nextInt(); data.setAlpha(voxels[rem].id, alpha); assert alpha == data.getVoxel(voxels[rem].id).getAlpha(); } } } public void clear() { if ( data.getSelectedLayer() != -1) { data.clearV(data.getSelectedLayer()); assert data.getLayerVoxels(data.getSelectedLayer()).length == 0; } } public void selectVoxel() { if ( data.getSelectedLayer() != -1) { Voxel[] voxels = data.getLayerVoxels(data.getSelectedLayer()); if (voxels.length > 0) { int rem = rand.nextInt(voxels.length); boolean bool = rand.nextBoolean(); data.setVoxelSelected(voxels[rem].id, bool); assert bool == data.getVoxel(voxels[rem].id).isSelected(); } } } public void selectLayerSoft() { Integer[] layers = data.getLayers(); if (layers.length > 0) { int rem = rand.nextInt(layers.length); data.selectLayerSoft(layers[rem]); assert ((Integer)data.getSelectedLayer()).equals(layers[rem]); } } public void mergeLayers() { data.mergeVisibleLayers(); } public void migrateSelection() { data.migrateVoxels(data.getSelectedVoxels()); } public void massSelect() { ArrayList<Integer> voxelIds = new ArrayList<Integer>(); for (int layerId : data.getLayers()) { Voxel[] voxels = data.getLayerVoxels(layerId); if (voxels.length > 0) { int count = rand.nextInt(voxels.length); for (int i = 0; i < count; i++) { int pos = rand.nextInt(voxels.length); voxelIds.add(voxels[pos].id); } } } Integer[] voxelIdsStatic = new Integer[voxelIds.size()]; voxelIds.toArray(voxelIdsStatic); data.massSetVoxelSelected(voxelIdsStatic, rand.nextBoolean()); } public void massRemove() { Voxel[] voxels = data.getSelectedVoxels(); Integer[] voxelIds = new Integer[voxels.length]; int i = 0; for (Voxel voxel : voxels) { voxelIds[i++] = voxel.id; } data.massRemoveVoxel(voxelIds); } public void massAdd() { int length = rand.nextInt(20); Voxel[] voxel = new Voxel[length]; int layerId = data.getSelectedLayer(); for (int i = 0; i < length; i++) { voxel[i] = new Voxel(-1, randPos(), randCol(), false, null, layerId); } data.massAddVoxel(voxel); } public void massColor() { Voxel[] voxels = data.getSelectedVoxels(); Integer[] voxelIds = new Integer[voxels.length]; int i = 0; for (Voxel voxel : voxels) { voxelIds[i++] = voxel.id; } data.massSetColor(voxelIds,randCol()); } public void massMove() { data.massMoveVoxel(data.getSelectedVoxels(), randPos()); } public void rotate() { data.rotateVoxelCenter(data.getSelectedVoxels(), rand.nextInt(3), 90 * rand.nextInt(3)); } public void mirror() { data.mirrorVoxel(data.getSelectedVoxels(),rand.nextInt(3)); } } final int poss = 24; for (int seed = 1140; seed < 2000; seed ++) { Util util = new Util(seed); float[] prob = new float[poss]; for (int k = 0; k < prob.length; k++) { prob[k] = util.getFloat(); } for (int k = 0; k < 20000; k++) { switch (util.getInt(poss) + 1) { case 1: if (util.getFloat() < prob[0]) { util.createLayer(); } break; case 2: if (util.getFloat() < prob[1]) { util.deleteLayer(); } break; case 3: if (util.getFloat() < prob[2]) { util.renameLayer(); } break; case 4: if (util.getFloat() < prob[3]) { util.selectLayer(); } break; case 5: if (util.getFloat() < prob[4]) { util.setVisible(); } break; case 6: if (util.getFloat() < prob[5]) { util.moveLayerUp(); } break; case 7: if (util.getFloat() < prob[6]) { util.moveLayerDown(); } break; case 8: if (util.getFloat() < prob[7]) { util.addVoxel(); } break; case 9: if (util.getFloat() < prob[8]) { util.deleteVoxel(); } break; case 10: if (util.getFloat() < prob[9]) { util.moveVoxel(); } break; case 11: if (util.getFloat() < prob[10]) { util.colorVoxel(); } break; case 12: if (util.getFloat() < prob[11]) { util.alphaVoxel(); } break; case 13: if (util.getFloat() < prob[12]) { util.clear(); } break; case 14: if (util.getFloat() < prob[13]) { util.selectLayerSoft(); } break; case 15: if (util.getFloat() < prob[14]) { util.mergeLayers(); } break; case 16: if (util.getFloat() < prob[15]) { util.migrateSelection(); } break; case 17: if (util.getFloat() < prob[16]) { util.massSelect(); } break; case 18: if (util.getFloat() < prob[17]) { util.massRemove(); } break; case 19: if (util.getFloat() < prob[18]) { util.massAdd(); } break; case 20: if (util.getFloat() < prob[19]) { util.massColor(); } break; case 21: if (util.getFloat() < prob[20]) { util.massMove(); } break; case 22: if (util.getFloat() < prob[21]) { util.rotate(); } break; case 23: if (util.getFloat() < prob[22]) { util.mirror(); } break; case 24: if (util.getFloat() < prob[23]) { util.selectVoxel(); } break; default: break; } // if (data.getVoxel(20390) != null) { // data.historyManagerV.debug(); //// System.out.println( //// data.getVoxel(20390).getPosAsInt()[0] + " " + //// data.getVoxel(20390).getPosAsInt()[1] + " " + //// data.getVoxel(20390).getPosAsInt()[2] //// ); //// data.moveVoxel(20390, new int[]{0,0,0}); //// System.out.println( //// data.getVoxel(20390).getPosAsInt()[0] + " " + //// data.getVoxel(20390).getPosAsInt()[1] + " " + //// data.getVoxel(20390).getPosAsInt()[2] //// ); // } } System.out.println(seed); // wind forward while (data.canRedoV()) { data.redoV(); } // store Integer[] layers = data.getLayers(); String[] layerNames = data.getLayerNames(); Voxel[][] layerVoxel = new Voxel[layers.length][]; int c = 0; for (int i : layers) { layerVoxel[c++] = data.getLayerVoxels(i); } // wind backwards while (data.canUndoV()) { data.undoV(); } // assert assert data.getLayers().length == 0; assert data.getLayerNames().length == 0; // wind forward while (data.canRedoV()) { data.redoV(); } // store new version Integer[] layersN = data.getLayers(); String[] layerNamesN = data.getLayerNames(); Voxel[][] layerVoxelN = new Voxel[layers.length][]; c = 0; for (int i : layers) { layerVoxelN[c++] = data.getLayerVoxels(i); } // check assert layersN.length == layers.length; assert layerNamesN.length == layers.length; assert layerNamesN.length == layerNames.length; for (int i = 0; i < layersN.length; i++) { assert layersN[i].equals(layers[i]); assert layerNamesN[i].equals(layerNames[i]); } for (int i = 0; i < layers.length; i++) { for (int j = 0; j < Math.max(layerVoxel[i].length, layerVoxelN[i].length); j++) { assert layerVoxel[i][j].equals(layerVoxelN[i][j]); } } // wind backwards again while (data.canUndoV()) { data.undoV(); } // assert assert data.getLayers().length == 0; assert data.getLayerNames().length == 0; } } }
18,485
6,160
/* * 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.jmeter.gui.action.template; import java.io.File; import java.util.Map; import java.util.Objects; /** * Template Bean * * @since 2.10 */ public class Template { private boolean isTestPlan; private String name; private String fileName; private String description; private transient File parent; // for relative links private Map<String, String> parameters; /** @return the name */ public String getName() { return name; } /** @param name the name to set */ public void setName(String name) { this.name = name; } /** @return the relativeFileName */ public String getFileName() { return fileName; } /** @param relativeFileName the relativeFileName to set */ public void setFileName(String relativeFileName) { fileName = relativeFileName; } /** @return the description */ public String getDescription() { return description; } /** @param description the description to set */ public void setDescription(String description) { this.description = description; } public boolean isTestPlan() { return isTestPlan; } public void setTestPlan(boolean isTestPlan) { this.isTestPlan = isTestPlan; } public File getParent() { return parent; } public void setParent(File parent) { this.parent = parent; } public Map<String, String> getParameters() { return parameters; } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Template other = (Template) o; return isTestPlan == other.isTestPlan && Objects.equals(name, other.name) && Objects.equals(fileName, other.fileName) && Objects.equals(description, other.description) && Objects.equals(parent, other.parent) && Objects.equals(parameters, other.parameters); } @Override public int hashCode() { return Objects.hash(isTestPlan, name, fileName, description, parent, parameters); } @Override public String toString() { return "Template [isTestPlan=" + isTestPlan + ", name=" + name + ", fileName=" + fileName + ", description=" + description + ", parameters=" + parameters + "]"; } }
1,239
2,772
<filename>tests/test_onnxml_binarizer_converter.py """ Tests onnxml Binarizer converter """ import unittest import warnings import numpy as np import torch from sklearn.preprocessing import Binarizer from hummingbird.ml._utils import onnx_ml_tools_installed, onnx_runtime_installed, lightgbm_installed from hummingbird.ml import convert if onnx_runtime_installed(): import onnxruntime as ort if onnx_ml_tools_installed(): from onnxmltools import convert_sklearn from onnxmltools.convert.common.data_types import FloatTensorType as FloatTensorType_onnx class TestONNXBinarizer(unittest.TestCase): def _test_binarizer_converter(self, threshold): warnings.filterwarnings("ignore") X = np.array([[1, 2, 3], [4, 3, 0], [0, 1, 4], [0, 5, 6]], dtype=np.float32) # Create SKL model for testing model = Binarizer(threshold=threshold) model.fit(X) # Create ONNX-ML model onnx_ml_model = convert_sklearn(model, initial_types=[("float_input", FloatTensorType_onnx(X.shape))]) # Create ONNX model by calling converter onnx_model = convert(onnx_ml_model, "onnx", X) # Get the predictions for the ONNX-ML model session = ort.InferenceSession(onnx_ml_model.SerializeToString()) output_names = [session.get_outputs()[i].name for i in range(len(session.get_outputs()))] inputs = {session.get_inputs()[0].name: X} onnx_ml_pred = session.run(output_names, inputs)[0] # Get the predictions for the ONNX model onnx_pred = onnx_model.transform(X) return onnx_ml_pred, onnx_pred @unittest.skipIf( not (onnx_ml_tools_installed() and onnx_runtime_installed()), reason="ONNXML test requires ONNX, ORT and ONNXMLTOOLS" ) # Check 0.0 threshold def test_binarizer_converter_0thresh(self, rtol=1e-06, atol=1e-06): onnx_ml_pred, onnx_pred = self._test_binarizer_converter(0.0) np.testing.assert_allclose(onnx_ml_pred, onnx_pred, rtol=rtol, atol=atol) @unittest.skipIf( not (onnx_ml_tools_installed() and onnx_runtime_installed()), reason="ONNXML test requires ONNX, ORT and ONNXMLTOOLS" ) # Check positive threshold def test_binarizer_converter_posthresh(self, rtol=1e-06, atol=1e-06): onnx_ml_pred, onnx_pred = self._test_binarizer_converter(2.0) # Check that predicted values match np.testing.assert_allclose(onnx_ml_pred, onnx_pred, rtol=rtol, atol=atol) @unittest.skipIf( not (onnx_ml_tools_installed() and onnx_runtime_installed()), reason="ONNXML test requires ONNX, ORT and ONNXMLTOOLS" ) # Check neg threshold def test_binarizer_converter_negthresh(self, rtol=1e-06, atol=1e-06): onnx_ml_pred, onnx_pred = self._test_binarizer_converter(-2.0) # Check that predicted values match np.testing.assert_allclose(onnx_ml_pred, onnx_pred, rtol=rtol, atol=atol) @unittest.skipIf( not (onnx_ml_tools_installed() and onnx_runtime_installed()), reason="ONNXML test requires ONNX, ORT and ONNXMLTOOLS" ) # if the model is corrupt, we should get a RuntimeError def test_onnx_binarizer_converter_raises_rt(self): warnings.filterwarnings("ignore") X = np.array([[1, 2, 3], [4, 3, 0], [0, 1, 4], [0, 5, 6]], dtype=np.float32) model = Binarizer(threshold=0) model.fit(X) # generate test input onnx_ml_model = convert_sklearn(model, initial_types=[("float_input", FloatTensorType_onnx(X.shape))]) onnx_ml_model.graph.node[0].attribute[0].name = "".encode() self.assertRaises(RuntimeError, convert, onnx_ml_model, "onnx", X) @unittest.skipIf( not (onnx_ml_tools_installed() and onnx_runtime_installed()), reason="ONNXML test requires ONNX, ORT and ONNXMLTOOLS" ) # if the user doesn't add test input when converting to torch, we should get an error def test_onnx_binarizer_converter_raises_rt_no_input(self): warnings.filterwarnings("ignore") X = np.array([[1, 2, 3], [4, 3, 0], [0, 1, 4], [0, 5, 6]], dtype=np.float32) model = Binarizer(threshold=0) model.fit(X) # generate test input onnx_ml_model = convert_sklearn(model, initial_types=[("float_input", FloatTensorType_onnx(X.shape))]) onnx_ml_model.graph.node[0].attribute[0].name = "".encode() self.assertRaises(RuntimeError, convert, onnx_ml_model, "torch") if __name__ == "__main__": unittest.main()
1,990
1,097
// // HCPXmlConfigParser.h // // Created by <NAME> on 07.08.15. // #import <Foundation/Foundation.h> #import "HCPXmlConfig.h" /** * XML parser for Cordova's config.xml. * Used to read plugin specific preferences. */ @interface HCPXmlConfigParser : NSObject /** * Parse the config and return only plugin specific preferences. * * @return plugin preferences from config.xml * * @see HCPXmlConfig */ + (HCPXmlConfig *)parse; @end
156
1,444
package mage.abilities.effects.common; import mage.abilities.Ability; import mage.abilities.dynamicvalue.DynamicValue; import mage.abilities.dynamicvalue.common.StaticValue; import mage.abilities.effects.OneShotEffect; import mage.constants.Outcome; import mage.constants.Zone; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; public class LoseLifeControllerAttachedEffect extends OneShotEffect { protected DynamicValue amount; public LoseLifeControllerAttachedEffect(int amount) { this(StaticValue.get(amount)); } public LoseLifeControllerAttachedEffect(DynamicValue amount) { super(Outcome.LoseLife); this.amount = amount; setText(); } public LoseLifeControllerAttachedEffect(final LoseLifeControllerAttachedEffect effect) { super(effect); this.amount = effect.amount.copy(); } @Override public LoseLifeControllerAttachedEffect copy() { return new LoseLifeControllerAttachedEffect(this); } @Override public boolean apply(Game game, Ability source) { Permanent enchantment = game.getPermanent(source.getSourceId()); if (enchantment == null) { enchantment = (Permanent) game.getLastKnownInformation(source.getSourceId(), Zone.BATTLEFIELD); } if (enchantment != null && enchantment.getAttachedTo() != null) { Permanent creature = game.getPermanent(enchantment.getAttachedTo()); if (creature == null) { creature = (Permanent) game.getLastKnownInformation(source.getSourceId(), Zone.BATTLEFIELD); } if (creature != null) { Player player = game.getPlayer(creature.getControllerId()); if (player != null) { player.loseLife(amount.calculate(game, source, this), game, source, false); return true; } } } return false; } private void setText() { StringBuilder sb = new StringBuilder(); sb.append("its controller loses ").append(amount.toString()).append(" life"); String message = amount.getMessage(); if (!message.isEmpty()) { sb.append(" for each "); sb.append(message); } staticText = sb.toString(); } }
930
839
<gh_stars>100-1000 /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.jaxrs.swagger; import java.net.URL; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.cxf.jaxrs.ext.MessageContext; import org.apache.cxf.jaxrs.model.ClassResourceInfo; import org.apache.cxf.jaxrs.model.OperationResourceInfo; import org.apache.cxf.jaxrs.model.doc.DocumentationProvider; import org.apache.cxf.jaxrs.model.doc.JavaDocProvider; import org.apache.cxf.jaxrs.utils.JAXRSUtils; import io.swagger.jaxrs.config.BeanConfig; import io.swagger.models.HttpMethod; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; import io.swagger.models.Tag; import io.swagger.models.parameters.Parameter; public class Swagger2Customizer { protected boolean dynamicBasePath; protected boolean replaceTags; protected boolean applyDefaultVersion = true; protected DocumentationProvider javadocProvider; protected List<ClassResourceInfo> cris; protected BeanConfig beanConfig; public Swagger customize(Swagger data) { if (dynamicBasePath) { MessageContext ctx = createMessageContext(); String currentBasePath = StringUtils.substringBeforeLast(ctx.getHttpServletRequest().getRequestURI(), "/"); data.setBasePath(currentBasePath); if (data.getHost() == null) { data.setHost(beanConfig.getHost()); } if (data.getInfo() == null) { data.setInfo(beanConfig.getInfo()); } if (beanConfig.getSwagger() != null && beanConfig.getSwagger().getSecurityDefinitions() != null && data.getSecurityDefinitions() == null) { data.setSecurityDefinitions(beanConfig.getSwagger().getSecurityDefinitions()); } } if (replaceTags || javadocProvider != null) { Map<String, ClassResourceInfo> operations = new HashMap<>(); Map<Pair<String, String>, OperationResourceInfo> methods = new HashMap<>(); for (ClassResourceInfo cri : cris) { for (OperationResourceInfo ori : cri.getMethodDispatcher().getOperationResourceInfos()) { String normalizedPath = getNormalizedPath( cri.getURITemplate().getValue(), ori.getURITemplate().getValue()); operations.put(normalizedPath, cri); methods.put(ImmutablePair.of(ori.getHttpMethod(), normalizedPath), ori); } } if (replaceTags && data.getTags() != null) { data.getTags().clear(); } for (final Map.Entry<String, Path> entry : data.getPaths().entrySet()) { Tag tag = null; if (replaceTags && operations.containsKey(entry.getKey())) { ClassResourceInfo cri = operations.get(entry.getKey()); tag = new Tag(); tag.setName(cri.getURITemplate().getValue().replaceAll("/", "_")); if (javadocProvider != null) { tag.setDescription(javadocProvider.getClassDoc(cri)); } data.addTag(tag); } for (Map.Entry<HttpMethod, Operation> subentry : entry.getValue().getOperationMap().entrySet()) { if (replaceTags && tag != null) { subentry.getValue().setTags(Collections.singletonList(tag.getName())); } Pair<String, String> key = ImmutablePair.of(subentry.getKey().name(), entry.getKey()); if (methods.containsKey(key) && javadocProvider != null) { OperationResourceInfo ori = methods.get(key); subentry.getValue().setSummary(javadocProvider.getMethodDoc(ori)); for (int i = 0; i < subentry.getValue().getParameters().size(); i++) { subentry.getValue().getParameters().get(i). setDescription(javadocProvider.getMethodParameterDoc(ori, i)); } addParameters(subentry.getValue().getParameters()); if (subentry.getValue().getResponses() != null && !subentry.getValue().getResponses().isEmpty()) { subentry.getValue().getResponses().entrySet().iterator().next().getValue(). setDescription(javadocProvider.getMethodResponseDoc(ori)); } } } } } if (replaceTags && data.getTags() != null) { Collections.sort(data.getTags(), new Comparator<Tag>() { @Override public int compare(final Tag tag1, final Tag tag2) { return tag1.getName().compareTo(tag2.getName()); } }); } applyDefaultVersion(data); return data; } private MessageContext createMessageContext() { return JAXRSUtils.createContextValue( JAXRSUtils.getCurrentMessage(), null, MessageContext.class); } protected String getNormalizedPath(String classResourcePath, String operationResourcePath) { StringBuilder normalizedPath = new StringBuilder(); String[] segments = (classResourcePath + operationResourcePath).split("/"); for (String segment : segments) { if (!StringUtils.isEmpty(segment)) { normalizedPath.append('/').append(segment); } } // Adapt to Swagger's path expression if (normalizedPath.toString().endsWith(":.*}")) { normalizedPath.setLength(normalizedPath.length() - 4); normalizedPath.append('}'); } return StringUtils.EMPTY.equals(normalizedPath.toString()) ? "/" : normalizedPath.toString(); } protected void applyDefaultVersion(Swagger data) { if (applyDefaultVersion && data.getInfo() != null && data.getInfo().getVersion() == null && beanConfig != null && beanConfig.getResourcePackage() != null) { Package resourcePackage = Package.getPackage(beanConfig.getResourcePackage()); if (resourcePackage != null) { data.getInfo().setVersion(resourcePackage.getImplementationVersion()); } } } /** * Allows to add parameters to the list, related to an {@link Operation} instance; the method is invoked * for all instances available. * * @param parameters list of parameters defined for an {@link Operation} * @see io.swagger.models.parameters.HeaderParameter * @see io.swagger.models.parameters.CookieParameter * @see io.swagger.models.parameters.PathParameter * @see io.swagger.models.parameters.BodyParameter * @see io.swagger.models.parameters.QueryParameter * @see io.swagger.models.parameters.RefParameter */ protected void addParameters(final List<Parameter> parameters) { // does nothing by default } public void setDynamicBasePath(final boolean dynamicBasePath) { this.dynamicBasePath = dynamicBasePath; } public void setReplaceTags(final boolean replaceTags) { this.replaceTags = replaceTags; } public void setJavadocProvider(final DocumentationProvider javadocProvider) { this.javadocProvider = javadocProvider; } public void setClassResourceInfos(final List<ClassResourceInfo> classResourceInfos) { this.cris = classResourceInfos; } public void setJavaDocPath(final String javaDocPath) throws Exception { this.javadocProvider = new JavaDocProvider(javaDocPath); } public void setJavaDocPaths(final String... javaDocPaths) throws Exception { this.javadocProvider = new JavaDocProvider(javaDocPaths); } public void setJavaDocURLs(final URL[] javaDocURLs) { this.javadocProvider = new JavaDocProvider(javaDocURLs); } public void setBeanConfig(BeanConfig beanConfig) { this.beanConfig = beanConfig; } public void setApplyDefaultVersion(boolean applyDefaultVersion) { this.applyDefaultVersion = applyDefaultVersion; } }
3,911
732
<reponame>whitemike889/afdko<gh_stars>100-1000 /* Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved. This software is licensed as OpenSource, under the Apache License, Version 2.0. This license is available at: http://opensource.org/licenses/Apache-2.0. */ /* Mac OS Romanian aggregate Unicode initializer. Element values are UVs. UV_UNDEF is 0xFFFF. Index by code, get UV. Source: ftp://ftp.unicode.org/Public/MAPPINGS/VENDORS/APPLE/ROMANIAN.TXT as of 9/9/99, with EURO SIGN replacing CURRENCY SIGN. 4 entries are mapped to Unicode 3.0 values for which Apple has defined a decomposition sequence in the source file above. The decomposition sequence is shown in parentheses for such mappings. */ UV_UNDEF, /* 00 */ UV_UNDEF, /* 01 */ UV_UNDEF, /* 02 */ UV_UNDEF, /* 03 */ UV_UNDEF, /* 04 */ UV_UNDEF, /* 05 */ UV_UNDEF, /* 06 */ UV_UNDEF, /* 07 */ UV_UNDEF, /* 08 */ UV_UNDEF, /* 09 */ UV_UNDEF, /* 0A */ UV_UNDEF, /* 0B */ UV_UNDEF, /* 0C */ UV_UNDEF, /* 0D */ UV_UNDEF, /* 0E */ UV_UNDEF, /* 0F */ UV_UNDEF, /* 10 */ UV_UNDEF, /* 11 */ UV_UNDEF, /* 12 */ UV_UNDEF, /* 13 */ UV_UNDEF, /* 14 */ UV_UNDEF, /* 15 */ UV_UNDEF, /* 16 */ UV_UNDEF, /* 17 */ UV_UNDEF, /* 18 */ UV_UNDEF, /* 19 */ UV_UNDEF, /* 1A */ UV_UNDEF, /* 1B */ UV_UNDEF, /* 1C */ UV_UNDEF, /* 1D */ UV_UNDEF, /* 1E */ UV_UNDEF, /* 1F */ 0x0020, /* 20 SPACE */ 0x0021, /* 21 EXCLAMATION MARK */ 0x0022, /* 22 QUOTATION MARK */ 0x0023, /* 23 NUMBER SIGN */ 0x0024, /* 24 DOLLAR SIGN */ 0x0025, /* 25 PERCENT SIGN */ 0x0026, /* 26 AMPERSAND */ 0x0027, /* 27 APOSTROPHE */ 0x0028, /* 28 LEFT PARENTHESIS */ 0x0029, /* 29 RIGHT PARENTHESIS */ 0x002A, /* 2A ASTERISK */ 0x002B, /* 2B PLUS SIGN */ 0x002C, /* 2C COMMA */ 0x002D, /* 2D HYPHEN-MINUS */ 0x002E, /* 2E FULL STOP */ 0x002F, /* 2F SOLIDUS */ 0x0030, /* 30 DIGIT ZERO */ 0x0031, /* 31 DIGIT ONE */ 0x0032, /* 32 DIGIT TWO */ 0x0033, /* 33 DIGIT THREE */ 0x0034, /* 34 DIGIT FOUR */ 0x0035, /* 35 DIGIT FIVE */ 0x0036, /* 36 DIGIT SIX */ 0x0037, /* 37 DIGIT SEVEN */ 0x0038, /* 38 DIGIT EIGHT */ 0x0039, /* 39 DIGIT NINE */ 0x003A, /* 3A COLON */ 0x003B, /* 3B SEMICOLON */ 0x003C, /* 3C LESS-THAN SIGN */ 0x003D, /* 3D EQUALS SIGN */ 0x003E, /* 3E GREATER-THAN SIGN */ 0x003F, /* 3F QUESTION MARK */ 0x0040, /* 40 COMMERCIAL AT */ 0x0041, /* 41 LATIN CAPITAL LETTER A */ 0x0042, /* 42 LATIN CAPITAL LETTER B */ 0x0043, /* 43 LATIN CAPITAL LETTER C */ 0x0044, /* 44 LATIN CAPITAL LETTER D */ 0x0045, /* 45 LATIN CAPITAL LETTER E */ 0x0046, /* 46 LATIN CAPITAL LETTER F */ 0x0047, /* 47 LATIN CAPITAL LETTER G */ 0x0048, /* 48 LATIN CAPITAL LETTER H */ 0x0049, /* 49 LATIN CAPITAL LETTER I */ 0x004A, /* 4A LATIN CAPITAL LETTER J */ 0x004B, /* 4B LATIN CAPITAL LETTER K */ 0x004C, /* 4C LATIN CAPITAL LETTER L */ 0x004D, /* 4D LATIN CAPITAL LETTER M */ 0x004E, /* 4E LATIN CAPITAL LETTER N */ 0x004F, /* 4F LATIN CAPITAL LETTER O */ 0x0050, /* 50 LATIN CAPITAL LETTER P */ 0x0051, /* 51 LATIN CAPITAL LETTER Q */ 0x0052, /* 52 LATIN CAPITAL LETTER R */ 0x0053, /* 53 LATIN CAPITAL LETTER S */ 0x0054, /* 54 LATIN CAPITAL LETTER T */ 0x0055, /* 55 LATIN CAPITAL LETTER U */ 0x0056, /* 56 LATIN CAPITAL LETTER V */ 0x0057, /* 57 LATIN CAPITAL LETTER W */ 0x0058, /* 58 LATIN CAPITAL LETTER X */ 0x0059, /* 59 LATIN CAPITAL LETTER Y */ 0x005A, /* 5A LATIN CAPITAL LETTER Z */ 0x005B, /* 5B LEFT SQUARE BRACKET */ 0x005C, /* 5C REVERSE SOLIDUS */ 0x005D, /* 5D RIGHT SQUARE BRACKET */ 0x005E, /* 5E CIRCUMFLEX ACCENT */ 0x005F, /* 5F LOW LINE */ 0x0060, /* 60 GRAVE ACCENT */ 0x0061, /* 61 LATIN SMALL LETTER A */ 0x0062, /* 62 LATIN SMALL LETTER B */ 0x0063, /* 63 LATIN SMALL LETTER C */ 0x0064, /* 64 LATIN SMALL LETTER D */ 0x0065, /* 65 LATIN SMALL LETTER E */ 0x0066, /* 66 LATIN SMALL LETTER F */ 0x0067, /* 67 LATIN SMALL LETTER G */ 0x0068, /* 68 LATIN SMALL LETTER H */ 0x0069, /* 69 LATIN SMALL LETTER I */ 0x006A, /* 6A LATIN SMALL LETTER J */ 0x006B, /* 6B LATIN SMALL LETTER K */ 0x006C, /* 6C LATIN SMALL LETTER L */ 0x006D, /* 6D LATIN SMALL LETTER M */ 0x006E, /* 6E LATIN SMALL LETTER N */ 0x006F, /* 6F LATIN SMALL LETTER O */ 0x0070, /* 70 LATIN SMALL LETTER P */ 0x0071, /* 71 LATIN SMALL LETTER Q */ 0x0072, /* 72 LATIN SMALL LETTER R */ 0x0073, /* 73 LATIN SMALL LETTER S */ 0x0074, /* 74 LATIN SMALL LETTER T */ 0x0075, /* 75 LATIN SMALL LETTER U */ 0x0076, /* 76 LATIN SMALL LETTER V */ 0x0077, /* 77 LATIN SMALL LETTER W */ 0x0078, /* 78 LATIN SMALL LETTER X */ 0x0079, /* 79 LATIN SMALL LETTER Y */ 0x007A, /* 7A LATIN SMALL LETTER Z */ 0x007B, /* 7B LEFT CURLY BRACKET */ 0x007C, /* 7C VERTICAL LINE */ 0x007D, /* 7D RIGHT CURLY BRACKET */ 0x007E, /* 7E TILDE */ UV_UNDEF, /* 7F */ 0x00C4, /* 80 LATIN CAPITAL LETTER A WITH DIAERESIS */ 0x00C5, /* 81 LATIN CAPITAL LETTER A WITH RING ABOVE */ 0x00C7, /* 82 LATIN CAPITAL LETTER C WITH CEDILLA */ 0x00C9, /* 83 LATIN CAPITAL LETTER E WITH ACUTE */ 0x00D1, /* 84 LATIN CAPITAL LETTER N WITH TILDE */ 0x00D6, /* 85 LATIN CAPITAL LETTER O WITH DIAERESIS */ 0x00DC, /* 86 LATIN CAPITAL LETTER U WITH DIAERESIS */ 0x00E1, /* 87 LATIN SMALL LETTER A WITH ACUTE */ 0x00E0, /* 88 LATIN SMALL LETTER A WITH GRAVE */ 0x00E2, /* 89 LATIN SMALL LETTER A WITH CIRCUMFLEX */ 0x00E4, /* 8A LATIN SMALL LETTER A WITH DIAERESIS */ 0x00E3, /* 8B LATIN SMALL LETTER A WITH TILDE */ 0x00E5, /* 8C LATIN SMALL LETTER A WITH RING ABOVE */ 0x00E7, /* 8D LATIN SMALL LETTER C WITH CEDILLA */ 0x00E9, /* 8E LATIN SMALL LETTER E WITH ACUTE */ 0x00E8, /* 8F LATIN SMALL LETTER E WITH GRAVE */ 0x00EA, /* 90 LATIN SMALL LETTER E WITH CIRCUMFLEX */ 0x00EB, /* 91 LATIN SMALL LETTER E WITH DIAERESIS */ 0x00ED, /* 92 LATIN SMALL LETTER I WITH ACUTE */ 0x00EC, /* 93 LATIN SMALL LETTER I WITH GRAVE */ 0x00EE, /* 94 LATIN SMALL LETTER I WITH CIRCUMFLEX */ 0x00EF, /* 95 LATIN SMALL LETTER I WITH DIAERESIS */ 0x00F1, /* 96 LATIN SMALL LETTER N WITH TILDE */ 0x00F3, /* 97 LATIN SMALL LETTER O WITH ACUTE */ 0x00F2, /* 98 LATIN SMALL LETTER O WITH GRAVE */ 0x00F4, /* 99 LATIN SMALL LETTER O WITH CIRCUMFLEX */ 0x00F6, /* 9A LATIN SMALL LETTER O WITH DIAERESIS */ 0x00F5, /* 9B LATIN SMALL LETTER O WITH TILDE */ 0x00FA, /* 9C LATIN SMALL LETTER U WITH ACUTE */ 0x00F9, /* 9D LATIN SMALL LETTER U WITH GRAVE */ 0x00FB, /* 9E LATIN SMALL LETTER U WITH CIRCUMFLEX */ 0x00FC, /* 9F LATIN SMALL LETTER U WITH DIAERESIS */ 0x2020, /* A0 DAGGER */ 0x00B0, /* A1 DEGREE SIGN */ 0x00A2, /* A2 CENT SIGN */ 0x00A3, /* A3 POUND SIGN */ 0x00A7, /* A4 SECTION SIGN */ 0x2022, /* A5 BULLET */ 0x00B6, /* A6 PILCROW SIGN */ 0x00DF, /* A7 LATIN SMALL LETTER SHARP S */ 0x00AE, /* A8 REGISTERED SIGN */ 0x00A9, /* A9 COPYRIGHT SIGN */ 0x2122, /* AA TRADE MARK SIGN */ 0x00B4, /* AB ACUTE ACCENT */ 0x00A8, /* AC DIAERESIS */ 0x2260, /* AD NOT EQUAL TO */ 0x0102, /* AE LATIN CAPITAL LETTER A WITH BREVE */ 0x0218, /* AF LATIN CAPITAL LETTER S + COMBINING COMMA BELOW (0x0053+0x0326) */ 0x221E, /* B0 INFINITY */ 0x00B1, /* B1 PLUS-MINUS SIGN */ 0x2264, /* B2 LESS-THAN OR EQUAL TO */ 0x2265, /* B3 GREATER-THAN OR EQUAL TO */ 0x00A5, /* B4 YEN SIGN */ 0x00B5, /* B5 MICRO SIGN */ 0x2202, /* B6 PARTIAL DIFFERENTIAL */ 0x2211, /* B7 N-ARY SUMMATION */ 0x220F, /* B8 N-ARY PRODUCT */ 0x03C0, /* B9 GREEK SMALL LETTER PI */ 0x222B, /* BA INTEGRAL */ 0x00AA, /* BB FEMININE ORDINAL INDICATOR */ 0x00BA, /* BC MASCULINE ORDINAL INDICATOR */ 0x03A9, /* BD GREEK CAPITAL LETTER OMEGA */ 0x0103, /* BE LATIN SMALL LETTER A WITH BREVE */ 0x0219, /* BF LATIN SMALL LETTER S + COMBINING COMMA BELOW (0x0073+0x0326) */ 0x00BF, /* C0 INVERTED QUESTION MARK */ 0x00A1, /* C1 INVERTED EXCLAMATION MARK */ 0x00AC, /* C2 NOT SIGN */ 0x221A, /* C3 SQUARE ROOT */ 0x0192, /* C4 LATIN SMALL LETTER F WITH HOOK */ 0x2248, /* C5 ALMOST EQUAL TO */ 0x2206, /* C6 INCREMENT */ 0x00AB, /* C7 LEFT-POINTING DOUBLE ANGLE QUOTATION MARK */ 0x00BB, /* C8 RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK */ 0x2026, /* C9 HORIZONTAL ELLIPSIS */ 0x00A0, /* CA NO-BREAK SPACE */ 0x00C0, /* CB LATIN CAPITAL LETTER A WITH GRAVE */ 0x00C3, /* CC LATIN CAPITAL LETTER A WITH TILDE */ 0x00D5, /* CD LATIN CAPITAL LETTER O WITH TILDE */ 0x0152, /* CE LATIN CAPITAL LIGATURE OE */ 0x0153, /* CF LATIN SMALL LIGATURE OE */ 0x2013, /* D0 EN DASH */ 0x2014, /* D1 EM DASH */ 0x201C, /* D2 LEFT DOUBLE QUOTATION MARK */ 0x201D, /* D3 RIGHT DOUBLE QUOTATION MARK */ 0x2018, /* D4 LEFT SINGLE QUOTATION MARK */ 0x2019, /* D5 RIGHT SINGLE QUOTATION MARK */ 0x00F7, /* D6 DIVISION SIGN */ 0x25CA, /* D7 LOZENGE */ 0x00FF, /* D8 LATIN SMALL LETTER Y WITH DIAERESIS */ 0x0178, /* D9 LATIN CAPITAL LETTER Y WITH DIAERESIS */ 0x2044, /* DA FRACTION SLASH */ 0x20AC, /* DB EURO SIGN */ 0x2039, /* DC SINGLE LEFT-POINTING ANGLE QUOTATION MARK */ 0x203A, /* DD SINGLE RIGHT-POINTING ANGLE QUOTATION MARK */ 0x021A, /* DE LATIN CAPITAL LETTER T + COMBINING COMMA BELOW (0x0054+0x0326) */ 0x021B, /* DF LATIN SMALL LETTER T + COMBINING COMMA BELOW (0x0074+0x0326) */ 0x2021, /* E0 DOUBLE DAGGER */ 0x00B7, /* E1 MIDDLE DOT */ 0x201A, /* E2 SINGLE LOW-9 QUOTATION MARK */ 0x201E, /* E3 DOUBLE LOW-9 QUOTATION MARK */ 0x2030, /* E4 PER MILLE SIGN */ 0x00C2, /* E5 LATIN CAPITAL LETTER A WITH CIRCUMFLEX */ 0x00CA, /* E6 LATIN CAPITAL LETTER E WITH CIRCUMFLEX */ 0x00C1, /* E7 LATIN CAPITAL LETTER A WITH ACUTE */ 0x00CB, /* E8 LATIN CAPITAL LETTER E WITH DIAERESIS */ 0x00C8, /* E9 LATIN CAPITAL LETTER E WITH GRAVE */ 0x00CD, /* EA LATIN CAPITAL LETTER I WITH ACUTE */ 0x00CE, /* EB LATIN CAPITAL LETTER I WITH CIRCUMFLEX */ 0x00CF, /* EC LATIN CAPITAL LETTER I WITH DIAERESIS */ 0x00CC, /* ED LATIN CAPITAL LETTER I WITH GRAVE */ 0x00D3, /* EE LATIN CAPITAL LETTER O WITH ACUTE */ 0x00D4, /* EF LATIN CAPITAL LETTER O WITH CIRCUMFLEX */ 0xF8FF, /* F0 Apple logo */ 0x00D2, /* F1 LATIN CAPITAL LETTER O WITH GRAVE */ 0x00DA, /* F2 LATIN CAPITAL LETTER U WITH ACUTE */ 0x00DB, /* F3 LATIN CAPITAL LETTER U WITH CIRCUMFLEX */ 0x00D9, /* F4 LATIN CAPITAL LETTER U WITH GRAVE */ 0x0131, /* F5 LATIN SMALL LETTER DOTLESS I */ 0x02C6, /* F6 MODIFIER LETTER CIRCUMFLEX ACCENT */ 0x02DC, /* F7 SMALL TILDE */ 0x00AF, /* F8 MACRON */ 0x02D8, /* F9 BREVE */ 0x02D9, /* FA DOT ABOVE */ 0x02DA, /* FB RING ABOVE */ 0x00B8, /* FC CEDILLA */ 0x02DD, /* FD DOUBLE ACUTE ACCENT */ 0x02DB, /* FE OGONEK */ 0x02C7, /* FF CARON */
5,610
32,544
package com.baeldung.restassured.learner; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @Service class CourseService { private static final Map<String, Course> COURSE_MAP = new ConcurrentHashMap<>(); static { Course wizardry = new Course("Wizardry"); COURSE_MAP.put(wizardry.getCode(), wizardry); } Collection<Course> getCourses() { return COURSE_MAP.values(); } Course getCourse(String code) { return Optional.ofNullable(COURSE_MAP.get(code)).orElseThrow(() -> new CourseNotFoundException(code)); } }
251