max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
625
#include "side_effect.h" #include "sir/util/irtools.h" #include "sir/util/operator.h" namespace seq { namespace ir { namespace analyze { namespace module { namespace { struct VarUseAnalyzer : public util::Operator { std::unordered_map<id_t, long> varCounts; std::unordered_map<id_t, long> varAssignCounts; void preHook(Node *v) override { for (auto *var : v->getUsedVariables()) { ++varCounts[var->getId()]; } } void handle(AssignInstr *v) override { ++varAssignCounts[v->getLhs()->getId()]; } }; struct SideEfectAnalyzer : public util::ConstVisitor { static const std::string PURE_ATTR; static const std::string NON_PURE_ATTR; VarUseAnalyzer &vua; bool globalAssignmentHasSideEffects; std::unordered_map<id_t, bool> result; bool exprSE; bool funcSE; // We have to sometimes be careful with globals since future // IR passes might introduce globals that we've eliminated // or demoted earlier. Hence the distinction with whether // global assignments are considered to have side effects. SideEfectAnalyzer(VarUseAnalyzer &vua, bool globalAssignmentHasSideEffects) : util::ConstVisitor(), vua(vua), globalAssignmentHasSideEffects(globalAssignmentHasSideEffects), result(), exprSE(true), funcSE(false) {} template <typename T> bool has(const T *v) { return result.find(v->getId()) != result.end(); } template <typename T> void set(const T *v, bool hasSideEffect, bool hasFuncSideEffect = false) { result[v->getId()] = exprSE = hasSideEffect; funcSE |= hasFuncSideEffect; } template <typename T> bool process(const T *v) { if (!v) return false; if (has(v)) return result[v->getId()]; v->accept(*this); seqassert(has(v), "node not added to results"); return result[v->getId()]; } void visit(const Module *v) override { process(v->getMainFunc()); for (auto *x : *v) { process(x); } } void visit(const Var *v) override { set(v, false); } void visit(const BodiedFunc *v) override { const bool pure = util::hasAttribute(v, PURE_ATTR); const bool nonPure = util::hasAttribute(v, NON_PURE_ATTR); set(v, !pure, !pure); // avoid infinite recursion bool oldFuncSE = funcSE; funcSE = false; process(v->getBody()); set(v, nonPure || (funcSE && !pure)); funcSE = oldFuncSE; } void visit(const ExternalFunc *v) override { set(v, !util::hasAttribute(v, PURE_ATTR)); } void visit(const InternalFunc *v) override { set(v, false); } void visit(const LLVMFunc *v) override { set(v, !util::hasAttribute(v, PURE_ATTR)); } void visit(const VarValue *v) override { set(v, false); } void visit(const PointerValue *v) override { set(v, false); } void visit(const SeriesFlow *v) override { bool s = false; for (auto *x : *v) { s |= process(x); } set(v, s); } void visit(const IfFlow *v) override { set(v, process(v->getCond()) | process(v->getTrueBranch()) | process(v->getFalseBranch())); } void visit(const WhileFlow *v) override { set(v, process(v->getCond()) | process(v->getBody())); } void visit(const ForFlow *v) override { bool s = process(v->getIter()) | process(v->getBody()); if (auto *sched = v->getSchedule()) { for (auto *x : sched->getUsedValues()) { s |= process(x); } } set(v, s); } void visit(const ImperativeForFlow *v) override { bool s = process(v->getStart()) | process(v->getEnd()) | process(v->getBody()); if (auto *sched = v->getSchedule()) { for (auto *x : sched->getUsedValues()) { s |= process(x); } } set(v, s); } void visit(const TryCatchFlow *v) override { bool s = process(v->getBody()) | process(v->getFinally()); for (auto &x : *v) { s |= process(x.getHandler()); } set(v, s); } void visit(const PipelineFlow *v) override { bool s = false; bool callSE = false; for (auto &stage : *v) { // make sure we're treating this as a call if (auto *f = util::getFunc(stage.getCallee())) { bool stageCallSE = process(f); callSE |= stageCallSE; s |= stageCallSE; } else { // unknown function process(stage.getCallee()); s = true; } for (auto *arg : stage) { s |= process(arg); } } set(v, s, callSE); } void visit(const dsl::CustomFlow *v) override { bool s = v->hasSideEffect(); set(v, s, s); } void visit(const IntConst *v) override { set(v, false); } void visit(const FloatConst *v) override { set(v, false); } void visit(const BoolConst *v) override { set(v, false); } void visit(const StringConst *v) override { set(v, false); } void visit(const dsl::CustomConst *v) override { set(v, false); } void visit(const AssignInstr *v) override { auto id = v->getLhs()->getId(); auto it1 = vua.varCounts.find(id); auto it2 = vua.varAssignCounts.find(id); auto count1 = (it1 != vua.varCounts.end()) ? it1->second : 0; auto count2 = (it2 != vua.varAssignCounts.end()) ? it2->second : 0; bool g = v->getLhs()->isGlobal(); bool s = (count1 != count2); if (globalAssignmentHasSideEffects) { set(v, s | g | process(v->getRhs()), g); } else { set(v, s | process(v->getRhs()), s & g); } } void visit(const ExtractInstr *v) override { set(v, process(v->getVal())); } void visit(const InsertInstr *v) override { process(v->getLhs()); process(v->getRhs()); set(v, true, true); } void visit(const CallInstr *v) override { bool s = false; bool callSE = true; for (auto *x : *v) { s |= process(x); } if (auto *f = util::getFunc(v->getCallee())) { callSE = process(f); s |= callSE; } else { // unknown function process(v->getCallee()); s = true; } set(v, s, callSE); } void visit(const StackAllocInstr *v) override { set(v, false); } void visit(const TypePropertyInstr *v) override { set(v, false); } void visit(const YieldInInstr *v) override { set(v, true); } void visit(const TernaryInstr *v) override { set(v, process(v->getCond()) | process(v->getTrueValue()) | process(v->getFalseValue())); } void visit(const BreakInstr *v) override { set(v, true); } void visit(const ContinueInstr *v) override { set(v, true); } void visit(const ReturnInstr *v) override { process(v->getValue()); set(v, true); } void visit(const YieldInstr *v) override { process(v->getValue()); set(v, true); } void visit(const ThrowInstr *v) override { process(v->getValue()); set(v, true, true); } void visit(const FlowInstr *v) override { set(v, process(v->getFlow()) | process(v->getValue())); } void visit(const dsl::CustomInstr *v) override { bool s = v->hasSideEffect(); set(v, s, s); } }; const std::string SideEfectAnalyzer::PURE_ATTR = "std.internal.attributes.pure"; const std::string SideEfectAnalyzer::NON_PURE_ATTR = "std.internal.attributes.nonpure"; } // namespace const std::string SideEffectAnalysis::KEY = "core-analyses-side-effect"; bool SideEffectResult::hasSideEffect(Value *v) const { auto it = result.find(v->getId()); return it == result.end() || it->second; } std::unique_ptr<Result> SideEffectAnalysis::run(const Module *m) { VarUseAnalyzer vua; const_cast<Module *>(m)->accept(vua); SideEfectAnalyzer sea(vua, globalAssignmentHasSideEffects); m->accept(sea); return std::make_unique<SideEffectResult>(sea.result); } } // namespace module } // namespace analyze } // namespace ir } // namespace seq
3,030
432
<reponame>lambdaxymox/DragonFlyBSD /* $NetBSD: hack.monst.c,v 1.7 2011/08/16 09:26:22 christos Exp $ */ /* * Copyright (c) 1985, Stichting Centrum voor Wiskunde en Informatica, * Amsterdam * 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 Stichting Centrum voor Wiskunde en * Informatica, 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. */ /* * Copyright (c) 1982 <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "hack.h" #include "extern.h" #include "def.eshk.h" const struct permonst mons[CMNUM + 2] = { {"bat", 'B', 1, 22, 8, 1, 4, 0}, {"gnome", 'G', 1, 6, 5, 1, 6, 0}, {"hobgoblin", 'H', 1, 9, 5, 1, 8, 0}, {"jackal", 'J', 0, 12, 7, 1, 2, 0}, {"kobold", 'K', 1, 6, 7, 1, 4, 0}, {"leprechaun", 'L', 5, 15, 8, 1, 2, 0}, {"giant rat", 'r', 0, 12, 7, 1, 3, 0}, {"acid blob", 'a', 2, 3, 8, 0, 0, 0}, {"floating eye", 'E', 2, 1, 9, 0, 0, 0}, {"homunculus", 'h', 2, 6, 6, 1, 3, 0}, {"imp", 'i', 2, 6, 2, 1, 4, 0}, {"orc", 'O', 2, 9, 6, 1, 8, 0}, {"yellow light", 'y', 3, 15, 0, 0, 0, 0}, {"zombie", 'Z', 2, 6, 8, 1, 8, 0}, {"giant ant", 'A', 3, 18, 3, 1, 6, 0}, {"fog cloud", 'f', 3, 1, 0, 1, 6, 0}, {"nymph", 'N', 6, 12, 9, 1, 2, 0}, {"piercer", 'p', 3, 1, 3, 2, 6, 0}, {"quasit", 'Q', 3, 15, 3, 1, 4, 0}, {"quivering blob", 'q', 3, 1, 8, 1, 8, 0}, {"violet fungi", 'v', 3, 1, 7, 1, 4, 0}, {"giant beetle", 'b', 4, 6, 4, 3, 4, 0}, {"centaur", 'C', 4, 18, 4, 1, 6, 0}, {"cockatrice", 'c', 4, 6, 6, 1, 3, 0}, {"gelatinous cube", 'g', 4, 6, 8, 2, 4, 0}, {"jaguar", 'j', 4, 15, 6, 1, 8, 0}, {"killer bee", 'k', 4, 14, 4, 2, 4, 0}, {"snake", 'S', 4, 15, 3, 1, 6, 0}, {"freezing sphere", 'F', 2, 13, 4, 0, 0, 0}, {"owlbear", 'o', 5, 12, 5, 2, 6, 0}, {"rust monster", 'R', 10, 18, 3, 0, 0, 0}, {"scorpion", 's', 5, 15, 3, 1, 4, 0}, {"tengu", 't', 5, 13, 5, 1, 7, 0}, {"wraith", 'W', 5, 12, 5, 1, 6, 0}, #ifdef NOWORM {"wumpus", 'w', 8, 3, 2, 3, 6, 0}, #else {"long worm", 'w', 8, 3, 5, 1, 4, 0}, #endif /* NOWORM */ {"large dog", 'd', 6, 15, 4, 2, 4, 0}, {"leocrotta", 'l', 6, 18, 4, 3, 6, 0}, {"mimic", 'M', 7, 3, 7, 3, 4, 0}, {"troll", 'T', 7, 12, 4, 2, 7, 0}, {"unicorn", 'u', 8, 24, 5, 1, 10, 0}, {"yeti", 'Y', 5, 15, 6, 1, 6, 0}, {"stalker", 'I', 8, 12, 3, 4, 4, 0}, {"umber hulk", 'U', 9, 6, 2, 2, 10, 0}, {"vampire", 'V', 8, 12, 1, 1, 6, 0}, {"xorn", 'X', 8, 9, -2, 4, 6, 0}, {"xan", 'x', 7, 18, -2, 2, 4, 0}, {"zruty", 'z', 9, 8, 3, 3, 6, 0}, {"chameleon", ':', 6, 5, 6, 4, 2, 0}, {"dragon", 'D', 10, 9, -1, 3, 8, 0}, {"ettin", 'e', 10, 12, 3, 2, 8, 0}, {"lurker above", '\'', 10, 3, 3, 0, 0, 0}, {"nurse", 'n', 11, 6, 0, 1, 3, 0}, {"trapper", ',', 12, 3, 3, 0, 0, 0}, {"purple worm", 'P', 15, 9, 6, 2, 8, 0}, {"demon", '&', 10, 12, -4, 1, 4, 0}, {"minotaur", 'm', 15, 15, 6, 4, 10, 0}, {"shopkeeper", '@', 12, 18, 0, 4, 8, sizeof(struct eshk)} }; const struct permonst pm_ghost = {"ghost", ' ', 10, 3, -5, 1, 1, sizeof(plname)}; const struct permonst pm_wizard = { "wizard of Yendor", '1', 15, 12, -2, 1, 12, 0 }; #ifdef MAIL const struct permonst pm_mail_daemon = {"mail daemon", '2', 100, 1, 10, 0, 0, 0}; #endif /* MAIL */ const struct permonst pm_eel = {"giant eel", ';', 15, 6, -3, 3, 6, 0}; void * monster_private(struct monst *mon) { return mon->mextra; }
2,404
321
<filename>apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/dao/DeliveryMethodDao.java<gh_stars>100-1000 /** * Most of the code in the Qalingo project is copyrighted Hoteia and licensed * under the Apache License Version 2.0 (release version 0.8.0) * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Hoteia, 2012-2014 * http://www.hoteia.com - http://twitter.com/hoteia - <EMAIL> * */ package org.hoteia.qalingo.core.dao; import java.util.Date; import java.util.List; import org.hibernate.Criteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.hibernate.sql.JoinType; import org.hoteia.qalingo.core.domain.DeliveryMethod; import org.hoteia.qalingo.core.fetchplan.FetchPlan; import org.hoteia.qalingo.core.fetchplan.common.FetchPlanGraphDeliveryMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; @Repository("deliveryMethodDao") public class DeliveryMethodDao extends AbstractGenericDao { private final Logger logger = LoggerFactory.getLogger(getClass()); public DeliveryMethod getDeliveryMethodById(final Long deliveryMethodId, Object... params) { Criteria criteria = createDefaultCriteria(DeliveryMethod.class); FetchPlan fetchPlan = handleSpecificFetchMode(criteria, params); criteria.add(Restrictions.eq("id", deliveryMethodId)); DeliveryMethod deliveryMethod = (DeliveryMethod) criteria.uniqueResult(); if(deliveryMethod != null){ deliveryMethod.setFetchPlan(fetchPlan); } return deliveryMethod; } public DeliveryMethod getDeliveryMethodByCode(final String code, Object... params) { Criteria criteria = createDefaultCriteria(DeliveryMethod.class); FetchPlan fetchPlan = handleSpecificFetchMode(criteria, params); criteria.add(Restrictions.eq("code", handleCodeValue(code))); DeliveryMethod deliveryMethod = (DeliveryMethod) criteria.uniqueResult(); if(deliveryMethod != null){ deliveryMethod.setFetchPlan(fetchPlan); } return deliveryMethod; } public List<DeliveryMethod> findDeliveryMethods(Object... params) { Criteria criteria = createDefaultCriteria(DeliveryMethod.class); handleSpecificFetchMode(criteria, params); criteria.addOrder(Order.asc("id")); @SuppressWarnings("unchecked") List<DeliveryMethod> deliveryMethods = criteria.list(); return deliveryMethods; } public List<DeliveryMethod> findDeliveryMethodsByWarehouseId(Long warehouseId, Object... params) { Criteria criteria = createDefaultCriteria(DeliveryMethod.class); handleSpecificFetchMode(criteria, params); criteria.createAlias("warehouses", "warehouse", JoinType.LEFT_OUTER_JOIN); criteria.add(Restrictions.eq("warehouse.id", warehouseId)); criteria.addOrder(Order.asc("id")); @SuppressWarnings("unchecked") List<DeliveryMethod> deliveryMethods = criteria.list(); return deliveryMethods; } public List<DeliveryMethod> findDeliveryMethodsByMarketAreaId(Long marketAreaId, Object... params) { Criteria criteria = createDefaultCriteria(DeliveryMethod.class); handleSpecificFetchMode(criteria, params); criteria.createAlias("warehouses", "warehouse", JoinType.LEFT_OUTER_JOIN); criteria.createAlias("warehouse.warehouseMarketAreaRels", "warehouseMarketAreaRel", JoinType.LEFT_OUTER_JOIN); criteria.add(Restrictions.eq("warehouseMarketAreaRel.pk.marketArea.id", marketAreaId)); criteria.addOrder(Order.asc("id")); @SuppressWarnings("unchecked") List<DeliveryMethod> deliveryMethods = criteria.list(); return deliveryMethods; } public DeliveryMethod saveOrUpdateDeliveryMethod(final DeliveryMethod deliveryMethod) { if (deliveryMethod.getDateCreate() == null) { deliveryMethod.setDateCreate(new Date()); } deliveryMethod.setDateUpdate(new Date()); if (deliveryMethod.getId() != null) { if(em.contains(deliveryMethod)){ em.refresh(deliveryMethod); } DeliveryMethod mergedDeliveryMethod = em.merge(deliveryMethod); em.flush(); return mergedDeliveryMethod; } else { em.persist(deliveryMethod); return deliveryMethod; } } public void deleteDeliveryMethod(final DeliveryMethod deliveryMethod) { em.remove(em.contains(deliveryMethod) ? deliveryMethod : em.merge(deliveryMethod)); } @Override protected FetchPlan handleSpecificFetchMode(Criteria criteria, Object... params) { if (params != null && params.length > 0) { return super.handleSpecificFetchMode(criteria, params); } else { return super.handleSpecificFetchMode(criteria, FetchPlanGraphDeliveryMethod.defaultDeliveryMethodFetchPlan()); } } }
2,032
1,686
// Copyright (c) 2021 <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 Google Inc. nor the name Chromium Embedded // Framework 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. // // --------------------------------------------------------------------------- // // The contents of this file must follow a specific format in order to // support the CEF translator tool. See the translator.README.txt file in the // tools directory for more information. // #ifndef CEF_INCLUDE_CEF_FRAME_HANDLER_H_ #define CEF_INCLUDE_CEF_FRAME_HANDLER_H_ #pragma once #include "include/cef_base.h" #include "include/cef_browser.h" #include "include/cef_frame.h" /// // Implement this interface to handle events related to CefFrame life span. The // order of callbacks is: // // (1) During initial CefBrowserHost creation and navigation of the main frame: // - CefFrameHandler::OnFrameCreated => The initial main frame object has been // created. Any commands will be queued until the frame is attached. // - CefFrameHandler::OnMainFrameChanged => The initial main frame object has // been assigned to the browser. // - CefLifeSpanHandler::OnAfterCreated => The browser is now valid and can be // used. // - CefFrameHandler::OnFrameAttached => The initial main frame object is now // connected to its peer in the renderer process. Commands can be routed. // // (2) During further CefBrowserHost navigation/loading of the main frame and/or // sub-frames: // - CefFrameHandler::OnFrameCreated => A new main frame or sub-frame object has // been created. Any commands will be queued until the frame is attached. // - CefFrameHandler::OnFrameAttached => A new main frame or sub-frame object is // now connected to its peer in the renderer process. Commands can be routed. // - CefFrameHandler::OnFrameDetached => An existing main frame or sub-frame // object has lost its connection to the renderer process. If multiple objects // are detached at the same time then notifications will be sent for any // sub-frame objects before the main frame object. Commands can no longer be // routed and will be discarded. // - CefFrameHandler::OnMainFrameChanged => A new main frame object has been // assigned to the browser. This will only occur with cross-origin navigation // or re-navigation after renderer process termination (due to crashes, etc). // // (3) During final CefBrowserHost destruction of the main frame: // - CefFrameHandler::OnFrameDetached => Any sub-frame objects have lost their // connection to the renderer process. Commands can no longer be routed and // will be discarded. // - CefLifeSpanHandler::OnBeforeClose => The browser has been destroyed. // - CefFrameHandler::OnFrameDetached => The main frame object have lost its // connection to the renderer process. Notifications will be sent for any // sub-frame objects before the main frame object. Commands can no longer be // routed and will be discarded. // - CefFrameHandler::OnMainFrameChanged => The final main frame object has been // removed from the browser. // // Cross-origin navigation and/or loading receives special handling. // // When the main frame navigates to a different origin the OnMainFrameChanged // callback (2) will be executed with the old and new main frame objects. // // When a new sub-frame is loaded in, or an existing sub-frame is navigated to, // a different origin from the parent frame, a temporary sub-frame object will // first be created in the parent's renderer process. That temporary sub-frame // will then be discarded after the real cross-origin sub-frame is created in // the new/target renderer process. The client will receive cross-origin // navigation callbacks (2) for the transition from the temporary sub-frame to // the real sub-frame. The temporary sub-frame will not recieve or execute // commands during this transitional period (any sent commands will be // discarded). // // When a new popup browser is created in a different origin from the parent // browser, a temporary main frame object for the popup will first be created in // the parent's renderer process. That temporary main frame will then be // discarded after the real cross-origin main frame is created in the new/target // renderer process. The client will recieve creation and initial navigation // callbacks (1) for the temporary main frame, followed by cross-origin // navigation callbacks (2) for the transition from the temporary main frame to // the real main frame. The temporary main frame may receive and execute // commands during this transitional period (any sent commands may be executed, // but the behavior is potentially undesirable since they execute in the parent // browser's renderer process and not the new/target renderer process). // // Callbacks will not be executed for placeholders that may be created during // pre-commit navigation for sub-frames that do not yet exist in the renderer // process. Placeholders will have CefFrame::GetIdentifier() == -4. // // The methods of this class will be called on the UI thread unless otherwise // indicated. /// /*--cef(source=client)--*/ class CefFrameHandler : public virtual CefBaseRefCounted { public: /// // Called when a new frame is created. This will be the first notification // that references |frame|. Any commands that require transport to the // associated renderer process (LoadRequest, SendProcessMessage, GetSource, // etc.) will be queued until OnFrameAttached is called for |frame|. /// /*--cef()--*/ virtual void OnFrameCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame) {} /// // Called when a frame can begin routing commands to/from the associated // renderer process. |reattached| will be true if the frame was re-attached // after exiting the BackForwardCache. Any commands that were queued have now // been dispatched. /// /*--cef()--*/ virtual void OnFrameAttached(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, bool reattached) {} /// // Called when a frame loses its connection to the renderer process and will // be destroyed. Any pending or future commands will be discarded and // CefFrame::IsValid() will now return false for |frame|. If called after // CefLifeSpanHandler::OnBeforeClose() during browser destruction then // CefBrowser::IsValid() will return false for |browser|. /// /*--cef()--*/ virtual void OnFrameDetached(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame) {} /// // Called when the main frame changes due to (a) initial browser creation, (b) // final browser destruction, (c) cross-origin navigation or (d) re-navigation // after renderer process termination (due to crashes, etc). |old_frame| will // be NULL and |new_frame| will be non-NULL when a main frame is assigned to // |browser| for the first time. |old_frame| will be non-NULL and |new_frame| // will be NULL and when a main frame is removed from |browser| for the last // time. Both |old_frame| and |new_frame| will be non-NULL for cross-origin // navigations or re-navigation after renderer process termination. This // method will be called after OnFrameCreated() for |new_frame| and/or after // OnFrameDetached() for |old_frame|. If called after // CefLifeSpanHandler::OnBeforeClose() during browser destruction then // CefBrowser::IsValid() will return false for |browser|. /// /*--cef(optional_param=old_frame,optional_param=new_frame)--*/ virtual void OnMainFrameChanged(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> old_frame, CefRefPtr<CefFrame> new_frame) {} }; #endif // CEF_INCLUDE_CEF_FRAME_HANDLER_H_
2,614
390
<filename>genrl/agents/bandits/contextual/base.py<gh_stars>100-1000 from typing import Optional import torch from genrl.core import Bandit, BanditAgent class DCBAgent(BanditAgent): """Base class for deep contextual bandit solving agents Args: bandit (gennav.deep.bandit.data_bandits.DataBasedBandit): The bandit to solve device (str): Device to use for tensor operations. "cpu" for cpu or "cuda" for cuda. Defaults to "cpu". Attributes: bandit (gennav.deep.bandit.data_bandits.DataBasedBandit): The bandit to solve device (torch.device): Device to use for tensor operations. """ def __init__(self, bandit: Bandit, device: str = "cpu", **kwargs): super(DCBAgent, self).__init__() if "cuda" in device and torch.cuda.is_available(): self.device = torch.device(device) else: self.device = torch.device("cpu") self._bandit = bandit self.context_dim = self._bandit.context_dim self.n_actions = self._bandit.n_actions self._action_hist = [] self.init_pulls = kwargs.get("init_pulls", 3) def select_action(self, context: torch.Tensor) -> int: """Select an action based on given context Args: context (torch.Tensor): The context vector to select action for Note: This method needs to be implemented in the specific agent. Returns: int: The action to take """ raise NotImplementedError def update_parameters( self, action: Optional[int] = None, batch_size: Optional[int] = None, train_epochs: Optional[int] = None, ) -> None: """Update parameters of the agent. Args: action (Optional[int], optional): Action to update the parameters for. Defaults to None. batch_size (Optional[int], optional): Size of batch to update parameters with. Defaults to None. train_epochs (Optional[int], optional): Epochs to train neural network for. Defaults to None. Note: This method needs to be implemented in the specific agent. """ raise NotImplementedError
897
456
<reponame>pafri/DJV<gh_stars>100-1000 // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2004-2020 <NAME> // All rights reserved. namespace djv { namespace System { inline const std::weak_ptr<Context>& IObject::getContext() const { return _context; } inline const std::string& IObject::getClassName() const { return _className; } inline const std::string& IObject::getObjectName() const { return _objectName; } inline void IObject::setClassName(const std::string& name) { _className = name; } inline void IObject::setObjectName(const std::string& name) { _objectName = name; } inline const std::weak_ptr<IObject>& IObject::getParent() const { return _parent; } template<typename T> inline std::shared_ptr<T> IObject::getParentRecursiveT() const { for (auto parent = _parent.lock(); parent.get(); parent = parent->_parent.lock()) { if (auto parentT = std::dynamic_pointer_cast<T>(parent)) { return parentT; } } return nullptr; } template<typename T> inline std::vector<std::shared_ptr<T> > IObject::getChildrenT() const { std::vector<std::shared_ptr<T> > out; for (const auto& child : _children) { if (auto childT = std::dynamic_pointer_cast<T>(child)) { out.push_back(childT); } } return out; } template<typename T> inline std::vector<std::shared_ptr<T> > IObject::getChildrenRecursiveT() const { std::vector<std::shared_ptr<T> > out; for (const auto& child : _children) { _getChildrenRecursiveT(child, out); } return out; } template <typename T> inline std::shared_ptr<T> IObject::getFirstChildT() const { for (const auto& child : _children) { if (auto childT = std::dynamic_pointer_cast<T>(child)) { return childT; } } return nullptr; } template<typename T> inline std::shared_ptr<T> IObject::getFirstChildRecursiveT() const { std::shared_ptr<T> out; for (const auto& child : _children) { _getFirstChildRecursiveT(child, out); if (out.get()) { break; } } return out; } inline const std::vector<std::shared_ptr<IObject> >& IObject::getChildren() const { return _children; } inline bool IObject::isEnabled(bool parents) const { return parents ? (_parentsEnabled && _enabled) : _enabled; } inline void IObject::setEnabled(bool value) { _enabled = value; } inline const std::shared_ptr<ResourceSystem>& IObject::_getResourceSystem() const { return _resourceSystem; } inline const std::shared_ptr<LogSystem>& IObject::_getLogSystem() const { return _logSystem; } inline const std::shared_ptr<TextSystem>& IObject::_getTextSystem() const { return _textSystem; } template<typename T> inline void IObject::_getChildrenRecursiveT(const std::shared_ptr<IObject>& value, std::vector<std::shared_ptr<T> >& out) { if (auto valueT = std::dynamic_pointer_cast<T>(value)) { out.push_back(valueT); } for (const auto& child : value->_children) { _getChildrenRecursiveT(child, out); } } template<typename T> inline void IObject::_getFirstChildRecursiveT(const std::shared_ptr<IObject>& value, std::shared_ptr<T>& out) { if (auto valueT = std::dynamic_pointer_cast<T>(value)) { out = valueT; return; } for (const auto& child : value->_children) { _getFirstChildRecursiveT(child, out); } } } // namespace System } // namespace djv
2,443
1,805
<reponame>qiuhere/Bench #include <gtest/gtest.h> #include "Snap.h" int BuildCapacityNetwork(const TStr& InFNm, PNEANet &Net, const int& SrcColId = 0, const int& DstColId = 1, const int& CapColId = 2) { TSsParser Ss(InFNm, ssfWhiteSep, true, true, true); TRnd Random; Net.Clr(); Net = TNEANet::New(); int SrcNId, DstNId, CapVal, EId; int MaxCap = 0; while (Ss.Next()) { if (! Ss.GetInt(SrcColId, SrcNId) || ! Ss.GetInt(DstColId, DstNId) || ! Ss.GetInt(CapColId, CapVal)) { continue; } MaxCap = MAX(CapVal, MaxCap); if (! Net->IsNode(SrcNId)) { Net->AddNode(SrcNId); } if (! Net->IsNode(DstNId)) { Net->AddNode(DstNId); } EId = Net->AddEdge(SrcNId, DstNId); Net->AddIntAttrDatE(EId, CapVal, TSnap::CapAttrName); } return MaxCap; } TEST(FlowTest, BasicTest) { PNEANet Net; BuildCapacityNetwork("flow/small_sample.txt", Net); int PRFlow1 = TSnap::GetMaxFlowIntPR(Net, 53, 2); int EKFlow1 = TSnap::GetMaxFlowIntEK(Net, 53, 2); int PRFlow2 = TSnap::GetMaxFlowIntPR(Net, 86, 77); int EKFlow2 = TSnap::GetMaxFlowIntEK(Net, 86, 77); int PRFlow3 = TSnap::GetMaxFlowIntPR(Net, 62, 81); int EKFlow3 = TSnap::GetMaxFlowIntEK(Net, 62, 81); int PRFlow4 = TSnap::GetMaxFlowIntPR(Net, 92, 92); int EKFlow4 = TSnap::GetMaxFlowIntEK(Net, 92, 92); EXPECT_EQ (PRFlow1, EKFlow1); EXPECT_EQ (PRFlow2, EKFlow2); EXPECT_EQ (PRFlow3, EKFlow3); EXPECT_EQ (PRFlow4, EKFlow4); EXPECT_EQ (PRFlow1, 1735); EXPECT_EQ (PRFlow2, 3959); EXPECT_EQ (PRFlow3, 2074); EXPECT_EQ (PRFlow4, 0); }
729
353
""" This global flag controls whether to assign new tensors to the parameters instead of changing the existing parameters in-place when converting an `nn.Module` using the following methods: 1. `module.cuda()` / `.cpu()` (for moving `module` between devices) 2. `module.float()` / `.double()` / `.half()` (for converting `module` to a different dtype) 3. `module.to()` / `.type()` (for changing `module`'s device or dtype) 4. `module._apply(fn)` (for generic functions applied to `module`) Default: False """ _overwrite_module_params_on_conversion = False def set_overwrite_module_params_on_conversion(value): global _overwrite_module_params_on_conversion _overwrite_module_params_on_conversion = value def get_overwrite_module_params_on_conversion(): return _overwrite_module_params_on_conversion
276
794
#ifndef __HelloCpp__RootWindow__ #define __HelloCpp__RootWindow__ #include <iostream> #include "CrossApp.h" USING_NS_CC; class RootWindow: public CAWindow { public: static RootWindow* getInstance(); static void destroyInstance(); RootWindow(); virtual ~RootWindow(); virtual bool init(); private: }; #endif /* defined(__HelloCpp__ViewController__) */
178
304
<reponame>NoahFetz/CloudNet-v3<filename>cloudnet-modules/cloudnet-bridge/src/main/java/de/dytanic/cloudnet/ext/bridge/BridgeConstants.java<gh_stars>100-1000 /* * Copyright 2019-2021 CloudNetService team & 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 * * 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 de.dytanic.cloudnet.ext.bridge; public interface BridgeConstants { String BRIDGE_CUSTOM_CHANNEL_MESSAGING_CHANNEL = "cloudnet-bridge-channel"; String BRIDGE_PLAYER_API_CHANNEL = "cloudnet-bridge-player-channel"; String BRIDGE_NETWORK_CHANNEL_MESSAGE_GET_BRIDGE_CONFIGURATION = "cloudnet_bridge_get_bridge_configuration"; String BRIDGE_NETWORK_CHANNEL_CLUSTER_MESSAGE_UPDATE_BRIDGE_CONFIGURATION_LISTENER = "update_bridge_configuration"; String BRIDGE_EVENT_CHANNEL_MESSAGE_NAME_PROXY_LOGIN_REQUEST = "proxy_player_login_request_event"; String BRIDGE_EVENT_CHANNEL_MESSAGE_NAME_PROXY_LOGIN_SUCCESS = "proxy_player_login_success_event"; String BRIDGE_EVENT_CHANNEL_MESSAGE_NAME_PROXY_SERVER_CONNECT_REQUEST = "proxy_player_server_connect_request"; String BRIDGE_EVENT_CHANNEL_MESSAGE_NAME_PROXY_SERVER_SWITCH = "proxy_player_server_switch_event"; String BRIDGE_EVENT_CHANNEL_MESSAGE_NAME_PROXY_DISCONNECT = "proxy_player_disconnect_event"; String BRIDGE_EVENT_CHANNEL_MESSAGE_NAME_PROXY_MISSING_DISCONNECT = "proxy_player_disconnect_missing"; String BRIDGE_EVENT_CHANNEL_MESSAGE_NAME_SERVER_LOGIN_REQUEST = "server_player_login_request_event"; String BRIDGE_EVENT_CHANNEL_MESSAGE_NAME_SERVER_LOGIN_SUCCESS = "server_player_login_success_event"; String BRIDGE_EVENT_CHANNEL_MESSAGE_NAME_SERVER_DISCONNECT = "server_player_disconnect_event"; }
763
2,180
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.util; import junit.framework.TestCase; import org.apache.commons.lang.math.RandomUtils; import st.ata.util.FPGenerator; public class LongToIntConsistentHashTest extends TestCase { protected LongToIntConsistentHash conhash; @Override protected void setUp() throws Exception { super.setUp(); conhash = new LongToIntConsistentHash(); } public void testRange() { for(long in = 0; in < 10000; in++) { long longHash = FPGenerator.std64.fp(""+in); int upTo = RandomUtils.nextInt(32)+1; int bucket = conhash.bucketFor(longHash, upTo); assertTrue("bucket returned >= upTo",bucket < upTo); assertTrue("bucket returned < 0: "+bucket,bucket >= 0); } } public void testTwoWayDistribution() { // SecureRandom rand = new SecureRandom("foobar".getBytes()); for(int p = 0; p < 20; p++) { int[] landings = new int[2]; for(long in = 0; in < 100000; in++) { long longHash = FPGenerator.std64.fp(p+"a"+in); // long longHash = rand.nextLong(); // long longHash = ArchiveUtils.doubleMurmur((p+":"+in).getBytes()); landings[conhash.bucketFor(longHash, 2)]++; } // System.out.println(landings[0]+","+landings[1]); assertTrue("excessive changes",Math.abs(landings[0]-landings[1]) < 2000); } } public void testConsistencyUp() { int initialUpTo = 10; int changedCount = 0; for(long in = 0; in < 10000; in++) { long longHash = FPGenerator.std64.fp(""+in); int firstBucket = conhash.bucketFor(longHash, initialUpTo); int secondBucket = conhash.bucketFor(longHash, initialUpTo+1); if(secondBucket!=firstBucket) { changedCount++; } } assertTrue("excessive changes: "+changedCount,changedCount < 2000); } public void testConsistencyDown() { int initialUpTo = 10; int changedCount = 0; for(long in = 0; in < 10000; in++) { long longHash = FPGenerator.std64.fp(""+in); int firstBucket = conhash.bucketFor(longHash, initialUpTo); int secondBucket = conhash.bucketFor(longHash, initialUpTo-1); if(secondBucket!=firstBucket) { changedCount++; } } assertTrue("excessive changes: "+changedCount,changedCount < 2000); } }
1,491
14,793
package me.chanjar.weixin.cp.api.impl; import com.google.common.collect.ImmutableMap; import com.google.gson.reflect.TypeToken; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.util.json.GsonParser; import me.chanjar.weixin.cp.api.WxCpOaScheduleService; import me.chanjar.weixin.cp.api.WxCpService; import me.chanjar.weixin.cp.bean.oa.WxCpOaSchedule; import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.Oa.*; /** * 企业微信日程接口实现类. * * @author <a href="https://github.com/binarywang"><NAME></a> * @date 2020-12-25 */ @Slf4j @RequiredArgsConstructor public class WxCpOaOaScheduleServiceImpl implements WxCpOaScheduleService { private final WxCpService cpService; @Override public String add(WxCpOaSchedule schedule, Integer agentId) throws WxErrorException { Map<String, Serializable> param; if (agentId == null) { param = ImmutableMap.of("schedule", schedule); } else { param = ImmutableMap.of("schedule", schedule, "agentid", agentId); } return this.cpService.post(this.cpService.getWxCpConfigStorage().getApiUrl(SCHEDULE_ADD), WxCpGsonBuilder.create().toJson(param)); } @Override public void update(WxCpOaSchedule schedule) throws WxErrorException { this.cpService.post(this.cpService.getWxCpConfigStorage().getApiUrl(SCHEDULE_UPDATE), WxCpGsonBuilder.create().toJson(ImmutableMap.of("schedule", schedule))); } @Override public List<WxCpOaSchedule> getDetails(List<String> scheduleIds) throws WxErrorException { final String response = this.cpService.post(this.cpService.getWxCpConfigStorage().getApiUrl(SCHEDULE_GET), WxCpGsonBuilder.create().toJson(ImmutableMap.of("schedule_id_list", scheduleIds))); return WxCpGsonBuilder.create().fromJson(GsonParser.parse(response).get("schedule_list"), new TypeToken<List<WxCpOaSchedule>>() { }.getType()); } @Override public void delete(String scheduleId) throws WxErrorException { this.cpService.post(this.cpService.getWxCpConfigStorage().getApiUrl(SCHEDULE_DEL), WxCpGsonBuilder.create().toJson(ImmutableMap.of("schedule_id", scheduleId))); } @Override public List<WxCpOaSchedule> listByCalendar(String calId, Integer offset, Integer limit) throws WxErrorException { final Map<String, Object> param = new HashMap<>(3); param.put("cal_id", calId); if (offset != null) { param.put("offset", offset); } if (limit != null) { param.put("limit", limit); } final String response = this.cpService.post(this.cpService.getWxCpConfigStorage().getApiUrl(SCHEDULE_LIST), WxCpGsonBuilder.create().toJson(param)); return WxCpGsonBuilder.create().fromJson(GsonParser.parse(response).get("schedule_list"), new TypeToken<List<WxCpOaSchedule>>() { }.getType()); } }
1,217
575
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /** * @file MessageReceiver.h */ #ifndef _FASTDDS_RTPS_MESSAGERECEIVER_H_ #define _FASTDDS_RTPS_MESSAGERECEIVER_H_ #ifndef DOXYGEN_SHOULD_SKIP_THIS_PUBLIC #include <fastrtps/rtps/common/all_common.h> #include <fastrtps/rtps/writer/StatelessWriter.h> #include <fastrtps/rtps/writer/StatefulWriter.h> namespace eprosima { namespace fastrtps { namespace rtps { class RTPSWriter; class RTPSReader; struct SubmessageHeader_t; class ReceiverResource; /** * Class MessageReceiver, process the received messages. * @ingroup MANAGEMENT_MODULE */ class MessageReceiver { public: MessageReceiver( RTPSParticipantImpl* /*participant*/, ReceiverResource* /*receiverResource*/) { } virtual ~MessageReceiver() { } void reset() { } void init( uint32_t /*rec_buffer_size*/) { } virtual void processCDRMsg( const Locator_t& /*loc*/, CDRMessage_t* /*msg*/) { } void setReceiverResource( ReceiverResource* /*receiverResource*/) { } }; } // namespace rtps } /* namespace rtps */ } /* namespace eprosima */ #endif // ifndef DOXYGEN_SHOULD_SKIP_THIS_PUBLIC #endif /* _FASTDDS_RTPS_MESSAGERECEIVER_H_*/
710
10,225
package io.quarkus.it.cache; import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.jboss.resteasy.annotations.jaxrs.PathParam; import org.jboss.resteasy.annotations.jaxrs.QueryParam; @ApplicationScoped @Path("sunrise") public class SunriseRestServerResource { private int sunriseTimeInvocations; @GET @Path("time/{city}") public String getSunriseTime(@PathParam String city, @QueryParam String date) { sunriseTimeInvocations++; return "2020-12-20T10:15:30"; } @GET @Path("invocations") public Integer getSunriseTimeInvocations() { return sunriseTimeInvocations; } @DELETE @Path("invalidate/{city}") public void invalidate(@PathParam String city, @QueryParam String notPartOfTheCacheKey, @QueryParam String date) { // Do nothing. We only need to test the caching annotation on the client side. } @DELETE @Path("invalidate") public void invalidateAll() { // Do nothing. We only need to test the caching annotation on the client side. } }
423
327
<reponame>jtravee/neuvector<gh_stars>100-1000 #ifndef _URCU_ARCH_UATOMIC_X86_H #define _URCU_ARCH_UATOMIC_X86_H /* * Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved. * Copyright (c) 1996-1999 by Silicon Graphics. All rights reserved. * Copyright (c) 1999-2004 Hewlett-Packard Development Company, L.P. * Copyright (c) 2009 <NAME> * * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED * OR IMPLIED. ANY USE IS AT YOUR OWN RISK. * * Permission is hereby granted to use or copy this program * for any purpose, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * * Code inspired from libuatomic_ops-1.2, inherited in part from the * Boehm-Demers-Weiser conservative garbage collector. */ #include <urcu/compiler.h> #include <urcu/system.h> #define UATOMIC_HAS_ATOMIC_BYTE #define UATOMIC_HAS_ATOMIC_SHORT #ifdef __cplusplus extern "C" { #endif /* * Derived from AO_compare_and_swap() and AO_test_and_set_full(). */ struct __uatomic_dummy { unsigned long v[10]; }; #define __hp(x) ((struct __uatomic_dummy *)(x)) #define _uatomic_set(addr, v) ((void) CMM_STORE_SHARED(*(addr), (v))) /* cmpxchg */ static inline __attribute__((always_inline)) unsigned long __uatomic_cmpxchg(void *addr, unsigned long old, unsigned long _new, int len) { switch (len) { case 1: { unsigned char result = old; __asm__ __volatile__( "lock; cmpxchgb %2, %1" : "+a"(result), "+m"(*__hp(addr)) : "q"((unsigned char)_new) : "memory"); return result; } case 2: { unsigned short result = old; __asm__ __volatile__( "lock; cmpxchgw %2, %1" : "+a"(result), "+m"(*__hp(addr)) : "r"((unsigned short)_new) : "memory"); return result; } case 4: { unsigned int result = old; __asm__ __volatile__( "lock; cmpxchgl %2, %1" : "+a"(result), "+m"(*__hp(addr)) : "r"((unsigned int)_new) : "memory"); return result; } #if (CAA_BITS_PER_LONG == 64) case 8: { unsigned long result = old; __asm__ __volatile__( "lock; cmpxchgq %2, %1" : "+a"(result), "+m"(*__hp(addr)) : "r"((unsigned long)_new) : "memory"); return result; } #endif } /* * generate an illegal instruction. Cannot catch this with * linker tricks when optimizations are disabled. */ __asm__ __volatile__("ud2"); return 0; } #define _uatomic_cmpxchg(addr, old, _new) \ ((__typeof__(*(addr))) __uatomic_cmpxchg((addr), \ caa_cast_long_keep_sign(old), \ caa_cast_long_keep_sign(_new),\ sizeof(*(addr)))) /* xchg */ static inline __attribute__((always_inline)) unsigned long __uatomic_exchange(void *addr, unsigned long val, int len) { /* Note: the "xchg" instruction does not need a "lock" prefix. */ switch (len) { case 1: { unsigned char result; __asm__ __volatile__( "xchgb %0, %1" : "=q"(result), "+m"(*__hp(addr)) : "0" ((unsigned char)val) : "memory"); return result; } case 2: { unsigned short result; __asm__ __volatile__( "xchgw %0, %1" : "=r"(result), "+m"(*__hp(addr)) : "0" ((unsigned short)val) : "memory"); return result; } case 4: { unsigned int result; __asm__ __volatile__( "xchgl %0, %1" : "=r"(result), "+m"(*__hp(addr)) : "0" ((unsigned int)val) : "memory"); return result; } #if (CAA_BITS_PER_LONG == 64) case 8: { unsigned long result; __asm__ __volatile__( "xchgq %0, %1" : "=r"(result), "+m"(*__hp(addr)) : "0" ((unsigned long)val) : "memory"); return result; } #endif } /* * generate an illegal instruction. Cannot catch this with * linker tricks when optimizations are disabled. */ __asm__ __volatile__("ud2"); return 0; } #define _uatomic_xchg(addr, v) \ ((__typeof__(*(addr))) __uatomic_exchange((addr), \ caa_cast_long_keep_sign(v), \ sizeof(*(addr)))) /* uatomic_add_return */ static inline __attribute__((always_inline)) unsigned long __uatomic_add_return(void *addr, unsigned long val, int len) { switch (len) { case 1: { unsigned char result = val; __asm__ __volatile__( "lock; xaddb %1, %0" : "+m"(*__hp(addr)), "+q" (result) : : "memory"); return result + (unsigned char)val; } case 2: { unsigned short result = val; __asm__ __volatile__( "lock; xaddw %1, %0" : "+m"(*__hp(addr)), "+r" (result) : : "memory"); return result + (unsigned short)val; } case 4: { unsigned int result = val; __asm__ __volatile__( "lock; xaddl %1, %0" : "+m"(*__hp(addr)), "+r" (result) : : "memory"); return result + (unsigned int)val; } #if (CAA_BITS_PER_LONG == 64) case 8: { unsigned long result = val; __asm__ __volatile__( "lock; xaddq %1, %0" : "+m"(*__hp(addr)), "+r" (result) : : "memory"); return result + (unsigned long)val; } #endif } /* * generate an illegal instruction. Cannot catch this with * linker tricks when optimizations are disabled. */ __asm__ __volatile__("ud2"); return 0; } #define _uatomic_add_return(addr, v) \ ((__typeof__(*(addr))) __uatomic_add_return((addr), \ caa_cast_long_keep_sign(v), \ sizeof(*(addr)))) /* uatomic_and */ static inline __attribute__((always_inline)) void __uatomic_and(void *addr, unsigned long val, int len) { switch (len) { case 1: { __asm__ __volatile__( "lock; andb %1, %0" : "=m"(*__hp(addr)) : "iq" ((unsigned char)val) : "memory"); return; } case 2: { __asm__ __volatile__( "lock; andw %1, %0" : "=m"(*__hp(addr)) : "ir" ((unsigned short)val) : "memory"); return; } case 4: { __asm__ __volatile__( "lock; andl %1, %0" : "=m"(*__hp(addr)) : "ir" ((unsigned int)val) : "memory"); return; } #if (CAA_BITS_PER_LONG == 64) case 8: { __asm__ __volatile__( "lock; andq %1, %0" : "=m"(*__hp(addr)) : "er" ((unsigned long)val) : "memory"); return; } #endif } /* * generate an illegal instruction. Cannot catch this with * linker tricks when optimizations are disabled. */ __asm__ __volatile__("ud2"); return; } #define _uatomic_and(addr, v) \ (__uatomic_and((addr), caa_cast_long_keep_sign(v), sizeof(*(addr)))) /* uatomic_or */ static inline __attribute__((always_inline)) void __uatomic_or(void *addr, unsigned long val, int len) { switch (len) { case 1: { __asm__ __volatile__( "lock; orb %1, %0" : "=m"(*__hp(addr)) : "iq" ((unsigned char)val) : "memory"); return; } case 2: { __asm__ __volatile__( "lock; orw %1, %0" : "=m"(*__hp(addr)) : "ir" ((unsigned short)val) : "memory"); return; } case 4: { __asm__ __volatile__( "lock; orl %1, %0" : "=m"(*__hp(addr)) : "ir" ((unsigned int)val) : "memory"); return; } #if (CAA_BITS_PER_LONG == 64) case 8: { __asm__ __volatile__( "lock; orq %1, %0" : "=m"(*__hp(addr)) : "er" ((unsigned long)val) : "memory"); return; } #endif } /* * generate an illegal instruction. Cannot catch this with * linker tricks when optimizations are disabled. */ __asm__ __volatile__("ud2"); return; } #define _uatomic_or(addr, v) \ (__uatomic_or((addr), caa_cast_long_keep_sign(v), sizeof(*(addr)))) /* uatomic_add */ static inline __attribute__((always_inline)) void __uatomic_add(void *addr, unsigned long val, int len) { switch (len) { case 1: { __asm__ __volatile__( "lock; addb %1, %0" : "=m"(*__hp(addr)) : "iq" ((unsigned char)val) : "memory"); return; } case 2: { __asm__ __volatile__( "lock; addw %1, %0" : "=m"(*__hp(addr)) : "ir" ((unsigned short)val) : "memory"); return; } case 4: { __asm__ __volatile__( "lock; addl %1, %0" : "=m"(*__hp(addr)) : "ir" ((unsigned int)val) : "memory"); return; } #if (CAA_BITS_PER_LONG == 64) case 8: { __asm__ __volatile__( "lock; addq %1, %0" : "=m"(*__hp(addr)) : "er" ((unsigned long)val) : "memory"); return; } #endif } /* * generate an illegal instruction. Cannot catch this with * linker tricks when optimizations are disabled. */ __asm__ __volatile__("ud2"); return; } #define _uatomic_add(addr, v) \ (__uatomic_add((addr), caa_cast_long_keep_sign(v), sizeof(*(addr)))) /* uatomic_inc */ static inline __attribute__((always_inline)) void __uatomic_inc(void *addr, int len) { switch (len) { case 1: { __asm__ __volatile__( "lock; incb %0" : "=m"(*__hp(addr)) : : "memory"); return; } case 2: { __asm__ __volatile__( "lock; incw %0" : "=m"(*__hp(addr)) : : "memory"); return; } case 4: { __asm__ __volatile__( "lock; incl %0" : "=m"(*__hp(addr)) : : "memory"); return; } #if (CAA_BITS_PER_LONG == 64) case 8: { __asm__ __volatile__( "lock; incq %0" : "=m"(*__hp(addr)) : : "memory"); return; } #endif } /* generate an illegal instruction. Cannot catch this with linker tricks * when optimizations are disabled. */ __asm__ __volatile__("ud2"); return; } #define _uatomic_inc(addr) (__uatomic_inc((addr), sizeof(*(addr)))) /* uatomic_dec */ static inline __attribute__((always_inline)) void __uatomic_dec(void *addr, int len) { switch (len) { case 1: { __asm__ __volatile__( "lock; decb %0" : "=m"(*__hp(addr)) : : "memory"); return; } case 2: { __asm__ __volatile__( "lock; decw %0" : "=m"(*__hp(addr)) : : "memory"); return; } case 4: { __asm__ __volatile__( "lock; decl %0" : "=m"(*__hp(addr)) : : "memory"); return; } #if (CAA_BITS_PER_LONG == 64) case 8: { __asm__ __volatile__( "lock; decq %0" : "=m"(*__hp(addr)) : : "memory"); return; } #endif } /* * generate an illegal instruction. Cannot catch this with * linker tricks when optimizations are disabled. */ __asm__ __volatile__("ud2"); return; } #define _uatomic_dec(addr) (__uatomic_dec((addr), sizeof(*(addr)))) #if ((CAA_BITS_PER_LONG != 64) && defined(CONFIG_RCU_COMPAT_ARCH)) extern int __rcu_cas_avail; extern int __rcu_cas_init(void); #define UATOMIC_COMPAT(insn) \ ((caa_likely(__rcu_cas_avail > 0)) \ ? (_uatomic_##insn) \ : ((caa_unlikely(__rcu_cas_avail < 0) \ ? ((__rcu_cas_init() > 0) \ ? (_uatomic_##insn) \ : (compat_uatomic_##insn)) \ : (compat_uatomic_##insn)))) /* * We leave the return value so we don't break the ABI, but remove the * return value from the API. */ extern unsigned long _compat_uatomic_set(void *addr, unsigned long _new, int len); #define compat_uatomic_set(addr, _new) \ ((void) _compat_uatomic_set((addr), \ caa_cast_long_keep_sign(_new), \ sizeof(*(addr)))) extern unsigned long _compat_uatomic_xchg(void *addr, unsigned long _new, int len); #define compat_uatomic_xchg(addr, _new) \ ((__typeof__(*(addr))) _compat_uatomic_xchg((addr), \ caa_cast_long_keep_sign(_new), \ sizeof(*(addr)))) extern unsigned long _compat_uatomic_cmpxchg(void *addr, unsigned long old, unsigned long _new, int len); #define compat_uatomic_cmpxchg(addr, old, _new) \ ((__typeof__(*(addr))) _compat_uatomic_cmpxchg((addr), \ caa_cast_long_keep_sign(old), \ caa_cast_long_keep_sign(_new), \ sizeof(*(addr)))) extern void _compat_uatomic_and(void *addr, unsigned long _new, int len); #define compat_uatomic_and(addr, v) \ (_compat_uatomic_and((addr), \ caa_cast_long_keep_sign(v), \ sizeof(*(addr)))) extern void _compat_uatomic_or(void *addr, unsigned long _new, int len); #define compat_uatomic_or(addr, v) \ (_compat_uatomic_or((addr), \ caa_cast_long_keep_sign(v), \ sizeof(*(addr)))) extern unsigned long _compat_uatomic_add_return(void *addr, unsigned long _new, int len); #define compat_uatomic_add_return(addr, v) \ ((__typeof__(*(addr))) _compat_uatomic_add_return((addr), \ caa_cast_long_keep_sign(v), \ sizeof(*(addr)))) #define compat_uatomic_add(addr, v) \ ((void)compat_uatomic_add_return((addr), (v))) #define compat_uatomic_inc(addr) \ (compat_uatomic_add((addr), 1)) #define compat_uatomic_dec(addr) \ (compat_uatomic_add((addr), -1)) #else #define UATOMIC_COMPAT(insn) (_uatomic_##insn) #endif /* Read is atomic even in compat mode */ #define uatomic_set(addr, v) \ UATOMIC_COMPAT(set(addr, v)) #define uatomic_cmpxchg(addr, old, _new) \ UATOMIC_COMPAT(cmpxchg(addr, old, _new)) #define uatomic_xchg(addr, v) \ UATOMIC_COMPAT(xchg(addr, v)) #define uatomic_and(addr, v) \ UATOMIC_COMPAT(and(addr, v)) #define cmm_smp_mb__before_uatomic_and() cmm_barrier() #define cmm_smp_mb__after_uatomic_and() cmm_barrier() #define uatomic_or(addr, v) \ UATOMIC_COMPAT(or(addr, v)) #define cmm_smp_mb__before_uatomic_or() cmm_barrier() #define cmm_smp_mb__after_uatomic_or() cmm_barrier() #define uatomic_add_return(addr, v) \ UATOMIC_COMPAT(add_return(addr, v)) #define uatomic_add(addr, v) UATOMIC_COMPAT(add(addr, v)) #define cmm_smp_mb__before_uatomic_add() cmm_barrier() #define cmm_smp_mb__after_uatomic_add() cmm_barrier() #define uatomic_inc(addr) UATOMIC_COMPAT(inc(addr)) #define cmm_smp_mb__before_uatomic_inc() cmm_barrier() #define cmm_smp_mb__after_uatomic_inc() cmm_barrier() #define uatomic_dec(addr) UATOMIC_COMPAT(dec(addr)) #define cmm_smp_mb__before_uatomic_dec() cmm_barrier() #define cmm_smp_mb__after_uatomic_dec() cmm_barrier() #ifdef __cplusplus } #endif #include <urcu/uatomic/generic.h> #endif /* _URCU_ARCH_UATOMIC_X86_H */
6,379
1,056
<filename>ide/derby/test/unit/src/org/netbeans/modules/derby/test/TestBase.java<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.derby.test; import java.io.File; import java.io.IOException; import org.netbeans.api.db.explorer.JDBCDriver; import org.netbeans.api.db.explorer.JDBCDriverManager; import org.netbeans.junit.NbTestCase; import org.netbeans.modules.derby.api.DerbyDatabasesTest; import org.openide.util.Lookup; import org.openide.util.lookup.Lookups; import org.openide.util.lookup.ProxyLookup; /** * Common ancestor for all test classes. * * @author <NAME> */ public class TestBase extends NbTestCase { protected Lookup sampleDBLookup; public TestBase(String name) { super(name); } @Override public void setUp() throws Exception { super.setUp(); clearWorkDir(); DerbyDatabasesTest.SampleDatabaseLocator sdl = new DerbyDatabasesTest.SampleDatabaseLocator(); sampleDBLookup = new ProxyLookup(Lookup.getDefault(), Lookups.singleton(sdl)); Lookups.executeWith(sampleDBLookup, new Runnable() { @Override public void run() { // Force initialization of JDBCDrivers JDBCDriverManager jdm = JDBCDriverManager.getDefault(); JDBCDriver[] registeredDrivers = jdm.getDrivers(); } }); } public static void createFakeDerbyInstallation(File location) throws IOException { if (!location.mkdirs()) { throw new IOException("Could not create " + location.getAbsolutePath()); } File lib = new File(location, "lib"); if (!lib.mkdir()) { throw new IOException("Could not create " + lib.getAbsolutePath()); } new File(lib, "derby.jar").createNewFile(); new File(lib, "derbyclient.jar").createNewFile(); } }
985
702
<filename>bin/update_dependencies.py #!/usr/bin/env python3 # This file supports 3.6+ import os import shutil import subprocess import sys from pathlib import Path DIR = Path(__file__).parent.resolve() RESOURCES = DIR.parent / "cibuildwheel/resources" python_version = "".join(str(v) for v in sys.version_info[:2]) env = os.environ.copy() # CUSTOM_COMPILE_COMMAND is a pip-compile option that tells users how to # regenerate the constraints files env["CUSTOM_COMPILE_COMMAND"] = "bin/update_dependencies.py" os.chdir(DIR.parent) subprocess.run( [ "pip-compile", "--allow-unsafe", "--upgrade", "cibuildwheel/resources/constraints.in", f"--output-file=cibuildwheel/resources/constraints-python{python_version}.txt", ], check=True, env=env, ) # default constraints.txt if python_version == "39": shutil.copyfile( RESOURCES / f"constraints-python{python_version}.txt", RESOURCES / "constraints.txt", )
404
1,296
<reponame>shuryanc/sdk<gh_stars>1000+ /** * @file MAccountPurchase.cpp * @brief Get details about a MEGA purchase. * * (c) 2013-2014 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "MAccountPurchase.h" using namespace mega; using namespace Platform; MAccountPurchase::MAccountPurchase(MegaAccountPurchase *accountPurchase, bool cMemoryOwn) { this->accountPurchase = accountPurchase; this->cMemoryOwn; } MAccountPurchase::~MAccountPurchase() { if (cMemoryOwn) delete accountPurchase; } MegaAccountPurchase* MAccountPurchase::getCPtr() { return accountPurchase; } int64 MAccountPurchase::getTimestamp() { return accountPurchase ? accountPurchase->getTimestamp() : 0; } String^ MAccountPurchase::getHandle() { if (!accountPurchase) return nullptr; std::string utf16handle; const char *utf8handle = accountPurchase->getHandle(); if (!utf8handle) return nullptr; MegaApi::utf8ToUtf16(utf8handle, &utf16handle); delete[] utf8handle; return ref new String((wchar_t *)utf16handle.data()); } String^ MAccountPurchase::getCurrency() { if (!accountPurchase) return nullptr; std::string utf16currency; const char *utf8currency = accountPurchase->getCurrency(); if (!utf8currency) return nullptr; MegaApi::utf8ToUtf16(utf8currency, &utf16currency); delete[] utf8currency; return ref new String((wchar_t *)utf16currency.data()); } double MAccountPurchase::getAmount() { return accountPurchase ? accountPurchase->getAmount() : 0; } int MAccountPurchase::getMethod() { return accountPurchase ? accountPurchase->getMethod() : 0; }
714
660
/* * Copyright (c) 2019, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <cm/cm.h> #define CURBEDATACTR_SIZE 10 const uint Stat_offsets[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; static const ushort masktab[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}; static const uint offset_idx[] = {0,1,2,3,4,5,6,7}; #define NV12 0 #define P010 1 #define P210 2 #define YUY2 3 #define Y210 4 #define ARGB 5 #define NV12_Linear 6 #define HEVC_HISTORY_BUFFER_ENTRY_SIZE 32 #define HEVC_MT_TASKDATA_BUFFER_ENTRY_SIZE 96 ////////////////////CURBE and VME////////////////////////////////////// extern "C" _GENX_MAIN_ void DS_Convert( vector<uint, CURBEDATACTR_SIZE> CURBEData, SurfaceIndex PakSurfIndex, SurfaceIndex EncSurfIndex, SurfaceIndex DS4XSurf, SurfaceIndex MBStats, SurfaceIndex DS2XSurf, SurfaceIndex Hevc_History_Surface_index, SurfaceIndex Hevc_History_Sum_Surface_index, SurfaceIndex Scratch_Surface_index ) { ushort h_pos = get_thread_origin_x(); ushort v_pos = get_thread_origin_y(); vector_ref<uchar, 4 * CURBEDATACTR_SIZE> CURBEData_U8 = CURBEData.format<uchar>(); vector_ref<ushort, 2 * CURBEDATACTR_SIZE> CURBEData_U16 = CURBEData.format<ushort>(); uchar ENCChromaDepth = CURBEData_U8(2); uchar ENCLumaDepth = CURBEData_U8(3) & 0x7F; uchar colorformat = CURBEData_U8(4); vector<ushort, 1>uWidth = CURBEData_U8.format<ushort>().select<1, 1>(4); vector<ushort, 1>uHeight = CURBEData_U8.format<ushort>().select<1, 1>(5); uint height, width; uchar bflagConvert = CURBEData_U8(5) & 0x01; uchar stage = (CURBEData_U8(5) >> 1) & 0x7; uchar MBStatflag = (CURBEData_U8(5) >> 4) & 0x1; if(stage == 3) { height = (((uHeight(0) >> 2) + 31) / 32) * 32; width = (((uWidth(0) >> 2) + 31) / 32) * 32; } else { height = uHeight(0); width = uWidth(0); } uint Flatness_Threshold = CURBEData(3); // CSC Coefficients ushort CSC0 = CURBEData_U16(8); ushort CSC1 = CURBEData_U16(9); ushort CSC2 = CURBEData_U16(10); ushort CSC3 = CURBEData_U16(11); ushort CSC4 = CURBEData_U16(12); ushort CSC5 = CURBEData_U16(13); ushort CSC6 = CURBEData_U16(14); ushort CSC7 = CURBEData_U16(15); ushort CSC8 = CURBEData_U16(16); ushort CSC9 = CURBEData_U16(17); ushort CSC10 = CURBEData_U16(18); ushort CSC11 = CURBEData_U16(19); // Chroma Siting Location uchar chroma_siting_location = CURBEData_U8(6); vector<uint, 1> numLCUs; matrix<uchar, 32, 32> YPix; vector<ushort, 1> replicate; replicate[0] = 0; ushort h_pos_write = h_pos << 3; ushort v_pos_write = v_pos << 3; ushort h_pos_read = h_pos_write; vector<ushort, 1> v_pos_read = v_pos_write; vector<ushort, 1> max_dst_row = v_pos_write + 8; vector<ushort, 1> max_real_dst_row = (height >> 2); if (stage == 3) { max_real_dst_row = uHeight(0) >> 4; } replicate.merge((max_dst_row - max_real_dst_row), (max_dst_row > max_real_dst_row)); v_pos_read.merge(((max_real_dst_row << 2) - 4) >> 2, v_pos_write >= max_real_dst_row); replicate.merge(7, v_pos_write >= max_real_dst_row); int final_h_pos = h_pos_read << 2; int final_h_pos_plus_32 = 2 * final_h_pos + 32; int final_v_pos = v_pos_read(0) << 2; int final_v_pos_c = final_v_pos >> 1 ; vector<ushort, 1> replicate2; replicate2[0] = 0; ushort h_pos_write2 = h_pos << 4; ushort v_pos_write2 = v_pos << 4; ushort h_pos_read2 = h_pos_write2; vector<ushort, 1> v_pos_read2 = v_pos_write2; vector<ushort, 1> max_dst_row2 = v_pos_write2 + 16; vector<ushort, 1> max_real_dst_row2 = (height >> 1); if(stage==3) { max_real_dst_row2 = uHeight(0) >> 5; } replicate2.merge((max_dst_row2 - max_real_dst_row2), (max_dst_row2 > max_real_dst_row2)); v_pos_read2.merge(max_real_dst_row2 - 1, v_pos_write2 >= max_real_dst_row2); replicate2.merge(15, v_pos_write2 >= max_real_dst_row2); v_pos_read2[0] = v_pos_read2[0] << 1; uint final_h_pos_argb = 0; uchar quot = 0, first_index_val = 0, first_index = 0; if(bflagConvert) { final_h_pos_argb = final_h_pos; if(final_h_pos == width) { final_h_pos_argb = final_h_pos - 32; } quot = (final_h_pos + 31) / width; first_index_val = (final_h_pos + 31) % width; first_index = first_index_val; if((first_index_val > 32) && (quot > 0)) { final_h_pos_argb = final_h_pos - (first_index_val / 32) * 32; first_index = first_index_val - (first_index_val / 32) * 32; if(final_h_pos_argb == width) { final_h_pos_argb = final_h_pos_argb - 32; } } if(colorformat == P010) { matrix<ushort, 32, 32> YPix_16; vector<ushort, 1> max_col = h_pos_write; vector<ushort, 1> max_real_col = width >> 2; vector<ushort, 1> replicate_col(0); replicate_col.merge(1, (max_col >= max_real_col)); if(replicate_col[0]) { read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, 2 * width - 2, final_v_pos, YPix_16.select<32, 1, 4, 1>(0, 0)); YPix_16.select<32, 1, 4, 1>(0, 4) = YPix_16.select<32, 1, 4, 1>(0, 0); YPix_16.select<32, 1, 8, 1>(0, 8) = YPix_16.select<32, 1, 8, 1>(0, 0); YPix_16.select<32, 1, 16, 1>(0, 16) = YPix_16.select<32, 1, 16,1>(0, 0); } else { read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, 2 * final_h_pos, final_v_pos, YPix_16.select<8, 1, 16, 1>(0, 0)); read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos_plus_32, final_v_pos, YPix_16.select<8, 1, 16, 1>(0, 16)); read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, 2 * final_h_pos, final_v_pos + 8, YPix_16.select<8, 1, 16, 1>(8, 0)); read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos_plus_32, final_v_pos + 8, YPix_16.select<8, 1, 16, 1>(8, 16)); read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, 2 * final_h_pos, final_v_pos + 16, YPix_16.select<8, 1, 16, 1>(16, 0)); read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos_plus_32, final_v_pos + 16, YPix_16.select<8, 1, 16, 1>(16, 16)); read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, 2 * final_h_pos, final_v_pos + 24, YPix_16.select<8, 1, 16, 1>(24, 0)); read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos_plus_32, final_v_pos + 24, YPix_16.select<8, 1, 16, 1>(24, 16)); } uint shiftval = 16 - ENCLumaDepth; uint tempval = 1 << (shiftval - 1); vector<ushort, 32> roundval; vector<uchar, 32> roundingenable = 1; roundval.merge(tempval, 0, roundingenable); vector<ushort, 32> temptemp; int cnt; for(cnt=0; cnt < 32; cnt++) { temptemp = YPix_16.row(cnt); temptemp.merge(temptemp, 0xFF00, temptemp < 0xFF00); YPix.row(cnt) = cm_shr<uchar>(temptemp + tempval, shiftval); } matrix_ref<ushort, 16, 32> UVPix_16 = YPix_16.select<16, 1, 32, 1>(0, 0); matrix<uchar, 16, 32> UVPix; read_plane(PakSurfIndex, GENX_SURFACE_UV_PLANE, 2 * final_h_pos, final_v_pos_c, UVPix_16.select<8, 1, 16, 1>(0, 0)); read_plane(PakSurfIndex, GENX_SURFACE_UV_PLANE, final_h_pos_plus_32, final_v_pos_c, UVPix_16.select<8, 1, 16, 1>(0, 16)); read_plane(PakSurfIndex, GENX_SURFACE_UV_PLANE, 2 * final_h_pos, final_v_pos_c + 8, UVPix_16.select<8, 1, 16, 1>(8, 0)); read_plane(PakSurfIndex, GENX_SURFACE_UV_PLANE, final_h_pos_plus_32, final_v_pos_c + 8, UVPix_16.select<8, 1, 16, 1>(8, 16)); shiftval = 16 - ENCChromaDepth; tempval = 1 << (shiftval - 1); roundval.merge(tempval, 0, roundingenable); for(cnt = 0; cnt < 16; cnt++) { temptemp = UVPix_16.row(cnt); temptemp.merge(temptemp, 0xFF00, temptemp < 0xFF00); UVPix.row(cnt) = cm_shr<uchar>(temptemp + tempval, shiftval); } write_plane(EncSurfIndex, GENX_SURFACE_UV_PLANE, final_h_pos, final_v_pos_c, UVPix.select<8, 1, 32, 1>(0, 0)); write_plane(EncSurfIndex, GENX_SURFACE_UV_PLANE, final_h_pos, final_v_pos_c + 8, UVPix.select<8, 1, 32, 1>(8, 0)); write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos, YPix.select<8, 1, 32, 1>(0, 0)); write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + 8, YPix.select<8, 1, 32, 1>(8, 0)); write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + 16, YPix.select<8, 1, 32, 1>(16,0)); write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + 24, YPix.select<8, 1, 32, 1>(24,0)); if (!stage) { cm_fence(); return; } } else if (colorformat == Y210) { matrix<ushort, 8, 32> YUV_Data16_10bit; matrix<uchar, 8, 32> UVPix_422; read (PakSurfIndex, 4 * final_h_pos_argb, final_v_pos, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 0)); read (PakSurfIndex, 4 * final_h_pos_argb + 32, final_v_pos, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 16)); YUV_Data16_10bit.merge(YUV_Data16_10bit, 0xFF00, YUV_Data16_10bit < 0xFF00); YPix.select<8, 1, 16, 1>(0, 0) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 0) + 0x80, 8); UVPix_422.select<8, 1, 16, 1>(0, 0) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 1) + 0x80, 8); read (PakSurfIndex, 4 * final_h_pos_argb+64, final_v_pos, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 0)); read (PakSurfIndex, 4 * final_h_pos_argb+96, final_v_pos, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 16)); YUV_Data16_10bit.merge(YUV_Data16_10bit, 0xFF00, YUV_Data16_10bit < 0xFF00); YPix.select<8, 1, 16, 1>(0, 16) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 0) + 0x80, 8); UVPix_422.select<8,1,16,1>(0,16) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 1) + 0x80, 8); if((final_v_pos + 8) <= height) { write(EncSurfIndex, final_h_pos, final_v_pos, YPix.select<8, 1, 32, 1>(0, 0)); } write(EncSurfIndex, final_h_pos, height + final_v_pos, UVPix_422 ); read (PakSurfIndex, 4 * final_h_pos_argb, final_v_pos + 8, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 0)); read (PakSurfIndex, 4 * final_h_pos_argb + 32, final_v_pos + 8, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 16)); YUV_Data16_10bit.merge(YUV_Data16_10bit, 0xFF00, YUV_Data16_10bit < 0xFF00); YPix.select<8, 1, 16, 1>(8, 0) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 0) + 0x80, 8); UVPix_422.select<8,1,16,1>(0, 0) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 1) + 0x80, 8); read (PakSurfIndex, 4 * final_h_pos_argb + 64, final_v_pos + 8, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 0)); read (PakSurfIndex, 4 * final_h_pos_argb + 96, final_v_pos + 8, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 16)); YUV_Data16_10bit.merge(YUV_Data16_10bit, 0xFF00, YUV_Data16_10bit < 0xFF00); YPix.select<8, 1, 16, 1>(8, 16) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 0) + 0x80, 8); UVPix_422.select<8,1,16,1>(0, 16) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 1) + 0x80, 8); if( (final_v_pos + 16) <= height) { write(EncSurfIndex, final_h_pos, final_v_pos + 8, YPix.select<8, 1, 32, 1>(8, 0) ); } write(EncSurfIndex, final_h_pos, height + final_v_pos + 8, UVPix_422 ); read (PakSurfIndex, 4 * final_h_pos_argb, final_v_pos + 16, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 0)); read (PakSurfIndex, 4 * final_h_pos_argb + 32, final_v_pos + 16, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 16)); YUV_Data16_10bit.merge(YUV_Data16_10bit, 0xFF00, YUV_Data16_10bit < 0xFF00); YPix.select<8, 1, 16, 1>(16, 0) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 0) + 0x80, 8); UVPix_422.select<8, 1, 16, 1>(0, 0) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 1) + 0x80, 8); read (PakSurfIndex, 4 * final_h_pos_argb + 64, final_v_pos+16, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 0)); read (PakSurfIndex, 4 * final_h_pos_argb + 96, final_v_pos+16, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 16)); YUV_Data16_10bit.merge(YUV_Data16_10bit, 0xFF00, YUV_Data16_10bit < 0xFF00); YPix.select<8, 1, 16, 1>(16, 16) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 0) + 0x80, 8); UVPix_422.select<8,1,16,1>(0, 16) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 1) + 0x80, 8); if( (final_v_pos + 24) <= height) { write(EncSurfIndex, final_h_pos, final_v_pos+16, YPix.select<8, 1, 32, 1>(16, 0) ); } write(EncSurfIndex, final_h_pos, height + final_v_pos + 16, UVPix_422 ); read (PakSurfIndex, 4 * final_h_pos_argb, final_v_pos + 24, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 0)); read (PakSurfIndex, 4 * final_h_pos_argb + 32, final_v_pos + 24, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 16)); YUV_Data16_10bit.merge(YUV_Data16_10bit, 0xFF00, YUV_Data16_10bit < 0xFF00); YPix.select<8, 1, 16, 1>(24, 0) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 0) + 0x80, 8); UVPix_422.select<8, 1, 16, 1>(0, 0) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 1) + 0x80, 8); read (PakSurfIndex, 4 * final_h_pos_argb + 64, final_v_pos + 24, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 0)); read (PakSurfIndex, 4 * final_h_pos_argb + 96, final_v_pos + 24, YUV_Data16_10bit.select<8, 1, 16, 1>(0, 16)); YUV_Data16_10bit.merge(YUV_Data16_10bit, 0xFF00, YUV_Data16_10bit < 0xFF00); YPix.select<8, 1, 16, 1>(24, 16) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 0) + 0x80, 8); UVPix_422.select<8, 1, 16, 1>(0, 16) = cm_shr<uchar>(YUV_Data16_10bit.select<8, 1, 16, 2>(0, 1) + 0x80, 8); if( (final_v_pos + 32) <= height) { write(EncSurfIndex, final_h_pos, final_v_pos + 24, YPix.select<8, 1, 32, 1>(24, 0) ); } write(EncSurfIndex, final_h_pos, height + final_v_pos+24, UVPix_422 ); } else if(colorformat == ARGB) { matrix<uchar, 16, 32> ARGB_Data; matrix_ref<uchar, 8, 32> c1 = ARGB_Data.select<8,1,32,1>(0, 0); matrix<uchar, 16, 32> r; matrix<uchar, 16, 32> g; matrix<uchar, 16, 32> b; for(uint i = 0; i < 2; i++) { #pragma unroll for( int j = 0; j < 4;j++) { read(PakSurfIndex, 4 * final_h_pos_argb + 32 * j, final_v_pos + i * 16, c1); r.select<8, 1, 8, 1>(0, 8 * j) = c1.select<8, 1, 8, 4>(0, 2); g.select<8, 1, 8, 1>(0, 8 * j) = c1.select<8, 1, 8, 4>(0, 1); b.select<8, 1, 8, 1>(0, 8 * j) = c1.select<8, 1, 8, 4>(0, 0); } #pragma unroll for( int j = 0; j < 4;j++) { read(PakSurfIndex, 4 * final_h_pos_argb + 32 * j, final_v_pos + i * 16 + 8, c1); r.select<8,1,8,1>(8,8*j) = c1.select<8, 1, 8, 4>(0, 2); g.select<8,1,8,1>(8,8*j) = c1.select<8, 1, 8, 4>(0, 1); b.select<8,1,8,1>(8,8*j) = c1.select<8, 1, 8, 4>(0, 0); } if(quot > 0) { vector<uchar, 32> replicants; vector<ushort, 32> masktable = 1; vector<ushort, 32> final_h_pos_mask(masktab); final_h_pos_mask = final_h_pos_mask + final_h_pos; masktable.merge(masktable, 0, final_h_pos_mask < width); for(uint mcount=0;mcount<16;mcount++) { replicants = r(mcount,first_index); r.row(mcount).merge(r.row(mcount), replicants, masktable); replicants = g(mcount,first_index); g.row(mcount).merge(g.row(mcount), replicants, masktable); replicants = b(mcount,first_index); b.row(mcount).merge(b.row(mcount), replicants, masktable); } } vector<uint, 32> temp; matrix_ref<uchar, 16, 32> v = YPix.select<16, 1, 32, 1>(16, 0).format<uchar, 16, 32>(); #pragma unroll for(uint k = 0; k < 16; k++) { temp = g.row(k) * CSC8; temp = temp + r.row(k) * CSC10; temp = (temp + b.row(k) * CSC9) >> 7; ARGB_Data.row(k) = temp.select<32,1>(0) + CSC11; } #pragma unroll for(uint k=0; k<16; k++) { temp = r.row(k) * CSC2; temp = temp + g.row(k) * CSC0; temp = (temp + b.row(k) * CSC1) >> 7; v.row(k) = temp.select<32,1>(0) + CSC3; } matrix<ushort, 4, 16> first_sum; if (chroma_siting_location == 1) { #pragma unroll for(uint k = 0; k < 2; k++) { first_sum.select<4, 1, 16, 1>(0, 0) = ARGB_Data.select<4, 2, 16, 2>(8 * k, 0) + ARGB_Data.select<4, 2, 16, 2>(8 * k, 1); first_sum.select<4, 1, 16, 1>(0, 0) += 1; ARGB_Data.select<4, 1, 16, 2>(4 * k, 0) = first_sum.select<4, 1, 16, 1>(0, 0) >> 1; } #pragma unroll for(uint k=0; k<2; k++) { first_sum.select<4, 1, 16, 1>(0, 0) = v.select<4, 2, 16, 2>(8 * k, 0) + v.select<4, 2, 16, 2>(8 * k, 1); first_sum.select<4, 1, 16, 1>(0, 0) += 1; ARGB_Data.select<4, 1, 16, 2>(4 * k, 1) = first_sum.select<4, 1, 16, 1>(0, 0) >> 1; } } else if (chroma_siting_location == 2) { #pragma unroll for(uint k = 0; k < 2; k++) { first_sum.select<4, 1, 16, 1>(0, 0) = ARGB_Data.select<4, 2, 16, 2>(8 * k + 1, 0) + ARGB_Data.select<4, 2, 16, 2>(8 * k + 1, 1); first_sum.select<4, 1, 16, 1>(0, 0) += 1; ARGB_Data.select<4, 1, 16, 2>(4 * k, 0) = first_sum.select<4, 1, 16, 1>(0, 0) >> 1; } #pragma unroll for(uint k=0; k<2; k++) { first_sum.select<4, 1, 16, 1>(0, 0) = v.select<4, 2, 16, 2>(8 * k + 1, 0) + v.select<4, 2, 16, 2>(8 * k + 1, 1); first_sum.select<4, 1, 16, 1>(0, 0) += 1; ARGB_Data.select<4, 1, 16, 2>(4 * k, 1) = first_sum.select<4, 1, 16, 1>(0, 0) >> 1; } } else if (chroma_siting_location == 3) { ARGB_Data.select<8, 1, 16, 2>(0, 0) = ARGB_Data.select<8, 2, 16, 2>(0, 0); ARGB_Data.select<8, 1, 16, 2>(0, 1) = v.select<8, 2, 16, 2>(0, 0); } else if (chroma_siting_location == 4) { #pragma unroll for(uint k=0; k<2; k++) { first_sum.select<4, 1, 16, 1>(0, 0) = ARGB_Data.select<4, 2, 16, 2>(8 * k, 0) + ARGB_Data.select<4, 2, 16, 2>(8 * k + 1, 0); first_sum.select<4, 1, 16, 1>(0, 0) += 1; ARGB_Data.select<4, 1, 16, 2>(4 * k, 0) = first_sum.select<4, 1, 16, 1>(0, 0) >> 1; } #pragma unroll for(uint k=0; k<2; k++) { first_sum.select<4, 1, 16, 1>(0, 0) = v.select<4, 2, 16, 2>(8 * k, 0) + v.select<4, 2, 16, 2>(8 * k + 1, 0); first_sum.select<4, 1, 16, 1>(0, 0) += 1; ARGB_Data.select<4, 1, 16, 2>(4 * k, 1) = first_sum.select<4, 1, 16, 1>(0, 0) >> 1; } } else if (chroma_siting_location == 5) { ARGB_Data.select<8, 1, 16, 2>(0, 0) = ARGB_Data.select<8, 2, 16, 2>(1, 0); ARGB_Data.select<8, 1, 16, 2>(0, 1) = v.select<8, 2, 16, 2>(1, 0); } else { #pragma unroll for(uint k = 0; k < 4; k++) { first_sum = ARGB_Data.select<4, 1, 16, 2>(4 * k, 0) + ARGB_Data.select<4, 1, 16, 2>(4 * k, 1); first_sum.select<2, 1, 16, 1>(0, 0) = first_sum.select<2, 2, 16, 1>(0, 0) + first_sum.select<2, 2, 16, 1>(1, 0); first_sum.select<2, 1, 16, 1>(0, 0) += 2; ARGB_Data.select<2, 1, 16, 2>(2*k, 0) = first_sum.select<2, 1, 16, 1>(0, 0) >> 2; } #pragma unroll for(uint k=0; k<4; k++) { first_sum = v.select<4, 1, 16, 2>(4 * k, 0) + v.select<4, 1, 16, 2>(4 * k, 1); first_sum.select<2, 1, 16, 1>(0, 0) = first_sum.select<2, 2, 16, 1>(0, 0) + first_sum.select<2, 2, 16, 1>(1, 0); first_sum.select<2, 1, 16, 1>(0, 0) += 2; ARGB_Data.select<2, 1, 16, 2>(2 * k, 1) = first_sum.select<2, 1, 16, 1>(0, 0) >> 2; } } write_plane(EncSurfIndex, GENX_SURFACE_UV_PLANE, final_h_pos, (final_v_pos >> 1) + i * 8, ARGB_Data.select<8, 1, 32, 1>(0, 0)); #pragma unroll for(uint k=0; k < 16; k++) { temp = r.row(k) * CSC6; temp = temp + g.row(k) * CSC4; temp = (temp + b.row(k) * CSC5) >> 7; ARGB_Data.row(k) = temp.select<32,1>(0) + CSC7; } write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + i*16, ARGB_Data.select<8, 1, 32, 1>(0, 0)); write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + i*16 + 8, ARGB_Data.select<8, 1, 32, 1>(8, 0)); YPix.select<16,1,32,1>(0+i*16,0) = ARGB_Data.select<16,1,32,1>(0,0); } if (!stage) { cm_fence(); return; } } else if (colorformat == YUY2) { matrix<uchar, 8, 64> YUV_Data8_8bit; matrix<ushort, 4, 32> temp = 0; uchar YUY2convertflag = (CURBEData_U8(5) >> 5) & 0x1; for(int i=0; i<2; i++) { read (PakSurfIndex, 2 * final_h_pos_argb, final_v_pos + i * 16, YUV_Data8_8bit.select<8, 1, 32, 1>(0, 0)); read (PakSurfIndex, 2 * final_h_pos_argb + 32, final_v_pos + i * 16, YUV_Data8_8bit.select<8, 1, 32, 1>(0, 32)); YPix.select<8, 1, 32, 1>(i * 16, 0) = YUV_Data8_8bit.select<8, 1, 32, 2>(0, 0); if(YUY2convertflag) { matrix_ref<uchar, 8, 32> uv_channel = YUV_Data8_8bit.select<8, 1, 32, 2>(0, 1); temp.select<4, 1, 32, 1>(0, 0) = uv_channel.select<4, 2, 32, 1>(0, 0) + uv_channel.select<4, 2, 32, 1>(1, 0); temp.select<4, 1, 32, 1>(0, 0) += 1; temp.select<4, 1, 32, 1>(0, 0) = temp.select<4, 1, 32, 1>(0, 0) >> 1; matrix_ref <uchar, 4, 64> uv_temp = temp.format<uchar, 4, 64>(); matrix_ref <uchar, 4, 32> uv = uv_temp.select<4, 1, 32, 2>(0, 0); if( (final_v_pos+8 + i * 16) <= height) { write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + i * 16, YUV_Data8_8bit.select<8, 1, 32, 2>(0, 0)); } write_plane(EncSurfIndex, GENX_SURFACE_UV_PLANE, final_h_pos, (final_v_pos >> 1) + i * 8, uv.select<4, 1, 32, 1>(0, 0)); } else { if( (final_v_pos + 8 + i * 16) <= height) { write(EncSurfIndex, final_h_pos, final_v_pos + i * 16, YUV_Data8_8bit.select<8, 1, 32, 2>(0, 0)); } write(EncSurfIndex, final_h_pos, height + final_v_pos + i * 16, YUV_Data8_8bit.select<8, 1, 32, 2>(0, 1)); } read (PakSurfIndex, 2 * final_h_pos_argb, final_v_pos + 8 + i * 16, YUV_Data8_8bit.select<8, 1, 32, 1>(0, 0)); read (PakSurfIndex, 2 * final_h_pos_argb + 32, final_v_pos + 8 + i * 16, YUV_Data8_8bit.select<8, 1, 32, 1>(0, 32)); YPix.select<8, 1, 32, 1>(8 + i * 16, 0) = YUV_Data8_8bit.select<8, 1, 32, 2>(0, 0); if(YUY2convertflag) { matrix_ref<uchar, 8, 32> uv_channel = YUV_Data8_8bit.select<8, 1, 32, 2>(0, 1); temp.select<4, 1, 32, 1>(0, 0) = uv_channel.select<4, 2, 32, 1>(0, 0) + uv_channel.select<4, 2, 32, 1>(1, 0); temp.select<4, 1, 32, 1>(0, 0) += 1; temp.select<4, 1, 32, 1>(0, 0) = temp.select<4, 1, 32, 1>(0, 0) >> 1; matrix_ref<uchar, 4, 64> uv_temp = temp.format<uchar, 4, 64>(); matrix_ref<uchar, 4, 32> uv = uv_temp.select<4, 1, 32, 2>(0, 0); if ((final_v_pos+16 + i * 16) <= height) { write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + 8 + i * 16, YUV_Data8_8bit.select<8, 1, 32, 2>(0, 0) ); } write_plane(EncSurfIndex, GENX_SURFACE_UV_PLANE, final_h_pos, (final_v_pos >> 1) + 4 + i * 8, uv.select<4, 1, 32, 1>(0, 0)); } else { if ((final_v_pos + 16 + i * 16) <= height) { write(EncSurfIndex, final_h_pos, final_v_pos + 8 + i * 16, YUV_Data8_8bit.select<8, 1, 32, 2>(0, 0)); } write(EncSurfIndex, final_h_pos, height + final_v_pos + 8 + i * 16, YUV_Data8_8bit.select<8, 1, 32, 2>(0, 1)); } } if(!stage) { cm_fence(); return; } } else if (colorformat == NV12_Linear) { read(PakSurfIndex, final_h_pos, height + (final_v_pos >> 1), YPix.select<8,1,32,1>(0, 0)); read(PakSurfIndex, final_h_pos, height + (final_v_pos >> 1) + 8, YPix.select<8,1,32,1>(8, 0)); write_plane(EncSurfIndex, GENX_SURFACE_UV_PLANE, final_h_pos, final_v_pos >> 1, YPix.select<8,1,32,1>(0, 0)); write_plane(EncSurfIndex, GENX_SURFACE_UV_PLANE, final_h_pos, (final_v_pos >> 1) + 8, YPix.select<8,1,32,1>(8, 0)); read(PakSurfIndex, final_h_pos, final_v_pos, YPix.select<8, 1, 32, 1>(0, 0)); read(PakSurfIndex, final_h_pos, final_v_pos + 8, YPix.select<8, 1, 32, 1>(8, 0)); read(PakSurfIndex, final_h_pos, final_v_pos + 16, YPix.select<8, 1, 32, 1>(16,0)); read(PakSurfIndex, final_h_pos, final_v_pos + 24, YPix.select<8, 1, 32, 1>(24,0)); write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos, YPix.select<8, 1, 32, 1>(0, 0)); write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + 8, YPix.select<8, 1, 32, 1>(8, 0)); write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + 16, YPix.select<8, 1, 32, 1>(16,0)); write_plane(EncSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + 24, YPix.select<8, 1, 32, 1>(24,0)); } if( (colorformat == YUY2) || (colorformat == Y210) ) { if(quot > 0) { vector<ushort, 32> maskgb = masktab; first_index = first_index >> 1; vector<ushort, 16> replicants = 0; vector<ushort, 16> masktable = 0; vector<ushort, 16> final_h_pos_mask = 0; final_h_pos_mask = final_h_pos + 2 * maskgb.select<16, 1>(); matrix_ref<ushort, 32, 16>YPix_2byte = YPix.format<ushort, 32, 16>(); masktable = 1; masktable.merge(masktable, 0, final_h_pos_mask < width); for(uint mcount = 0; mcount < 32; mcount++) { replicants = YPix_2byte(mcount, first_index); YPix_2byte.row(mcount).merge(YPix_2byte.row(mcount), replicants, masktable); mcount++; replicants = YPix_2byte(mcount, first_index); YPix_2byte.row(mcount).merge(YPix_2byte.row(mcount), replicants, masktable); mcount++; replicants = YPix_2byte(mcount, first_index); YPix_2byte.row(mcount).merge(YPix_2byte.row(mcount), replicants, masktable); mcount++; replicants = YPix_2byte(mcount,first_index); YPix_2byte.row(mcount).merge(YPix_2byte.row(mcount), replicants, masktable); } } } } else { read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos, YPix.select<8, 1, 32, 1>(0, 0)); read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + 8, YPix.select<8, 1, 32, 1>(8, 0)); read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + 16, YPix.select<8, 1, 32, 1>(16,0)); read_plane(PakSurfIndex, GENX_SURFACE_Y_PLANE, final_h_pos, final_v_pos + 24, YPix.select<8, 1, 32, 1>(24,0)); } matrix<uchar, 16, 16> YDown2 = 0; matrix<ushort, 8, 16> temp1 = 0; matrix<ushort, 8, 8> temp2 = 0; matrix<ushort, 4, 4> temp3 = 0; matrix<uchar, 8, 8> out = 0; #pragma unroll for(uint i = 0; i < 2; i++) { #pragma unroll for(uint j = 0; j< 2; j++) { temp1.select<8, 1, 16, 1>(0, 0) = YPix.select<8, 2, 16, 1>(i << 4, j << 4) + YPix.select<8, 2, 16, 1>((i << 4) + 1, j << 4 ); temp2.select<8, 1, 8, 1>(0, 0) = temp1.select<8, 1, 8, 2>(0, 0) + temp1.select<8, 1, 8, 2>(0, 1); temp2.select<8, 1, 8, 1>(0, 0) += 2; temp2.select<8, 1, 8, 1>(0, 0) = temp2.select<8, 1, 8, 1>(0, 0) >> 2; if((stage == 1) || (stage == 4)) { YDown2.select<8, 1, 8, 1>(i << 3, j << 3) = temp2.select<8, 1, 8, 1>(0, 0); } temp2.select<4, 2, 8, 1>(0, 0) = temp2.select<4, 2, 8, 1>(0, 0) + temp2.select<4, 2, 8, 1>(1, 0); temp3.select<4, 1, 4, 1>(0, 0) = temp2.select<4, 2, 4, 2>(0, 0) + temp2.select<4, 2, 4, 2>(0, 1); temp3.select<4, 1, 4, 1>(0, 0) += 2; temp3.select<4, 1, 4, 1>(0, 0) = temp3.select<4, 1, 4, 1>(0, 0) >> 2; out.select<4, 1, 4, 1>(i << 2, j << 2) = temp3.select<4, 1, 4, 1>(0, 0); } } if ((!replicate[0]) || (!replicate2[0])) { if(stage>1) { write(DS4XSurf, h_pos_write, v_pos_write, out); } if(stage ==1 || stage == 4) { write(DS2XSurf, h_pos_write2, v_pos_write2, YDown2); } } else { matrix<uchar, 1, 8>last_line = out.select<1, 1, 8, 1>(7 - replicate[0], 0); vector<int, 16>mask2; vector_ref<int, 8>mask = mask2.select<8, 1>(); #pragma unroll for(uint i = 1; i < 8; i++) { mask = i > 7 - replicate[0]; out.select<1, 1, 8, 1>(i, 0).merge(last_line, mask); } if ((stage == 4) || (stage == 1)) { if(replicate2[0] >= 15) { matrix<uchar, 1, 16> lastline2 = YDown2.row(1); for(uint i=0; i<16; i++) { YDown2.row(i) = lastline2; } } else { matrix<uchar, 1, 16> last_line2 = YDown2.select<1, 1, 16, 1>(15 - replicate2[0], 0); #pragma unroll for(uint i = 1; i < 16; i++) { mask2 = i > 15 - replicate2[0]; YDown2.select<1, 1, 16, 1>(i, 0).merge(last_line2, mask2 ); } } write(DS2XSurf, h_pos_write2, v_pos_write2, YDown2); } if(stage>1) write(DS4XSurf, h_pos_write, v_pos_write, out); } if(MBStatflag) { width = uWidth(0); height = uHeight(0); matrix<ushort, 32, 32> squared; matrix<uint, 2, 2> sum; matrix<uint, 2, 2> pixAvg; matrix<uint, 2, 2> SumOfSquared; matrix_ref<uint,2, 2> VarianceLuma = SumOfSquared; matrix_ref<uint,2, 2> flatness_check = sum; squared = YPix * YPix; sum[0][0] = cm_sum<uint>(YPix.select<16, 1, 16, 1>(0, 0), SAT); SumOfSquared[0][0] = cm_sum<uint>(squared.select<16, 1, 16, 1>(0, 0), SAT); sum[0][1] = cm_sum<uint>(YPix.select<16, 1, 16, 1>(0, 16), SAT); SumOfSquared[0][1] = cm_sum<uint>(squared.select<16, 1, 16, 1>(0, 16), SAT); sum[1][0] = cm_sum<uint>(YPix.select<16, 1, 16, 1>(16, 0), SAT); SumOfSquared[1][0] = cm_sum<uint>(squared.select<16, 1, 16, 1>(16, 0), SAT); sum[1][1] = cm_sum<uint>(YPix.select<16, 1, 16, 1>(16, 16), SAT); SumOfSquared[1][1] = cm_sum<uint>(squared.select<16, 1, 16, 1>(16, 16), SAT); pixAvg = sum >> 8; sum *= sum; sum >>= 8; VarianceLuma = SumOfSquared - sum; VarianceLuma >>= 8; flatness_check = (VarianceLuma < Flatness_Threshold); unsigned short NumMBperRow = width / 16; NumMBperRow += ((width % 16)> 0); unsigned int offset_vp = (2 * 16 * 4 * (v_pos * NumMBperRow + h_pos)); unsigned int offset2_vp = offset_vp + NumMBperRow * 64; vector<uint, 64> writeVProc(0); vector<uint, 16> Element_Offset(Stat_offsets); offset_vp >>= 2; offset2_vp >>= 2; writeVProc.select<2,16>(5) = flatness_check.row(0); writeVProc.select<2,16>(37) = flatness_check.row(1); writeVProc.select<2,16>(6) = VarianceLuma.row(0); writeVProc.select<2,16>(38) = VarianceLuma.row(1); writeVProc.select<2,16>(11) = pixAvg.row(0); writeVProc.select<2,16>(43) = pixAvg.row(1); if((h_pos * 32 < width) && (v_pos * 32 < height)) { if((h_pos * 32)+ 16 >= width) { write(MBStats, offset_vp, Element_Offset, writeVProc.select<16,1>(0)); } else { write(MBStats, offset_vp, Element_Offset, writeVProc.select<16,1>(0)); write(MBStats, offset_vp + 16, Element_Offset, writeVProc.select<16,1>(16)); } if((v_pos * 32)+16 < height) { if((h_pos * 32)+ 16 >= width) { write(MBStats, offset2_vp, Element_Offset, writeVProc.select<16,1>(32)); } else { write(MBStats, offset2_vp, Element_Offset, writeVProc.select<16,1>(32)); write(MBStats, offset2_vp + 16, Element_Offset, writeVProc.select<16,1>(48)); } } } } uchar hevc_enc_history = (CURBEData_U8(5) >> 6) & 0x1; if(hevc_enc_history) { uchar LCUtype = (CURBEData_U8(5) >> 7) & 0x1; vector<ushort, 32> clear_buffer; vector_ref<ushort, 16> clear_buffer1 = clear_buffer.select<16, 1>(0); vector<ushort, 16> History_perLCU; uint offset = 0; uchar shift_factor = LCUtype == 0 ? 6 : 5; vector_ref<ushort, 1> WidthLCU = History_perLCU.select<1, 1>(0); vector_ref<ushort, 1> HeightLCU = History_perLCU.select<1, 1>(1); WidthLCU(0) = (uWidth(0) + ((1 << shift_factor) - 1)) >> shift_factor; HeightLCU(0) = (uHeight(0) + ((1 << shift_factor) - 1)) >> shift_factor; if(h_pos == 0 && v_pos == 0) { clear_buffer = 0; numLCUs = WidthLCU * HeightLCU; for(uint i = 0; i < numLCUs(0); i++) { read(Hevc_History_Surface_index, offset, History_perLCU); clear_buffer.select<16, 1>(0) += History_perLCU; offset += HEVC_HISTORY_BUFFER_ENTRY_SIZE; } clear_buffer.select<4,1>(4) = History_perLCU.select<4,1>(4); clear_buffer.select<8,1>(8) = History_perLCU.select<8,1>(8); write(Hevc_History_Sum_Surface_index, 0, clear_buffer); } if((h_pos == 1) && (v_pos == 0)) { offset = 0; clear_buffer1 = 0; numLCUs = WidthLCU * HeightLCU; for(uint i = 0; i < numLCUs(0); i++) { write(Scratch_Surface_index, offset, clear_buffer1); write(Scratch_Surface_index, offset + 32, clear_buffer1); write(Scratch_Surface_index, offset + 64, clear_buffer1); offset += 96; } } } cm_fence(); }
23,393
432
package us.parr.bookish.model; public class InlineEquation extends InlineImage { public String eqn; public float height, depth; public int descentPercentage; public int depthRounded; public float depthTweaked; public InlineEquation(String imageFilename, String eqn, float height, float depth) { super(imageFilename); this.eqn = eqn; this.height = height; this.depth = depth; if ( depth < 0.5 ) { depthTweaked = 0.5f; } else if ( depth < 1.3 ) { depthTweaked = depth;//0.5f; } else { depthTweaked = depth*1.05f; } this.descentPercentage = (int)(100*depth/(height+depth)); depthRounded = Math.round(depth); } }
249
620
<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- import os import argparse import os.path as osp from tqdm import tqdm from utils import (dump_data, read_meta, write_meta, build_knns, filter_clusters, labels2clusters, clusters2labels, BasicDataset, Timer) from proposals import super_vertex def parse_args(): parser = argparse.ArgumentParser(description='Generate Basic Proposals') parser.add_argument("--name", type=str, default='part1_test', help="image features") parser.add_argument("--prefix", type=str, default='./data', help="prefix of dataset") parser.add_argument("--oprefix", type=str, default='./data/cluster_proposals', help="prefix of saving super vertx") parser.add_argument("--dim", type=int, default=256, help="dimension of feature") parser.add_argument("--no_normalize", action='store_true', help="normalize feature by default") parser.add_argument('--k', default=80, type=int) parser.add_argument('--th_knn', default=0.7, type=float) parser.add_argument('--th_step', default=0.05, type=float) parser.add_argument('--knn_method', default='faiss', choices=['faiss', 'hnsw']) parser.add_argument('--maxsz', default=300, type=int) parser.add_argument('--minsz', default=3, type=int) parser.add_argument('--is_rebuild', action='store_true') parser.add_argument('--is_save_proposals', action='store_true') parser.add_argument('--force', action='store_true') args = parser.parse_args() return args def save_proposals(clusters, knns, ofolder, force=False): for lb, nodes in enumerate(tqdm(clusters)): opath_node = osp.join(ofolder, '{}_node.npz'.format(lb)) opath_edge = osp.join(ofolder, '{}_edge.npz'.format(lb)) if not force and osp.exists(opath_node) and osp.exists(opath_edge): continue nodes = set(nodes) edges = [] visited = set() # get edges from knn for idx in nodes: ners, dists = knns[idx] for n, dist in zip(ners, dists): if n == idx or n not in nodes: continue idx1, idx2 = (idx, n) if idx < n else (n, idx) key = '{}-{}'.format(idx1, idx2) if key not in visited: visited.add(key) edges.append([idx1, idx2, dist]) # save to npz file nodes = list(nodes) dump_data(opath_node, data=nodes, force=force) dump_data(opath_edge, data=edges, force=force) def generate_basic_proposals(oprefix, knn_prefix, feats, feat_dim=256, knn_method='faiss', k=80, th_knn=0.6, th_step=0.05, minsz=3, maxsz=300, is_rebuild=False, is_save_proposals=True, force=False, **kwargs): print('k={}, th_knn={}, th_step={}, maxsz={}, is_rebuild={}'.format( k, th_knn, th_step, maxsz, is_rebuild)) # build knns knns = build_knns(knn_prefix, feats, knn_method, k, is_rebuild) # obtain cluster proposals ofolder = osp.join( oprefix, '{}_k_{}_th_{}_step_{}_minsz_{}_maxsz_{}_iter_0'.format( knn_method, k, th_knn, th_step, minsz, maxsz)) ofn_pred_labels = osp.join(ofolder, 'pred_labels.txt') if not osp.exists(ofolder): os.makedirs(ofolder) if not osp.isfile(ofn_pred_labels) or is_rebuild: with Timer('build super vertices'): clusters = super_vertex(knns, k, th_knn, th_step, maxsz) with Timer('dump clustering to {}'.format(ofn_pred_labels)): labels = clusters2labels(clusters) write_meta(ofn_pred_labels, labels) else: print('read clusters from {}'.format(ofn_pred_labels)) lb2idxs, _ = read_meta(ofn_pred_labels) clusters = labels2clusters(lb2idxs) clusters = filter_clusters(clusters, minsz) # output cluster proposals ofolder_proposals = osp.join(ofolder, 'proposals') if is_save_proposals: print('saving cluster proposals to {}'.format(ofolder_proposals)) if not osp.exists(ofolder_proposals): os.makedirs(ofolder_proposals) save_proposals(clusters, knns, ofolder=ofolder_proposals, force=force) return ofolder_proposals, ofn_pred_labels if __name__ == '__main__': args = parse_args() ds = BasicDataset(name=args.name, prefix=args.prefix, dim=args.dim, normalize=not args.no_normalize) ds.info() generate_basic_proposals(osp.join(args.oprefix, args.name), osp.join(args.prefix, 'knns', args.name), ds.features, args.dim, args.knn_method, args.k, args.th_knn, args.th_step, args.minsz, args.maxsz, is_rebuild=args.is_rebuild, is_save_proposals=args.is_save_proposals, force=args.force)
3,272
496
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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 co.elastic.apm.agent.collections; import co.elastic.apm.agent.impl.transaction.AbstractSpan; import co.elastic.apm.agent.sdk.weakconcurrent.DetachedThreadLocal; import co.elastic.apm.agent.sdk.weakconcurrent.WeakConcurrent; import co.elastic.apm.agent.sdk.weakconcurrent.WeakMap; import co.elastic.apm.agent.sdk.weakconcurrent.WeakSet; import com.blogspot.mydailyjava.weaklockfree.AbstractWeakConcurrentMap; import com.blogspot.mydailyjava.weaklockfree.WeakConcurrentSet; import javax.annotation.Nullable; import java.util.concurrent.ConcurrentHashMap; /** * The canonical place to get a new instance of a {@link WeakMap}, {@link WeakSet}, or {@link DetachedThreadLocal}. * Do not instantiate a {@link AbstractWeakConcurrentMap} directly to benefit from the global cleanup of stale entries. */ public class WeakConcurrentProviderImpl implements WeakConcurrent.WeakConcurrentProvider { private static final WeakConcurrentSet<AbstractWeakConcurrentMap<?, ?, ?>> registeredMaps = new WeakConcurrentSet<>(WeakConcurrentSet.Cleaner.INLINE); public static <K, V extends AbstractSpan<?>> WeakMap<K, V> createWeakSpanMap() { SpanConcurrentHashMap<AbstractWeakConcurrentMap.WeakKey<K>, V> map = new SpanConcurrentHashMap<>(); NullSafeWeakConcurrentMap<K, V> result = new NullSafeWeakConcurrentMap<>(map); registeredMaps.add(result); return result; } @Override public <K, V> WeakConcurrent.WeakMapBuilder<K, V> weakMapBuilder() { return new WeakConcurrent.WeakMapBuilder<K, V>() { @Nullable private WeakMap.DefaultValueSupplier<K, V> defaultValueSupplier; private int initialCapacity = 16; @Override public WeakConcurrent.WeakMapBuilder<K, V> withInitialCapacity(int initialCapacity) { this.initialCapacity = initialCapacity; return this; } @Override public WeakConcurrent.WeakMapBuilder<K, V> withDefaultValueSupplier(@Nullable WeakMap.DefaultValueSupplier<K, V> defaultValueSupplier) { this.defaultValueSupplier = defaultValueSupplier; return this; } @Override public WeakMap<K, V> build() { NullSafeWeakConcurrentMap<K, V> map = new NullSafeWeakConcurrentMap<K, V>(new ConcurrentHashMap<AbstractWeakConcurrentMap.WeakKey<K>, V>(initialCapacity), defaultValueSupplier); registeredMaps.add(map); return map; } }; } @Override public <T> WeakConcurrent.ThreadLocalBuilder<T> threadLocalBuilder() { return new WeakConcurrent.ThreadLocalBuilder<T>() { @Nullable private WeakMap.DefaultValueSupplier<Thread, T> defaultValueSupplier; @Override public WeakConcurrent.ThreadLocalBuilder<T> withDefaultValueSupplier(@Nullable WeakMap.DefaultValueSupplier<Thread, T> defaultValueSupplier) { this.defaultValueSupplier = defaultValueSupplier; return this; } @Override public DetachedThreadLocal<T> build() { return new DetachedThreadLocalImpl<T>(WeakConcurrentProviderImpl.this.<Thread, T>weakMapBuilder() .withDefaultValueSupplier(defaultValueSupplier) .build()); } }; } public <V> WeakSet<V> buildSet() { return new NullSafeWeakConcurrentSet<V>(this.<V, Boolean>weakMapBuilder().build()); } /** * Calls {@link AbstractWeakConcurrentMap#expungeStaleEntries()} on all registered maps, * causing the entries of already collected keys to be removed. * Avoids that the maps take unnecessary space for the {@link java.util.Map.Entry}, the {@link java.lang.ref.WeakReference} and the value. * Failing to call this does not mean the keys cannot be collected. */ public static void expungeStaleEntries() { for (AbstractWeakConcurrentMap<?, ?, ?> weakMap : registeredMaps) { weakMap.expungeStaleEntries(); } } }
1,816
1,143
#!/usr/bin/env python # -*- coding: utf-8 -*- # # tests/find.py # # 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 project nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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. # import json import os import unittest from king_phisher import find from king_phisher import testing class FindTests(testing.KingPhisherTestCase): def setUp(self): find.init_data_path() def test_find_data_file(self): self.assertIsNotNone(find.data_file('security.json')) def test_find_data_directory(self): self.assertIsNotNone(find.data_directory('schemas')) class JSONSchemaDataTests(testing.KingPhisherTestCase): def test_json_schema_directories(self): find.init_data_path() directory = find.data_directory(os.path.join('schemas', 'json')) self.assertIsNotNone(directory) for schema_file in os.listdir(directory): self.assertTrue(schema_file.endswith('.json')) schema_file = os.path.join(directory, schema_file) with open(schema_file, 'r') as file_h: schema_data = json.load(file_h) self.assertIsInstance(schema_data, dict) self.assertEqual(schema_data.get('$schema'), 'http://json-schema.org/draft-04/schema#') self.assertEqual(schema_data.get('id'), os.path.basename(schema_file)[:-5]) if __name__ == '__main__': unittest.main()
886
778
package org.aion.log; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.Logger; import org.slf4j.Marker; /** * Verifies that the method calls are correctly delegated to the wrapped objects and that checks for * enabled are made before attempts to loggit add messages. * * @author <NAME> */ public class AionLoggerTest { @Mock Logger log; AionLogger wrapped; @Before public void setup() { MockitoAnnotations.initMocks(this); wrapped = AionLogger.wrap(log); } @Test public void test_getName() { // call wrapper wrapped.getName(); // verify enclosed object call verify(log, times(1)).getName(); } @Test public void test_isTraceEnabled() { // call wrapper wrapped.isTraceEnabled(); // verify enclosed object call verify(log, times(1)).isTraceEnabled(); } @Test public void test_isDebugEnabled() { // call wrapper wrapped.isDebugEnabled(); // verify enclosed object call verify(log, times(1)).isDebugEnabled(); } @Test public void test_isInfoEnabled() { // call wrapper wrapped.isInfoEnabled(); // verify enclosed object call verify(log, times(1)).isInfoEnabled(); } @Test public void test_isWarnEnabled() { // call wrapper wrapped.isWarnEnabled(); // verify enclosed object call verify(log, times(1)).isWarnEnabled(); } @Test public void test_isErrorEnabled() { // call wrapper wrapped.isErrorEnabled(); // verify enclosed object call verify(log, times(1)).isErrorEnabled(); } @Test public void test_isTraceEnabled_withMarker() { Marker marker = mock(Marker.class); // call wrapper wrapped.isTraceEnabled(marker); // verify enclosed object call verify(log, times(1)).isTraceEnabled(marker); } @Test public void test_isDebugEnabled_withMarker() { Marker marker = mock(Marker.class); // call wrapper wrapped.isDebugEnabled(marker); // verify enclosed object call verify(log, times(1)).isDebugEnabled(marker); } @Test public void test_isInfoEnabled_withMarker() { Marker marker = mock(Marker.class); // call wrapper wrapped.isInfoEnabled(marker); // verify enclosed object call verify(log, times(1)).isInfoEnabled(marker); } @Test public void test_isWarnEnabled_withMarker() { Marker marker = mock(Marker.class); // call wrapper wrapped.isWarnEnabled(marker); // verify enclosed object call verify(log, times(1)).isWarnEnabled(marker); } @Test public void test_isErrorEnabled_withMarker() { Marker marker = mock(Marker.class); // call wrapper wrapped.isErrorEnabled(marker); // verify enclosed object call verify(log, times(1)).isErrorEnabled(marker); } @Test public void test_trace_enable_withMessage() { when(log.isTraceEnabled()).thenReturn(true); String msg = "message"; // call wrapper wrapped.trace(msg); // verify enclosed object call verify(log, times(1)).isTraceEnabled(); verify(log, times(1)).trace(msg); } @Test public void test_trace_disabled_withMessage() { when(log.isTraceEnabled()).thenReturn(false); String msg = "message"; // call wrapper wrapped.trace(msg); // verify enclosed object call verify(log, times(1)).isTraceEnabled(); verify(log, times(0)).trace(msg); } @Test public void test_trace_enable_withFormat1() { when(log.isTraceEnabled()).thenReturn(true); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.trace(format, obj); // verify enclosed object call verify(log, times(1)).isTraceEnabled(); verify(log, times(1)).trace(format, obj); } @Test public void test_trace_disabled_withFormat1() { when(log.isTraceEnabled()).thenReturn(false); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.trace(format, obj); // verify enclosed object call verify(log, times(1)).isTraceEnabled(); verify(log, times(0)).trace(format, obj); } @Test public void test_trace_enable_withFormat2() { when(log.isTraceEnabled()).thenReturn(true); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.trace(format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isTraceEnabled(); verify(log, times(1)).trace(format, obj1, obj2); } @Test public void test_trace_disabled_withFormat2() { when(log.isTraceEnabled()).thenReturn(false); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.trace(format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isTraceEnabled(); verify(log, times(0)).trace(format, obj1, obj2); } @Test public void test_trace_enable_withFormat3() { when(log.isTraceEnabled()).thenReturn(true); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.trace(format, obj); // verify enclosed object call verify(log, times(1)).isTraceEnabled(); verify(log, times(1)).trace(format, obj); } @Test public void test_trace_disabled_withFormat3() { when(log.isTraceEnabled()).thenReturn(false); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.trace(format, obj); // verify enclosed object call verify(log, times(1)).isTraceEnabled(); verify(log, times(0)).trace(format, obj); } @Test public void test_trace_enable_withThrowable() { when(log.isTraceEnabled()).thenReturn(true); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.trace(msg, t); // verify enclosed object call verify(log, times(1)).isTraceEnabled(); verify(log, times(1)).trace(msg, t); } @Test public void test_trace_disabled_withThrowable() { when(log.isTraceEnabled()).thenReturn(false); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.trace(msg, t); // verify enclosed object call verify(log, times(1)).isTraceEnabled(); verify(log, times(0)).trace(msg, t); } @Test public void test_trace_withMarker_enable_withMessage() { Marker marker = mock(Marker.class); when(log.isTraceEnabled(marker)).thenReturn(true); String msg = "message"; // call wrapper wrapped.trace(marker, msg); // verify enclosed object call verify(log, times(1)).isTraceEnabled(marker); verify(log, times(1)).trace(marker, msg); } @Test public void test_trace_withMarker_disabled_withMessage() { Marker marker = mock(Marker.class); when(log.isTraceEnabled(marker)).thenReturn(false); String msg = "message"; // call wrapper wrapped.trace(marker, msg); // verify enclosed object call verify(log, times(1)).isTraceEnabled(marker); verify(log, times(0)).trace(marker, msg); } @Test public void test_trace_withMarker_enable_withFormat1() { Marker marker = mock(Marker.class); when(log.isTraceEnabled(marker)).thenReturn(true); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.trace(marker, format, obj); // verify enclosed object call verify(log, times(1)).isTraceEnabled(marker); verify(log, times(1)).trace(marker, format, obj); } @Test public void test_trace_withMarker_disabled_withFormat1() { Marker marker = mock(Marker.class); when(log.isTraceEnabled(marker)).thenReturn(false); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.trace(marker, format, obj); // verify enclosed object call verify(log, times(1)).isTraceEnabled(marker); verify(log, times(0)).trace(marker, format, obj); } @Test public void test_trace_withMarker_enable_withFormat2() { Marker marker = mock(Marker.class); when(log.isTraceEnabled(marker)).thenReturn(true); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.trace(marker, format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isTraceEnabled(marker); verify(log, times(1)).trace(marker, format, obj1, obj2); } @Test public void test_trace_withMarker_disabled_withFormat2() { Marker marker = mock(Marker.class); when(log.isTraceEnabled(marker)).thenReturn(false); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.trace(marker, format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isTraceEnabled(marker); verify(log, times(0)).trace(marker, format, obj1, obj2); } @Test public void test_trace_withMarker_enable_withFormat3() { Marker marker = mock(Marker.class); when(log.isTraceEnabled(marker)).thenReturn(true); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.trace(marker, format, obj); // verify enclosed object call verify(log, times(1)).isTraceEnabled(marker); verify(log, times(1)).trace(marker, format, obj); } @Test public void test_trace_withMarker_disabled_withFormat3() { Marker marker = mock(Marker.class); when(log.isTraceEnabled(marker)).thenReturn(false); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.trace(marker, format, obj); // verify enclosed object call verify(log, times(1)).isTraceEnabled(marker); verify(log, times(0)).trace(marker, format, obj); } @Test public void test_trace_withMarker_enable_withThrowable() { Marker marker = mock(Marker.class); when(log.isTraceEnabled(marker)).thenReturn(true); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.trace(marker, msg, t); // verify enclosed object call verify(log, times(1)).isTraceEnabled(marker); verify(log, times(1)).trace(marker, msg, t); } @Test public void test_trace_withMarker_disabled_withThrowable() { Marker marker = mock(Marker.class); when(log.isTraceEnabled(marker)).thenReturn(false); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.trace(marker, msg, t); // verify enclosed object call verify(log, times(1)).isTraceEnabled(marker); verify(log, times(0)).trace(marker, msg, t); } @Test public void test_debug_enable_withMessage() { when(log.isDebugEnabled()).thenReturn(true); String msg = "message"; // call wrapper wrapped.debug(msg); // verify enclosed object call verify(log, times(1)).isDebugEnabled(); verify(log, times(1)).debug(msg); } @Test public void test_debug_disabled_withMessage() { when(log.isDebugEnabled()).thenReturn(false); String msg = "message"; // call wrapper wrapped.debug(msg); // verify enclosed object call verify(log, times(1)).isDebugEnabled(); verify(log, times(0)).debug(msg); } @Test public void test_debug_enable_withFormat1() { when(log.isDebugEnabled()).thenReturn(true); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.debug(format, obj); // verify enclosed object call verify(log, times(1)).isDebugEnabled(); verify(log, times(1)).debug(format, obj); } @Test public void test_debug_disabled_withFormat1() { when(log.isDebugEnabled()).thenReturn(false); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.debug(format, obj); // verify enclosed object call verify(log, times(1)).isDebugEnabled(); verify(log, times(0)).debug(format, obj); } @Test public void test_debug_enable_withFormat2() { when(log.isDebugEnabled()).thenReturn(true); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.debug(format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isDebugEnabled(); verify(log, times(1)).debug(format, obj1, obj2); } @Test public void test_debug_disabled_withFormat2() { when(log.isDebugEnabled()).thenReturn(false); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.debug(format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isDebugEnabled(); verify(log, times(0)).debug(format, obj1, obj2); } @Test public void test_debug_enable_withFormat3() { when(log.isDebugEnabled()).thenReturn(true); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.debug(format, obj); // verify enclosed object call verify(log, times(1)).isDebugEnabled(); verify(log, times(1)).debug(format, obj); } @Test public void test_debug_disabled_withFormat3() { when(log.isDebugEnabled()).thenReturn(false); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.debug(format, obj); // verify enclosed object call verify(log, times(1)).isDebugEnabled(); verify(log, times(0)).debug(format, obj); } @Test public void test_debug_enable_withThrowable() { when(log.isDebugEnabled()).thenReturn(true); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.debug(msg, t); // verify enclosed object call verify(log, times(1)).isDebugEnabled(); verify(log, times(1)).debug(msg, t); } @Test public void test_debug_disabled_withThrowable() { when(log.isDebugEnabled()).thenReturn(false); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.debug(msg, t); // verify enclosed object call verify(log, times(1)).isDebugEnabled(); verify(log, times(0)).debug(msg, t); } @Test public void test_debug_withMarker_enable_withMessage() { Marker marker = mock(Marker.class); when(log.isDebugEnabled(marker)).thenReturn(true); String msg = "message"; // call wrapper wrapped.debug(marker, msg); // verify enclosed object call verify(log, times(1)).isDebugEnabled(marker); verify(log, times(1)).debug(marker, msg); } @Test public void test_debug_withMarker_disabled_withMessage() { Marker marker = mock(Marker.class); when(log.isDebugEnabled(marker)).thenReturn(false); String msg = "message"; // call wrapper wrapped.debug(marker, msg); // verify enclosed object call verify(log, times(1)).isDebugEnabled(marker); verify(log, times(0)).debug(marker, msg); } @Test public void test_debug_withMarker_enable_withFormat1() { Marker marker = mock(Marker.class); when(log.isDebugEnabled(marker)).thenReturn(true); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.debug(marker, format, obj); // verify enclosed object call verify(log, times(1)).isDebugEnabled(marker); verify(log, times(1)).debug(marker, format, obj); } @Test public void test_debug_withMarker_disabled_withFormat1() { Marker marker = mock(Marker.class); when(log.isDebugEnabled(marker)).thenReturn(false); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.debug(marker, format, obj); // verify enclosed object call verify(log, times(1)).isDebugEnabled(marker); verify(log, times(0)).debug(marker, format, obj); } @Test public void test_debug_withMarker_enable_withFormat2() { Marker marker = mock(Marker.class); when(log.isDebugEnabled(marker)).thenReturn(true); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.debug(marker, format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isDebugEnabled(marker); verify(log, times(1)).debug(marker, format, obj1, obj2); } @Test public void test_debug_withMarker_disabled_withFormat2() { Marker marker = mock(Marker.class); when(log.isDebugEnabled(marker)).thenReturn(false); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.debug(marker, format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isDebugEnabled(marker); verify(log, times(0)).debug(marker, format, obj1, obj2); } @Test public void test_debug_withMarker_enable_withFormat3() { Marker marker = mock(Marker.class); when(log.isDebugEnabled(marker)).thenReturn(true); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.debug(marker, format, obj); // verify enclosed object call verify(log, times(1)).isDebugEnabled(marker); verify(log, times(1)).debug(marker, format, obj); } @Test public void test_debug_withMarker_disabled_withFormat3() { Marker marker = mock(Marker.class); when(log.isDebugEnabled(marker)).thenReturn(false); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.debug(marker, format, obj); // verify enclosed object call verify(log, times(1)).isDebugEnabled(marker); verify(log, times(0)).debug(marker, format, obj); } @Test public void test_debug_withMarker_enable_withThrowable() { Marker marker = mock(Marker.class); when(log.isDebugEnabled(marker)).thenReturn(true); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.debug(marker, msg, t); // verify enclosed object call verify(log, times(1)).isDebugEnabled(marker); verify(log, times(1)).debug(marker, msg, t); } @Test public void test_debug_withMarker_disabled_withThrowable() { Marker marker = mock(Marker.class); when(log.isDebugEnabled(marker)).thenReturn(false); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.debug(marker, msg, t); // verify enclosed object call verify(log, times(1)).isDebugEnabled(marker); verify(log, times(0)).debug(marker, msg, t); } @Test public void test_info_enable_withMessage() { when(log.isInfoEnabled()).thenReturn(true); String msg = "message"; // call wrapper wrapped.info(msg); // verify enclosed object call verify(log, times(1)).isInfoEnabled(); verify(log, times(1)).info(msg); } @Test public void test_info_disabled_withMessage() { when(log.isInfoEnabled()).thenReturn(false); String msg = "message"; // call wrapper wrapped.info(msg); // verify enclosed object call verify(log, times(1)).isInfoEnabled(); verify(log, times(0)).info(msg); } @Test public void test_info_enable_withFormat1() { when(log.isInfoEnabled()).thenReturn(true); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.info(format, obj); // verify enclosed object call verify(log, times(1)).isInfoEnabled(); verify(log, times(1)).info(format, obj); } @Test public void test_info_disabled_withFormat1() { when(log.isInfoEnabled()).thenReturn(false); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.info(format, obj); // verify enclosed object call verify(log, times(1)).isInfoEnabled(); verify(log, times(0)).info(format, obj); } @Test public void test_info_enable_withFormat2() { when(log.isInfoEnabled()).thenReturn(true); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.info(format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isInfoEnabled(); verify(log, times(1)).info(format, obj1, obj2); } @Test public void test_info_disabled_withFormat2() { when(log.isInfoEnabled()).thenReturn(false); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.info(format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isInfoEnabled(); verify(log, times(0)).info(format, obj1, obj2); } @Test public void test_info_enable_withFormat3() { when(log.isInfoEnabled()).thenReturn(true); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.info(format, obj); // verify enclosed object call verify(log, times(1)).isInfoEnabled(); verify(log, times(1)).info(format, obj); } @Test public void test_info_disabled_withFormat3() { when(log.isInfoEnabled()).thenReturn(false); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.info(format, obj); // verify enclosed object call verify(log, times(1)).isInfoEnabled(); verify(log, times(0)).info(format, obj); } @Test public void test_info_enable_withThrowable() { when(log.isInfoEnabled()).thenReturn(true); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.info(msg, t); // verify enclosed object call verify(log, times(1)).isInfoEnabled(); verify(log, times(1)).info(msg, t); } @Test public void test_info_disabled_withThrowable() { when(log.isInfoEnabled()).thenReturn(false); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.info(msg, t); // verify enclosed object call verify(log, times(1)).isInfoEnabled(); verify(log, times(0)).info(msg, t); } @Test public void test_info_withMarker_enable_withMessage() { Marker marker = mock(Marker.class); when(log.isInfoEnabled(marker)).thenReturn(true); String msg = "message"; // call wrapper wrapped.info(marker, msg); // verify enclosed object call verify(log, times(1)).isInfoEnabled(marker); verify(log, times(1)).info(marker, msg); } @Test public void test_info_withMarker_disabled_withMessage() { Marker marker = mock(Marker.class); when(log.isInfoEnabled(marker)).thenReturn(false); String msg = "message"; // call wrapper wrapped.info(marker, msg); // verify enclosed object call verify(log, times(1)).isInfoEnabled(marker); verify(log, times(0)).info(marker, msg); } @Test public void test_info_withMarker_enable_withFormat1() { Marker marker = mock(Marker.class); when(log.isInfoEnabled(marker)).thenReturn(true); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.info(marker, format, obj); // verify enclosed object call verify(log, times(1)).isInfoEnabled(marker); verify(log, times(1)).info(marker, format, obj); } @Test public void test_info_withMarker_disabled_withFormat1() { Marker marker = mock(Marker.class); when(log.isInfoEnabled(marker)).thenReturn(false); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.info(marker, format, obj); // verify enclosed object call verify(log, times(1)).isInfoEnabled(marker); verify(log, times(0)).info(marker, format, obj); } @Test public void test_info_withMarker_enable_withFormat2() { Marker marker = mock(Marker.class); when(log.isInfoEnabled(marker)).thenReturn(true); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.info(marker, format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isInfoEnabled(marker); verify(log, times(1)).info(marker, format, obj1, obj2); } @Test public void test_info_withMarker_disabled_withFormat2() { Marker marker = mock(Marker.class); when(log.isInfoEnabled(marker)).thenReturn(false); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.info(marker, format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isInfoEnabled(marker); verify(log, times(0)).info(marker, format, obj1, obj2); } @Test public void test_info_withMarker_enable_withFormat3() { Marker marker = mock(Marker.class); when(log.isInfoEnabled(marker)).thenReturn(true); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.info(marker, format, obj); // verify enclosed object call verify(log, times(1)).isInfoEnabled(marker); verify(log, times(1)).info(marker, format, obj); } @Test public void test_info_withMarker_disabled_withFormat3() { Marker marker = mock(Marker.class); when(log.isInfoEnabled(marker)).thenReturn(false); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.info(marker, format, obj); // verify enclosed object call verify(log, times(1)).isInfoEnabled(marker); verify(log, times(0)).info(marker, format, obj); } @Test public void test_info_withMarker_enable_withThrowable() { Marker marker = mock(Marker.class); when(log.isInfoEnabled(marker)).thenReturn(true); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.info(marker, msg, t); // verify enclosed object call verify(log, times(1)).isInfoEnabled(marker); verify(log, times(1)).info(marker, msg, t); } @Test public void test_info_withMarker_disabled_withThrowable() { Marker marker = mock(Marker.class); when(log.isInfoEnabled(marker)).thenReturn(false); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.info(marker, msg, t); // verify enclosed object call verify(log, times(1)).isInfoEnabled(marker); verify(log, times(0)).info(marker, msg, t); } @Test public void test_warn_enable_withMessage() { when(log.isWarnEnabled()).thenReturn(true); String msg = "message"; // call wrapper wrapped.warn(msg); // verify enclosed object call verify(log, times(1)).isWarnEnabled(); verify(log, times(1)).warn(msg); } @Test public void test_warn_disabled_withMessage() { when(log.isWarnEnabled()).thenReturn(false); String msg = "message"; // call wrapper wrapped.warn(msg); // verify enclosed object call verify(log, times(1)).isWarnEnabled(); verify(log, times(0)).warn(msg); } @Test public void test_warn_enable_withFormat1() { when(log.isWarnEnabled()).thenReturn(true); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.warn(format, obj); // verify enclosed object call verify(log, times(1)).isWarnEnabled(); verify(log, times(1)).warn(format, obj); } @Test public void test_warn_disabled_withFormat1() { when(log.isWarnEnabled()).thenReturn(false); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.warn(format, obj); // verify enclosed object call verify(log, times(1)).isWarnEnabled(); verify(log, times(0)).warn(format, obj); } @Test public void test_warn_enable_withFormat2() { when(log.isWarnEnabled()).thenReturn(true); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.warn(format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isWarnEnabled(); verify(log, times(1)).warn(format, obj1, obj2); } @Test public void test_warn_disabled_withFormat2() { when(log.isWarnEnabled()).thenReturn(false); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.warn(format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isWarnEnabled(); verify(log, times(0)).warn(format, obj1, obj2); } @Test public void test_warn_enable_withFormat3() { when(log.isWarnEnabled()).thenReturn(true); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.warn(format, obj); // verify enclosed object call verify(log, times(1)).isWarnEnabled(); verify(log, times(1)).warn(format, obj); } @Test public void test_warn_disabled_withFormat3() { when(log.isWarnEnabled()).thenReturn(false); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.warn(format, obj); // verify enclosed object call verify(log, times(1)).isWarnEnabled(); verify(log, times(0)).warn(format, obj); } @Test public void test_warn_enable_withThrowable() { when(log.isWarnEnabled()).thenReturn(true); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.warn(msg, t); // verify enclosed object call verify(log, times(1)).isWarnEnabled(); verify(log, times(1)).warn(msg, t); } @Test public void test_warn_disabled_withThrowable() { when(log.isWarnEnabled()).thenReturn(false); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.warn(msg, t); // verify enclosed object call verify(log, times(1)).isWarnEnabled(); verify(log, times(0)).warn(msg, t); } @Test public void test_warn_withMarker_enable_withMessage() { Marker marker = mock(Marker.class); when(log.isWarnEnabled(marker)).thenReturn(true); String msg = "message"; // call wrapper wrapped.warn(marker, msg); // verify enclosed object call verify(log, times(1)).isWarnEnabled(marker); verify(log, times(1)).warn(marker, msg); } @Test public void test_warn_withMarker_disabled_withMessage() { Marker marker = mock(Marker.class); when(log.isWarnEnabled(marker)).thenReturn(false); String msg = "message"; // call wrapper wrapped.warn(marker, msg); // verify enclosed object call verify(log, times(1)).isWarnEnabled(marker); verify(log, times(0)).warn(marker, msg); } @Test public void test_warn_withMarker_enable_withFormat1() { Marker marker = mock(Marker.class); when(log.isWarnEnabled(marker)).thenReturn(true); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.warn(marker, format, obj); // verify enclosed object call verify(log, times(1)).isWarnEnabled(marker); verify(log, times(1)).warn(marker, format, obj); } @Test public void test_warn_withMarker_disabled_withFormat1() { Marker marker = mock(Marker.class); when(log.isWarnEnabled(marker)).thenReturn(false); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.warn(marker, format, obj); // verify enclosed object call verify(log, times(1)).isWarnEnabled(marker); verify(log, times(0)).warn(marker, format, obj); } @Test public void test_warn_withMarker_enable_withFormat2() { Marker marker = mock(Marker.class); when(log.isWarnEnabled(marker)).thenReturn(true); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.warn(marker, format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isWarnEnabled(marker); verify(log, times(1)).warn(marker, format, obj1, obj2); } @Test public void test_warn_withMarker_disabled_withFormat2() { Marker marker = mock(Marker.class); when(log.isWarnEnabled(marker)).thenReturn(false); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.warn(marker, format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isWarnEnabled(marker); verify(log, times(0)).warn(marker, format, obj1, obj2); } @Test public void test_warn_withMarker_enable_withFormat3() { Marker marker = mock(Marker.class); when(log.isWarnEnabled(marker)).thenReturn(true); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.warn(marker, format, obj); // verify enclosed object call verify(log, times(1)).isWarnEnabled(marker); verify(log, times(1)).warn(marker, format, obj); } @Test public void test_warn_withMarker_disabled_withFormat3() { Marker marker = mock(Marker.class); when(log.isWarnEnabled(marker)).thenReturn(false); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.warn(marker, format, obj); // verify enclosed object call verify(log, times(1)).isWarnEnabled(marker); verify(log, times(0)).warn(marker, format, obj); } @Test public void test_warn_withMarker_enable_withThrowable() { Marker marker = mock(Marker.class); when(log.isWarnEnabled(marker)).thenReturn(true); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.warn(marker, msg, t); // verify enclosed object call verify(log, times(1)).isWarnEnabled(marker); verify(log, times(1)).warn(marker, msg, t); } @Test public void test_warn_withMarker_disabled_withThrowable() { Marker marker = mock(Marker.class); when(log.isWarnEnabled(marker)).thenReturn(false); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.warn(marker, msg, t); // verify enclosed object call verify(log, times(1)).isWarnEnabled(marker); verify(log, times(0)).warn(marker, msg, t); } @Test public void test_error_enable_withMessage() { when(log.isErrorEnabled()).thenReturn(true); String msg = "message"; // call wrapper wrapped.error(msg); // verify enclosed object call verify(log, times(1)).isErrorEnabled(); verify(log, times(1)).error(msg); } @Test public void test_error_disabled_withMessage() { when(log.isErrorEnabled()).thenReturn(false); String msg = "message"; // call wrapper wrapped.error(msg); // verify enclosed object call verify(log, times(1)).isErrorEnabled(); verify(log, times(0)).error(msg); } @Test public void test_error_enable_withFormat1() { when(log.isErrorEnabled()).thenReturn(true); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.error(format, obj); // verify enclosed object call verify(log, times(1)).isErrorEnabled(); verify(log, times(1)).error(format, obj); } @Test public void test_error_disabled_withFormat1() { when(log.isErrorEnabled()).thenReturn(false); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.error(format, obj); // verify enclosed object call verify(log, times(1)).isErrorEnabled(); verify(log, times(0)).error(format, obj); } @Test public void test_error_enable_withFormat2() { when(log.isErrorEnabled()).thenReturn(true); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.error(format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isErrorEnabled(); verify(log, times(1)).error(format, obj1, obj2); } @Test public void test_error_disabled_withFormat2() { when(log.isErrorEnabled()).thenReturn(false); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.error(format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isErrorEnabled(); verify(log, times(0)).error(format, obj1, obj2); } @Test public void test_error_enable_withFormat3() { when(log.isErrorEnabled()).thenReturn(true); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.error(format, obj); // verify enclosed object call verify(log, times(1)).isErrorEnabled(); verify(log, times(1)).error(format, obj); } @Test public void test_error_disabled_withFormat3() { when(log.isErrorEnabled()).thenReturn(false); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.error(format, obj); // verify enclosed object call verify(log, times(1)).isErrorEnabled(); verify(log, times(0)).error(format, obj); } @Test public void test_error_enable_withThrowable() { when(log.isErrorEnabled()).thenReturn(true); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.error(msg, t); // verify enclosed object call verify(log, times(1)).isErrorEnabled(); verify(log, times(1)).error(msg, t); } @Test public void test_error_disabled_withThrowable() { when(log.isErrorEnabled()).thenReturn(false); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.error(msg, t); // verify enclosed object call verify(log, times(1)).isErrorEnabled(); verify(log, times(0)).error(msg, t); } @Test public void test_error_withMarker_enable_withMessage() { Marker marker = mock(Marker.class); when(log.isErrorEnabled(marker)).thenReturn(true); String msg = "message"; // call wrapper wrapped.error(marker, msg); // verify enclosed object call verify(log, times(1)).isErrorEnabled(marker); verify(log, times(1)).error(marker, msg); } @Test public void test_error_withMarker_disabled_withMessage() { Marker marker = mock(Marker.class); when(log.isErrorEnabled(marker)).thenReturn(false); String msg = "message"; // call wrapper wrapped.error(marker, msg); // verify enclosed object call verify(log, times(1)).isErrorEnabled(marker); verify(log, times(0)).error(marker, msg); } @Test public void test_error_withMarker_enable_withFormat1() { Marker marker = mock(Marker.class); when(log.isErrorEnabled(marker)).thenReturn(true); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.error(marker, format, obj); // verify enclosed object call verify(log, times(1)).isErrorEnabled(marker); verify(log, times(1)).error(marker, format, obj); } @Test public void test_error_withMarker_disabled_withFormat1() { Marker marker = mock(Marker.class); when(log.isErrorEnabled(marker)).thenReturn(false); String format = "message {}"; Object obj = "data"; // call wrapper wrapped.error(marker, format, obj); // verify enclosed object call verify(log, times(1)).isErrorEnabled(marker); verify(log, times(0)).error(marker, format, obj); } @Test public void test_error_withMarker_enable_withFormat2() { Marker marker = mock(Marker.class); when(log.isErrorEnabled(marker)).thenReturn(true); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.error(marker, format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isErrorEnabled(marker); verify(log, times(1)).error(marker, format, obj1, obj2); } @Test public void test_error_withMarker_disabled_withFormat2() { Marker marker = mock(Marker.class); when(log.isErrorEnabled(marker)).thenReturn(false); String format = "message {} {}"; Object obj1 = "data1"; Object obj2 = "data2"; // call wrapper wrapped.error(marker, format, obj1, obj2); // verify enclosed object call verify(log, times(1)).isErrorEnabled(marker); verify(log, times(0)).error(marker, format, obj1, obj2); } @Test public void test_error_withMarker_enable_withFormat3() { Marker marker = mock(Marker.class); when(log.isErrorEnabled(marker)).thenReturn(true); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.error(marker, format, obj); // verify enclosed object call verify(log, times(1)).isErrorEnabled(marker); verify(log, times(1)).error(marker, format, obj); } @Test public void test_error_withMarker_disabled_withFormat3() { Marker marker = mock(Marker.class); when(log.isErrorEnabled(marker)).thenReturn(false); String format = "message {} {} {}"; Object[] obj = new Object[] {"data1", "data2", "data2"}; // call wrapper wrapped.error(marker, format, obj); // verify enclosed object call verify(log, times(1)).isErrorEnabled(marker); verify(log, times(0)).error(marker, format, obj); } @Test public void test_error_withMarker_enable_withThrowable() { Marker marker = mock(Marker.class); when(log.isErrorEnabled(marker)).thenReturn(true); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.error(marker, msg, t); // verify enclosed object call verify(log, times(1)).isErrorEnabled(marker); verify(log, times(1)).error(marker, msg, t); } @Test public void test_error_withMarker_disabled_withThrowable() { Marker marker = mock(Marker.class); when(log.isErrorEnabled(marker)).thenReturn(false); String msg = "message"; Throwable t = mock(Throwable.class); // call wrapper wrapped.error(marker, msg, t); // verify enclosed object call verify(log, times(1)).isErrorEnabled(marker); verify(log, times(0)).error(marker, msg, t); } }
19,753
563
<reponame>kdima001/mesh package com.gentics.mesh.core.rest.schema; import com.gentics.mesh.core.rest.microschema.MicroschemaVersionModel; /** * A schema storage is a store which hold schemas. Schema storages are used to quickly load a schema in order to deserialize or serialize a node. TODO: add * version */ public interface SchemaStorage { /** * Remove the schema with the given name in all versions from the storage. * * @param name * Schema name */ void removeSchema(String name); /** * Remove the schema with the given name in the given version from the storage. * * @param name * Schema name * @param version * Schema version */ void removeSchema(String name, String version); /** * Return the schema with the given name in the newest version. * * @param name * Schema name * @return Found schema or null when no schema could be found */ SchemaVersionModel getSchema(String name); /** * Return the schema with the given name in the given version. * * @param name * Schema name * @param version * Schema version * @return Found schema or null when no schema could be found */ SchemaVersionModel getSchema(String name, String version); /** * Add the given schema to the storage. Existing schemas will be updated. * * @param schema * Schema */ void addSchema(SchemaVersionModel schema); /** * Get the microschema with the given name in the newest version * * @param name * microschema name * @return microschema instance or null if the schema could not be found */ MicroschemaVersionModel getMicroschema(String name); /** * Return the microschema with the given name in the given version. * * @param name * Microschema name * @param version * Microschema version * @return Found microschema or null when no microschema could be found */ MicroschemaVersionModel getMicroschema(String name, String version); /** * Add the given microschema to the storage * * @param microschema * microschema instance */ void addMicroschema(MicroschemaVersionModel microschema); /** * Remove the microschema with the given name from the storage * * @param name * microschema name */ void removeMicroschema(String name); /** * Remove the microschema with the given name in the given version from the storage. * * @param name * microschema name * @param version * microschema version */ void removeMicroschema(String name, String version); /** * Return the size of the storage (schemas an microschemas) * * @return Size of the storage */ int size(); /** * Clear the storage and remove all stored schemas and microschemas */ void clear(); }
984
338
package fr.lteconsulting.pomexplorer; public interface Log { void html( String log ); }
33
2,220
from abc import ABCMeta, abstractmethod class Rebalance(object): """ Interface to a generic list of system logic and trade order rebalance timestamps. """ __metaclass__ = ABCMeta @abstractmethod def output_rebalances(self): raise NotImplementedError( "Should implement output_rebalances()" )
133
1,546
#ifndef __eglplatform_h_ #define __eglplatform_h_ /* ** Copyright 2007-2020 The Khronos Group Inc. ** SPDX-License-Identifier: Apache-2.0 */ /* Platform-specific types and definitions for egl.h * * Adopters may modify khrplatform.h and this file to suit their platform. * You are encouraged to submit all modifications to the Khronos group so that * they can be included in future versions of this file. Please submit changes * by filing an issue or pull request on the public Khronos EGL Registry, at * https://www.github.com/KhronosGroup/EGL-Registry/ */ #include <KHR/khrplatform.h> /* Macros used in EGL function prototype declarations. * * EGL functions should be prototyped as: * * EGLAPI return-type EGLAPIENTRY eglFunction(arguments); * typedef return-type (EXPAPIENTRYP PFNEGLFUNCTIONPROC) (arguments); * * KHRONOS_APICALL and KHRONOS_APIENTRY are defined in KHR/khrplatform.h */ #ifndef EGLAPI #define EGLAPI KHRONOS_APICALL #endif #ifndef EGLAPIENTRY #define EGLAPIENTRY KHRONOS_APIENTRY #endif #define EGLAPIENTRYP EGLAPIENTRY* /* The types NativeDisplayType, NativeWindowType, and NativePixmapType * are aliases of window-system-dependent types, such as X Display * or * Windows Device Context. They must be defined in platform-specific * code below. The EGL-prefixed versions of Native*Type are the same * types, renamed in EGL 1.3 so all types in the API start with "EGL". * * Khronos STRONGLY RECOMMENDS that you use the default definitions * provided below, since these changes affect both binary and source * portability of applications using EGL running on different EGL * implementations. */ #if defined(EGL_NO_PLATFORM_SPECIFIC_TYPES) typedef void *EGLNativeDisplayType; typedef void *EGLNativePixmapType; typedef void *EGLNativeWindowType; #elif defined(_WIN32) || defined(__VC32__) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) /* Win32 and WinCE */ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #include <windows.h> typedef HDC EGLNativeDisplayType; typedef HBITMAP EGLNativePixmapType; #if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) /* Windows Desktop */ typedef HWND EGLNativeWindowType; #else /* Windows Store */ #include <inspectable.h> typedef IInspectable* EGLNativeWindowType; #endif #elif defined(__EMSCRIPTEN__) typedef int EGLNativeDisplayType; typedef int EGLNativePixmapType; typedef int EGLNativeWindowType; #elif defined(__WINSCW__) || defined(__SYMBIAN32__) /* Symbian */ typedef int EGLNativeDisplayType; typedef void *EGLNativePixmapType; typedef void *EGLNativeWindowType; #elif defined(WL_EGL_PLATFORM) typedef struct wl_display *EGLNativeDisplayType; typedef struct wl_egl_pixmap *EGLNativePixmapType; typedef struct wl_egl_window *EGLNativeWindowType; #elif defined(__GBM__) typedef struct gbm_device *EGLNativeDisplayType; typedef struct gbm_bo *EGLNativePixmapType; typedef void *EGLNativeWindowType; #elif defined(__ANDROID__) || defined(ANDROID) struct ANativeWindow; struct egl_native_pixmap_t; typedef void* EGLNativeDisplayType; typedef struct egl_native_pixmap_t* EGLNativePixmapType; typedef struct ANativeWindow* EGLNativeWindowType; #elif defined(USE_OZONE) typedef intptr_t EGLNativeDisplayType; typedef intptr_t EGLNativePixmapType; typedef intptr_t EGLNativeWindowType; #elif defined(__unix__) && defined(EGL_NO_X11) typedef void *EGLNativeDisplayType; typedef khronos_uintptr_t EGLNativePixmapType; typedef khronos_uintptr_t EGLNativeWindowType; #elif defined(__unix__) || defined(USE_X11) /* X11 (tentative) */ #include <X11/Xlib.h> #include <X11/Xutil.h> typedef Display *EGLNativeDisplayType; typedef Pixmap EGLNativePixmapType; typedef Window EGLNativeWindowType; #elif defined(__APPLE__) typedef int EGLNativeDisplayType; typedef void *EGLNativePixmapType; typedef void *EGLNativeWindowType; #elif defined(__HAIKU__) #include <kernel/image.h> typedef void *EGLNativeDisplayType; typedef khronos_uintptr_t EGLNativePixmapType; typedef khronos_uintptr_t EGLNativeWindowType; #elif defined(__Fuchsia__) typedef void *EGLNativeDisplayType; typedef khronos_uintptr_t EGLNativePixmapType; typedef khronos_uintptr_t EGLNativeWindowType; #else #error "Platform not recognized" #endif /* EGL 1.2 types, renamed for consistency in EGL 1.3 */ typedef EGLNativeDisplayType NativeDisplayType; typedef EGLNativePixmapType NativePixmapType; typedef EGLNativeWindowType NativeWindowType; /* Define EGLint. This must be a signed integral type large enough to contain * all legal attribute names and values passed into and out of EGL, whether * their type is boolean, bitmask, enumerant (symbolic constant), integer, * handle, or other. While in general a 32-bit integer will suffice, if * handles are 64 bit types, then EGLint should be defined as a signed 64-bit * integer type. */ typedef khronos_int32_t EGLint; /* C++ / C typecast macros for special EGL handle values */ #if defined(__cplusplus) #define EGL_CAST(type, value) (static_cast<type>(value)) #else #define EGL_CAST(type, value) ((type) (value)) #endif #endif /* __eglplatform_h */
1,942
841
<gh_stars>100-1000 package org.jboss.resteasy.embedded.test.core.basic.resource; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; @Path("/singletons") public class ApplicationTestSingletonB { @Path("b") @GET public String get() { return "b"; } }
111
4,124
from deep_daze.deep_daze import DeepDaze, Imagine
17
475
<reponame>islandempty/zfoo /* * Copyright (C) 2020 The zfoo 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 com.zfoo.orm.model.accessor; import com.zfoo.orm.model.entity.IEntity; import org.springframework.lang.Nullable; import java.util.List; /** * 对数据库进行(增,删,改)的相关方法 * * @author jaysunxiao * @version 3.0 */ public interface IAccessor { <E extends IEntity<?>> boolean insert(E entity); <E extends IEntity<?>> void batchInsert(List<E> entities); <E extends IEntity<?>> boolean update(E entity); <E extends IEntity<?>> void batchUpdate(List<E> entities); <E extends IEntity<?>> boolean delete(E entity); <E extends IEntity<?>> boolean delete(Object pk, Class<E> entityClazz); <E extends IEntity<?>> void batchDelete(List<E> entities); <E extends IEntity<?>> void batchDelete(List<?> pks, Class<E> entityClazz); @Nullable <E extends IEntity<?>> E load(Object pk, Class<E> entityClazz); }
492
778
package org.aion.p2p; import java.util.HashSet; import java.util.Set; /** @author chris */ public class Ver { public static final short V0 = 0; /** New protocol version supporting fast sync. */ public static final short V1 = 1; // for test public static final short VTEST = Byte.MAX_VALUE; public static final short UNKNOWN = Short.MAX_VALUE; private static Set<Short> active = new HashSet<>() { { this.add(V0); this.add(V1); this.add(VTEST); } }; /** * @param _version short * @return short method provided to filter any decoded version (short) */ public static short filter(short _version) { return active.contains(_version) ? _version : UNKNOWN; } }
367
513
<gh_stars>100-1000 package com.zmops.iot.message.config; /** * @author nantian created at 2021/9/26 23:15 */ public interface Event { /** * 聊天事件 */ String CHAT = "chat"; /** * 广播消息 */ String BROADCAST = "broadcast"; /** * 群聊 */ String GROUP = "group"; /** * 加入群聊 */ String JOIN = "join"; }
202
1,405
<reponame>jarekankowski/pegasus_spyware package com.lenovo.safecenter.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.lenovo.safecenter.R; import com.lenovo.safecenter.support.Contract; import com.lenovo.safecenter.utils.ContractHelpUtils; import java.util.List; public class ManwhiteSmsAdapter extends BaseAdapter { Context a; List<Contract> b; public ManwhiteSmsAdapter(Context context, List<Contract> list) { this.a = context; this.b = list; } public int getCount() { return this.b.size(); } public Object getItem(int position) { return this.b.get(position); } public long getItemId(int position) { return (long) position; } public void removeItem(int position) { this.b.remove(position); notifyDataSetChanged(); } public View getView(int position, View convertView, ViewGroup parent) { a holder; if (convertView == null) { convertView = LayoutInflater.from(this.a).inflate(R.layout.whiteloginfo, (ViewGroup) null); holder = new a(this, (byte) 0); holder.a = (ImageView) convertView.findViewById(R.id.safemode_icon_call); holder.b = (ImageView) convertView.findViewById(R.id.safemode_type_icon); holder.c = (TextView) convertView.findViewById(R.id.safemode_whitesms_date); holder.d = (TextView) convertView.findViewById(R.id.safemode_whitesms_name); holder.e = (TextView) convertView.findViewById(R.id.safemode_whitesms_content); convertView.setTag(holder); } else { holder = (a) convertView.getTag(); } Contract sms = this.b.get(position); if (sms.getFromtype() == 0) { String str = sms.getName(); if (sms.getName() == null) { str = sms.getPhoneNumber(); } int count = sms.getCount(); if (count > 0) { str = str + String.format(this.a.getString(R.string.record_count), String.valueOf(count)); } if (sms.isSelect()) { holder.a.setImageResource(R.drawable.ic_checkbox_select); } else { holder.a.setImageResource(R.drawable.ic_checkbox); } holder.b.setImageResource(R.drawable.safemode_pri_message); holder.d.setText(str); holder.c.setText(String.format(this.a.getString(R.string.formattime), ContractHelpUtils.formatTime(sms.getDate(), this.a))); holder.e.setText(sms.getSmsContent()); } else if (sms.getFromtype() == 1) { String str2 = sms.getName(); if (sms.getName() == null) { str2 = sms.getPhoneNumber(); } if (sms.isSelect()) { holder.a.setImageResource(R.drawable.ic_checkbox_select); } else { holder.a.setImageResource(R.drawable.ic_checkbox); } if (sms.getCallType() == 1) { holder.b.setImageResource(R.drawable.list_icon_in_call); } else if (sms.getCallType() == 3) { holder.b.setImageResource(R.drawable.list_icon_miss_call); } else if (sms.getCallType() == 2) { holder.b.setImageResource(R.drawable.list_icon_out_call); } holder.d.setText(str2); holder.c.setText(ContractHelpUtils.formatTime(sms.getDate(), this.a)); } return convertView; } private class a { ImageView a; ImageView b; TextView c; TextView d; TextView e; private a() { } /* synthetic */ a(ManwhiteSmsAdapter x0, byte b2) { this(); } } }
1,902
1,444
package mage.cards.r; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.costs.mana.GenericManaCost; import mage.abilities.effects.common.DamageTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Zone; import mage.target.common.TargetAnyTarget; /** * * @author Loki */ public final class RodOfRuin extends CardImpl { public RodOfRuin(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT},"{4}"); Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new DamageTargetEffect(1), new GenericManaCost(3)); ability.addCost(new TapSourceCost()); ability.addTarget(new TargetAnyTarget()); this.addAbility(ability); } private RodOfRuin(final RodOfRuin card) { super(card); } @Override public RodOfRuin copy() { return new RodOfRuin(this); } }
385
879
package org.zstack.externalservice.cronjob; import org.springframework.beans.factory.annotation.Autowired; import org.zstack.core.externalservice.ExternalService; import org.zstack.core.externalservice.ExternalServiceFactory; import org.zstack.core.externalservice.ExternalServiceManager; import org.zstack.core.externalservice.ExternalServiceType; public class CronJobFactory implements ExternalServiceFactory { public static final ExternalServiceType type = new ExternalServiceType("CronJob"); @Autowired private ExternalServiceManager manager; @Override public String getExternalServiceType() { return type.toString(); } public CronJob getCronJob() { CronJob job = new CronJobImpl(); return (CronJob) manager.getService(job.getName(), () -> job); } }
265
1,350
<filename>sdk/resourcemanagerhybrid/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/WhatIfOperationResult.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.resources.models; import com.azure.core.annotation.Fluent; import com.azure.core.management.exception.ManagementError; import com.azure.resourcemanager.resources.fluentcore.model.HasInnerModel; import com.azure.resourcemanager.resources.fluent.models.WhatIfOperationResultInner; import java.util.List; /** * An immutable client-side representation of an Azure deployment What-if operation result. */ @Fluent public interface WhatIfOperationResult extends HasInnerModel<WhatIfOperationResultInner> { /** * @return status of the What-If operation. */ String status(); /** * @return list of resource changes predicted by What-If operation. */ List<WhatIfChange> changes(); /** * @return error when What-If operation fails. */ ManagementError error(); }
338
372
<reponame>wuyinlei/VideoDemo<filename>library/src/main/java/org/sunger/net/widget/SolidToast.java package org.sunger.net.widget; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Handler; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.AnimationUtils; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView; import org.sunger.net.R; public class SolidToast { public static final int DURATION_LONG = 3000; public static final int DURATION_SHORT = 1200; public static final int GRAVITY_DEFAULT = -1; private ViewGroup mParent; private View mToastView; private Activity mActivity; private LayoutParams mLayoutParams; private TranslateAnimation mUpAnim; private AlphaAnimation mFadeInAnim; private AlphaAnimation mFadeOutAnim; private int mDuration; private int mGravity; private boolean mIsShowing; private boolean mIsReused; private int mBackgroundColor; private CharSequence mMsg; public SolidToast(Context context) { mUpAnim = (TranslateAnimation) AnimationUtils.loadAnimation(context, R.anim.slide_up_in); mFadeInAnim = (AlphaAnimation) AnimationUtils.loadAnimation(context, R.anim.fade_in); mFadeOutAnim = (AlphaAnimation) AnimationUtils.loadAnimation(context, R.anim.fade_out); mUpAnim.setDuration(300); mFadeInAnim.setDuration(200); mFadeOutAnim.setDuration(500); } /** * Return a SolidToast with custom text,default root view and default * duration. * * @param activity current activity * @param text the text you want to display * @return */ public static SolidToast make(Activity activity, CharSequence text) { return make(activity, text, null, DURATION_SHORT, GRAVITY_DEFAULT); } public static SolidToast make(Activity activity, int resId) { return make(activity, activity.getString(resId)); } /** * Return a SolidToast with custom text,custom gravity, default root view * and default duration. * * @param activity current activity * @param text the text you want to display * @param gravity display gravity * @return */ public static SolidToast make(Activity activity, CharSequence text, int gravity) { return make(activity, text, null, DURATION_SHORT, gravity); } public static SolidToast make(Activity activity, int resId, int gravity) { return make(activity, activity.getString(resId), gravity); } /** * Return a SolidToast with custom text,default root view and display * duration. * * @param activity current activity * @param text the text you want to display * @param duration display duration, in ms. * @return SolidToast instance. */ public static SolidToast make(Activity activity, CharSequence text, int duration, int gravity) { return make(activity, text, null, duration, gravity); } public static SolidToast make(Activity activity, int resId, int duration, int gravity) { return make(activity, activity.getString(resId), duration, gravity); } public static SolidToast make(Activity activity, int resId, ViewGroup parent, int duration, int gravity) { return make(activity, activity.getString(resId), parent, duration, gravity); } /** * Return a SolidToast with custom text,parent view and display duration. * * @param activity current activity * @param text the text you want to display * @param parent parent view of toast display on * @param duration display duration, in ms. * @return SolidToast instance. */ public static SolidToast make(Activity activity, CharSequence text, ViewGroup parent, int duration, int gravity) { boolean isReused = true; View view = activity.findViewById(R.id.toast_background); if (view == null) { view = View.inflate(activity, R.layout.view_solid_toast, null); isReused = false; } LinearLayout background = (LinearLayout) view .findViewById(R.id.toast_background); TextView msg = (TextView) view.findViewById(R.id.toast_msg); background.setBackgroundColor(Color.BLUE); msg.setText(text); SolidToast toast = new SolidToast(activity); toast.setViewIsReused(isReused); toast.setMsg(text); toast.setParent(parent); toast.setActivity(activity); toast.setDuration(duration); toast.setGravity(gravity); toast.setToastView(view); return toast; } public static boolean isToastShowing(Activity activity) { View view = getToastView(activity); return view != null && view.getVisibility() == View.VISIBLE; } public static View getToastView(Activity activity) { return activity.findViewById(R.id.toast_background); } public static void hideToastView(Activity activity) { View view = getToastView(activity); if (view != null && view.getVisibility() == View.VISIBLE) { AlphaAnimation alphaAnimation = (AlphaAnimation) AnimationUtils .loadAnimation(activity, R.anim.fade_out); alphaAnimation.setDuration(300); view.startAnimation(alphaAnimation); view.setVisibility(View.GONE); } } public View getToastView() { return mToastView; } public void setToastView(View view) { mToastView = view; mToastView.setLayoutParams(getLayoutParams()); } public void setViewIsReused(boolean isReused) { mIsReused = isReused; } public ViewGroup getParent() { return mParent; } public void setParent(ViewGroup parent) { this.mParent = parent; } public Activity getActivity() { return mActivity; } public void setActivity(Activity activity) { this.mActivity = activity; } public LayoutParams getLayoutParams() { if (mLayoutParams == null) { mLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, getGravity()); } return mLayoutParams; } public void setLayoutParams(LayoutParams mLayoutParams) { this.mLayoutParams = mLayoutParams; } public int getGravity() { if (mGravity == GRAVITY_DEFAULT) mGravity = Gravity.BOTTOM; return mGravity; } public void setGravity(int mGravity) { this.mGravity = mGravity; } public int getDuration() { return mDuration; } public void setDuration(int duration) { this.mDuration = duration; } public CharSequence getMsg() { return mMsg; } public void setMsg(CharSequence msg) { mMsg = msg; } public boolean isShowing() { return mIsShowing; } public int getBackgroundColor() { return mBackgroundColor; } public SolidToast setBackgroundColorId(int colorId) { int color = getToastView().getResources().getColor(colorId); mBackgroundColor = color; getToastView().setBackgroundColor(color); return this; } /** * display prepared SolidToast */ public void show() { if (TextUtils.isEmpty(mMsg)) return; mIsShowing = true; View view = getToastView(); if (mIsReused) { TextView textView = (TextView) getActivity().findViewById( R.id.toast_msg); if (textView != null) { textView.setText(mMsg); } } else { if (view.getParent() == null) { if (getParent() != null) { getParent().addView(view, getLayoutParams()); } else { getActivity().addContentView(view, getLayoutParams()); } } } view.clearAnimation(); if (getGravity() == Gravity.BOTTOM) view.startAnimation(mUpAnim); else if (getGravity() == Gravity.TOP) view.startAnimation(mFadeInAnim); if (view.getVisibility() != View.VISIBLE) view.setVisibility(View.VISIBLE); new Handler().postDelayed(new Runnable() { public void run() { hide(); } }, getDuration()); } /** * display SolidToast with specified margin based on gravity * * @param margin */ public void showWithMargin(int margin) { LayoutParams params = getLayoutParams(); switch (getGravity()) { case Gravity.BOTTOM: params.bottomMargin = margin; break; case Gravity.TOP: params.topMargin = margin; break; case Gravity.LEFT: params.leftMargin = margin; break; case Gravity.RIGHT: params.rightMargin = margin; break; } show(); } public void hide() { View toastView = getToastView(); if (mIsShowing && toastView.getVisibility() == View.VISIBLE) { toastView.startAnimation(mFadeOutAnim); toastView.setVisibility(View.GONE); mIsShowing = false; } } }
4,252
2,519
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited. package com.starrocks.sql.optimizer.rule.transformation; import com.google.common.collect.Lists; import com.starrocks.sql.optimizer.OptExpression; import com.starrocks.sql.optimizer.OptimizerContext; import com.starrocks.sql.optimizer.operator.OperatorType; import com.starrocks.sql.optimizer.operator.logical.LogicalCTEConsumeOperator; import com.starrocks.sql.optimizer.operator.logical.LogicalFilterOperator; import com.starrocks.sql.optimizer.operator.pattern.Pattern; import com.starrocks.sql.optimizer.rule.RuleType; import java.util.List; /* * Filter CTEConsume(Predicate) * | | * CTEConsume => Filter * | | * Node Node * * */ public class PushDownPredicateCTEConsumeRule extends TransformationRule { public PushDownPredicateCTEConsumeRule() { super(RuleType.TF_PUSH_DOWN_PREDICATE_CTE_CONSUME, Pattern.create(OperatorType.LOGICAL_FILTER) .addChildren(Pattern.create(OperatorType.LOGICAL_CTE_CONSUME, OperatorType.PATTERN_LEAF))); } @Override public List<OptExpression> transform(OptExpression input, OptimizerContext context) { LogicalFilterOperator filter = (LogicalFilterOperator) input.getOp(); LogicalCTEConsumeOperator consume = (LogicalCTEConsumeOperator) input.getInputs().get(0).getOp(); LogicalCTEConsumeOperator newConsume = new LogicalCTEConsumeOperator.Builder() .withOperator(consume).setPredicate(filter.getPredicate()).build(); OptExpression output = OptExpression.create(newConsume, OptExpression.create(filter, input.getInputs().get(0).getInputs())); return Lists.newArrayList(output); } }
740
3,897
/******************************************************************************* * DISCLAIMER * This software is supplied by Renesas Electronics Corporation and is only * intended for use with Renesas products. No other uses are authorized. This * software is owned by Renesas Electronics Corporation and is protected under * all applicable laws, including copyright laws. * THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING * THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT * LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. * TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS * ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE * FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR * ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * Renesas reserves the right, without notice, to make changes to this software * and to discontinue the availability of this software. By using this software, * you agree to the additional terms and conditions found by accessing the * following link: * http://www.renesas.com/disclaimer * Copyright (C) 2019 Renesas Electronics Corporation. All rights reserved. *******************************************************************************/ /* Copyright (c) 2019-2020 Renesas Electronics Corporation. * SPDX-License-Identifier: Apache-2.0 * * 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. */ /******************************************************************************* * Rev: 3.01 * Description : IO bitmask header *******************************************************************************/ #ifndef RIIC_IOBITMASK_H #define RIIC_IOBITMASK_H /* ==== Mask values for IO registers ==== */ #define RIIC_ICCR1_SDAI (0x00000001u) #define RIIC_ICCR1_SDAI_SHIFT (0u) #define RIIC_ICCR1_SCLI (0x00000002u) #define RIIC_ICCR1_SCLI_SHIFT (1u) #define RIIC_ICCR1_SDAO (0x00000004u) #define RIIC_ICCR1_SDAO_SHIFT (2u) #define RIIC_ICCR1_SCLO (0x00000008u) #define RIIC_ICCR1_SCLO_SHIFT (3u) #define RIIC_ICCR1_SOWP (0x00000010u) #define RIIC_ICCR1_SOWP_SHIFT (4u) #define RIIC_ICCR1_CLO (0x00000020u) #define RIIC_ICCR1_CLO_SHIFT (5u) #define RIIC_ICCR1_IICRST (0x00000040u) #define RIIC_ICCR1_IICRST_SHIFT (6u) #define RIIC_ICCR1_ICE (0x00000080u) #define RIIC_ICCR1_ICE_SHIFT (7u) #define RIIC_ICCR2_ST (0x00000002u) #define RIIC_ICCR2_ST_SHIFT (1u) #define RIIC_ICCR2_RS (0x00000004u) #define RIIC_ICCR2_RS_SHIFT (2u) #define RIIC_ICCR2_SP (0x00000008u) #define RIIC_ICCR2_SP_SHIFT (3u) #define RIIC_ICCR2_TRS (0x00000020u) #define RIIC_ICCR2_TRS_SHIFT (5u) #define RIIC_ICCR2_MST (0x00000040u) #define RIIC_ICCR2_MST_SHIFT (6u) #define RIIC_ICCR2_BBSY (0x00000080u) #define RIIC_ICCR2_BBSY_SHIFT (7u) #define RIIC_ICMR1_BC (0x00000007u) #define RIIC_ICMR1_BC_SHIFT (0u) #define RIIC_ICMR1_BCWP (0x00000008u) #define RIIC_ICMR1_BCWP_SHIFT (3u) #define RIIC_ICMR1_CKS (0x00000070u) #define RIIC_ICMR1_CKS_SHIFT (4u) #define RIIC_ICMR2_TMOS (0x00000001u) #define RIIC_ICMR2_TMOS_SHIFT (0u) #define RIIC_ICMR2_TMOL (0x00000002u) #define RIIC_ICMR2_TMOL_SHIFT (1u) #define RIIC_ICMR2_TMOH (0x00000004u) #define RIIC_ICMR2_TMOH_SHIFT (2u) #define RIIC_ICMR2_SDDL (0x00000070u) #define RIIC_ICMR2_SDDL_SHIFT (4u) #define RIIC_ICMR2_DLCS (0x00000080u) #define RIIC_ICMR2_DLCS_SHIFT (7u) #define RIIC_ICMR3_NF (0x00000003u) #define RIIC_ICMR3_NF_SHIFT (0u) #define RIIC_ICMR3_ACKBR (0x00000004u) #define RIIC_ICMR3_ACKBR_SHIFT (2u) #define RIIC_ICMR3_ACKBT (0x00000008u) #define RIIC_ICMR3_ACKBT_SHIFT (3u) #define RIIC_ICMR3_ACKWP (0x00000010u) #define RIIC_ICMR3_ACKWP_SHIFT (4u) #define RIIC_ICMR3_RDRFS (0x00000020u) #define RIIC_ICMR3_RDRFS_SHIFT (5u) #define RIIC_ICMR3_WAIT (0x00000040u) #define RIIC_ICMR3_WAIT_SHIFT (6u) #define RIIC_ICMR3_SMBE (0x00000080u) #define RIIC_ICMR3_SMBE_SHIFT (7u) #define RIIC_ICFER_TMOE (0x00000001u) #define RIIC_ICFER_TMOE_SHIFT (0u) #define RIIC_ICFER_MALE (0x00000002u) #define RIIC_ICFER_MALE_SHIFT (1u) #define RIIC_ICFER_NALE (0x00000004u) #define RIIC_ICFER_NALE_SHIFT (2u) #define RIIC_ICFER_SALE (0x00000008u) #define RIIC_ICFER_SALE_SHIFT (3u) #define RIIC_ICFER_NACKE (0x00000010u) #define RIIC_ICFER_NACKE_SHIFT (4u) #define RIIC_ICFER_NFE (0x00000020u) #define RIIC_ICFER_NFE_SHIFT (5u) #define RIIC_ICFER_SCLE (0x00000040u) #define RIIC_ICFER_SCLE_SHIFT (6u) #define RIIC_ICFER_FMPE (0x00000080u) #define RIIC_ICFER_FMPE_SHIFT (7u) #define RIIC_ICSER_SAR0 (0x00000001u) #define RIIC_ICSER_SAR0_SHIFT (0u) #define RIIC_ICSER_SAR1 (0x00000002u) #define RIIC_ICSER_SAR1_SHIFT (1u) #define RIIC_ICSER_SAR2 (0x00000004u) #define RIIC_ICSER_SAR2_SHIFT (2u) #define RIIC_ICSER_GCE (0x00000008u) #define RIIC_ICSER_GCE_SHIFT (3u) #define RIIC_ICSER_DIDE (0x00000020u) #define RIIC_ICSER_DIDE_SHIFT (5u) #define RIIC_ICSER_HOAE (0x00000080u) #define RIIC_ICSER_HOAE_SHIFT (7u) #define RIIC_ICIER_TMOIE (0x00000001u) #define RIIC_ICIER_TMOIE_SHIFT (0u) #define RIIC_ICIER_ALIE (0x00000002u) #define RIIC_ICIER_ALIE_SHIFT (1u) #define RIIC_ICIER_STIE (0x00000004u) #define RIIC_ICIER_STIE_SHIFT (2u) #define RIIC_ICIER_SPIE (0x00000008u) #define RIIC_ICIER_SPIE_SHIFT (3u) #define RIIC_ICIER_NAKIE (0x00000010u) #define RIIC_ICIER_NAKIE_SHIFT (4u) #define RIIC_ICIER_RIE (0x00000020u) #define RIIC_ICIER_RIE_SHIFT (5u) #define RIIC_ICIER_TEIE (0x00000040u) #define RIIC_ICIER_TEIE_SHIFT (6u) #define RIIC_ICIER_TIE (0x00000080u) #define RIIC_ICIER_TIE_SHIFT (7u) #define RIIC_ICSR1_AAS0 (0x00000001u) #define RIIC_ICSR1_AAS0_SHIFT (0u) #define RIIC_ICSR1_AAS1 (0x00000002u) #define RIIC_ICSR1_AAS1_SHIFT (1u) #define RIIC_ICSR1_AAS2 (0x00000004u) #define RIIC_ICSR1_AAS2_SHIFT (2u) #define RIIC_ICSR1_GCA (0x00000008u) #define RIIC_ICSR1_GCA_SHIFT (3u) #define RIIC_ICSR1_DID (0x00000020u) #define RIIC_ICSR1_DID_SHIFT (5u) #define RIIC_ICSR1_HOA (0x00000080u) #define RIIC_ICSR1_HOA_SHIFT (7u) #define RIIC_ICSR2_TMOF (0x00000001u) #define RIIC_ICSR2_TMOF_SHIFT (0u) #define RIIC_ICSR2_AL (0x00000002u) #define RIIC_ICSR2_AL_SHIFT (1u) #define RIIC_ICSR2_START (0x00000004u) #define RIIC_ICSR2_START_SHIFT (2u) #define RIIC_ICSR2_STOP (0x00000008u) #define RIIC_ICSR2_STOP_SHIFT (3u) #define RIIC_ICSR2_NACKF (0x00000010u) #define RIIC_ICSR2_NACKF_SHIFT (4u) #define RIIC_ICSR2_RDRF (0x00000020u) #define RIIC_ICSR2_RDRF_SHIFT (5u) #define RIIC_ICSR2_TEND (0x00000040u) #define RIIC_ICSR2_TEND_SHIFT (6u) #define RIIC_ICSR2_TDRE (0x00000080u) #define RIIC_ICSR2_TDRE_SHIFT (7u) #define RIIC_ICSAR0_SVA0 (0x00000001u) #define RIIC_ICSAR0_SVA0_SHIFT (0u) #define RIIC_ICSAR0_SVA (0x000003FEu) #define RIIC_ICSAR0_SVA_SHIFT (1u) #define RIIC_ICSAR0_FS0 (0x00008000u) #define RIIC_ICSAR0_FS0_SHIFT (15u) #define RIIC_ICSAR1_SVA0 (0x00000001u) #define RIIC_ICSAR1_SVA0_SHIFT (0u) #define RIIC_ICSAR1_SVA (0x000003FEu) #define RIIC_ICSAR1_SVA_SHIFT (1u) #define RIIC_ICSAR1_FS1 (0x00008000u) #define RIIC_ICSAR1_FS1_SHIFT (15u) #define RIIC_ICSAR2_SVA0 (0x00000001u) #define RIIC_ICSAR2_SVA0_SHIFT (0u) #define RIIC_ICSAR2_SVA (0x000003FEu) #define RIIC_ICSAR2_SVA_SHIFT (1u) #define RIIC_ICSAR2_FS2 (0x00008000u) #define RIIC_ICSAR2_FS2_SHIFT (15u) #define RIIC_ICBRL_BRL (0x0000001Fu) #define RIIC_ICBRL_BRL_SHIFT (0u) #define RIIC_ICBRH_BRH (0x0000001Fu) #define RIIC_ICBRH_BRH_SHIFT (0u) #define RIIC_ICDRT_DRT (0x000000FFu) #define RIIC_ICDRT_DRT_SHIFT (0u) #define RIIC_ICDRR_DRR (0x000000FFu) #define RIIC_ICDRR_DRR_SHIFT (0u) #endif
11,723
402
#pragma once #define MAX(a, b) ({ \ __typeof__(a) __max_tmp_a = (a); \ __typeof__(a) __max_tmp_b = (b); \ (__max_tmp_a >= __max_tmp_b ? __max_tmp_a : __max_tmp_b); \ }) #define MIN(a, b) ({ \ __typeof__(a) __min_tmp_a = (a); \ __typeof__(a) __min_tmp_b = (b); \ (__min_tmp_a <= __min_tmp_b ? __min_tmp_a : __min_tmp_b); \ })
178
335
{ "word": "Parachute", "definitions": [ "A cloth canopy which fills with air and allows a person or heavy object attached to it to descend slowly when dropped from an aircraft, or which is released from the rear of an aircraft on landing to act as a brake." ], "parts-of-speech": "Noun" }
97
5,169
<filename>Specs/HJRSeparatableView/1.1.0/HJRSeparatableView.podspec.json { "name": "HJRSeparatableView", "version": "1.1.0", "summary": "An extended view with a single line separator like UITableViewCell.", "homepage": "https://github.com/hedjirog/HJRSeparatableView", "screenshots": "https://raw.github.com/hedjirog/HJRSeparatableView/master/Demo/Resources/Demo.gif", "license": { "type": "MIT", "file": "LICENSE" }, "authors": "<NAME>", "social_media_url": "http://twitter.com/hedjirog", "platforms": { "ios": "5.0" }, "source": { "git": "https://github.com/hedjirog/HJRSeparatableView.git", "tag": "1.1.0" }, "source_files": "HJRSeparatableView", "requires_arc": true }
306
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. */ /** * @file * Declares ignite::cache::CacheEntry class. */ #ifndef _IGNITE_CACHE_CACHE_ENTRY #define _IGNITE_CACHE_CACHE_ENTRY #include <utility> #include <ignite/common/common.h> namespace ignite { namespace cache { /** * %Cache entry class template. * * Both key and value types should be default-constructable, * copy-constructable and assignable. */ template<typename K, typename V> class CacheEntry { public: /** * Default constructor. * * Creates instance with both key and value default-constructed. */ CacheEntry() : key(), val(), hasValue(false) { // No-op. } /** * Constructor. * * @param key Key. * @param val Value. */ CacheEntry(const K& key, const V& val) : key(key), val(val), hasValue(true) { // No-op. } /** * Copy constructor. * * @param other Other instance. */ CacheEntry(const CacheEntry& other) : key(other.key), val(other.val), hasValue(other.hasValue) { // No-op. } /** * Constructor. * * @param p Pair. */ CacheEntry(const std::pair<K, V>& p) : key(p.first), val(p.second), hasValue(true) { // No-op. } /** * Destructor. */ virtual ~CacheEntry() { // No-op. } /** * Assignment operator. * * @param other Other instance. */ CacheEntry& operator=(const CacheEntry& other) { if (this != &other) { key = other.key; val = other.val; hasValue = other.hasValue; } return *this; } /** * Get key. * * @return Key. */ const K& GetKey() const { return key; } /** * Get value. * * @return Value. */ const V& GetValue() const { return val; } /** * Check if the value exists. * * @return True, if the value exists. */ bool HasValue() const { return hasValue; } protected: /** Key. */ K key; /** Value. */ V val; /** Indicates whether value exists */ bool hasValue; }; } } #endif //_IGNITE_CACHE_CACHE_ENTRY
2,255
526
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.commonservices.ocf.metadatamanagement.rest; import com.fasterxml.jackson.databind.ObjectMapper; import org.testng.annotations.Test; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /** * Validate that the TagRequestBody bean can be cloned, compared, serialized, deserialized and printed as a String. */ public class TagRequestBodyTest { /** * Default constructor */ public TagRequestBodyTest() { } /** * Set up an example object to test. * * @return filled in object */ private TagRequestBody getTestObject() { TagRequestBody testObject = new TagRequestBody(); testObject.setTagName("TestTagName"); testObject.setTagDescription("TestTagDescription"); return testObject; } /** * Validate that the object that comes out of the test has the same content as the original test object. * * @param resultObject object returned by the test */ private void validateResultObject(TagRequestBody resultObject) { assertTrue(resultObject.getTagName().equals("TestTagName")); assertTrue(resultObject.getTagDescription().equals("TestTagDescription")); } /** * Validate that the object is initialized properly */ @Test public void testNullObject() { TagRequestBody nullObject = new TagRequestBody(); assertTrue(nullObject.getTagName() == null); assertTrue(nullObject.getTagDescription() == null); nullObject = new TagRequestBody(null); assertTrue(nullObject.getTagName() == null); assertTrue(nullObject.getTagDescription() == null); } /** * Validate that 2 different objects with the same content are evaluated as equal. * Also that different objects are considered not equal. */ @Test public void testEquals() { assertFalse(getTestObject().equals("DummyString")); assertTrue(getTestObject().equals(getTestObject())); TagRequestBody sameObject = getTestObject(); assertTrue(sameObject.equals(sameObject)); TagRequestBody differentObject = getTestObject(); differentObject.setTagName("DifferentTag"); assertFalse(getTestObject().equals(differentObject)); } /** * Validate that 2 different objects with the same content have the same hash code. */ @Test public void testHashCode() { assertTrue(getTestObject().hashCode() == getTestObject().hashCode()); } /** * Validate that an object cloned from another object has the same content as the original */ @Test public void testClone() { validateResultObject(new TagRequestBody(getTestObject())); } /** * Validate that an object generated from a JSON String has the same content as the object used to * create the JSON String. */ @Test public void testJSON() { ObjectMapper objectMapper = new ObjectMapper(); String jsonString = null; /* * This class */ try { jsonString = objectMapper.writeValueAsString(getTestObject()); } catch (Throwable exc) { assertTrue(false, "Exception: " + exc.getMessage()); } try { validateResultObject(objectMapper.readValue(jsonString, TagRequestBody.class)); } catch (Throwable exc) { assertTrue(false, "Exception: " + exc.getMessage()); } /* * Through superclass */ OCFOMASAPIRequestBody superObject = getTestObject(); try { jsonString = objectMapper.writeValueAsString(superObject); } catch (Throwable exc) { assertTrue(false, "Exception: " + exc.getMessage()); } try { validateResultObject((TagRequestBody) objectMapper.readValue(jsonString, OCFOMASAPIRequestBody.class)); } catch (Throwable exc) { assertTrue(false, "Exception: " + exc.getMessage()); } } /** * Test that toString is overridden. */ @Test public void testToString() { assertTrue(getTestObject().toString().contains("TagRequestBody")); } }
1,769
190,993
<gh_stars>1000+ /* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/platform/denormal.h" #include "tensorflow/core/platform/cpu_info.h" #include "tensorflow/core/platform/platform.h" // If we're on gcc 4.8 or older, there's a known bug that prevents the use of // intrinsics when the architecture is not defined in the flags. See // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57202 #if !defined(__SSE3__) && !defined(__clang__) && \ (defined(__GNUC__) && (__GNUC__ < 4) || \ ((__GNUC__ == 4) && (__GNUC_MINOR__ < 9))) #define GCC_WITHOUT_INTRINSICS #endif // Only try to use SSE3 instructions if we're on an x86 platform, and it's not // mobile, and we're not on a known bad gcc version. #if defined(PLATFORM_IS_X86) && !defined(IS_MOBILE_PLATFORM) && \ !defined(GCC_WITHOUT_INTRINSICS) #define X86_DENORM_USE_INTRINSICS #endif #ifdef X86_DENORM_USE_INTRINSICS #include <pmmintrin.h> #endif // If on ARM, only access the control register if hardware floating-point // support is available. #if defined(PLATFORM_IS_ARM) && defined(__ARM_FP) && (__ARM_FP > 0) #define ARM_DENORM_AVAILABLE // Flush-to-zero bit on the ARM floating-point control register. #define ARM_FPCR_FZ (1 << 24) #endif namespace tensorflow { namespace port { bool DenormalState::operator==(const DenormalState& other) const { return flush_to_zero() == other.flush_to_zero() && denormals_are_zero() == other.denormals_are_zero(); } bool DenormalState::operator!=(const DenormalState& other) const { return !(this->operator==(other)); } #ifdef ARM_DENORM_AVAILABLE // Although the ARM ACLE does have a specification for __arm_rsr/__arm_wsr // for reading and writing to the status registers, they are not implemented // by GCC, so we need to resort to inline assembly. static inline void ArmSetFloatingPointControlRegister(uint32_t fpcr) { #ifdef PLATFORM_IS_ARM64 __asm__ __volatile__("msr fpcr, %[fpcr]" : : [fpcr] "r"(static_cast<uint64_t>(fpcr))); #else __asm__ __volatile__("vmsr fpscr, %[fpcr]" : : [fpcr] "r"(fpcr)); #endif } static inline uint32_t ArmGetFloatingPointControlRegister() { uint32_t fpcr; #ifdef PLATFORM_IS_ARM64 uint64_t fpcr64; __asm__ __volatile__("mrs %[fpcr], fpcr" : [fpcr] "=r"(fpcr64)); fpcr = static_cast<uint32_t>(fpcr64); #else __asm__ __volatile__("vmrs %[fpcr], fpscr" : [fpcr] "=r"(fpcr)); #endif return fpcr; } #endif // ARM_DENORM_AVAILABLE bool SetDenormalState(const DenormalState& state) { // For now, we flush denormals only on SSE 3 and ARM. Other architectures // can be added as needed. #ifdef X86_DENORM_USE_INTRINSICS if (TestCPUFeature(SSE3)) { // Restore flags _MM_SET_FLUSH_ZERO_MODE(state.flush_to_zero() ? _MM_FLUSH_ZERO_ON : _MM_FLUSH_ZERO_OFF); _MM_SET_DENORMALS_ZERO_MODE(state.denormals_are_zero() ? _MM_DENORMALS_ZERO_ON : _MM_DENORMALS_ZERO_OFF); return true; } #endif #ifdef ARM_DENORM_AVAILABLE // ARM only has one setting controlling both denormal inputs and outputs. if (state.flush_to_zero() == state.denormals_are_zero()) { uint32_t fpcr = ArmGetFloatingPointControlRegister(); if (state.flush_to_zero()) { fpcr |= ARM_FPCR_FZ; } else { fpcr &= ~ARM_FPCR_FZ; } ArmSetFloatingPointControlRegister(fpcr); return true; } #endif // Setting denormal handling to the provided state is not supported. return false; } DenormalState GetDenormalState() { #ifdef X86_DENORM_USE_INTRINSICS if (TestCPUFeature(SSE3)) { // Save existing flags bool flush_zero_mode = _MM_GET_FLUSH_ZERO_MODE() == _MM_FLUSH_ZERO_ON; bool denormals_zero_mode = _MM_GET_DENORMALS_ZERO_MODE() == _MM_DENORMALS_ZERO_ON; return DenormalState(flush_zero_mode, denormals_zero_mode); } #endif #ifdef ARM_DENORM_AVAILABLE uint32_t fpcr = ArmGetFloatingPointControlRegister(); if ((fpcr & ARM_FPCR_FZ) != 0) { return DenormalState(true, true); } #endif return DenormalState(false, false); } ScopedRestoreFlushDenormalState::ScopedRestoreFlushDenormalState() : denormal_state_(GetDenormalState()) {} ScopedRestoreFlushDenormalState::~ScopedRestoreFlushDenormalState() { SetDenormalState(denormal_state_); } ScopedFlushDenormal::ScopedFlushDenormal() { SetDenormalState( DenormalState(/*flush_to_zero=*/true, /*denormals_are_zero=*/true)); } ScopedDontFlushDenormal::ScopedDontFlushDenormal() { SetDenormalState( DenormalState(/*flush_to_zero=*/false, /*denormals_are_zero=*/false)); } } // namespace port } // namespace tensorflow
2,096
648
<reponame>swrobel/fhir {"resourceType":"CodeSystem","id":"match-grade","meta":{"lastUpdated":"2019-11-01T09:29:23.356+11:00"},"url":"http://terminology.hl7.org/CodeSystem/match-grade","identifier":[{"system":"urn:ietf:rfc:3986","value":"urn:oid:2.16.840.1.113883.4.642.4.1289"}],"version":"4.0.1","name":"MatchGrade","title":"MatchGrade","status":"draft","experimental":false,"date":"2019-11-01T09:29:23+11:00","publisher":"HL7 (FHIR Project)","contact":[{"telecom":[{"system":"url","value":"http://hl7.org/fhir"},{"system":"email","value":"<EMAIL>"}]}],"description":"A Master Patient Index (MPI) assessment of whether a candidate patient record is a match or not.","caseSensitive":true,"valueSet":"http://hl7.org/fhir/ValueSet/match-grade","content":"complete","concept":[{"code":"certain","display":"Certain Match","definition":"This record meets the matching criteria to be automatically considered as a full match."},{"code":"probable","display":"Probable Match","definition":"This record is a close match, but not a certain match. Additional review (e.g. by a human) may be required before using this as a match."},{"code":"possible","display":"Possible Match","definition":"This record may be a matching one. Additional review (e.g. by a human) SHOULD be performed before using this as a match."},{"code":"certainly-not","display":"Certainly Not a Match","definition":"This record is known not to be a match. Note that usually non-matching records are not returned, but in some cases records previously or likely considered as a match may specifically be negated by the matching engine."}]}
438
14,668
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/webtransport/test_utils.h" #include "base/check.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_tester.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" #include "third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_web_transport_options.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/streams/readable_stream.h" #include "third_party/blink/renderer/core/streams/readable_stream_generic_reader.h" #include "third_party/blink/renderer/modules/webtransport/web_transport.h" #include "third_party/blink/renderer/platform/heap/visitor.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/wtf/functional.h" namespace blink { bool CreateDataPipeForWebTransportTests( mojo::ScopedDataPipeProducerHandle* producer, mojo::ScopedDataPipeConsumerHandle* consumer) { MojoCreateDataPipeOptions options; options.struct_size = sizeof(MojoCreateDataPipeOptions); options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE; options.element_num_bytes = 1; options.capacity_num_bytes = 0; // 0 means the system default size. MojoResult result = mojo::CreateDataPipe(&options, *producer, *consumer); if (result != MOJO_RESULT_OK) { ADD_FAILURE() << "CreateDataPipe() returned " << result; return false; } return true; } v8::Local<v8::Value> ReadValueFromStream(const V8TestingScope& scope, ReadableStream* stream) { auto* script_state = scope.GetScriptState(); auto* reader = stream->GetDefaultReaderForTesting(script_state, ASSERT_NO_EXCEPTION); ScriptPromise read_promise = reader->read(script_state, ASSERT_NO_EXCEPTION); ScriptPromiseTester read_tester(script_state, read_promise); read_tester.WaitUntilSettled(); EXPECT_TRUE(read_tester.IsFulfilled()); v8::Local<v8::Value> result = read_tester.Value().V8Value(); DCHECK(result->IsObject()); v8::Local<v8::Value> v8value; bool done = false; EXPECT_TRUE( V8UnpackIteratorResult(script_state, result.As<v8::Object>(), &done) .ToLocal(&v8value)); EXPECT_FALSE(done); return v8value; } TestWebTransportCreator::TestWebTransportCreator() = default; void TestWebTransportCreator::Init(ScriptState* script_state, CreateStubCallback create_stub) { browser_interface_broker_ = &ExecutionContext::From(script_state)->GetBrowserInterfaceBroker(); create_stub_ = std::move(create_stub); browser_interface_broker_->SetBinderForTesting( mojom::blink::WebTransportConnector::Name_, WTF::BindRepeating(&TestWebTransportCreator::BindConnector, weak_ptr_factory_.GetWeakPtr())); web_transport_ = WebTransport::Create( script_state, "https://example.com/", MakeGarbageCollected<WebTransportOptions>(), ASSERT_NO_EXCEPTION); test::RunPendingTasks(); } TestWebTransportCreator::~TestWebTransportCreator() { browser_interface_broker_->SetBinderForTesting( mojom::blink::WebTransportConnector::Name_, {}); } // Implementation of mojom::blink::WebTransportConnector. void TestWebTransportCreator::Connect( const KURL&, Vector<network::mojom::blink::WebTransportCertificateFingerprintPtr>, mojo::PendingRemote<network::mojom::blink::WebTransportHandshakeClient> pending_handshake_client) { mojo::Remote<network::mojom::blink::WebTransportHandshakeClient> handshake_client(std::move(pending_handshake_client)); mojo::PendingRemote<network::mojom::blink::WebTransport> web_transport_to_pass; create_stub_.Run(web_transport_to_pass); mojo::PendingRemote<network::mojom::blink::WebTransportClient> client_remote; handshake_client->OnConnectionEstablished( std::move(web_transport_to_pass), client_remote.InitWithNewPipeAndPassReceiver(), network::mojom::blink::HttpResponseHeaders::New()); client_remote_.Bind(std::move(client_remote)); } void TestWebTransportCreator::BindConnector( mojo::ScopedMessagePipeHandle handle) { connector_receiver_.Bind( mojo::PendingReceiver<mojom::blink::WebTransportConnector>( std::move(handle))); } void TestWebTransportCreator::Reset() { client_remote_.reset(); connector_receiver_.reset(); } } // namespace blink
1,825
1,043
<filename>SwiftExample/Pods/Headers/Private/KZPlayground/KZPPlaygroundViewController.h // // Created by <NAME>(http://twitter.com/merowing_) on 19/10/14. // // // @import Foundation; @import UIKit; @interface KZPPlaygroundViewController : UIViewController @property(nonatomic, assign) BOOL timelineHidden; + (instancetype)playgroundViewController; + (instancetype)newPlaygroundViewController; @end
137
12,278
<gh_stars>1000+ // Copyright <NAME> 2005. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_PARAMETER_AUX_PREPROCESSOR_SEQ_ENUM_HPP #define BOOST_PARAMETER_AUX_PREPROCESSOR_SEQ_ENUM_HPP #include <boost/preprocessor/seq/enum.hpp> #include <boost/config.hpp> #include <boost/config/workaround.hpp> #if BOOST_WORKAROUND(__MWERKS__, <= 0x3003) #include <boost/preprocessor/seq/size.hpp> // Temporary version of BOOST_PP_SEQ_ENUM // until <NAME>. integrates the workaround. #define BOOST_PARAMETER_SEQ_ENUM_I(size, seq) \ BOOST_PP_CAT(BOOST_PP_SEQ_ENUM_, size) seq #define BOOST_PARAMETER_SEQ_ENUM(seq) \ BOOST_PARAMETER_SEQ_ENUM_I(BOOST_PP_SEQ_SIZE(seq), seq) #else #define BOOST_PARAMETER_SEQ_ENUM(seq) BOOST_PP_SEQ_ENUM(seq) #endif #endif // include guard
396
3,200
<filename>mindspore/lite/src/common/config_file.h<gh_stars>1000+ /** * Copyright 2021 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 MINDSPORE_LITE_SRC_COMMON_CONFIG_FILE_H_ #define MINDSPORE_LITE_SRC_COMMON_CONFIG_FILE_H_ #include <limits.h> #include <string.h> #include <cstdio> #include <cstdlib> #include <iostream> #include <memory> #include <fstream> #include <string> #include <map> #include <vector> #include <utility> #include "src/common/utils.h" #include "src/common/log_adapter.h" #include "ir/dtype/type_id.h" namespace mindspore { namespace lite { constexpr int MAX_CONFIG_FILE_LENGTH = 1024; #define CONFIG_FILE_EXECUTION_PLAN "execution_plan" int GetSectionInfoFromConfigFile(const std::string &file, const std::string &section_name, std::map<std::string, std::string> *section_info); void ParserExecutionPlan(const std::map<std::string, std::string> *config_infos, std::map<std::string, TypeId> *data_type_plan); } // namespace lite } // namespace mindspore #endif // MINDSPORE_LITE_SRC_COMMON_CONFIG_FILE_H_
588
38,247
<reponame>Linuxinet/PayloadsAllTheThings #! /usr/bin/env python2 #Jenkins Groovy XML RCE (CVE-2016-0792) #Note: Although this is listed as a pre-auth RCE, during my testing it only worked if authentication was disabled in Jenkins #Made with <3 by @byt3bl33d3r from __future__ import print_function import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) import argparse import sys parser = argparse.ArgumentParser() parser.add_argument('target', type=str, help='Target IP:PORT') parser.add_argument('command', type=str, help='Command to run on target') parser.add_argument('--proto', choices={'http', 'https'}, default='http', help='Send exploit over http or https (default: http)') if len(sys.argv) < 2: parser.print_help() sys.exit(1) args = parser.parse_args() if len(args.target.split(':')) != 2: print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: print('[-] You must specify a command to run') sys.exit(1) ip, port = args.target.split(':') print('[*] Target IP: {}'.format(ip)) print('[*] Target PORT: {}'.format(port)) xml_formatted = '' command_list = args.command.split() for cmd in command_list: xml_formatted += '{:>16}<string>{}</string>\n'.format('', cmd) xml_payload = '''<map> <entry> <groovy.util.Expando> <expandoProperties> <entry> <string>hashCode</string> <org.codehaus.groovy.runtime.MethodClosure> <delegate class="groovy.util.Expando" reference="../../../.."/> <owner class="java.lang.ProcessBuilder"> <command> {} </command> <redirectErrorStream>false</redirectErrorStream> </owner> <resolveStrategy>0</resolveStrategy> <directive>0</directive> <parameterTypes/> <maximumNumberOfParameters>0</maximumNumberOfParameters> <method>start</method> </org.codehaus.groovy.runtime.MethodClosure> </entry> </expandoProperties> </groovy.util.Expando> <int>1</int> </entry> </map>'''.format(xml_formatted.strip()) print('[*] Generated XML payload:') print(xml_payload) print() print('[*] Sending payload') headers = {'Content-Type': 'text/xml'} r = requests.post('{}://{}:{}/createItem?name=rand_dir'.format(args.proto, ip, port), verify=False, headers=headers, data=xml_payload) paths_in_trace = ['jobs/rand_dir/config.xml', 'jobs\\rand_dir\\config.xml'] if r.status_code == 500: for path in paths_in_trace: if path in r.text: print('[+] Command executed successfully') break
1,106
407
package com.alibaba.tesla.appmanager.server.event.componentpackage; import com.alibaba.tesla.appmanager.common.enums.KanikoBuildEventEnum; /** * @ClassName: AddKanikoPodEvent * @Author: dyj * @DATE: 2021-07-14 * @Description: **/ public class FailedKanikoPodEvent extends KanikoPodEvent { public FailedKanikoPodEvent(Object source, String obj) { super(source, obj); this.CURRENT_STATUS = KanikoBuildEventEnum.FAILED; } }
170
407
package com.alibaba.tesla.authproxy.model; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class TeslaServiceExtAppDO implements Serializable { private Integer id; private String name; private String secret; private String comments; private Integer creator; private Date createtime; private Integer modifier; private Date modifytime; private Byte validflag; private static final long serialVersionUID = 1L; }
150
839
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hello_world_soap_http; import javax.jws.WebService; import org.apache.hello_world_rpclit.GreeterRPCLit; import org.apache.hello_world_rpclit.types.MyComplexStruct; @WebService(name = "GreeterRPCLit", serviceName = "SOAPServiceRPCLit", portName = "SoapPortRPCLit", targetNamespace = "http://apache.org/hello_world_rpclit", endpointInterface = "org.apache.hello_world_rpclit.GreeterRPCLit", wsdlLocation = "testutils/hello_world_rpc_lit.wsdl") public class RPCLitGreeterImpl implements GreeterRPCLit { public String greetMe(String me) { //System.out.println("Executing operation greetMe"); //System.out.println("Message received: " + me + "\n"); if ("return null".equals(me)) { return null; } return "Hello " + me; } public String sayHi() { //System.out.println("Executing operation sayHi" + "\n"); return "Bonjour"; } public MyComplexStruct sendReceiveData(MyComplexStruct in) { //System.out.println("Executing operation sendReceiveData"); //System.out.println("Received struct with values :\nElement-1 : " + in.getElem1() + "\nElement-2 : " // + in.getElem2() + "\nElement-3 : " + in.getElem3() + "\n"); if ("invalid".equals(in.getElem2())) { in.setElem2(null); } return in; } public String greetUs(String you, String me) { //System.out.println("Executing operation greetUs"); //System.out.println("Message received: you are " + you + " I'm " + me + "\n"); return "Hello " + you + " and " + me; } }
936
14,668
<reponame>chromium/chromium // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer.h" #include <string> #include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" #include "chrome/browser/browser_process.h" #include "components/page_load_metrics/browser/observers/core/largest_contentful_paint_handler.h" #include "components/page_load_metrics/browser/page_load_metrics_util.h" #include "components/page_load_metrics/common/page_load_timing.h" #include "content/public/browser/navigation_handle.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_recorder.h" using page_load_metrics::PageAbortReason; namespace internal { const char kHistogramFromGWSDomContentLoaded[] = "PageLoad.Clients.FromGoogleSearch.DocumentTiming." "NavigationToDOMContentLoadedEventFired"; const char kHistogramFromGWSLoad[] = "PageLoad.Clients.FromGoogleSearch.DocumentTiming." "NavigationToLoadEventFired"; const char kHistogramFromGWSFirstPaint[] = "PageLoad.Clients.FromGoogleSearch.PaintTiming.NavigationToFirstPaint"; const char kHistogramFromGWSFirstImagePaint[] = "PageLoad.Clients.FromGoogleSearch.PaintTiming.NavigationToFirstImagePaint"; const char kHistogramFromGWSFirstContentfulPaint[] = "PageLoad.Clients.FromGoogleSearch.PaintTiming." "NavigationToFirstContentfulPaint"; const char kHistogramFromGWSLargestContentfulPaint[] = "PageLoad.Clients.FromGoogleSearch.PaintTiming." "NavigationToLargestContentfulPaint"; const char kHistogramFromGWSParseStartToFirstContentfulPaint[] = "PageLoad.Clients.FromGoogleSearch.PaintTiming." "ParseStartToFirstContentfulPaint"; const char kHistogramFromGWSParseDuration[] = "PageLoad.Clients.FromGoogleSearch.ParseTiming.ParseDuration"; const char kHistogramFromGWSParseStart[] = "PageLoad.Clients.FromGoogleSearch.ParseTiming.NavigationToParseStart"; const char kHistogramFromGWSFirstInputDelay[] = "PageLoad.Clients.FromGoogleSearch.InteractiveTiming.FirstInputDelay4"; const char kHistogramFromGWSAbortNewNavigationBeforeCommit[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.NewNavigation." "BeforeCommit"; const char kHistogramFromGWSAbortNewNavigationBeforePaint[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.NewNavigation." "AfterCommit.BeforePaint"; const char kHistogramFromGWSAbortNewNavigationBeforeInteraction[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.NewNavigation." "AfterPaint.BeforeInteraction"; const char kHistogramFromGWSAbortStopBeforeCommit[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Stop." "BeforeCommit"; const char kHistogramFromGWSAbortStopBeforePaint[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Stop." "AfterCommit.BeforePaint"; const char kHistogramFromGWSAbortStopBeforeInteraction[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Stop." "AfterPaint.BeforeInteraction"; const char kHistogramFromGWSAbortCloseBeforeCommit[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Close." "BeforeCommit"; const char kHistogramFromGWSAbortCloseBeforePaint[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Close." "AfterCommit.BeforePaint"; const char kHistogramFromGWSAbortCloseBeforeInteraction[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Close." "AfterPaint.BeforeInteraction"; const char kHistogramFromGWSAbortOtherBeforeCommit[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Other." "BeforeCommit"; const char kHistogramFromGWSAbortReloadBeforeCommit[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Reload." "BeforeCommit"; const char kHistogramFromGWSAbortReloadBeforePaint[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Reload." "AfterCommit.BeforePaint"; const char kHistogramFromGWSAbortReloadBeforeInteraction[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Reload." "AfterPaint.Before1sDelayedInteraction"; const char kHistogramFromGWSAbortForwardBackBeforeCommit[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming." "ForwardBackNavigation.BeforeCommit"; const char kHistogramFromGWSAbortForwardBackBeforePaint[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming." "ForwardBackNavigation.AfterCommit.BeforePaint"; const char kHistogramFromGWSAbortForwardBackBeforeInteraction[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming." "ForwardBackNavigation.AfterPaint.Before1sDelayedInteraction"; const char kHistogramFromGWSAbortBackgroundBeforeCommit[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Background." "BeforeCommit"; const char kHistogramFromGWSAbortBackgroundBeforePaint[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Background." "AfterCommit.BeforePaint"; const char kHistogramFromGWSAbortBackgroundBeforeInteraction[] = "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Background." "AfterPaint.BeforeInteraction"; const char kHistogramFromGWSForegroundDuration[] = "PageLoad.Clients.FromGoogleSearch.PageTiming.ForegroundDuration"; const char kHistogramFromGWSForegroundDurationAfterPaint[] = "PageLoad.Clients.FromGoogleSearch.PageTiming.ForegroundDuration." "AfterPaint"; const char kHistogramFromGWSForegroundDurationWithPaint[] = "PageLoad.Clients.FromGoogleSearch.PageTiming.ForegroundDuration." "WithPaint"; const char kHistogramFromGWSForegroundDurationWithoutPaint[] = "PageLoad.Clients.FromGoogleSearch.PageTiming.ForegroundDuration." "WithoutPaint"; const char kHistogramFromGWSForegroundDurationNoCommit[] = "PageLoad.Clients.FromGoogleSearch.PageTiming.ForegroundDuration.NoCommit"; const char kHistogramFromGWSCumulativeLayoutShiftMainFrame[] = "PageLoad.Clients.FromGoogleSearch.LayoutInstability.CumulativeShiftScore." "MainFrame"; } // namespace internal namespace { void LogCommittedAbortsBeforePaint(PageAbortReason abort_reason, base::TimeDelta page_end_time) { switch (abort_reason) { case PageAbortReason::ABORT_STOP: PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSAbortStopBeforePaint, page_end_time); break; case PageAbortReason::ABORT_CLOSE: PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSAbortCloseBeforePaint, page_end_time); break; case PageAbortReason::ABORT_NEW_NAVIGATION: PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSAbortNewNavigationBeforePaint, page_end_time); break; case PageAbortReason::ABORT_RELOAD: PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSAbortReloadBeforePaint, page_end_time); break; case PageAbortReason::ABORT_FORWARD_BACK: PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSAbortForwardBackBeforePaint, page_end_time); break; case PageAbortReason::ABORT_BACKGROUND: PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSAbortBackgroundBeforePaint, page_end_time); break; default: // These should only be logged for provisional aborts. DCHECK_NE(abort_reason, PageAbortReason::ABORT_OTHER); break; } } void LogAbortsAfterPaintBeforeInteraction( const page_load_metrics::PageAbortInfo& abort_info) { switch (abort_info.reason) { case PageAbortReason::ABORT_STOP: PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSAbortStopBeforeInteraction, abort_info.time_to_abort); break; case PageAbortReason::ABORT_CLOSE: PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSAbortCloseBeforeInteraction, abort_info.time_to_abort); break; case PageAbortReason::ABORT_NEW_NAVIGATION: PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSAbortNewNavigationBeforeInteraction, abort_info.time_to_abort); break; case PageAbortReason::ABORT_RELOAD: PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSAbortReloadBeforeInteraction, abort_info.time_to_abort); break; case PageAbortReason::ABORT_FORWARD_BACK: PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSAbortForwardBackBeforeInteraction, abort_info.time_to_abort); break; case PageAbortReason::ABORT_BACKGROUND: PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSAbortBackgroundBeforeInteraction, abort_info.time_to_abort); break; default: // These should only be logged for provisional aborts. DCHECK_NE(abort_info.reason, PageAbortReason::ABORT_OTHER); break; } } void LogProvisionalAborts(const page_load_metrics::PageAbortInfo& abort_info) { switch (abort_info.reason) { case PageAbortReason::ABORT_STOP: PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSAbortStopBeforeCommit, abort_info.time_to_abort); break; case PageAbortReason::ABORT_CLOSE: PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSAbortCloseBeforeCommit, abort_info.time_to_abort); break; case PageAbortReason::ABORT_OTHER: PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSAbortOtherBeforeCommit, abort_info.time_to_abort); break; case PageAbortReason::ABORT_NEW_NAVIGATION: PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSAbortNewNavigationBeforeCommit, abort_info.time_to_abort); break; case PageAbortReason::ABORT_RELOAD: PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSAbortReloadBeforeCommit, abort_info.time_to_abort); break; case PageAbortReason::ABORT_FORWARD_BACK: PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSAbortForwardBackBeforeCommit, abort_info.time_to_abort); break; case PageAbortReason::ABORT_BACKGROUND: PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSAbortBackgroundBeforeCommit, abort_info.time_to_abort); break; default: NOTREACHED(); break; } } void LogForegroundDurations( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate, base::TimeTicks app_background_time) { absl::optional<base::TimeDelta> foreground_duration = page_load_metrics::GetInitialForegroundDuration(delegate, app_background_time); if (!foreground_duration) return; if (delegate.DidCommit()) { PAGE_LOAD_LONG_HISTOGRAM(internal::kHistogramFromGWSForegroundDuration, foreground_duration.value()); if (timing.paint_timing->first_paint && timing.paint_timing->first_paint < foreground_duration) { PAGE_LOAD_LONG_HISTOGRAM( internal::kHistogramFromGWSForegroundDurationAfterPaint, foreground_duration.value() - timing.paint_timing->first_paint.value()); PAGE_LOAD_LONG_HISTOGRAM( internal::kHistogramFromGWSForegroundDurationWithPaint, foreground_duration.value()); } else { PAGE_LOAD_LONG_HISTOGRAM( internal::kHistogramFromGWSForegroundDurationWithoutPaint, foreground_duration.value()); } } else { PAGE_LOAD_LONG_HISTOGRAM( internal::kHistogramFromGWSForegroundDurationNoCommit, foreground_duration.value()); } } bool WasAbortedInForeground( const page_load_metrics::PageLoadMetricsObserverDelegate& delegate, const page_load_metrics::PageAbortInfo& abort_info) { if (!delegate.StartedInForeground() || abort_info.reason == PageAbortReason::ABORT_NONE) return false; absl::optional<base::TimeDelta> time_to_abort(abort_info.time_to_abort); if (page_load_metrics::WasStartedInForegroundOptionalEventInForeground( time_to_abort, delegate)) return true; const base::TimeDelta time_to_first_background = delegate.GetTimeToFirstBackground().value(); DCHECK_GT(abort_info.time_to_abort, time_to_first_background); base::TimeDelta background_abort_delta = abort_info.time_to_abort - time_to_first_background; // Consider this a foregrounded abort if it occurred within 100ms of a // background. This is needed for closing some tabs, where the signal for // background is often slightly ahead of the signal for close. if (background_abort_delta.InMilliseconds() < 100) return true; return false; } bool WasAbortedBeforeInteraction( const page_load_metrics::PageAbortInfo& abort_info, const absl::optional<base::TimeDelta>& time_to_interaction) { // These conditions should be guaranteed by the call to // WasAbortedInForeground, which is called before WasAbortedBeforeInteraction // gets invoked. DCHECK(abort_info.reason != PageAbortReason::ABORT_NONE); if (!time_to_interaction) return true; // For the case the abort is a reload or forward_back. Since pull to // reload / forward_back is the most common user case such aborts being // triggered, add a sanitization threshold here: if the first user // interaction are received before a reload / forward_back in a very // short time, treat the interaction as a gesture to perform the abort. // Why 1000ms? // 1000ms is enough to perform a pull to reload / forward_back gesture. // It's also too short a time for a user to consume any content // revealed by the interaction. if (abort_info.reason == PageAbortReason::ABORT_RELOAD || abort_info.reason == PageAbortReason::ABORT_FORWARD_BACK) { return time_to_interaction.value() + base::Milliseconds(1000) > abort_info.time_to_abort; } else { return time_to_interaction > abort_info.time_to_abort; } } int32_t LayoutShiftUmaValue(float shift_score) { // Report (shift_score * 10) as an int in the range [0, 100]. return static_cast<int>(roundf(std::min(shift_score, 10.0f) * 10.0f)); } } // namespace FromGWSPageLoadMetricsLogger::FromGWSPageLoadMetricsLogger() = default; FromGWSPageLoadMetricsLogger::~FromGWSPageLoadMetricsLogger() = default; void FromGWSPageLoadMetricsLogger::SetPreviouslyCommittedUrl(const GURL& url) { if (page_load_metrics::IsGoogleSearchResultUrl(url)) { previously_committed_url_is_search_results_ = true; previously_committed_url_search_mode_ = google_util::GoogleSearchModeFromUrl(url); } previously_committed_url_is_search_redirector_ = page_load_metrics::IsGoogleSearchRedirectorUrl(url); } void FromGWSPageLoadMetricsLogger::SetProvisionalUrl(const GURL& url) { provisional_url_has_search_hostname_ = page_load_metrics::IsGoogleSearchHostname(url); } FromGWSPageLoadMetricsObserver::FromGWSPageLoadMetricsObserver() {} page_load_metrics::PageLoadMetricsObserver::ObservePolicy FromGWSPageLoadMetricsObserver::OnStart( content::NavigationHandle* navigation_handle, const GURL& currently_committed_url, bool started_in_foreground) { logger_.SetPreviouslyCommittedUrl(currently_committed_url); logger_.SetProvisionalUrl(navigation_handle->GetURL()); return CONTINUE_OBSERVING; } page_load_metrics::PageLoadMetricsObserver::ObservePolicy FromGWSPageLoadMetricsObserver::OnCommit( content::NavigationHandle* navigation_handle, ukm::SourceId source_id) { // We'd like to also check navigation_handle->HasUserGesture() here, however // this signal is not carried forward for navigations that open links in new // tabs, so we look only at PAGE_TRANSITION_LINK. Back/forward navigations // that were originally navigated from a link will continue to report a core // type of link, so to filter out back/forward navs, we also check that the // page transition is a new navigation. logger_.set_navigation_initiated_via_link( ui::PageTransitionCoreTypeIs(navigation_handle->GetPageTransition(), ui::PAGE_TRANSITION_LINK) && ui::PageTransitionIsNewNavigation( navigation_handle->GetPageTransition())); logger_.SetNavigationStart(navigation_handle->NavigationStart()); logger_.OnCommit(navigation_handle, source_id); return CONTINUE_OBSERVING; } page_load_metrics::PageLoadMetricsObserver::ObservePolicy FromGWSPageLoadMetricsObserver::FlushMetricsOnAppEnterBackground( const page_load_metrics::mojom::PageLoadTiming& timing) { logger_.FlushMetricsOnAppEnterBackground(timing, GetDelegate()); return STOP_OBSERVING; } void FromGWSPageLoadMetricsObserver::OnDomContentLoadedEventStart( const page_load_metrics::mojom::PageLoadTiming& timing) { logger_.OnDomContentLoadedEventStart(timing, GetDelegate()); } void FromGWSPageLoadMetricsObserver::OnLoadEventStart( const page_load_metrics::mojom::PageLoadTiming& timing) { logger_.OnLoadEventStart(timing, GetDelegate()); } void FromGWSPageLoadMetricsObserver::OnFirstPaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing) { logger_.OnFirstPaintInPage(timing, GetDelegate()); } void FromGWSPageLoadMetricsObserver::OnFirstImagePaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing) { logger_.OnFirstImagePaintInPage(timing, GetDelegate()); } void FromGWSPageLoadMetricsObserver::OnFirstContentfulPaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing) { logger_.OnFirstContentfulPaintInPage(timing, GetDelegate()); } void FromGWSPageLoadMetricsObserver::OnFirstInputInPage( const page_load_metrics::mojom::PageLoadTiming& timing) { logger_.OnFirstInputInPage(timing, GetDelegate()); } void FromGWSPageLoadMetricsObserver::OnParseStart( const page_load_metrics::mojom::PageLoadTiming& timing) { logger_.OnParseStart(timing, GetDelegate()); } void FromGWSPageLoadMetricsObserver::OnParseStop( const page_load_metrics::mojom::PageLoadTiming& timing) { logger_.OnParseStop(timing, GetDelegate()); } void FromGWSPageLoadMetricsObserver::OnComplete( const page_load_metrics::mojom::PageLoadTiming& timing) { logger_.OnComplete(timing, GetDelegate()); } void FromGWSPageLoadMetricsObserver::OnFailedProvisionalLoad( const page_load_metrics::FailedProvisionalLoadInfo& failed_load_info) { logger_.OnFailedProvisionalLoad(failed_load_info, GetDelegate()); } void FromGWSPageLoadMetricsObserver::OnUserInput( const blink::WebInputEvent& event, const page_load_metrics::mojom::PageLoadTiming& timing) { logger_.OnUserInput(event, timing, GetDelegate()); } void FromGWSPageLoadMetricsLogger::OnCommit( content::NavigationHandle* navigation_handle, ukm::SourceId source_id) { if (!ShouldLogPostCommitMetrics(navigation_handle->GetURL())) return; ukm::builders::PageLoad_FromGoogleSearch(source_id) .SetGoogleSearchMode( static_cast<int64_t>(previously_committed_url_search_mode_)) .Record(ukm::UkmRecorder::Get()); } void FromGWSPageLoadMetricsLogger::OnComplete( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (!ShouldLogPostCommitMetrics(delegate.GetUrl())) return; LogMetricsOnComplete(delegate); page_load_metrics::PageAbortInfo abort_info = GetPageAbortInfo(delegate); if (!WasAbortedInForeground(delegate, abort_info)) return; // If we did not receive any timing IPCs from the render process, we can't // know for certain if the page was truly aborted before paint, or if the // abort happened before we received the IPC from the render process. Thus, we // do not log aborts for these page loads. Tracked page loads that receive no // timing IPCs are tracked via the ERR_NO_IPCS_RECEIVED error code in the // PageLoad.Events.InternalError histogram, so we can keep track of how often // this happens. if (page_load_metrics::IsEmpty(timing)) return; if (!timing.paint_timing->first_paint || timing.paint_timing->first_paint >= abort_info.time_to_abort) { LogCommittedAbortsBeforePaint(abort_info.reason, abort_info.time_to_abort); } else if (WasAbortedBeforeInteraction(abort_info, first_user_interaction_after_paint_)) { LogAbortsAfterPaintBeforeInteraction(abort_info); } LogForegroundDurations(timing, delegate, base::TimeTicks()); } void FromGWSPageLoadMetricsLogger::OnFailedProvisionalLoad( const page_load_metrics::FailedProvisionalLoadInfo& failed_load_info, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (!ShouldLogFailedProvisionalLoadMetrics()) return; page_load_metrics::PageAbortInfo abort_info = GetPageAbortInfo(delegate); if (!WasAbortedInForeground(delegate, abort_info)) return; LogProvisionalAborts(abort_info); LogForegroundDurations(page_load_metrics::mojom::PageLoadTiming(), delegate, base::TimeTicks()); } bool FromGWSPageLoadMetricsLogger::ShouldLogFailedProvisionalLoadMetrics() { // See comment in ShouldLogPostCommitMetrics above the call to // page_load_metrics::IsGoogleSearchHostname for more info on this if test. if (provisional_url_has_search_hostname_) return false; return previously_committed_url_is_search_results_ || previously_committed_url_is_search_redirector_; } bool FromGWSPageLoadMetricsLogger::ShouldLogPostCommitMetrics(const GURL& url) { DCHECK(!url.is_empty()); // If this page has a URL on a known google search hostname, then it may be a // page associated with search (either a search results page, or a search // redirector url), so we should not log stats. We could try to detect only // the specific known search URLs here, and log navigations to other pages on // the google search hostname (for example, a search for 'about google' // includes a result for https://www.google.com/about/), however, we assume // these cases are relatively uncommon, and we run the risk of logging metrics // for some search redirector URLs. Thus we choose the more conservative // approach of ignoring all urls on known search hostnames. if (page_load_metrics::IsGoogleSearchHostname(url)) return false; // We're only interested in tracking navigations (e.g. clicks) initiated via // links. Note that the redirector will mask these, so don't enforce this if // the navigation came from a redirect url. TODO(csharrison): Use this signal // for provisional loads when the content APIs allow for it. if (previously_committed_url_is_search_results_ && navigation_initiated_via_link_) { return true; } // If the navigation was via the search redirector, then the information about // whether the navigation was from a link would have been associated with the // navigation to the redirector, and not included in the redirected // navigation. Therefore, do not require link navigation this case. return previously_committed_url_is_search_redirector_; } bool FromGWSPageLoadMetricsLogger::ShouldLogForegroundEventAfterCommit( const absl::optional<base::TimeDelta>& event, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { DCHECK(delegate.DidCommit()) << "ShouldLogForegroundEventAfterCommit called without committed URL."; return ShouldLogPostCommitMetrics(delegate.GetUrl()) && page_load_metrics::WasStartedInForegroundOptionalEventInForeground( event, delegate); } void FromGWSPageLoadMetricsLogger::OnDomContentLoadedEventStart( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (ShouldLogForegroundEventAfterCommit( timing.document_timing->dom_content_loaded_event_start, delegate)) { PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSDomContentLoaded, timing.document_timing->dom_content_loaded_event_start.value()); } } void FromGWSPageLoadMetricsLogger::OnLoadEventStart( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (ShouldLogForegroundEventAfterCommit( timing.document_timing->load_event_start, delegate)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSLoad, timing.document_timing->load_event_start.value()); } } void FromGWSPageLoadMetricsLogger::OnFirstPaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (ShouldLogForegroundEventAfterCommit(timing.paint_timing->first_paint, delegate)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSFirstPaint, timing.paint_timing->first_paint.value()); } first_paint_triggered_ = true; } void FromGWSPageLoadMetricsLogger::OnFirstImagePaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (ShouldLogForegroundEventAfterCommit( timing.paint_timing->first_image_paint, delegate)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSFirstImagePaint, timing.paint_timing->first_image_paint.value()); } } void FromGWSPageLoadMetricsLogger::OnFirstContentfulPaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (ShouldLogForegroundEventAfterCommit( timing.paint_timing->first_contentful_paint, delegate)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSFirstContentfulPaint, timing.paint_timing->first_contentful_paint.value()); // If we have a foreground paint, we should have a foreground parse start, // since paints can't happen until after parsing starts. DCHECK(page_load_metrics::WasStartedInForegroundOptionalEventInForeground( timing.parse_timing->parse_start, delegate)); PAGE_LOAD_HISTOGRAM( internal::kHistogramFromGWSParseStartToFirstContentfulPaint, timing.paint_timing->first_contentful_paint.value() - timing.parse_timing->parse_start.value()); } } void FromGWSPageLoadMetricsLogger::OnFirstInputInPage( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (ShouldLogForegroundEventAfterCommit( timing.interactive_timing->first_input_delay, delegate)) { UMA_HISTOGRAM_CUSTOM_TIMES( internal::kHistogramFromGWSFirstInputDelay, timing.interactive_timing->first_input_delay.value(), base::Milliseconds(1), base::Seconds(60), 50); } } void FromGWSPageLoadMetricsLogger::OnParseStart( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (ShouldLogForegroundEventAfterCommit(timing.parse_timing->parse_start, delegate)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSParseStart, timing.parse_timing->parse_start.value()); } } void FromGWSPageLoadMetricsLogger::OnParseStop( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (ShouldLogForegroundEventAfterCommit(timing.parse_timing->parse_stop, delegate)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSParseDuration, timing.parse_timing->parse_stop.value() - timing.parse_timing->parse_start.value()); } } void FromGWSPageLoadMetricsLogger::OnUserInput( const blink::WebInputEvent& event, const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (first_paint_triggered_ && !first_user_interaction_after_paint_) { DCHECK(!navigation_start_.is_null()); first_user_interaction_after_paint_ = base::TimeTicks::Now() - navigation_start_; } } void FromGWSPageLoadMetricsLogger::FlushMetricsOnAppEnterBackground( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { LogMetricsOnComplete(delegate); LogForegroundDurations(timing, delegate, base::TimeTicks::Now()); } void FromGWSPageLoadMetricsLogger::LogMetricsOnComplete( const page_load_metrics::PageLoadMetricsObserverDelegate& delegate) { if (!delegate.DidCommit() || !ShouldLogPostCommitMetrics(delegate.GetUrl())) return; const page_load_metrics::ContentfulPaintTimingInfo& all_frames_largest_contentful_paint = delegate.GetLargestContentfulPaintHandler() .MergeMainFrameAndSubframes(); if (all_frames_largest_contentful_paint.ContainsValidTime() && WasStartedInForegroundOptionalEventInForeground( all_frames_largest_contentful_paint.Time(), delegate)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFromGWSLargestContentfulPaint, all_frames_largest_contentful_paint.Time().value()); } UMA_HISTOGRAM_COUNTS_100( internal::kHistogramFromGWSCumulativeLayoutShiftMainFrame, LayoutShiftUmaValue( delegate.GetMainFrameRenderData().layout_shift_score)); }
11,071
335
{ "word": "Beachfront", "definitions": [ "The part of a coastal town next to and directly facing the sea; the seafront." ], "parts-of-speech": "Noun" }
71
1,139
package com.journaldev.androidcanvasbasics; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.RelativeLayout; public class MainActivity extends AppCompatActivity { LinearLayout linearLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); linearLayout = findViewById(R.id.linearLayout); MyView myView = new MyView(this); linearLayout.addView(myView); } }
205
8,148
#pragma once #include "../dxvk_device.h" #include "dxvk_hud_item.h" #include "dxvk_hud_renderer.h" namespace dxvk::hud { /** * \brief HUD uniform data * Shader data for the HUD. */ struct HudUniformData { VkExtent2D surfaceSize; }; /** * \brief DXVK HUD * * Can be used by the presentation backend to * display performance and driver information. */ class Hud : public RcObject { public: Hud(const Rc<DxvkDevice>& device); ~Hud(); /** * \brief Update HUD * * Updates the data to display. * Should be called once per frame. */ void update(); /** * \brief Render HUD * * Renders the HUD to the given context. * \param [in] ctx Device context * \param [in] surfaceSize Image size, in pixels */ void render( const Rc<DxvkContext>& ctx, VkSurfaceFormatKHR surfaceFormat, VkExtent2D surfaceSize); /** * \brief Adds a HUD item if enabled * * \tparam T The HUD item type * \param [in] name HUD item name * \param [in] args Constructor arguments */ template<typename T, typename... Args> void addItem(const char* name, int32_t at, Args... args) { m_hudItems.add<T>(name, at, std::forward<Args>(args)...); } /** * \brief Creates the HUD * * Creates and initializes the HUD if the * \c DXVK_HUD environment variable is set. * \param [in] device The DXVK device * \returns HUD object, if it was created. */ static Rc<Hud> createHud( const Rc<DxvkDevice>& device); private: const Rc<DxvkDevice> m_device; DxvkRasterizerState m_rsState; DxvkBlendMode m_blendMode; HudUniformData m_uniformData; HudRenderer m_renderer; HudItemSet m_hudItems; float m_scale; void setupRendererState( const Rc<DxvkContext>& ctx, VkSurfaceFormatKHR surfaceFormat, VkExtent2D surfaceSize); void resetRendererState( const Rc<DxvkContext>& ctx); void renderHudElements( const Rc<DxvkContext>& ctx); }; }
1,062
558
/* SPDX-License-Identifier: Apache-2.0 */ /* * Copyright (C) 2015-2017,2021 Micron Technology, Inc. All rights reserved. */ #ifndef HSE_UTEST_COMMON_H #define HSE_UTEST_COMMON_H #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <assert.h> #define MTF_PAGE_SIZE getpagesize() #define ___MTF_MAX_VALUE_COUNT 1000 #define ___MTF_MAX_UTEST_INSTANCES 250 #define ___MTF_MAX_COLL_NAME_LENGTH 100 enum mtf_test_coll_state { ST_INITIALIZING, ST_READY, ST_RUNNING, ST_DONE, ST_ERROR }; enum mtf_read_state { RD_READY, RD_STARTED }; enum mtf_test_result { TR_NONE = 1, TR_PASS, TR_FAIL }; struct mtf_test_coll_info; struct mtf_test_info; extern int mtf_verify_flag; extern int mtf_verify_line; extern const char *mtf_verify_file; typedef void (*test_function)(struct mtf_test_info *); typedef int (*prepost_hook)(struct mtf_test_info *); struct mtf_test_info { struct mtf_test_coll_info *ti_coll; const char * ti_name; int ti_index; int ti_status; }; struct mtf_test_coll_info { /* general test collection info */ const char *tci_coll_name; int tci_num_tests; const char *tci_named; int tci_argc; char ** tci_argv; int tci_optind; /* test collection overall state */ enum mtf_test_coll_state tci_state; enum mtf_read_state tci_res_rd_state; int tci_res_rd_index; enum mtf_read_state tci_out_rd_state; unsigned long tci_out_rd_offst; /* test collection pre-/post- run hooks */ prepost_hook tci_pre_run_hook; prepost_hook tci_post_run_hook; /* individual test cases, names, and associated pre-/pos- run hooks */ const char * tci_test_names[___MTF_MAX_UTEST_INSTANCES]; test_function tci_test_pointers[___MTF_MAX_UTEST_INSTANCES]; prepost_hook tci_test_prehooks[___MTF_MAX_UTEST_INSTANCES]; prepost_hook tci_test_posthooks[___MTF_MAX_UTEST_INSTANCES]; /* test collection info for a particular tun */ const char * tci_failed_tests[___MTF_MAX_UTEST_INSTANCES]; enum mtf_test_result tci_test_results[___MTF_MAX_UTEST_INSTANCES]; void * tci_outbuf; int tci_outbuf_len; unsigned long tci_outbuf_pos; void *tci_rock; }; #define MTF_SET_ROCK(coll_name, rock) (_mtf_##coll_name##_tci.tci_rock = (void *)rock) #define MTF_GET_ROCK(coll_name) (_mtf_##coll_name##_tci.tci_rock) static inline int inner_mtf_print(struct mtf_test_coll_info *tci, const char *fmt_str, ...) { va_list args; char * tgt = tci->tci_outbuf + tci->tci_outbuf_pos; int rem = tci->tci_outbuf_len - tci->tci_outbuf_pos; int bc; va_start(args, fmt_str); bc = vsnprintf(tgt, rem - 1, fmt_str, args); va_end(args); if (bc >= rem) { *tgt = 0; return -1; } else { tci->tci_outbuf_pos += bc; return 0; } } #define mtf_print(tci, ...) \ do { \ printf(__VA_ARGS__); \ fflush(stdout); \ } while (0) #endif
1,551
945
<reponame>RYH61/iotdb /* * 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.iotdb.metrics.predefined.jvm; import org.apache.iotdb.metrics.MetricManager; import org.apache.iotdb.metrics.predefined.IMetricSet; import org.apache.iotdb.metrics.utils.JvmUtils; import org.apache.iotdb.metrics.utils.MetricLevel; import org.apache.iotdb.metrics.utils.PredefinedMetric; import java.lang.management.BufferPoolMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryType; import java.lang.management.MemoryUsage; /** This file is modified from io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics */ public class JvmMemoryMetrics implements IMetricSet { @Override public void bindTo(MetricManager metricManager) { for (BufferPoolMXBean bufferPoolBean : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) { metricManager.getOrCreateAutoGauge( "jvm.buffer.count.buffers", MetricLevel.IMPORTANT, bufferPoolBean, BufferPoolMXBean::getCount, "id", bufferPoolBean.getName()); metricManager.getOrCreateAutoGauge( "jvm.buffer.memory.used.bytes", MetricLevel.IMPORTANT, bufferPoolBean, BufferPoolMXBean::getMemoryUsed, "id", bufferPoolBean.getName()); metricManager.getOrCreateAutoGauge( "jvm.buffer.total.capacity.bytes", MetricLevel.IMPORTANT, bufferPoolBean, BufferPoolMXBean::getTotalCapacity, "id", bufferPoolBean.getName()); } for (MemoryPoolMXBean memoryPoolBean : ManagementFactory.getPlatformMXBeans(MemoryPoolMXBean.class)) { String area = MemoryType.HEAP.equals(memoryPoolBean.getType()) ? "heap" : "nonheap"; metricManager.getOrCreateAutoGauge( "jvm.memory.used.bytes", MetricLevel.IMPORTANT, memoryPoolBean, (mem) -> (long) JvmUtils.getUsageValue(mem, MemoryUsage::getUsed), "id", memoryPoolBean.getName(), "area", area); metricManager.getOrCreateAutoGauge( "jvm.memory.committed.bytes", MetricLevel.IMPORTANT, memoryPoolBean, (mem) -> (long) JvmUtils.getUsageValue(mem, MemoryUsage::getCommitted), "id", memoryPoolBean.getName(), "area", area); metricManager.getOrCreateAutoGauge( "jvm.memory.max.bytes", MetricLevel.IMPORTANT, memoryPoolBean, (mem) -> (long) JvmUtils.getUsageValue(mem, MemoryUsage::getMax), "id", memoryPoolBean.getName(), "area", area); } } @Override public PredefinedMetric getType() { return PredefinedMetric.JVM; } }
1,463
373
package com.dianrong.common.uniauth.common.server; import org.springframework.web.servlet.LocaleResolver; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; /** * . uniauth local resolver. * * @author wanglin */ public class UniauthLocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { return UniauthLocaleInfoHolder.getLocale(); } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { UniauthLocaleInfoHolder.setLocale(locale); } }
214
617
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include <openenclave/bits/defs.h> #include <openenclave/corelibc/bits/defs.h> #include <stdlib.h> OE_NO_RETURN void exit(int code) { _Exit(code); }
91
347
<reponame>hbraha/ovirt-engine<gh_stars>100-1000 package org.ovirt.engine.core.common.businessentities; /** * Status of host kdump flow */ public enum KdumpFlowStatus { /** * Kdump flow started */ STARTED, /** * Kdump flow is currently running */ DUMPING, /** * Kdump flow finished successfully */ FINISHED; /** * Returns string value (lowercase name) */ public String getAsString() { return name().toLowerCase(); } /** * Creates an enum instance for specified string value * * @param value * string value */ public static KdumpFlowStatus forString(String value) { KdumpFlowStatus result = null; if (value != null) { result = KdumpFlowStatus.valueOf(value.toUpperCase()); } return result; } }
369
400
/* * priority_buffer_queue.h - priority buffer queue * * Copyright (c) 2015 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: <NAME> <<EMAIL>> */ #ifndef XCAM_PRIORITY_BUFFER_QUEUE_H #define XCAM_PRIORITY_BUFFER_QUEUE_H #include <xcam_std.h> #include <safe_list.h> #include <ocl/cl_image_handler.h> namespace XCam { struct PriorityBuffer { SmartPtr<VideoBuffer> data; SmartPtr<CLImageHandler> handler; uint32_t rank; uint32_t seq_num; public: PriorityBuffer () : rank (0) , seq_num (0) {} void set_seq_num (const uint32_t value) { seq_num = value; } uint32_t get_seq_num () const { return seq_num; } // when change to next rank void down_rank () { ++rank; } bool priority_greater_than (const PriorityBuffer& buf) const; }; class PriorityBufferQueue : public SafeList<PriorityBuffer> { public: PriorityBufferQueue () {} ~PriorityBufferQueue () {} bool push_priority_buf (const SmartPtr<PriorityBuffer> &buf); private: XCAM_DEAD_COPY (PriorityBufferQueue); }; }; #endif //XCAM_PRIORITY_BUFFER_QUEUE_H
652
877
<filename>checker/tests/mustcall/TryWithResourcesCrash.java<gh_stars>100-1000 // A test case for a crash while checking hfds. import java.io.Closeable; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; class TryWithResourcesCrash { void test(FileSystem fs, byte[] bytes, String path) throws IOException { try (FSDataOutputStream out = fs.createFile(path).overwrite(true).build()) { out.write(bytes); } } class FSDataOutputStream extends DataOutputStream { FSDataOutputStream(OutputStream os) { super(os); } } abstract class FSDataOutputStreamBuilder< S extends FSDataOutputStream, B extends FSDataOutputStreamBuilder<S, B>> { abstract S build(); abstract B overwrite(boolean b); } abstract class FileSystem implements Closeable { abstract FSDataOutputStreamBuilder createFile(String s); } }
287
474
<gh_stars>100-1000 from .execution_statistics_viewer import ExecutionStatisticsViewer
25
372
<gh_stars>100-1000 /* * DISTRHO Plugin Framework (DPF) * Copyright (C) 2012-2021 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and/or distribute this software for any purpose with * or without fee is hereby granted, provided that the above copyright notice and this * permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef DISTRHO_LIBRARY_UTILS_HPP_INCLUDED #define DISTRHO_LIBRARY_UTILS_HPP_INCLUDED #include "../DistrhoUtils.hpp" #ifdef DISTRHO_OS_WINDOWS # ifndef NOMINMAX # define NOMINMAX # endif # include <winsock2.h> # include <windows.h> typedef HMODULE lib_t; #else # include <dlfcn.h> typedef void* lib_t; #endif START_NAMESPACE_DISTRHO // ----------------------------------------------------------------------- // library related calls /* * Open 'filename' library (must not be null). * May return null, in which case "lib_error" has the error. */ static inline lib_t lib_open(const char* const filename) noexcept { DISTRHO_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', nullptr); try { #ifdef DISTRHO_OS_WINDOWS return ::LoadLibraryA(filename); #else return ::dlopen(filename, RTLD_NOW|RTLD_LOCAL); #endif } DISTRHO_SAFE_EXCEPTION_RETURN("lib_open", nullptr); } /* * Close a previously opened library (must not be null). * If false is returned, "lib_error" has the error. */ static inline bool lib_close(const lib_t lib) noexcept { DISTRHO_SAFE_ASSERT_RETURN(lib != nullptr, false); try { #ifdef DISTRHO_OS_WINDOWS return ::FreeLibrary(lib); #else return (::dlclose(lib) == 0); #endif } DISTRHO_SAFE_EXCEPTION_RETURN("lib_close", false); } /* * Get a library symbol (must not be null). * Returns null if the symbol is not found. */ template<typename Func> static inline Func lib_symbol(const lib_t lib, const char* const symbol) noexcept { DISTRHO_SAFE_ASSERT_RETURN(lib != nullptr, nullptr); DISTRHO_SAFE_ASSERT_RETURN(symbol != nullptr && symbol[0] != '\0', nullptr); try { #ifdef DISTRHO_OS_WINDOWS # if defined(__GNUC__) && (__GNUC__ >= 9) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wcast-function-type" # endif return (Func)::GetProcAddress(lib, symbol); # if defined(__GNUC__) && (__GNUC__ >= 9) # pragma GCC diagnostic pop # endif #else return (Func)(uintptr_t)::dlsym(lib, symbol); #endif } DISTRHO_SAFE_EXCEPTION_RETURN("lib_symbol", nullptr); } /* * Return the last operation error ('filename' must not be null). * May return null. */ static inline const char* lib_error(const char* const filename) noexcept { DISTRHO_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', nullptr); #ifdef DISTRHO_OS_WINDOWS static char libError[2048+1]; std::memset(libError, 0, sizeof(libError)); try { const DWORD winErrorCode = ::GetLastError(); const int winErrorFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS; LPVOID winErrorString; ::FormatMessage(winErrorFlags, nullptr, winErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&winErrorString, 0, nullptr); std::snprintf(libError, 2048, "%s: error code %li: %s", filename, winErrorCode, (const char*)winErrorString); ::LocalFree(winErrorString); } DISTRHO_SAFE_EXCEPTION("lib_error"); return (libError[0] != '\0') ? libError : nullptr; #else return ::dlerror(); #endif } // ----------------------------------------------------------------------- END_NAMESPACE_DISTRHO #endif // DISTRHO_LIBRARY_UTILS_HPP_INCLUDED
1,488
331
package com.lauzy.freedom.data.local.data.impl; import android.content.Context; import com.lauzy.freedom.data.local.data.CacheRepo; /** * Desc : 缓存 * Author : Lauzy * Date : 2018/4/3 * Blog : http://www.jianshu.com/u/e76853f863a9 * Email : <EMAIL> */ public class CacheRepoImpl extends SharedPreferenceDataRepo implements CacheRepo { private static final String FILE_NAME = "ticktock_cache_sp"; private static final String ARTIST_SHARED_KEY = "key_artist_avatar"; public CacheRepoImpl(Context context) { super(context, FILE_NAME, Context.MODE_PRIVATE); } @Override public void setArtistAvatar(String artistName, String avatarUrl) { put(artistName, avatarUrl); } @Override public String getArtistAvatar(String artistName) { return getString(artistName); } }
308
14,668
// Copyright 2019 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 UI_OZONE_PLATFORM_WAYLAND_TEST_TEST_DATA_DEVICE_MANAGER_H_ #define UI_OZONE_PLATFORM_WAYLAND_TEST_TEST_DATA_DEVICE_MANAGER_H_ #include <wayland-server-protocol.h> #include "ui/ozone/platform/wayland/test/global_object.h" namespace wl { extern const struct wl_data_device_manager_interface kTestDataDeviceManagerImpl; class TestDataDevice; class TestDataSource; // Manage wl_data_device_manager object. class TestDataDeviceManager : public GlobalObject { public: TestDataDeviceManager(); TestDataDeviceManager(const TestDataDeviceManager&) = delete; TestDataDeviceManager& operator=(const TestDataDeviceManager&) = delete; ~TestDataDeviceManager() override; TestDataDevice* data_device() const { return data_device_; } void set_data_device(TestDataDevice* data_device) { data_device_ = data_device; } TestDataSource* data_source() const { return data_source_; } void set_data_source(TestDataSource* data_source) { data_source_ = data_source; } private: TestDataDevice* data_device_ = nullptr; TestDataSource* data_source_ = nullptr; }; } // namespace wl #endif // UI_OZONE_PLATFORM_WAYLAND_TEST_TEST_DATA_DEVICE_MANAGER_H_
456
575
<reponame>sarang-apps/darshan_browser // Copyright 2019 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 "ash/public/cpp/split_view_test_api.h" #include "ash/shell.h" #include "ash/wm/splitview/split_view_controller.h" namespace ash { namespace { SplitViewController* split_view_controller() { return SplitViewController::Get(Shell::GetPrimaryRootWindow()); } } // namespace SplitViewTestApi::SplitViewTestApi() = default; SplitViewTestApi::~SplitViewTestApi() = default; void SplitViewTestApi::SnapWindow( aura::Window* window, SplitViewTestApi::SnapPosition snap_position) { SplitViewController::SnapPosition position; switch (snap_position) { case SnapPosition::NONE: position = SplitViewController::NONE; break; case SnapPosition::LEFT: position = SplitViewController::LEFT; break; case SnapPosition::RIGHT: position = SplitViewController::RIGHT; break; } split_view_controller()->SnapWindow(window, position); } void SplitViewTestApi::SwapWindows() { split_view_controller()->SwapWindows(); } } // namespace ash
409
14,668
<reponame>chromium/chromium // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/page_load_metrics/observers/data_saver_site_breakdown_metrics_observer.h" #include "base/metrics/field_trial_params.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h" #include "chrome/browser/profiles/profile.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_features.h" #include "url/gurl.h" DataSaverSiteBreakdownMetricsObserver::DataSaverSiteBreakdownMetricsObserver() = default; DataSaverSiteBreakdownMetricsObserver:: ~DataSaverSiteBreakdownMetricsObserver() = default; page_load_metrics::PageLoadMetricsObserver::ObservePolicy DataSaverSiteBreakdownMetricsObserver::OnCommit( content::NavigationHandle* navigation_handle, ukm::SourceId source_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); Profile* profile = Profile::FromBrowserContext( navigation_handle->GetWebContents()->GetBrowserContext()); // Skip if Lite mode is not enabled. if (!profile || !data_reduction_proxy::DataReductionProxySettings:: IsDataSaverEnabledByUser(profile->IsOffTheRecord(), profile->GetPrefs())) { return STOP_OBSERVING; } // This BrowserContext is valid for the lifetime of // DataReductionProxyMetricsObserver. BrowserContext is always valid and // non-nullptr in NavigationControllerImpl, which is a member of WebContents. // A raw pointer to BrowserContext taken at this point will be valid until // after WebContent's destructor. The latest that PageLoadTracker's destructor // will be called is in MetricsWebContentsObserver's destructor, which is // called in WebContents destructor. browser_context_ = navigation_handle->GetWebContents()->GetBrowserContext(); // Use the virtual URL that is meant to be displayed to the user, instead of // actual URL, since certain previews redirect to an optimized page that has // different URL than shown in the titlebar. committed_host_ = navigation_handle->GetWebContents() ->GetLastCommittedURL() .HostNoBrackets(); committed_origin_ = navigation_handle->GetWebContents() ->GetLastCommittedURL() .DeprecatedGetOriginAsURL() .spec(); return CONTINUE_OBSERVING; } void DataSaverSiteBreakdownMetricsObserver::OnResourceDataUseObserved( content::RenderFrameHost* rfh, const std::vector<page_load_metrics::mojom::ResourceDataUpdatePtr>& resources) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); data_reduction_proxy::DataReductionProxySettings* data_reduction_proxy_settings = DataReductionProxyChromeSettingsFactory::GetForBrowserContext( browser_context_); if (data_reduction_proxy_settings && data_reduction_proxy_settings->data_reduction_proxy_service()) { DCHECK(!committed_host_.empty()); DCHECK(!committed_origin_.empty()); int64_t received_data_length = 0; int64_t data_reduction_proxy_bytes_saved = 0; for (auto const& resource : resources) { received_data_length += resource->delta_bytes; // Estimate savings based on network bytes used. data_reduction_proxy_bytes_saved += resource->delta_bytes * (resource->data_reduction_proxy_compression_ratio_estimate - 1.0); if (resource->is_complete) { // Record the actual data savings based on body length. Remove // previously added savings from network usage. data_reduction_proxy_bytes_saved += (resource->encoded_body_length - resource->received_data_length) * (resource->data_reduction_proxy_compression_ratio_estimate - 1.0); } } double origin_save_data_savings = data_reduction_proxy_settings->data_reduction_proxy_service() ->GetSaveDataSavingsPercentEstimate(committed_origin_); if (origin_save_data_savings) { data_reduction_proxy_bytes_saved += received_data_length * origin_save_data_savings / 100; } data_reduction_proxy_settings->data_reduction_proxy_service() ->UpdateDataUseForHost( received_data_length, received_data_length + data_reduction_proxy_bytes_saved, committed_host_); // TODO(rajendrant): Fix the |request_type| and |mime_type| sent below or // remove the respective histograms. data_reduction_proxy_settings->data_reduction_proxy_service() ->UpdateContentLengths( received_data_length, received_data_length + data_reduction_proxy_bytes_saved, data_reduction_proxy_settings->IsDataReductionProxyEnabled(), std::string() /* mime_type */, true /*is_user_traffic*/, data_use_measurement::DataUseUserData::OTHER, 0); } } void DataSaverSiteBreakdownMetricsObserver::OnNewDeferredResourceCounts( const page_load_metrics::mojom::DeferredResourceCounts& new_deferred_resource_data) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); data_reduction_proxy::DataReductionProxySettings* data_reduction_proxy_settings = DataReductionProxyChromeSettingsFactory::GetForBrowserContext( browser_context_); if (!data_reduction_proxy_settings || !data_reduction_proxy_settings->data_reduction_proxy_service()) { return; } DCHECK(!committed_host_.empty()); int64_t previously_reported_savings_that_no_longer_apply = 0; int64_t new_reported_savings = 0; int typical_frame_savings = base::GetFieldTrialParamByFeatureAsInt( features::kLazyFrameLoading, "typical_frame_size_in_bytes", 50000); int typical_image_savings = base::GetFieldTrialParamByFeatureAsInt( features::kLazyFrameLoading, "typical_image_size_in_bytes", 10000); new_reported_savings += new_deferred_resource_data.deferred_frames * typical_frame_savings; new_reported_savings += new_deferred_resource_data.deferred_images * typical_image_savings; previously_reported_savings_that_no_longer_apply += new_deferred_resource_data.frames_loaded_after_deferral * typical_frame_savings; previously_reported_savings_that_no_longer_apply += new_deferred_resource_data.images_loaded_after_deferral * typical_image_savings; // This can be negative if we previously recorded savings that need to be // undone. int64_t savings_to_report = new_reported_savings - previously_reported_savings_that_no_longer_apply; data_reduction_proxy_settings->data_reduction_proxy_service() ->UpdateDataUseForHost(0, savings_to_report, committed_host_); data_reduction_proxy_settings->data_reduction_proxy_service() ->UpdateContentLengths( 0, savings_to_report, data_reduction_proxy_settings->IsDataReductionProxyEnabled(), std::string() /* mime_type */, true /*is_user_traffic*/, data_use_measurement::DataUseUserData::OTHER, 0); } page_load_metrics::PageLoadMetricsObserver::ObservePolicy DataSaverSiteBreakdownMetricsObserver::ShouldObserveMimeType( const std::string& mime_type) const { // Observe all MIME types. We still only use actual data usage, so strange // cases (e.g., data:// URLs) will still record the right amount of data // usage. return CONTINUE_OBSERVING; }
2,949
381
<reponame>joyrun/ActivityRouter package com.grouter.compiler; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.List; import javax.lang.model.element.Modifier; public class RouterComponentCodeBuilder { public static JavaFile getJavaFile(String centerName, List<ComponentModel> componentModels) { TypeSpec.Builder componentHelper = TypeSpec.classBuilder(centerName) .addModifiers(Modifier.PUBLIC); ClassName ComponentUtils = ClassName.bestGuess("com.grouter.ComponentUtils"); for (ComponentModel component : componentModels) { ClassName protocol = ClassName.bestGuess(component.protocol); ClassName implement = ClassName.bestGuess(component.implement); for (ComponentModel.ConstructorBean constructor : component.constructors) { MethodSpec.Builder methodSpec = MethodSpec.methodBuilder(implement.simpleName()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(protocol); if (constructor.parameterTypes.size() > 0) { methodSpec.addStatement("Class[] classes = new Class[$L]", constructor.parameterTypes.size()); methodSpec.addStatement("Object[] objects = new Object[$L]", constructor.parameterTypes.size()); for (int i = 0; i < constructor.parameterTypes.size(); i++) { String clazz = constructor.parameterTypes.get(i); String name = constructor.parameterNames.get(i); TypeName typeName = TypeUtils.getTypeNameFull(clazz); methodSpec.addParameter(typeName, name); if (typeName instanceof ParameterizedTypeName) { methodSpec.addStatement("classes[$L] = $T.class", i, ((ParameterizedTypeName) typeName).rawType); } else { methodSpec.addStatement("classes[$L] = $T.class", i, typeName); } methodSpec.addStatement("objects[$L] = $N", i, name); } methodSpec.addStatement("return $T.getInstance($T.class,$S,classes,objects)", ComponentUtils, protocol, TypeUtils.reflectionName(implement)); } else { methodSpec.addStatement("return $T.getInstance($T.class,$S)", ComponentUtils, protocol, TypeUtils.reflectionName(implement)); } componentHelper.addMethod(methodSpec.build()); } } // AnnotationSpec annotationSpec = AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "\"unused\"").build(); // componentHelper.addAnnotation(annotationSpec); return JavaFile.builder("com.grouter", componentHelper.build()).build(); } }
1,360
530
import pytest from tartiflette.language.ast import ObjectTypeExtensionNode def test_objecttypeextensionnode__init__(): object_type_extension_node = ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ) assert object_type_extension_node.name == "objectTypeExtensionName" assert ( object_type_extension_node.interfaces == "objectTypeExtensionInterfaces" ) assert ( object_type_extension_node.directives == "objectTypeExtensionDirectives" ) assert object_type_extension_node.fields == "objectTypeExtensionFields" assert object_type_extension_node.location == "objectTypeExtensionLocation" @pytest.mark.parametrize( "object_type_extension_node,other,expected", [ ( ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), Ellipsis, False, ), ( ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), ObjectTypeExtensionNode( name="objectTypeExtensionNameBis", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), False, ), ( ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfacesBis", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), False, ), ( ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectivesBis", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), False, ), ( ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFieldsBis", location="objectTypeExtensionLocation", ), False, ), ( ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocationBis", ), False, ), ( ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), True, ), ], ) def test_objecttypeextensionnode__eq__( object_type_extension_node, other, expected ): assert (object_type_extension_node == other) is expected @pytest.mark.parametrize( "object_type_extension_node,expected", [ ( ObjectTypeExtensionNode( name="objectTypeExtensionName", interfaces="objectTypeExtensionInterfaces", directives="objectTypeExtensionDirectives", fields="objectTypeExtensionFields", location="objectTypeExtensionLocation", ), "ObjectTypeExtensionNode(" "name='objectTypeExtensionName', " "interfaces='objectTypeExtensionInterfaces', " "directives='objectTypeExtensionDirectives', " "fields='objectTypeExtensionFields', " "location='objectTypeExtensionLocation')", ) ], ) def test_objecttypeextensionnode__repr__(object_type_extension_node, expected): assert object_type_extension_node.__repr__() == expected
3,043
587
<gh_stars>100-1000 /* * Copyright 2012-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lightadmin.core.persistence.repository.invoker; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.rest.core.invoke.RepositoryInvoker; import java.util.List; public interface DynamicRepositoryInvoker extends RepositoryInvoker { Page findAll(Specification spec, Pageable pageable); List findAll(Specification spec, Sort sort); List findAll(Specification spec); long count(Specification spec); }
342
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 "chrome/browser/devtools/chrome_devtools_manager_delegate.h" #include <utility> #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/devtools/chrome_devtools_session.h" #include "chrome/browser/devtools/device/android_device_manager.h" #include "chrome/browser/devtools/device/tcp_device_provider.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/devtools/protocol/target_handler.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_navigator_params.h" #include "chrome/browser/ui/tab_contents/tab_contents_iterator.h" #include "chrome/grit/browser_resources.h" #include "components/guest_view/browser/guest_view_base.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/process_manager.h" #include "ui/base/resource/resource_bundle.h" using content::DevToolsAgentHost; const char ChromeDevToolsManagerDelegate::kTypeApp[] = "app"; const char ChromeDevToolsManagerDelegate::kTypeBackgroundPage[] = "background_page"; namespace { bool GetExtensionInfo(content::WebContents* wc, std::string* name, std::string* type) { Profile* profile = Profile::FromBrowserContext(wc->GetBrowserContext()); if (!profile) return false; const extensions::Extension* extension = extensions::ProcessManager::Get(profile)->GetExtensionForWebContents(wc); if (!extension) return false; extensions::ExtensionHost* extension_host = extensions::ProcessManager::Get(profile)->GetBackgroundHostForExtension( extension->id()); if (extension_host && extension_host->host_contents() == wc) { *name = extension->name(); *type = ChromeDevToolsManagerDelegate::kTypeBackgroundPage; return true; } if (extension->is_hosted_app() || extension->is_legacy_packaged_app() || extension->is_platform_app()) { *name = extension->name(); *type = ChromeDevToolsManagerDelegate::kTypeApp; return true; } return false; } ChromeDevToolsManagerDelegate* g_instance; } // namespace // static ChromeDevToolsManagerDelegate* ChromeDevToolsManagerDelegate::GetInstance() { return g_instance; } ChromeDevToolsManagerDelegate::ChromeDevToolsManagerDelegate() { DCHECK(!g_instance); g_instance = this; } ChromeDevToolsManagerDelegate::~ChromeDevToolsManagerDelegate() { DCHECK(g_instance == this); g_instance = nullptr; } void ChromeDevToolsManagerDelegate::Inspect( content::DevToolsAgentHost* agent_host) { DevToolsWindow::OpenDevToolsWindow(agent_host, nullptr); } bool ChromeDevToolsManagerDelegate::HandleCommand( DevToolsAgentHost* agent_host, content::DevToolsAgentHostClient* client, base::DictionaryValue* command_dict) { DCHECK(sessions_.find(client) != sessions_.end()); auto response = sessions_[client]->dispatcher()->dispatch( protocol::toProtocolValue(command_dict, 1000)); return response != protocol::DispatchResponse::Status::kFallThrough; } std::string ChromeDevToolsManagerDelegate::GetTargetType( content::WebContents* web_contents) { auto& all_tabs = AllTabContentses(); auto it = std::find(all_tabs.begin(), all_tabs.end(), web_contents); if (it != all_tabs.end()) return DevToolsAgentHost::kTypePage; std::string extension_name; std::string extension_type; if (!GetExtensionInfo(web_contents, &extension_name, &extension_type)) return DevToolsAgentHost::kTypeOther; return extension_type; } std::string ChromeDevToolsManagerDelegate::GetTargetTitle( content::WebContents* web_contents) { std::string extension_name; std::string extension_type; if (!GetExtensionInfo(web_contents, &extension_name, &extension_type)) return std::string(); return extension_name; } void ChromeDevToolsManagerDelegate::ClientAttached( content::DevToolsAgentHost* agent_host, content::DevToolsAgentHostClient* client) { DCHECK(sessions_.find(client) == sessions_.end()); sessions_[client] = std::make_unique<ChromeDevToolsSession>(agent_host, client); } void ChromeDevToolsManagerDelegate::ClientDetached( content::DevToolsAgentHost* agent_host, content::DevToolsAgentHostClient* client) { sessions_.erase(client); } scoped_refptr<DevToolsAgentHost> ChromeDevToolsManagerDelegate::CreateNewTarget(const GURL& url) { NavigateParams params(ProfileManager::GetLastUsedProfile(), url, ui::PAGE_TRANSITION_AUTO_TOPLEVEL); params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; Navigate(&params); if (!params.navigated_or_inserted_contents) return nullptr; return DevToolsAgentHost::GetOrCreateFor( params.navigated_or_inserted_contents); } std::string ChromeDevToolsManagerDelegate::GetDiscoveryPageHTML() { return ui::ResourceBundle::GetSharedInstance() .GetRawDataResource(IDR_DEVTOOLS_DISCOVERY_PAGE_HTML) .as_string(); } bool ChromeDevToolsManagerDelegate::HasBundledFrontendResources() { return true; } void ChromeDevToolsManagerDelegate::DevicesAvailable( const DevToolsDeviceDiscovery::CompleteDevices& devices) { DevToolsAgentHost::List remote_targets; for (const auto& complete : devices) { for (const auto& browser : complete.second->browsers()) { for (const auto& page : browser->pages()) remote_targets.push_back(page->CreateTarget()); } } remote_agent_hosts_.swap(remote_targets); } void ChromeDevToolsManagerDelegate::UpdateDeviceDiscovery() { RemoteLocations remote_locations; for (const auto& it : sessions_) { TargetHandler* target_handler = it.second->target_handler(); if (!target_handler) continue; RemoteLocations& locations = target_handler->remote_locations(); remote_locations.insert(locations.begin(), locations.end()); } bool equals = remote_locations.size() == remote_locations_.size(); if (equals) { RemoteLocations::iterator it1 = remote_locations.begin(); RemoteLocations::iterator it2 = remote_locations_.begin(); while (it1 != remote_locations.end()) { DCHECK(it2 != remote_locations_.end()); if (!(*it1).Equals(*it2)) equals = false; ++it1; ++it2; } DCHECK(it2 == remote_locations_.end()); } if (equals) return; if (remote_locations.empty()) { device_discovery_.reset(); remote_agent_hosts_.clear(); } else { if (!device_manager_) device_manager_ = AndroidDeviceManager::Create(); AndroidDeviceManager::DeviceProviders providers; providers.push_back(new TCPDeviceProvider(remote_locations)); device_manager_->SetDeviceProviders(providers); device_discovery_.reset(new DevToolsDeviceDiscovery(device_manager_.get(), base::Bind(&ChromeDevToolsManagerDelegate::DevicesAvailable, base::Unretained(this)))); } remote_locations_.swap(remote_locations); }
2,562
809
<filename>lenskit-core/src/test/java/org/lenskit/data/entities/EntityDefaultsTest.java /* * LensKit, an open-source toolkit for recommender systems. * Copyright 2014-2017 LensKit contributors (see CONTRIBUTORS.md) * Copyright 2010-2014 Regents of the University of Minnesota * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.lenskit.data.entities; import org.junit.Test; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class EntityDefaultsTest { @Test public void testMissingDefaults() { EntityDefaults defaults = EntityDefaults.lookup(EntityType.forName("wombat")); // we don't know anything about wombats assertThat(defaults, nullValue()); } @Test public void testRatingDefaults() { EntityDefaults defaults = EntityDefaults.lookup(EntityType.forName("rating")); assertThat(defaults, notNullValue()); assertThat(defaults.getEntityType(), equalTo(EntityType.forName("rating"))); assertThat(defaults.getCommonAttributes(), containsInAnyOrder((TypedName) CommonAttributes.USER_ID, CommonAttributes.ITEM_ID, CommonAttributes.RATING, CommonAttributes.TIMESTAMP)); assertThat(defaults.getDefaultColumns(), contains((TypedName) CommonAttributes.USER_ID, CommonAttributes.ITEM_ID, CommonAttributes.RATING, CommonAttributes.TIMESTAMP)); // FIXME Re-enable this assert when rating builders work // assertThat(defaults.getDefaultBuilder(), // equalTo((Class) RatingBuilder.class)); } }
1,020
743
<reponame>davidpete9/guacamole-client<filename>extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-postgresql/src/main/java/org/apache/guacamole/auth/postgresql/conf/PostgreSQLSSLMode.java<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.guacamole.auth.postgresql.conf; import org.apache.guacamole.properties.EnumGuacamoleProperty.PropertyValue; /** * Possible values for PostgreSQL SSL connectivity. */ public enum PostgreSQLSSLMode { /** * Do not use SSL to connect to server. */ @PropertyValue("disable") DISABLE("disable"), /** * Allow SSL connections, but try non-SSL, first. */ @PropertyValue("allow") ALLOW("allow"), /** * Prefer SSL connections, falling back to non-SSL if that fails. */ @PropertyValue("prefer") PREFER("prefer"), /** * Require SSL connections, do not connect if SSL fails. */ @PropertyValue("require") REQUIRE("require"), /** * Require SSL connections and validate the CA certificate. */ @PropertyValue("verify-ca") VERIFY_CA("verify-ca"), /** * Require SSL connections and validate both the CA and server certificates. */ @PropertyValue("verify-full") VERIFY_FULL("verify-full"); /** * The value expected by and passed on to the JDBC driver for the given * SSL operation mode. */ private final String driverValue; /** * Create a new instance of this enum with the given driverValue as the * value that will be used when configuring the JDBC driver. * * @param driverValue * The value to use when configuring the JDBC driver. */ PostgreSQLSSLMode(String driverValue) { this.driverValue = driverValue; } /** * Returns the String value for a given Enum that properly configures the * JDBC driver for the desired mode of SSL operation. * * @return * The String value for the current Enum that configures the JDBC driver * for the desired mode of SSL operation. */ public String getDriverValue() { return driverValue; } }
1,024
1,338
<reponame>Kirishikesan/haiku #ifndef _HAIKU_BUILD_COMPATIBILITY_FREEBSD_SYS_STAT #define _HAIKU_BUILD_COMPATIBILITY_FREEBSD_SYS_STAT #include_next <sys/stat.h> #include <sys/cdefs.h> #ifndef UTIME_NOW # define UTIME_NOW (-1) # define UTIME_OMIT (-2) __BEGIN_DECLS /* assume that futimens() and utimensat() aren't available */ int futimens(int fd, const struct timespec times[2]); int utimensat(int fd, const char* path, const struct timespec times[2], int flag); __END_DECLS # ifndef _HAIKU_BUILD_NO_FUTIMENS # define _HAIKU_BUILD_NO_FUTIMENS 1 # endif # ifndef _HAIKU_BUILD_NO_UTIMENSAT # define _HAIKU_BUILD_NO_UTIMENSAT 1 # endif #endif #endif /* _HAIKU_BUILD_COMPATIBILITY_FREEBSD_SYS_STAT */
327
4,036
<gh_stars>1000+ char *getenv(const char *name); void sink(const char *sinkparam); // $ ast,ir=global1 ast,ir=global2 void throughLocal() { char * local = getenv("VAR"); sink(local); } char * global1 = 0; void readWriteGlobal1() { sink(global1); // $ ast,ir=global1 global1 = getenv("VAR"); } static char * global2 = 0; void readGlobal2() { sink(global2); // $ ast,ir=global2 } void writeGlobal2() { global2 = getenv("VAR"); }
185
4,233
{ "name": "babel-preset-carbon", "private": true, "version": "0.1.0", "license": "Apache-2.0", "main": "index.js", "repository": { "type": "git", "url": "https://github.com/carbon-design-system/carbon.git", "directory": "config/babel-preset-carbon" }, "bugs": "https://github.com/carbon-design-system/carbon/issues", "keywords": [ "ibm", "carbon", "carbon-design-system", "components", "react" ], "dependencies": { "@babel/core": "^7.14.6", "@babel/plugin-proposal-class-properties": "^7.14.5", "@babel/plugin-proposal-export-default-from": "^7.14.5", "@babel/plugin-proposal-export-namespace-from": "^7.14.5", "@babel/plugin-transform-react-constant-elements": "^7.14.5", "@babel/preset-env": "^7.14.7", "@babel/preset-react": "^7.14.5", "babel-plugin-dev-expression": "^0.2.2", "browserslist-config-carbon": "^10.6.1" } }
418
380
<gh_stars>100-1000 /** * Author: <NAME> * Date: 21 July 2021 (Wednesday) */ import java.util.*; public class ImmediateSmallerThanX{ public static void main(String args[]){ Solution s = new Solution(); int arr[] = {4,67,13,12,15}; System.out.println(s.immediateSmaller(arr,arr.length,16)); } } class Solution { // Complete the function public static int immediateSmaller(int arr[], int n, int x) { int min = -1; for(int i=0;i<n;i++){ if(arr[i]<x){ min = Math.max(arr[i],min); } } return min == -1 ? -1 : min; } }
297
12,718
/* This file is automatically generated. It defines macros to allow user program to find the shared library files which come as part of GNU libc. */ #ifndef __GNU_LIB_NAMES_H #define __GNU_LIB_NAMES_H 1 #include <bits/wordsize.h> #if __WORDSIZE == 32 && defined __riscv_float_abi_soft # include <gnu/lib-names-ilp32.h> #endif #if __WORDSIZE == 32 && defined __riscv_float_abi_double # include <gnu/lib-names-ilp32d.h> #endif #if __WORDSIZE == 64 && defined __riscv_float_abi_soft # include <gnu/lib-names-lp64.h> #endif #if __WORDSIZE == 64 && defined __riscv_float_abi_double # include <gnu/lib-names-lp64d.h> #endif #endif /* gnu/lib-names.h */
255
325
<filename>google_play_scraper/exceptions.py class GooglePlayScraperException(Exception): pass class NotFoundError(GooglePlayScraperException): pass class ExtraHTTPError(GooglePlayScraperException): pass
66
897
<filename>C/math/reverse_number.c<gh_stars>100-1000 // C program to reverse a number. #include <stdio.h> // Function to reverse a number. int reverse(int num) { int rev = 0; while (num > 0) { rev = rev * 10; //Extract the last digit of the number. int rem = num % 10; rev = rev + rem; num = num / 10; } return rev; } int main() { int num; printf("Enter the number: "); scanf("%d", &num); int rev = reverse(num); printf("The reverse of the given number is %d.", rev); return 0; } /* Time Complexity: O(log(n)), where 'n' is the given number Space Complexity: O(1) SAMPLE INPUT AND OUTPUT SAMPLE 1 Enter the number: 1234 The reverse of the given number is 4321. SAMPLE 2 Enter the number: 785487 The reverse of the given number is 784587. */
337
2,205
<reponame>kiaplayer/mcrouter /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "mcrouter/routes/McRouteHandleProvider.h" #include <mcrouter/routes/FailoverRoute.h> namespace facebook { namespace memcache { namespace mcrouter { template MemcacheRouterInfo::RouteHandlePtr makeFailoverRouteWithFailoverErrorSettings< MemcacheRouterInfo, FailoverRoute, FailoverErrorsSettings>( const folly::dynamic& json, std::vector<MemcacheRouterInfo::RouteHandlePtr> children, FailoverErrorsSettings failoverErrors, const folly::dynamic* jFailoverPolicy); } // namespace mcrouter } // namespace memcache } // namespace facebook
250
500
package com.zulip.android.widget; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.text.TextUtils; import android.widget.RemoteViews; import com.zulip.android.R; import com.zulip.android.networking.AsyncGetEvents; import static com.zulip.android.widget.WidgetPreferenceFragment.FROM_PREFERENCE; import static com.zulip.android.widget.WidgetPreferenceFragment.INTERVAL_PREFERENCE; import static com.zulip.android.widget.WidgetPreferenceFragment.TITLE_PREFRENCE; public class ZulipWidget extends AppWidgetProvider { public static String WIDGET_REFRESH = "com.zulip.android.zulipwidget.REFRESH"; private static AsyncGetEvents asyncGetEvents; private static int intervalMilliseconds = 0; static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { String title = ZulipWidgetConfigureActivity.loadPref(context, appWidgetId, TITLE_PREFRENCE); if (title != null) { String from = ZulipWidgetConfigureActivity.loadPref(context, appWidgetId, FROM_PREFERENCE); String interval = ZulipWidgetConfigureActivity.loadPref(context, appWidgetId, INTERVAL_PREFERENCE); intervalMilliseconds = 60000 * Integer.parseInt(TextUtils.substring(interval, 0, interval.length() - 1)); // Construct the RemoteViews object RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.zulip_widget); final Intent intent = new Intent(context, ZulipWidgetService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(TITLE_PREFRENCE, title); intent.putExtra(FROM_PREFERENCE, from); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); remoteViews.setTextViewText(R.id.widget_title, title); remoteViews.setRemoteAdapter(appWidgetId, R.id.widget_list, intent); remoteViews.setEmptyView(R.id.widget_list, R.id.widget_nomsg); if (asyncGetEvents == null) { setupGetEvents(); } final Intent refreshIntent = new Intent(context, ZulipWidget.class); refreshIntent.setAction(ZulipWidget.WIDGET_REFRESH); final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.widget_refresh, refreshPendingIntent); appWidgetManager.updateAppWidget(appWidgetId, remoteViews); } } private static void setupGetEvents() { asyncGetEvents = new AsyncGetEvents(intervalMilliseconds); asyncGetEvents.start(); } @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (asyncGetEvents == null) { setupGetEvents(); } if (action.equals(WIDGET_REFRESH)) { final AppWidgetManager mgr = AppWidgetManager.getInstance(context); final ComponentName cn = new ComponentName(context, ZulipWidget.class); mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.widget_list); asyncGetEvents.interrupt(); } super.onReceive(context, intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { for (int appWidgetId : appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId); } } @Override public void onDeleted(Context context, int[] appWidgetIds) { } @Override public void onEnabled(Context context) { } @Override public void onDisabled(Context context) { asyncGetEvents = null; } }
1,660
335
{ "word": "Ionic", "definitions": [ "The Ionic order of architecture.", "The ancient Greek dialect used in Ionia." ], "parts-of-speech": "Noun" }
77
1,639
<filename>packages/@jsii/java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java package software.amazon.jsii; import software.amazon.jsii.api.Callback; import software.amazon.jsii.api.GetRequest; import software.amazon.jsii.api.InvokeRequest; import software.amazon.jsii.api.JsiiOverride; import software.amazon.jsii.api.SetRequest; import com.fasterxml.jackson.databind.JsonNode; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.*; import java.util.*; import static software.amazon.jsii.Util.isJavaPropertyMethod; import static software.amazon.jsii.Util.javaPropertyToJSProperty; import static software.amazon.jsii.Util.javaScriptPropertyToJavaPropertyName; /** * The javascript engine which supports jsii objects. */ @Internal public final class JsiiEngine implements JsiiCallbackHandler { /** * The singleton instance. */ private static JsiiEngine INSTANCE = null; /** * The suffix for interface proxy classes. */ private static final String INTERFACE_PROXY_CLASS_NAME = "Jsii$Proxy"; /** * A map that associates value instances with the {@link JsiiEngine} that * created them or which first interacted with them. Using a weak hash map * so that {@link JsiiEngine} instances can be garbage collected after all * instances they are assigned to are themselves collected. */ private static Map<Object, JsiiEngine> engineAssociations = new WeakHashMap<>(); /** * Object cache. */ private final Map<String, Object> objects = new HashMap<>(); /** * The jsii-server child process. */ private final JsiiRuntime runtime = new JsiiRuntime(); /** * The set of modules we already loaded into the VM. */ private Map<String, JsiiModule> loadedModules = new HashMap<>(); /** * A map that associates value instances with the {@link JsiiObjectRef} that * represents them across the jsii process boundary. Using a weak hash map * so that {@link JsiiObjectRef} instances can be garbage collected after * all instances they are assigned to are themselves collected. */ private Map<Object, JsiiObjectRef> objectRefs = new WeakHashMap<>(); /** * @return The singleton instance. */ public static JsiiEngine getInstance() { if (INSTANCE == null) { INSTANCE = new JsiiEngine(); } return INSTANCE; } /** * Retrieves the {@link JsiiEngine} associated with the provided instance. If none was assigned yet, the current * value of {@link JsiiEngine#getInstance()} will be assigned then returned. * * @param instance The object instance for which a {@link JsiiEngine} is requested. * * @return a {@link JsiiEngine} instance. */ static JsiiEngine getEngineFor(final Object instance) { return JsiiEngine.getEngineFor(instance, null); } /** * Retrieves the {@link JsiiEngine} associated with the provided instance. If none was assigned yet, the current * value of {@code defaultEngine} will be assigned then returned. If {@code instance} is a {@link JsiiObject} * instance, then the value will be recorded on the instance itself (the responsibility of this process is on the * {@link JsiiObject} constructors). * * @param instance The object instance for which a {@link JsiiEngine} is requested. * @param defaultEngine The engine to use if none was previously assigned. If {@code null}, the value of * {@link #getInstance()} is used instead. * * @return a {@link JsiiEngine} instance. */ static JsiiEngine getEngineFor(final Object instance, @Nullable final JsiiEngine defaultEngine) { Objects.requireNonNull(instance, "instance is required"); if (instance instanceof JsiiObject) { final JsiiObject jsiiObject = (JsiiObject) instance; if (jsiiObject.jsii$engine != null) { return jsiiObject.jsii$engine; } return defaultEngine != null ? defaultEngine : JsiiEngine.getInstance(); } return engineAssociations.computeIfAbsent( instance, (_k) -> defaultEngine != null ? defaultEngine : JsiiEngine.getInstance() ); } /** * Resets the singleton instance of JsiiEngine. This will cause a new process to be spawned (the previous process * will terminate itself). This method is intended to be used by compliance tests to ensure a complete and * reproductible kernel trace is obtained. */ static void reset() throws InterruptedException, IOException { final JsiiEngine toTerminate = INSTANCE; INSTANCE = null; if (toTerminate != null) { toTerminate.runtime.terminate(); } } /** * Silences any error and warning logging from the Engine. Useful when testing. * * @param value whether to silence the logs or not. */ public static void setQuietMode(boolean value) { getInstance().quietMode = value; } private boolean quietMode = true; /** * @return The jsii-server HTTP client. */ public JsiiClient getClient() { return runtime.getClient(); } /** * Initializes the engine. */ private JsiiEngine() { runtime.setCallbackHandler(this); } /** * Loads a JavaScript module into the remote jsii-server. * No-op if the module is already loaded. * @param moduleClass The jsii module class. */ public void loadModule(final Class<? extends JsiiModule> moduleClass) { if (!JsiiModule.class.isAssignableFrom(moduleClass)) { throw new JsiiException("Invalid module class " + moduleClass.getName() + ". It must be derived from JsiiModule"); } JsiiModule module; try { module = moduleClass.getConstructor().newInstance(); } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) { throw new JsiiException(e); } if (this.loadedModules.containsKey(module.getModuleName())) { return; } // Load dependencies for (Class<? extends JsiiModule> dep: module.getDependencies()) { loadModule(dep); } this.getClient().loadModule(module); // indicate that it was loaded this.loadedModules.put(module.getModuleName(), module); } /** * Returns the native java object for a given jsii object reference. * If it already exists in our native objects cache, we return it. * * If we can't find the object in the cache, it means it was created in javascript-land, so we need * to create a native wrapper with the correct type and add it to cache. * * @param objRef The object reference. * @return The jsii object the represents this remote object. */ public Object nativeFromObjRef(final JsiiObjectRef objRef) { Object obj = this.objects.get(objRef.getObjId()); if (obj == null) { obj = createNativeProxy(objRef.getFqn(), objRef); this.registerObject(objRef, obj); } return obj; } /** * Assigns a {@link JsiiObjectRef} to a given instance. * * @param objRef The object reference to be assigned. * @param instance The instance to which the JsiiObjectRef is to be linked. * * @throws IllegalStateException if another {@link JsiiObjectRef} was * previously assigned to {@code instance}. */ final void registerObject(final JsiiObjectRef objRef, final Object instance) { Objects.requireNonNull(instance, "instance is required"); Objects.requireNonNull(objRef, "objRef is required"); final JsiiObjectRef assigned; if (instance instanceof JsiiObject) { final JsiiObject jsiiObject = (JsiiObject) instance; if (jsiiObject.jsii$objRef == null) { jsiiObject.jsii$objRef = objRef; } assigned = jsiiObject.jsii$objRef; } else { assigned = this.objectRefs.computeIfAbsent( instance, (key) -> objRef ); } if (!assigned.equals(objRef)) { throw new IllegalStateException("Another object reference was previously assigned to this instance!"); } this.objects.put(assigned.getObjId(), instance); } /** * Returns the jsii object reference given a native object. If the object * does not have one yet, a new object reference is requested from the jsii * kernel, and gets assigned to the instance before being returned. * * @param nativeObject The native object to obtain the reference for * * @return A jsii object reference */ public JsiiObjectRef nativeToObjRef(final Object nativeObject) { if (nativeObject instanceof JsiiObject) { final JsiiObject jsiiObject = (JsiiObject) nativeObject; if (jsiiObject.jsii$objRef == null) { jsiiObject.jsii$objRef = this.createNewObject(jsiiObject); } return jsiiObject.jsii$objRef; } return this.objectRefs.computeIfAbsent( nativeObject, (_k) -> this.createNewObject(nativeObject) ); } /** * Gets an object by reference. Throws if the object cannot be found. * * @param objRef The object reference * @return a JsiiObject * @throws JsiiException If the object is not found. */ public Object getObject(final JsiiObjectRef objRef) { Object obj = this.objects.get(objRef.getObjId()); if (obj == null) { throw new JsiiException("Cannot find jsii object: " + objRef.getObjId()); } return obj; } /** * Given an obj ref, returns a Java object that represents it. * A new object proxy object will be allocated if needed. * @param objRefNode The objref * @return A Java object */ public Object getObject(final JsonNode objRefNode) { return this.getObject(JsiiObjectRef.parse(objRefNode)); } /** * Given a jsii FQN, returns the Java class for it. * * @param fqn The FQN. * * @return The Java class name. */ Class<?> resolveJavaClass(final String fqn) { if ("Object".equals(fqn)) { return JsiiObject.class; } String[] parts = fqn.split("\\."); if (parts.length < 2) { throw new JsiiException("Malformed FQN: " + fqn); } String moduleName = parts[0]; JsonNode names = this.getClient().getModuleNames(moduleName); if (!names.has("java")) { throw new JsiiException("No java name for module " + moduleName); } final JsiiModule module = this.loadedModules.get(moduleName); if (module == null) { throw new JsiiException("No loaded module is named " + moduleName); } try { return module.resolveClass(fqn); } catch (final ClassNotFoundException cfne) { throw new JsiiException(cfne); } } /** * Given a jsii FQN, instantiates a Java JsiiObject. * * NOTE: if a the Java class cannot be found, we will simply return a {@link JsiiObject}. * * @param fqn The jsii FQN of the type * @return An object derived from JsiiObject. */ private JsiiObject createNativeProxy(final String fqn, final JsiiObjectRef objRef) { try { Class<?> klass = resolveJavaClass(fqn); if (klass.isInterface() || Modifier.isAbstract(klass.getModifiers())) { // "$" is used to represent inner classes in Java klass = Class.forName(klass.getCanonicalName() + "$" + INTERFACE_PROXY_CLASS_NAME); } try { Constructor<? extends Object> ctor = klass.getDeclaredConstructor(JsiiObjectRef.class); ctor.setAccessible(true); JsiiObject newObj = (JsiiObject) ctor.newInstance(objRef); ctor.setAccessible(false); return newObj; } catch (NoSuchMethodException e) { throw new JsiiException("Cannot create native object of type " + klass.getName() + " without a constructor that accepts an InitializationMode argument", e); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new JsiiException("Unable to instantiate a new object for FQN " + fqn + ": " + e.getMessage(), e); } } catch (ClassNotFoundException e) { this.log("WARNING: Cannot find the class: %s. Defaulting to JsiiObject", fqn); return new JsiiObject(objRef); } } /** * Given a jsii enum ref in the form "fqn/member" returns the Java enum value for it. * @param enumRef The jsii enum ref. * @return The java enum value. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Enum<?> findEnumValue(final String enumRef) { int sep = enumRef.lastIndexOf('/'); if (sep == -1) { throw new JsiiException("Malformed enum reference: " + enumRef); } String typeName = enumRef.substring(0, sep); String valueName = enumRef.substring(sep + 1); Class klass = resolveJavaClass(typeName); return Enum.valueOf(klass, valueName); } /** * Dequeues and processes pending jsii callbacks until there are no more callbacks to process. */ public void processAllPendingCallbacks() { while (true) { List<Callback> callbacks = this.getClient().pendingCallbacks(); if (callbacks.size() == 0) { break; } callbacks.forEach(this::processCallback); } } /** * Invokes a local callback and returns the result/error. * @param callback The callback to invoke. * @return The return value * @throws JsiiException if the callback failed. */ public JsonNode handleCallback(final Callback callback) { if (callback.getInvoke() != null) { return invokeCallbackMethod(callback.getInvoke(), callback.getCookie()); } else if (callback.getGet() != null) { return invokeCallbackGet(callback.getGet()); } else if (callback.getSet() != null) { return invokeCallbackSet(callback.getSet()); } throw new JsiiException("Unrecognized callback type: get/set/invoke"); } /** * Invokes an override for a property getter. * @param req The get request * @return The override's return value. */ private JsonNode invokeCallbackGet(final GetRequest req) { Object obj = this.getObject(req.getObjref()); String methodName = javaScriptPropertyToJavaPropertyName("get", req.getProperty()); Method getter = this.findCallbackGetter(obj.getClass(), methodName); return JsiiObjectMapper.valueToTree(invokeMethod(obj, getter)); } /** * Invokes an override for a property setter. * @param req The set request * @return The setter return value (an empty object) */ private JsonNode invokeCallbackSet(final SetRequest req) { final Object obj = this.getObject(req.getObjref()); final String getterMethodName = javaScriptPropertyToJavaPropertyName("get", req.getProperty()); final Method getter = this.findCallbackGetter(obj.getClass(), getterMethodName); // Turns "get" into "set"! final String setterMethodName = getterMethodName.replaceFirst("g", "s"); final Method setter = this.findCallbackSetter(obj.getClass(), setterMethodName, getter.getReturnType()); final Object arg = JsiiObjectMapper.treeToValue(req.getValue(), NativeType.forType(setter.getGenericParameterTypes()[0])); return JsiiObjectMapper.valueToTree(invokeMethod(obj, setter, arg)); } /** * Invokes an override for a method. * @param req The request * @param cookie The cookie * @return The method's return value */ private JsonNode invokeCallbackMethod(final InvokeRequest req, final String cookie) { Object obj = this.getObject(req.getObjref()); Method method = this.findCallbackMethod(obj.getClass(), cookie); final Type[] argTypes = method.getGenericParameterTypes(); final Object[] args = new Object[argTypes.length]; for (int i = 0; i < argTypes.length; i++) { args[i] = JsiiObjectMapper.treeToValue(req.getArgs().get(i), NativeType.forType(argTypes[i])); } return JsiiObjectMapper.valueToTree(invokeMethod(obj, method, args)); } /** * Invokes a Java method, even if the method is protected. * @param obj The object * @param method The method * @param args Method arguments * @return The return value */ private Object invokeMethod(final Object obj, final Method method, final Object... args) { // turn method to accessible. otherwise, we won't be able to callback to methods // on non-public classes. boolean accessibility = method.isAccessible(); method.setAccessible(true); try { try { return method.invoke(obj, args); } catch (Exception e) { final StringWriter sw = new StringWriter(); try (final PrintWriter pw = new PrintWriter(sw)) { e.printStackTrace(pw); } this.log("Error while invoking %s with %s: %s", method, Arrays.toString(args), sw.toString()); throw e; } } catch (InvocationTargetException e) { throw new JsiiException(e.getTargetException()); } catch (IllegalAccessException e) { throw new JsiiException(e); } finally { // revert accessibility. method.setAccessible(accessibility); } } /** * Process a single callback by invoking the native method it refers to. * @param callback The callback to process. */ private void processCallback(final Callback callback) { try { JsonNode result = handleCallback(callback); this.getClient().completeCallback(callback, null, result); } catch (JsiiException e) { this.getClient().completeCallback(callback, e.getMessage(), null); } } /** * Finds the Java method that implements a callback. * @param klass The java class. * @param signature Method signature * @return a {@link Method}. */ private Method findCallbackMethod(final Class<?> klass, final String signature) { for (Method method : klass.getDeclaredMethods()) { if (method.toString().equals(signature)) { // found! return method; } } if (klass.getSuperclass() != null) { // Try to check parent class at this point return findCallbackMethod(klass.getSuperclass(), signature); } throw new JsiiException("Unable to find callback method with signature: " + signature); } /** * Tries to locate the getter method for a property * @param klass is the type on which the getter is to be searched for * @param methodName is the name of the getter method * @return the found Method * @throws JsiiException if no such method is found */ private Method findCallbackGetter(final Class<?> klass, final String methodName) { try { return klass.getDeclaredMethod(methodName); } catch (final NoSuchMethodException nsme) { if (klass.getSuperclass() != null) { try { return findCallbackGetter(klass.getSuperclass(), methodName); } catch (final JsiiException _ignored) { // Ignored! } } throw new JsiiException(nsme); } } /** * Tries to locate the setter method for a property * @param klass is the type on which the setter is to be searched for * @param methodName is the name of the setter method * @param valueType is the type of the argument the setter accepts * @return the found Method * @throws JsiiException if no such method is found */ private Method findCallbackSetter(final Class<?> klass, final String methodName, final Class<?> valueType) { try { return klass.getDeclaredMethod(methodName, valueType); } catch (final NoSuchMethodException nsme) { if (klass.getSuperclass() != null) { try { return findCallbackSetter(klass.getSuperclass(), methodName, valueType); } catch (final JsiiException _ignored) { // Ignored! } } throw new JsiiException(nsme); } } /** * Given an uninitialized native object instance, reads the @Jsii annotations to determine * the jsii module and FQN, and creates a JS object. * * Any methods implemented on the native object are passed in as "overrides", which are overridden * in the javascript side to call-back to the native method. * * @param uninitializedNativeObject An uninitialized native object * @param args Initializer arguments * @return An object reference for the new object. */ public JsiiObjectRef createNewObject(final Object uninitializedNativeObject, final Object... args) { Class<? extends Object> klass = uninitializedNativeObject.getClass(); Jsii jsii = tryGetJsiiAnnotation(klass, true); String fqn = "Object"; // if we can't determine FQN, we just create an empty JS object if (jsii != null) { fqn = jsii.fqn(); loadModule(jsii.module()); } Collection<JsiiOverride> overrides = discoverOverrides(klass); Collection<String> interfaces = discoverInterfaces(klass); JsiiObjectRef objRef = this.getClient().createObject(fqn, Arrays.asList(args), overrides, interfaces); registerObject(objRef, uninitializedNativeObject); return objRef; } /** * Prepare a list of methods which are overridden by Java classes. * @param classToInspect The java class to inspect for * @return A list of method names that should be overridden. */ private static Collection<JsiiOverride> discoverOverrides(final Class<?> classToInspect) { Map<String, JsiiOverride> overrides = new HashMap<>(); Class<?> klass = classToInspect; // if we reached a generated jsii class or Object, we should stop collecting those overrides since // all the rest of the hierarchy is generated all the way up to JsiiObject and java.lang.Object. while (klass != null && klass.getDeclaredAnnotationsByType(Jsii.class).length == 0 && klass != Object.class && klass != JsiiObject.class) { // add all the methods in the current class for (Method method : klass.getDeclaredMethods()) { if (Modifier.isPrivate(method.getModifiers())) { continue; } String methodName = method.getName(); // check if this is a property ("getXXX" or "setXXX", oh java!) if (isJavaPropertyMethod(method)) { String propertyName = javaPropertyToJSProperty(method); // skip if this property is already in the overrides list if (overrides.containsKey(propertyName)) { continue; } JsiiOverride override = new JsiiOverride(); override.setProperty(propertyName); overrides.put(propertyName, override); } else { // if this method is already overridden, skip it if (overrides.containsKey(methodName)) { continue; } // we use the method's .toString() as a cookie, which will later be used to identify the // method when it is called back. JsiiOverride override = new JsiiOverride(); override.setMethod(methodName); override.setCookie(method.toString()); overrides.put(methodName, override); } } klass = klass.getSuperclass(); } return overrides.values(); } /** * Crawls up the inheritance tree of {@code classToInspect} in order to determine the jsii-visible * interfaces that are implemented. * * @param classToInspect the class for which interfaces are needed * * @return the list of jsii FQNs of interfaces implemented by {@code classToInspect} */ private Collection<String> discoverInterfaces(final Class<?> classToInspect) { // If {@classToInspect} has the @Jsii annotation, it's a jsii well-known type final Jsii declaredAnnotation = classToInspect.getDeclaredAnnotation(Jsii.class); if (declaredAnnotation != null) { // If it's an interface, then we can return a singleton set with that! if (classToInspect.isInterface()) { // Ensure the interface's module has been loaded... loadModule(declaredAnnotation.module()); return Collections.singleton(declaredAnnotation.fqn()); } // If it was NOT an interface, then this type already "implies" all interfaces -- nothing to declare. return Collections.emptySet(); } // If this wasn't an @Jsii well-known type, browse up the interface declarations, and collect results final Set<String> interfaces = new HashSet<>(); for (final Class<?> iface : classToInspect.getInterfaces()) { interfaces.addAll(discoverInterfaces(iface)); } return interfaces; } private void log(final String format, final Object... args) { if (!this.quietMode) { System.err.println(String.format(format, args)); } } /** * Attempts to find the @Jsii annotation from a type. * @param type The type. * @param inherited If 'true' will look for the annotation up the class hierarchy. * @return The annotation or null. */ static Jsii tryGetJsiiAnnotation(final Class<?> type, final boolean inherited) { Jsii[] ann; if (inherited) { ann = (Jsii[]) type.getAnnotationsByType(Jsii.class); } else { ann = (Jsii[]) type.getDeclaredAnnotationsByType(Jsii.class); } if (ann.length == 0) { return null; } return ann[0]; } /** * Given a java class that extends a Jsii proxy, loads the corresponding jsii module * and returns the FQN of the jsii type. * @param nativeClass The java class. * @return The FQN. */ String loadModuleForClass(Class<?> nativeClass) { final Jsii jsii = tryGetJsiiAnnotation(nativeClass, true); if (jsii == null) { throw new JsiiException("Unable to find @Jsii annotation for class"); } this.loadModule(jsii.module()); return jsii.fqn(); } }
11,326
435
<reponame>Montana/datawave package datawave.query.index.lookup; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import datawave.accumulo.inmemory.InMemoryInstance; import datawave.data.type.LcNoDiacriticsType; import datawave.data.type.Type; import datawave.ingest.protobuf.Uid; import datawave.query.CloseableIterable; import datawave.query.config.ShardQueryConfiguration; import datawave.query.jexl.JexlASTHelper; import datawave.query.jexl.JexlNodeFactory; import datawave.query.jexl.visitors.JexlStringBuildingVisitor; import datawave.query.jexl.visitors.TreeEqualityVisitor; import datawave.query.planner.QueryPlan; import datawave.query.tables.ScannerFactory; import datawave.query.util.MockMetadataHelper; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.BatchWriterConfig; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.security.tokens.PasswordToken; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.commons.jexl2.parser.ASTJexlScript; import org.apache.hadoop.io.Text; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import static datawave.common.test.utils.query.RangeFactoryForTests.makeDayRange; import static datawave.common.test.utils.query.RangeFactoryForTests.makeShardedRange; import static datawave.common.test.utils.query.RangeFactoryForTests.makeTestRange; import static datawave.util.TableName.SHARD_INDEX; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Cover some basic tests involving streams of shards for a basic set of query structures. Only tests for correctness of shard intersection, not that the * underlying IndexInfo objects correctly intersect. * * 6 Basic Types of Query Structures * * 3 Stream Type Combinations (All shards, shards and days, all days) * * 2 Types of Unequal Stream Start/Stop (different start/end day) * * 2 Types of Uneven Stream Start/Stop (same start/end day, different shard) * * 1 Type of Tick-Tock Shards (alternating shards such that no hits are produced for a day) * * 1 Type of Missing Shards (missing shards should drop terms from query) */ public class RangeStreamTestX { // A && B // A || B // A && ( B || C ) // A || ( B && C ) // (A && B) || (C && D) // (A || B) && (C || D) private static InMemoryInstance instance = new InMemoryInstance(RangeStreamTestX.class.toString()); private static Connector connector; private ShardQueryConfiguration config; @BeforeClass public static void setupAccumulo() throws Exception { // Zero byte password, so secure it hurts. connector = instance.getConnector("", new PasswordToken(new byte[0])); connector.tableOperations().create(SHARD_INDEX); BatchWriter bw = connector.createBatchWriter(SHARD_INDEX, new BatchWriterConfig().setMaxLatency(10, TimeUnit.SECONDS).setMaxMemory(100000L) .setMaxWriteThreads(1)); // Some values Value valueForShard = buildValueForShard(); Value valueForDay = buildValueForDay(); // --------------- Hits on every shard for every day Mutation m = new Mutation("all"); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); } } bw.addMutation(m); // --------------- Hits on every shard for every day, shards will roll to a day range. m = new Mutation("all_day"); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); } } bw.addMutation(m); // --------------- Unequal start, each term misses day 1 m = new Mutation("unequal_start"); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (ii > 1) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); } } } bw.addMutation(m); // --------------- Unequal start, each term misses day 1, each term rolls to a day range m = new Mutation("unequal_start_day"); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (ii > 1) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); } } } bw.addMutation(m); // --------------- Unequal end, each term misses day 5 m = new Mutation("unequal_stop"); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (ii < 5) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); } } } bw.addMutation(m); // --------------- Unequal end, each term misses day 5 m = new Mutation("unequal_stop_day"); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (ii < 5) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); } } } bw.addMutation(m); // --------------- Uneven start, each term will miss the first two shards of each day m = new Mutation("uneven_start"); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (jj > 0) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); } } } bw.addMutation(m); // --------------- Uneven start, each term will miss the first two shards of each day, each term will roll to a day range m = new Mutation("uneven_start_day"); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (jj > 0) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); } } } bw.addMutation(m); // --------------- Uneven end, each term will miss the last two shards of each day m = new Mutation("uneven_stop"); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (jj < 9) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); } } } bw.addMutation(m); // --------------- Uneven end, each term will miss the last two shards of each day, each term will roll to a day range. m = new Mutation("uneven_stop_day"); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (jj < 9) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); } } } bw.addMutation(m); // --------------- Tick-tock shard 3, each term takes a turn m = new Mutation("tick_tock"); int counter = 0; for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (ii == 3) { int mod = counter % 4; switch (mod) { case 0: m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); break; case 1: m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); break; case 2: m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); break; case 3: default: m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); } } else { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); } counter++; } } bw.addMutation(m); // --------------- Tick-tock shard 3, each term takes a turn, shards roll to days except on day 3. m = new Mutation("tick_tock_day"); counter = 0; for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (ii == 3) { int mod = counter % 4; switch (mod) { case 0: m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); break; case 1: m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); break; case 2: m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); break; case 3: default: m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); } counter++; } else { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); } } } bw.addMutation(m); // --------------- Missing shards for day 3 m = new Mutation("missing_shards"); for (int ii = 1; ii <= 5; ii++) { if (ii == 3) { continue; } for (int jj = 0; jj < 10; jj++) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForShard); } } bw.addMutation(m); // --------------- Missing shards for day 3, existing shards roll to day range m = new Mutation("missing_shards_day"); for (int ii = 1; ii <= 5; ii++) { if (ii == 3) { continue; } for (int jj = 0; jj < 10; jj++) { m.put(new Text("A"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("B"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("C"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); m.put(new Text("D"), new Text("2020010" + ii + "_" + jj + "\0datatype1"), valueForDay); } } bw.addMutation(m); // --------------- bw.flush(); bw.close(); } private static Value buildValueForShard() { Uid.List.Builder builder = Uid.List.newBuilder(); builder.addUID("a.b.c"); builder.setIGNORE(false); builder.setCOUNT(1); Uid.List list = builder.build(); return new Value(list.toByteArray()); } // A value that will roll into a day range. private static Value buildValueForDay() { Uid.List.Builder builder = Uid.List.newBuilder(); builder.setIGNORE(true); builder.setCOUNT(5432); Uid.List list = builder.build(); return new Value(list.toByteArray()); } @Before public void setupTest() { config = new ShardQueryConfiguration(); config.setConnector(connector); config.setShardsPerDayThreshold(20); } // A && B @Test public void testIntersection_ofShards() throws Exception { String query = "A == 'all' && B == 'all'"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' && B == 'all'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShards_unequalStart() throws Exception { String query = "A == 'all' && B == 'unequal_start'"; // B term skips day 1 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 2; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' && B == 'unequal_start'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShards_unequalStop() throws Exception { String query = "A == 'all' && B == 'unequal_stop'"; // Day 1 is skipped in the unequal start and Day 5 is skipped in the unequal end List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 4; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' && B == 'unequal_stop'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShards_unevenStart() throws Exception { String query = "A == 'all' && B == 'uneven_start'"; // First shard is skipped for each day in the uneven start case. List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 1; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' && B == 'uneven_start'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShards_unevenStop() throws Exception { String query = "A == 'all' && B == 'uneven_stop'"; // First and last shards are skipped for each day in the uneven start/end case. List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 9; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' && B == 'uneven_stop'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShards_missingShards() throws Exception { String query = "A == 'all' && B == 'missing_shards'"; // Shards are missing for day 3 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii == 3) continue; for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' && B == 'missing_shards'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShards_tickTockShards() throws Exception { String query = "A == 'tick_tock' && B == 'tick_tock'"; // No intersection exists between A & B for tick-tock shards for day 3 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (ii != 3) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("(A == 'tick_tock' && B == 'tick_tock')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShardAndDay() throws Exception { String query = "A == 'all_day' && B == 'all'"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("(B == 'all' && ((_Delayed_ = true) && (A == 'all_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShardAndDay_unequalStart() throws Exception { String query = "A == 'unequal_start' && B == 'all_day'"; // Day 1 is skipped in the unequal start and Day 5 is skipped in the unequal end List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 2; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("(A == 'unequal_start' && ((_Delayed_ = true) && (B == 'all_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShardAndDay_unequalStop() throws Exception { String query = "A == 'unequal_stop' && B == 'all_day'"; // Day 1 is skipped in the unequal start and Day 5 is skipped in the unequal end List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 4; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("(A == 'unequal_stop' && ((_Delayed_ = true) && (B == 'all_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShardAndDay_unevenStart() throws Exception { String query = "A == 'uneven_start' && B == 'all_day'"; // Shard 1 is skipped for every day List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 1; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("(A == 'uneven_start' && ((_Delayed_ = true) && (B == 'all_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShardAndDay_unevenStop() throws Exception { String query = "A == 'uneven_stop' && B == 'all_day'"; // Shard 9 is skipped for every day List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 9; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("(A == 'uneven_stop' && ((_Delayed_ = true) && (B == 'all_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShardAndDay_missingShards() throws Exception { String query = "A == 'all_day' && B == 'missing_shards'"; // Shards are missing for day 3 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii == 3) continue; for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day')) && B == 'missing_shards'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofShardAndDay_tickTockShards() throws Exception { String query = "A == 'tick_tock' && B == 'tick_tock_day'"; // No intersection exists between A & B for tick-tock shards for day 3 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (ii != 3) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("(A == 'tick_tock' && ((_Delayed_ = true) && (B == 'tick_tock_day')))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofDays() throws Exception { String query = "A == 'all_day' && B == 'all_day'"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && ((_Delayed_ = true) && (B == 'all_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofDays_unequalStart() throws Exception { String query = "A == 'all_day' && B == 'unequal_start_day'"; // Day 1 is skipped in the unequal start and Day 5 is skipped in the unequal end List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 2; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && ((_Delayed_ = true) && (B == 'unequal_start_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofDays_unequalStop() throws Exception { String query = "A == 'all_day' && B == 'unequal_stop_day'"; // Day 1 is skipped in the unequal start and Day 5 is skipped in the unequal end List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 4; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && ((_Delayed_ = true) && (B == 'unequal_stop_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofDays_unevenStart() throws Exception { String query = "A == 'all_day' && B == 'uneven_start_day'"; // First and last shards are skipped for each day in the uneven start/end case. List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && ((_Delayed_ = true) && (B == 'uneven_start_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofDays_unevenStop() throws Exception { String query = "A == 'all_day' && B == 'uneven_stop_day'"; // First and last shards are skipped for each day in the uneven start/end case. List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && ((_Delayed_ = true) && (B == 'uneven_stop_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofDays_missingShards() throws Exception { String query = "A == 'all_day' && B == 'missing_shards_day'"; // Shards are missing for day 3 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii == 3) continue; expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && ((_Delayed_ = true) && (B == 'missing_shards_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A && B @Test public void testIntersection_ofDays_tickTockShards() throws Exception { String query = "A == 'tick_tock_day' && B == 'tick_tock_day'"; // No intersection exists between A & B for tick-tock shards for day 3 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii != 3) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'tick_tock_day')) && ((_Delayed_ = true) && (B == 'tick_tock_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShards() throws Exception { String query = "A == 'all' || B == 'all'"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' || B == 'all'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShards_unequalStart() throws Exception { String query = "A == 'all' || B == 'unequal_start'"; // Day 1 is skipped in the unequal start and Day 5 is skipped in the unequal end List<Range> expectedRanges = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); } } List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 0; ii < 10; ii++) expectedQueryStrings.add("A == 'all'"); for (int ii = 0; ii < 40; ii++) expectedQueryStrings.add("A == 'all' || B == 'unequal_start'"); runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShards_unequalStop() throws Exception { String query = "A == 'all' || B == 'unequal_stop'"; // Day 1 is skipped in the unequal start and Day 5 is skipped in the unequal end List<Range> expectedRanges = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); } } List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 0; ii < 40; ii++) expectedQueryStrings.add("A == 'all' || B == 'unequal_stop'"); for (int ii = 0; ii < 10; ii++) expectedQueryStrings.add("A == 'all'"); runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShards_unevenStart() throws Exception { String query = "A == 'all' || B == 'uneven_start'"; // First and last shards are skipped for each day in the uneven start/end case. List<Range> expectedRanges = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); } } List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 0; ii < 50; ii++) { int mod = ii % 10; if (mod == 0) { expectedQueryStrings.add("A == 'all'"); } else { expectedQueryStrings.add("A == 'all' || B == 'uneven_start'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShards_unevenStop() throws Exception { String query = "A == 'all' || B == 'uneven_stop'"; // First and last shards are skipped for each day in the uneven start/end case. List<Range> expectedRanges = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); } } List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 0; ii < 50; ii++) { int mod = ii % 10; if (mod == 9) { expectedQueryStrings.add("A == 'all'"); } else { expectedQueryStrings.add("A == 'all' || B == 'uneven_stop'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShards_missingShards() throws Exception { String query = "A == 'all' || B == 'missing_shards'"; // Shards are missing for day 3 List<Range> expectedRanges = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); } } List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 0; ii < 50; ii++) { if (ii >= 20 && ii < 30) { expectedQueryStrings.add("A == 'all'"); } else { expectedQueryStrings.add("A == 'all' || B == 'missing_shards'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShards_tickTockShards() throws Exception { String query = "A == 'tick_tock' || B == 'tick_tock'"; // Only hit on B's shards List<Range> expectedRanges = new ArrayList<>(); int mod; int counter = 0; for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { if (ii == 3) { mod = counter % 4; if (mod == 0 || mod == 1) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); } } else { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); } counter++; } } List<String> expectedQueryStrings = new ArrayList<>(); counter = 0; for (int ii = 0; ii < 50; ii++) { if (ii >= 20 && ii < 30) { mod = counter % 4; if (mod == 0) { expectedQueryStrings.add("A == 'tick_tock'"); } else if (mod == 1) { expectedQueryStrings.add("B == 'tick_tock'"); } } else { expectedQueryStrings.add("(A == 'tick_tock' || B == 'tick_tock')"); } counter++; } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShardAndDay() throws Exception { String query = "A == 'all' || B == 'all_day'"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(A == 'all' || ((_Delayed_ = true) && (B == 'all_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShardAndDay_unequalStart() throws Exception { String query = "A == 'all' || B == 'unequal_start_day'"; // B term skips day 1 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii == 1) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all'"); } } else { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || ((_Delayed_ = true) && (B == 'unequal_start_day'))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShardAndDay_unequalStop() throws Exception { String query = "A == 'all' || B == 'unequal_stop_day'"; // B term skips day 1 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii == 5) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all'"); } } else { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || ((_Delayed_ = true) && (B == 'unequal_stop_day'))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShardAndDay_unevenStart() throws Exception { String query = "A == 'all' || B == 'uneven_start_day'"; // B term skips day 1 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || ((_Delayed_ = true) && (B == 'uneven_start_day'))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShardAndDay_unevenStop() throws Exception { String query = "A == 'all' || B == 'uneven_stop_day'"; // B term skips day 1 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || ((_Delayed_ = true) && (B == 'uneven_stop_day'))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShardAndDay_missingShards() throws Exception { String query = "A == 'all' || B == 'missing_shards_day'"; // Shards are missing for day 3 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii == 3) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all'"); } } else { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || ((_Delayed_ = true) && (B == 'missing_shards_day'))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofShardAndDay_tickTockShards() throws Exception { String query = "A == 'all' || B == 'tick_tock_day'"; // Shards are missing for day 3 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); expectedRanges.add(makeDayRange("20200101")); expectedRanges.add(makeDayRange("20200102")); expectedRanges.add(makeTestRange("20200103_0", "datatype1\0a.b.c")); expectedRanges.add(makeShardedRange("20200103_1")); expectedRanges.add(makeTestRange("20200103_2", "datatype1\0a.b.c")); expectedRanges.add(makeTestRange("20200103_3", "datatype1\0a.b.c")); expectedRanges.add(makeTestRange("20200103_4", "datatype1\0a.b.c")); expectedRanges.add(makeShardedRange("20200103_5")); expectedRanges.add(makeTestRange("20200103_6", "datatype1\0a.b.c")); expectedRanges.add(makeTestRange("20200103_7", "datatype1\0a.b.c")); expectedRanges.add(makeTestRange("20200103_8", "datatype1\0a.b.c")); expectedRanges.add(makeShardedRange("20200103_9")); expectedRanges.add(makeDayRange("20200104")); expectedRanges.add(makeDayRange("20200105")); expectedQueryStrings.add("A == 'all' || ((_Delayed_ = true) && (B == 'tick_tock_day'))"); expectedQueryStrings.add("A == 'all' || ((_Delayed_ = true) && (B == 'tick_tock_day'))"); expectedQueryStrings.add("A == 'all'"); expectedQueryStrings.add("A == 'all' || B == 'tick_tock_day'"); expectedQueryStrings.add("A == 'all'"); expectedQueryStrings.add("A == 'all'"); expectedQueryStrings.add("A == 'all'"); expectedQueryStrings.add("A == 'all' || B == 'tick_tock_day'"); expectedQueryStrings.add("A == 'all'"); expectedQueryStrings.add("A == 'all'"); expectedQueryStrings.add("A == 'all'"); expectedQueryStrings.add("A == 'all' || B == 'tick_tock_day'"); expectedQueryStrings.add("A == 'all' || ((_Delayed_ = true) && (B == 'tick_tock_day'))"); expectedQueryStrings.add("A == 'all' || ((_Delayed_ = true) && (B == 'tick_tock_day'))"); runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofDays() throws Exception { String query = "A == 'all_day' || B == 'all_day'"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofDays_unequalStart() throws Exception { String query = "A == 'all_day' || B == 'unequal_start_day'"; // Day 1 is skipped in the unequal start and Day 5 is skipped in the unequal end List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 1) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day'))"); } else { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'unequal_start_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofDays_unequalStop() throws Exception { String query = "A == 'all_day' || B == 'unequal_stop_day'"; // Day 1 is skipped in the unequal start and Day 5 is skipped in the unequal end List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 5) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day'))"); } else { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'unequal_stop_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofDays_unevenStart() throws Exception { String query = "A == 'all_day' || B == 'uneven_start_day'"; // First and last shards are skipped for each day in the uneven start/end case. List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'uneven_start_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofDays_unevenStop() throws Exception { String query = "A == 'all_day' || B == 'uneven_stop_day'"; // First and last shards are skipped for each day in the uneven start/end case. List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'uneven_stop_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofDays_missingShards() throws Exception { String query = "A == 'all_day' || B == 'missing_shards_day'"; // Shards are missing for day 3 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 3) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day'))"); } else { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'missing_shards_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || B @Test public void testUnion_ofDays_tickTockShards() throws Exception { String query = "A == 'tick_tock_day' || B == 'tick_tock_day'"; // No intersection exists between A & B for tick-tock shards for day 3 List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii != 3) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'tick_tock_day')) || ((_Delayed_ = true) && (B == 'tick_tock_day')))"); } else { expectedRanges.add(makeShardedRange("20200103_0")); expectedRanges.add(makeShardedRange("20200103_1")); expectedRanges.add(makeShardedRange("20200103_4")); expectedRanges.add(makeShardedRange("20200103_5")); expectedRanges.add(makeShardedRange("20200103_8")); expectedRanges.add(makeShardedRange("20200103_9")); expectedQueryStrings.add("A == 'tick_tock_day'"); expectedQueryStrings.add("B == 'tick_tock_day'"); expectedQueryStrings.add("A == 'tick_tock_day'"); expectedQueryStrings.add("B == 'tick_tock_day'"); expectedQueryStrings.add("A == 'tick_tock_day'"); expectedQueryStrings.add("B == 'tick_tock_day'"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allShards() throws Exception { String query = "A == 'all' && (B == 'all' || C == 'all')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' && (B == 'all' || C == 'all')"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allShards_unequalStart() throws Exception { String query = "A == 'all' && (B == 'all' || C == 'unequal_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 1) { expectedQueryStrings.add("A == 'all' && B == 'all'"); } else { expectedQueryStrings.add("A == 'all' && (B == 'all' || C == 'unequal_start')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allShards_unequalStop() throws Exception { String query = "A == 'all' && (B == 'all' || C == 'unequal_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 5) { expectedQueryStrings.add("A == 'all' && B == 'all'"); } else { expectedQueryStrings.add("A == 'all' && (B == 'all' || C == 'unequal_stop')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allShards_unevenStart() throws Exception { String query = "A == 'all' && (B == 'all' || C == 'uneven_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (jj == 0) { expectedQueryStrings.add("A == 'all' && B == 'all'"); } else { expectedQueryStrings.add("A == 'all' && (B == 'all' || C == 'uneven_start')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allShards_unevenStop() throws Exception { String query = "A == 'all' && (B == 'all' || C == 'uneven_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (jj == 9) { expectedQueryStrings.add("A == 'all' && B == 'all'"); } else { expectedQueryStrings.add("A == 'all' && (B == 'all' || C == 'uneven_stop')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allShards_missingShards() throws Exception { String query = "A == 'all' && (B == 'all' || C == 'missing_shards')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 3) { expectedQueryStrings.add("A == 'all' && B == 'all'"); } else { expectedQueryStrings.add("A == 'all' && (B == 'all' || C == 'missing_shards')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allShards_tickTockShards() throws Exception { String query = "A == 'all' && (B == 'all' || C == 'tick_tock')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii != 3 || jj == 2 || jj == 6) { expectedQueryStrings.add("A == 'all' && (B == 'all' || C == 'tick_tock')"); } else { expectedQueryStrings.add("A == 'all' && B == 'all'"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allDays() throws Exception { String query = "A == 'all_day' && (B == 'all_day' || C == 'all_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'all_day'))))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allDays_unequalStart() throws Exception { String query = "A == 'all_day' && (B == 'all_day' || C == 'unequal_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 1) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day')) && (((_Delayed_ = true) && (B == 'all_day')))"); } else { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'unequal_start_day'))))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allDays_unequalStop() throws Exception { String query = "A == 'all_day' && (B == 'all_day' || C == 'unequal_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 5) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day')) && (((_Delayed_ = true) && (B == 'all_day')))"); } else { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'unequal_stop_day'))))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allDays_unevenStart() throws Exception { String query = "A == 'all_day' && (B == 'all_day' || C == 'uneven_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'uneven_start_day'))))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allDays_unevenStop() throws Exception { String query = "A == 'all_day' && (B == 'all_day' || C == 'uneven_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'uneven_stop_day'))))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allDays_missingShards() throws Exception { String query = "A == 'all_day' && (B == 'all_day' || C == 'missing_shards_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 3) { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && ((_Delayed_ = true) && (B == 'all_day')))"); } else { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'missing_shards_day'))))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_withNestedUnion_allDays_tickTockShards() throws Exception { String query = "A == 'all_day' && (B == 'all_day' || C == 'tick_tock')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && (((_Delayed_ = true) && (B == 'all_day')) || C == 'tick_tock'))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_dayWithNestedUnionOfShards() throws Exception { String query = "A == 'all_day' && (B == 'all' || C == 'all')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && (B == 'all' || C == 'all'))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_dayWithNestedUnionOfShards_unequalStart() throws Exception { String query = "A == 'all_day' && (B == 'all' || C == 'unequal_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 1) { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && B == 'all')"); } else { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && (B == 'all' || C == 'unequal_start'))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_dayWithNestedUnionOfShards_unequalStop() throws Exception { String query = "A == 'all_day' && (B == 'all' || C == 'unequal_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 5) { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && B == 'all')"); } else { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && (B == 'all' || C == 'unequal_stop'))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_dayWithNestedUnionOfShards_unevenStart() throws Exception { String query = "A == 'all_day' && (B == 'all' || C == 'uneven_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (jj == 0) { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && B == 'all')"); } else { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && (B == 'all' || C == 'uneven_start'))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_dayWithNestedUnionOfShards_unevenStop() throws Exception { String query = "A == 'all_day' && (B == 'all' || C == 'uneven_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (jj == 9) { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && B == 'all')"); } else { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && (B == 'all' || C == 'uneven_stop'))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_dayWithNestedUnionOfShards_missingShards() throws Exception { String query = "A == 'all_day' && (B == 'all' || C == 'missing_shards')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 3) { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && B == 'all')"); } else { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && (B == 'all' || C == 'missing_shards'))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_dayWithNestedUnionOfShards_tickTockShards() throws Exception { String query = "A == 'all_day' && (B == 'all' || C == 'tick_tock')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii != 3 || jj == 2 || jj == 6) { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && (B == 'all' || C == 'tick_tock'))"); } else { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) && B == 'all')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_shardWithNestedUnionOfDays() throws Exception { String query = "A == 'all' && (B == 'all_day' || C == 'all_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'all_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_shardWithNestedUnionOfDays_unequalStart() throws Exception { String query = "A == 'all' && (B == 'all_day' || C == 'unequal_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 1) { expectedQueryStrings.add("A == 'all' && (((_Delayed_ = true) && (B == 'all_day')))"); } else { expectedQueryStrings.add("A == 'all' && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'unequal_start_day')))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_shardWithNestedUnionOfDays_unequalStop() throws Exception { String query = "A == 'all' && (B == 'all_day' || C == 'unequal_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 5) { expectedQueryStrings.add("A == 'all' && (((_Delayed_ = true) && (B == 'all_day')))"); } else { expectedQueryStrings.add("A == 'all' && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'unequal_stop_day')))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_shardWithNestedUnionOfDays_unevenStart() throws Exception { String query = "A == 'all' && (B == 'all_day' || C == 'uneven_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'uneven_start_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_shardWithNestedUnionOfDays_unevenStop() throws Exception { String query = "A == 'all' && (B == 'all_day' || C == 'uneven_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'uneven_stop_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_shardWithNestedUnionOfDays_missingShards() throws Exception { String query = "A == 'all' && (B == 'all_day' || C == 'missing_shards_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 3) { expectedQueryStrings.add("A == 'all' && (((_Delayed_ = true) && (B == 'all_day')))"); } else { expectedQueryStrings.add("A == 'all' && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'missing_shards_day')))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A && ( B || C ) @Test public void testIntersection_shardWithNestedUnionOfDays_tickTockShards() throws Exception { String query = "A == 'all' && (B == 'all_day' || C == 'tick_tock_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 3) { // Not enough shards to force rolling the C-term to a day range, thus no delay. expectedQueryStrings.add("A == 'all' && (((_Delayed_ = true) && (B == 'all_day')) || (C == 'tick_tock_day'))"); } else { expectedQueryStrings.add("A == 'all' && (((_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'tick_tock_day')))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allShards() throws Exception { String query = "A == 'all' || (B == 'all' && C == 'all')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all' || (B == 'all' && C == 'all')"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allShards_unequalStart() throws Exception { String query = "A == 'all' || (B == 'all' && C == 'unequal_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 1) { // Can't intersect B-term with a non-existent C-term. Whole intersection is dropped for day 1. expectedQueryStrings.add("A == 'all'"); } else { expectedQueryStrings.add("A == 'all' || (B == 'all' && C == 'unequal_start')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allShards_unequalStop() throws Exception { String query = "A == 'all' || (B == 'all' && C == 'unequal_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 5) { // Can't intersect B-term with a non-existent C-term. Whole intersection is dropped for day 5. expectedQueryStrings.add("A == 'all'"); } else { expectedQueryStrings.add("A == 'all' || (B == 'all' && C == 'unequal_stop')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allShards_unevenStart() throws Exception { String query = "A == 'all' || (B == 'all' && C == 'uneven_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (jj == 0) { // Can't intersect B-term with a non-existent C-term. Whole intersection is dropped for first shard of each day. expectedQueryStrings.add("A == 'all'"); } else { expectedQueryStrings.add("A == 'all' || (B == 'all' && C == 'uneven_start')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allShards_unevenStop() throws Exception { String query = "A == 'all' || (B == 'all' && C == 'uneven_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (jj == 9) { // Can't intersect B-term with a non-existent C-term. Whole intersection is dropped for last shard of each day. expectedQueryStrings.add("A == 'all'"); } else { expectedQueryStrings.add("A == 'all' || (B == 'all' && C == 'uneven_stop')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allShards_missingShards() throws Exception { String query = "A == 'all' || (B == 'all' && C == 'missing_shards')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 3) { expectedQueryStrings.add("A == 'all'"); } else { expectedQueryStrings.add("A == 'all' || (B == 'all' && C == 'missing_shards')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allShards_tickTockShards() throws Exception { String query = "A == 'all' || (B == 'all' && C == 'tick_tock')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii != 3 || jj == 2 || jj == 6) { expectedQueryStrings.add("A == 'all' || (B == 'all' && C == 'tick_tock')"); } else { expectedQueryStrings.add("A == 'all'"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allDays() throws Exception { String query = "A == 'all_day' || (B == 'all_day' && C == 'all_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'all_day'))))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allDays_unequalStart() throws Exception { String query = "A == 'all_day' || (B == 'all_day' && C == 'unequal_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 1) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day'))"); } else { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'unequal_start_day'))))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allDays_unequalStop() throws Exception { String query = "A == 'all_day' || (B == 'all_day' && C == 'unequal_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 5) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day'))"); } else { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'unequal_stop_day'))))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allDays_unevenStart() throws Exception { String query = "A == 'all_day' || (B == 'all_day' && C == 'uneven_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'uneven_start_day'))))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allDays_unevenStop() throws Exception { String query = "A == 'all_day' || (B == 'all_day' && C == 'uneven_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'uneven_stop_day'))))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allDays_missingShards() throws Exception { String query = "A == 'all_day' || (B == 'all_day' && C == 'missing_shards_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 3) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day'))"); } else { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'missing_shards_day'))))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_withNestedIntersection_allDays_tickTockShards() throws Exception { String query = "A == 'all_day' || (B == 'all_day' && C == 'tick_tock_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 3) { expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) || (((_Delayed_ = true) && (B == 'all_day')) && C == 'tick_tock_day'))"); } else { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'tick_tock_day'))))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_dayWithNestedIntersectionOfShards() throws Exception { String query = "A == 'all_day' || (B == 'all' && C == 'all')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day')) || (B == 'all' && C == 'all')"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_dayWithNestedIntersectionOfShards_unequalStart() throws Exception { String query = "A == 'all_day' || (B == 'all' && C == 'unequal_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 1) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day'))"); } else { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day')) || (B == 'all' && C == 'unequal_start')"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_dayWithNestedIntersectionOfShards_unequalStop() throws Exception { String query = "A == 'all_day' || (B == 'all' && C == 'unequal_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 5) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day'))"); } else { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day')) || (B == 'all' && C == 'unequal_stop')"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_dayWithNestedIntersectionOfShards_unevenStart() throws Exception { String query = "A == 'all_day' || (B == 'all' && C == 'uneven_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 0) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day'))"); } else { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day')) || (B == 'all' && C == 'uneven_start')"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_dayWithNestedIntersectionOfShards_unevenStop() throws Exception { String query = "A == 'all_day' || (B == 'all' && C == 'uneven_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 0) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day'))"); } else { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day')) || (B == 'all' && C == 'uneven_stop')"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_dayWithNestedIntersectionOfShards_missingShards() throws Exception { String query = "A == 'all_day' || (B == 'all' && C == 'missing_shards')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 3) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day'))"); } else { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day')) || (B == 'all' && C == 'missing_shards')"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_dayWithNestedIntersectionOfShards_tickTockShards() throws Exception { String query = "A == 'all_day' || (B == 'all' && C == 'tick_tock')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day')) || (B == 'all' && C == 'tick_tock')"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_shardWithNestedIntersectionOfDays() throws Exception { String query = "A == 'all' || (B == 'all_day' && C == 'all_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'all_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_shardWithNestedIntersectionOfDays_unequalStart() throws Exception { String query = "A == 'all' || (B == 'all_day' && C == 'unequal_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii != 1) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'unequal_start_day')))"); } else { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all'"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_shardWithNestedIntersectionOfDays_unequalStop() throws Exception { String query = "A == 'all' || (B == 'all_day' && C == 'unequal_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii != 5) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'unequal_stop_day')))"); } else { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all'"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_shardWithNestedIntersectionOfDays_unevenStart() throws Exception { String query = "A == 'all' || (B == 'all_day' && C == 'uneven_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'uneven_start_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_shardWithNestedIntersectionOfDays_unevenStop() throws Exception { String query = "A == 'all' || (B == 'all_day' && C == 'uneven_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'uneven_stop_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_shardWithNestedIntersectionOfDays_missingShards() throws Exception { String query = "A == 'all' || (B == 'all_day' && C == 'missing_shards_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii == 3) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all'"); } } else { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'missing_shards_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // A || ( B && C ) @Test public void testUnion_shardWithNestedIntersectionOfDays_tickTockShards() throws Exception { String query = "A == 'all' || (B == 'all_day' && C == 'tick_tock_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii != 3) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("A == 'all' || (((_Delayed_ = true) && (B == 'all_day')) && ((_Delayed_ = true) && (C == 'tick_tock_day')))"); } else { for (int jj = 0; jj < 10; jj++) { if (jj == 2 || jj == 6) { expectedRanges.add(makeShardedRange("20200103_" + jj)); expectedQueryStrings.add("A == 'all' || (((_Delayed_ = true) && (B == 'all_day')) && (C == 'tick_tock_day'))"); } else { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("A == 'all'"); } } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allShards() throws Exception { String query = "(A == 'all' && B == 'all') || (C == 'all' && D == 'all')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("(A == 'all' && B == 'all') || (C == 'all' && D == 'all')"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allShards_unequalStart() throws Exception { String query = "(A == 'all' && B == 'all') || (C == 'all' && D == 'unequal_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 1) { expectedQueryStrings.add("(A == 'all' && B == 'all')"); } else { expectedQueryStrings.add("(A == 'all' && B == 'all') || (C == 'all' && D == 'unequal_start')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allShards_unequalStop() throws Exception { String query = "(A == 'all' && B == 'all') || (C == 'all' && D == 'unequal_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 5) { expectedQueryStrings.add("(A == 'all' && B == 'all')"); } else { expectedQueryStrings.add("(A == 'all' && B == 'all') || (C == 'all' && D == 'unequal_stop')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allShards_unevenStart() throws Exception { String query = "(A == 'all' && B == 'all') || (C == 'all' && D == 'uneven_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (jj == 0) { expectedQueryStrings.add("(A == 'all' && B == 'all')"); } else { expectedQueryStrings.add("(A == 'all' && B == 'all') || (C == 'all' && D == 'uneven_start')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allShards_unevenStop() throws Exception { String query = "(A == 'all' && B == 'all') || (C == 'all' && D == 'uneven_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (jj == 9) { expectedQueryStrings.add("(A == 'all' && B == 'all')"); } else { expectedQueryStrings.add("(A == 'all' && B == 'all') || (C == 'all' && D == 'uneven_stop')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allShards_missingShards() throws Exception { String query = "(A == 'all' && B == 'all') || (C == 'all' && D == 'missing_shards')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 3) { expectedQueryStrings.add("(A == 'all' && B == 'all')"); } else { expectedQueryStrings.add("(A == 'all' && B == 'all') || (C == 'all' && D == 'missing_shards')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allShards_tickTockShards() throws Exception { String query = "(A == 'all' && B == 'all') || (C == 'all' && D == 'tick_tock')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii != 3 || jj == 3 || jj == 7) { expectedQueryStrings.add("(A == 'all' && B == 'all') || (C == 'all' && D == 'tick_tock')"); } else { expectedQueryStrings.add("(A == 'all' && B == 'all')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allDays() throws Exception { String query = "(A == 'all_day' && B == 'all_day') || (C == 'all_day' && D == 'all_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("((_Delayed_ = true) && (A == 'all_day') && (_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'all_day') && (_Delayed_ = true) && (D == 'all_day'))"); } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allDays_unequalStart() throws Exception { String query = "(A == 'all_day' && B == 'all_day') || (C == 'all_day' && D == 'unequal_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 1) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day') && (_Delayed_ = true) && (B == 'all_day'))"); } else { expectedQueryStrings .add("((_Delayed_ = true) && (A == 'all_day') && (_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'all_day') && D == 'unequal_start')"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allDays_unequalStop() throws Exception { String query = "(A == 'all_day' && B == 'all_day') || (C == 'all_day' && D == 'unequal_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 5) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day') && (_Delayed_ = true) && (B == 'all_day'))"); } else { expectedQueryStrings .add("((_Delayed_ = true) && (A == 'all_day') && (_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'all_day') && D == 'unequal_stop')"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allDays_unevenStart() throws Exception { String query = "(A == 'all_day' && B == 'all_day') || (C == 'all_day' && D == 'uneven_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("((_Delayed_ = true) && (A == 'all_day') && (_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'all_day') && D == 'uneven_start')"); } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allDays_unevenStop() throws Exception { String query = "(A == 'all_day' && B == 'all_day') || (C == 'all_day' && D == 'uneven_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("((_Delayed_ = true) && (A == 'all_day') && (_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'all_day') && D == 'uneven_stop')"); } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allDays_missingShards() throws Exception { String query = "(A == 'all_day' && B == 'all_day') || (C == 'all_day' && D == 'missing_shards_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 3) { expectedQueryStrings.add("((_Delayed_ = true) && (A == 'all_day') && (_Delayed_ = true) && (B == 'all_day'))"); } else { expectedQueryStrings .add("((_Delayed_ = true) && (A == 'all_day') && (_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'all_day') && ((_Delayed_ = true) && (D == 'missing_shards_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_allDays_tickTockShards() throws Exception { String query = "(A == 'all_day' && B == 'all_day') || (C == 'all_day' && D == 'tick_tock')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("((_Delayed_ = true) && (A == 'all_day') && (_Delayed_ = true) && (B == 'all_day')) || ((_Delayed_ = true) && (C == 'all_day') && D == 'tick_tock')"); } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_distributedDays() throws Exception { String query = "(A == 'all' && B == 'all_day') || (C == 'all' && D == 'all_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings .add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day'))) || (C == 'all' && ((_Delayed_ = true) && (D == 'all_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_distributedDays_unequalStart() throws Exception { String query = "(A == 'all' && B == 'all_day') || (C == 'all' && D == 'unequal_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 1) { expectedQueryStrings.add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day')))"); } else { expectedQueryStrings .add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day'))) || (C == 'all' && ((_Delayed_ = true) && (D == 'unequal_start_day')))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_distributedDays_unequalStop() throws Exception { String query = "(A == 'all' && B == 'all_day') || (C == 'all' && D == 'unequal_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 5) { expectedQueryStrings.add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day')))"); } else { expectedQueryStrings .add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day'))) || (C == 'all' && ((_Delayed_ = true) && (D == 'unequal_stop_day')))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_distributedDays_unevenStart() throws Exception { String query = "(A == 'all' && B == 'all_day') || (C == 'all' && D == 'uneven_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 0) { expectedQueryStrings.add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day')))"); } else { expectedQueryStrings .add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day'))) || (C == 'all' && ((_Delayed_ = true) && (D == 'uneven_start_day')))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_distributedDays_unevenStop() throws Exception { String query = "(A == 'all' && B == 'all_day') || (C == 'all' && D == 'uneven_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 0) { expectedQueryStrings.add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day')))"); } else { expectedQueryStrings .add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day'))) || (C == 'all' && ((_Delayed_ = true) && (D == 'uneven_stop_day')))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_distributedDays_missingShards() throws Exception { String query = "(A == 'all' && B == 'all_day') || (C == 'all' && D == 'missing_shards_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 3) { expectedQueryStrings.add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day')))"); } else { expectedQueryStrings .add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day'))) || (C == 'all' && ((_Delayed_ = true) && (D == 'missing_shards_day')))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A && B) || (C && D) @Test public void testUnion_ofNestedIntersections_distributedDays_tickTockShards() throws Exception { String query = "(A == 'all' && B == 'all_day') || (C == 'all' && D == 'tick_tock')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii != 3 || jj == 3 || jj == 7) { expectedQueryStrings.add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day'))) || (C == 'all' && D == 'tick_tock')"); } else { expectedQueryStrings.add("(A == 'all' && ((_Delayed_ = true) && (B == 'all_day')))"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allShards() throws Exception { String query = "(A == 'all' || B == 'all') && (C == 'all' || D == 'all')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("(A == 'all' || B == 'all') && (C == 'all' || D == 'all')"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allShards_unequalStart() throws Exception { String query = "(A == 'all' || B == 'all') && (C == 'all' || D == 'unequal_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 1) { expectedQueryStrings.add("(A == 'all' || B == 'all') && C == 'all'"); } else { expectedQueryStrings.add("(A == 'all' || B == 'all') && (C == 'all' || D == 'unequal_start')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allShards_unequalStop() throws Exception { String query = "(A == 'all' || B == 'all') && (C == 'all' || D == 'unequal_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 5) { expectedQueryStrings.add("(A == 'all' || B == 'all') && C == 'all'"); } else { expectedQueryStrings.add("(A == 'all' || B == 'all') && (C == 'all' || D == 'unequal_stop')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allShards_unevenStart() throws Exception { String query = "(A == 'all' || B == 'all') && (C == 'all' || D == 'uneven_start')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (jj == 0) { expectedQueryStrings.add("(A == 'all' || B == 'all') && C == 'all'"); } else { expectedQueryStrings.add("(A == 'all' || B == 'all') && (C == 'all' || D == 'uneven_start')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allShards_unevenStop() throws Exception { String query = "(A == 'all' || B == 'all') && (C == 'all' || D == 'uneven_stop')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (jj == 9) { expectedQueryStrings.add("(A == 'all' || B == 'all') && C == 'all'"); } else { expectedQueryStrings.add("(A == 'all' || B == 'all') && (C == 'all' || D == 'uneven_stop')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allShards_missingShards() throws Exception { String query = "(A == 'all' || B == 'all') && (C == 'all' || D == 'missing_shards')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii == 3) { expectedQueryStrings.add("(A == 'all' || B == 'all') && C == 'all'"); } else { expectedQueryStrings.add("(A == 'all' || B == 'all') && (C == 'all' || D == 'missing_shards')"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allShards_tickTockShards() throws Exception { String query = "(A == 'all' || B == 'all') && (C == 'all' || D == 'tick_tock')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii != 3 || jj == 3 || jj == 7) { expectedQueryStrings.add("(A == 'all' || B == 'all') && (C == 'all' || D == 'tick_tock')"); } else { expectedQueryStrings.add("(A == 'all' || B == 'all') && C == 'all'"); } } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allDays() throws Exception { String query = "(A == 'all_day' || B == 'all_day') && (C == 'all_day' || D == 'all_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day'))) && (((_Delayed_ = true) && (C == 'all_day')) || ((_Delayed_ = true) && (D == 'all_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allDays_unequalStart() throws Exception { String query = "(A == 'all_day' || B == 'all_day') && (C == 'all_day' || D == 'unequal_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 1) { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day'))) && (((_Delayed_ = true) && (C == 'all_day')))"); } else { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day'))) && (((_Delayed_ = true) && (C == 'all_day')) || ((_Delayed_ = true) && (D == 'unequal_start_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allDays_unequalStop() throws Exception { String query = "(A == 'all_day' || B == 'all_day') && (C == 'all_day' || D == 'unequal_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 5) { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day'))) && (((_Delayed_ = true) && (C == 'all_day')))"); } else { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day'))) && (((_Delayed_ = true) && (C == 'all_day')) || ((_Delayed_ = true) && (D == 'unequal_stop_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allDays_unevenStart() throws Exception { String query = "(A == 'all_day' || B == 'all_day') && (C == 'all_day' || D == 'uneven_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day'))) && (((_Delayed_ = true) && (C == 'all_day')) || ((_Delayed_ = true) && (D == 'uneven_start_day')))"); } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allDays_unevenStop() throws Exception { String query = "(A == 'all_day' || B == 'all_day') && (C == 'all_day' || D == 'uneven_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); // if(ii == 5){ // expectedQueryStrings.add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day'))) && (((_Delayed_ = true) && (C == 'all_day')))"); // } else { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day'))) && (((_Delayed_ = true) && (C == 'all_day')) || ((_Delayed_ = true) && (D == 'uneven_stop_day')))"); // } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allDays_missingShards() throws Exception { String query = "(A == 'all_day' || B == 'all_day') && (C == 'all_day' || D == 'missing_shards_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); if (ii == 3) { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day'))) && (((_Delayed_ = true) && (C == 'all_day')))"); } else { expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day'))) && (((_Delayed_ = true) && (C == 'all_day')) || ((_Delayed_ = true) && (D == 'missing_shards_day')))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_allDays_tickTockShards() throws Exception { String query = "(A == 'all_day' || B == 'all_day') && (C == 'all_day' || D == 'tick_tock')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("(((_Delayed_ = true) && (A == 'all_day')) || ((_Delayed_ = true) && (B == 'all_day'))) && (((_Delayed_ = true) && (C == 'all_day')) || D == 'tick_tock')"); } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_distributedDays() throws Exception { String query = "(A == 'all' || B == 'all_day') && (C == 'all' || D == 'all_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings.add("((A == 'all') || ((_Delayed_ = true) && (B == 'all_day'))) && ((C == 'all') || (_Delayed_ = true) && (D == 'all_day'))"); } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_distributedDays_unequalStart() throws Exception { String query = "(A == 'all' || B == 'all_day') && (C == 'all' || D == 'unequal_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii == 1) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("((A == 'all') || ((_Delayed_ = true) && (B == 'all_day'))) && ((C == 'all'))"); } } else { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("((A == 'all') || ((_Delayed_ = true) && (B == 'all_day'))) && ((C == 'all') || (_Delayed_ = true) && (D == 'unequal_start_day'))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_distributedDays_unequalStop() throws Exception { String query = "(A == 'all' || B == 'all_day') && (C == 'all' || D == 'unequal_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { if (ii == 5) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("((A == 'all') || ((_Delayed_ = true) && (B == 'all_day'))) && ((C == 'all'))"); } } else { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("((A == 'all') || ((_Delayed_ = true) && (B == 'all_day'))) && ((C == 'all') || (_Delayed_ = true) && (D == 'unequal_stop_day'))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_distributedDays_unevenStart() throws Exception { String query = "(A == 'all' || B == 'all_day') && (C == 'all' || D == 'uneven_start_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("((A == 'all') || ((_Delayed_ = true) && (B == 'all_day'))) && ((C == 'all') || (_Delayed_ = true) && (D == 'uneven_start_day'))"); } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_distributedDays_unevenStop() throws Exception { String query = "(A == 'all' || B == 'all_day') && (C == 'all' || D == 'uneven_stop_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { expectedRanges.add(makeDayRange("2020010" + ii)); expectedQueryStrings .add("((A == 'all') || ((_Delayed_ = true) && (B == 'all_day'))) && ((C == 'all') || (_Delayed_ = true) && (D == 'uneven_stop_day'))"); } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_distributedDays_missingShards() throws Exception { String query = "(A == 'all' || B == 'all_day') && (C == 'all' || D == 'missing_shard_day')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); expectedQueryStrings.add("((A == 'all') || ((_Delayed_ = true) && (B == 'all_day'))) && ((C == 'all'))"); } } runTest(query, expectedRanges, expectedQueryStrings); } // (A || B) && (C || D) @Test public void testIntersection_ofNestedUnions_distributedDays_tickTockShards() throws Exception { String query = "(A == 'all' || B == 'all_day') && (C == 'all' || D == 'tick_tock')"; List<Range> expectedRanges = new ArrayList<>(); List<String> expectedQueryStrings = new ArrayList<>(); for (int ii = 1; ii <= 5; ii++) { for (int jj = 0; jj < 10; jj++) { expectedRanges.add(makeTestRange("2020010" + ii + "_" + jj, "datatype1\0a.b.c")); if (ii != 3 || jj == 3 || jj == 7) { expectedQueryStrings.add("(A == 'all' || ((_Delayed_ = true) && (B == 'all_day'))) && (C == 'all' || D == 'tick_tock')"); } else { expectedQueryStrings.add("(A == 'all' || ((_Delayed_ = true) && (B == 'all_day'))) && C == 'all'"); } } } runTest(query, expectedRanges, expectedQueryStrings); } private void runTest(String query, List<Range> expectedRanges, List<String> expectedQueries) throws Exception { assertEquals("Expected ranges and queries do not match, ranges: " + expectedRanges.size() + " queries: " + expectedQueries.size(), expectedRanges.size(), expectedQueries.size()); ASTJexlScript script = JexlASTHelper.parseJexlQuery(query); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // config.setBeginDate(new Date(0)); config.setBeginDate(sdf.parse("20200101")); config.setEndDate(sdf.parse("20200105")); config.setDatatypeFilter(Sets.newHashSet("datatype1")); Multimap<String,Type<?>> dataTypes = HashMultimap.create(); dataTypes.putAll("A", Sets.newHashSet(new LcNoDiacriticsType())); dataTypes.putAll("B", Sets.newHashSet(new LcNoDiacriticsType())); dataTypes.putAll("C", Sets.newHashSet(new LcNoDiacriticsType())); dataTypes.putAll("D", Sets.newHashSet(new LcNoDiacriticsType())); config.setQueryFieldsDatatypes(dataTypes); config.setIndexedFields(dataTypes); config.setShardsPerDayThreshold(2); MockMetadataHelper helper = new MockMetadataHelper(); helper.setIndexedFields(dataTypes.keySet()); // Run a standard limited-scanner range stream. RangeStream rangeStream = new RangeStream(config, new ScannerFactory(config.getConnector(), 1), helper); rangeStream.setLimitScanners(true); runTest(rangeStream, script, expectedRanges, expectedQueries); // Run a default range stream. rangeStream = new RangeStream(config, new ScannerFactory(config.getConnector(), 1), helper); rangeStream.setLimitScanners(false); runTest(rangeStream, script, expectedRanges, expectedQueries); } private void runTest(RangeStream rangeStream, ASTJexlScript script, List<Range> expectedRanges, List<String> expectedQueries) throws Exception { CloseableIterable<QueryPlan> queryPlans = rangeStream.streamPlans(script); assertEquals(IndexStream.StreamContext.PRESENT, rangeStream.context()); Iterator<Range> shardIter = expectedRanges.iterator(); Iterator<String> queryIter = expectedQueries.iterator(); // Should have one range per query plan int counter = 0; for (QueryPlan queryPlan : queryPlans) { // Assert proper range Iterator<Range> rangeIter = queryPlan.getRanges().iterator(); Range planRange = rangeIter.next(); Range expectedRange = shardIter.next(); assertEquals("Query produced unexpected range: " + planRange.toString(), expectedRange, planRange); assertFalse("Query plan had more than one range!", rangeIter.hasNext()); // Assert proper query string for this range. ASTJexlScript expectedScript = JexlASTHelper.parseJexlQuery(queryIter.next()); ASTJexlScript planScript = JexlNodeFactory.createScript(queryPlan.getQueryTree()); String expectedString = JexlStringBuildingVisitor.buildQuery(expectedScript); String plannedString = JexlStringBuildingVisitor.buildQuery(planScript); // Re-parse to avoid weird cases of DelayedPredicates expectedScript = JexlASTHelper.parseJexlQuery(expectedString); planScript = JexlASTHelper.parseJexlQuery(plannedString); assertTrue("Queries did not match for counter: " + counter + " on shard: " + planRange.toString() + "\nExpected: " + expectedString + "\nActual : " + plannedString, TreeEqualityVisitor.isEqual(expectedScript, planScript)); counter++; } // Ensure we didn't miss any expected ranges or queries if (shardIter.hasNext()) fail("Expected ranges still exist after test: " + shardIter.next()); if (queryIter.hasNext()) fail("Expected queries still exist after test: " + queryIter.next()); } }
69,734
378
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.openejb.activemq; import org.apache.openejb.junit.ApplicationComposer; import org.apache.openejb.testing.Classes; import org.apache.openejb.testing.ContainerProperties; import org.apache.openejb.testing.SimpleLog; import org.junit.Test; import org.junit.runner.RunWith; import javax.ejb.Singleton; import javax.inject.Inject; import javax.jms.ConnectionFactory; import javax.jms.JMSContext; import javax.naming.InitialContext; import javax.naming.NamingException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @SimpleLog @Classes(cdi = true, innerClassesAsBean = true) @RunWith(ApplicationComposer.class) @ContainerProperties(@ContainerProperties.Property(name = "openejb.environment.default", value = "true")) // off in embedded mode OOTB public class JMS2AMQDefaultConnectionFactoryTest { @Inject private JMSContext defaultContext; @Inject private JustToGetAJndiContext justToGetAJndiContext; @Test public void checkCF() throws Exception { assertEquals("test", defaultContext.createTextMessage("test").getText()); justToGetAJndiContext.checkJndi(); } @Singleton public static class JustToGetAJndiContext { public void checkJndi() { try { assertTrue(ConnectionFactory.class.isInstance(new InitialContext().lookup("java:comp/DefaultJMSConnectionFactory"))); } catch (final NamingException e) { fail(); } } } }
790
363
<gh_stars>100-1000 # -*- encoding: utf-8 -*- """ HubbleStack Nova module for auditing installed packages. Supports both blacklisting and whitelisting pacakges. Blacklisted packages must not be installed. Whitelisted packages must be installed, with options for requiring a specific version or a minimum or maximum version. Sample YAML data, with inline comments: pkg: # Must not be installed blacklist: # Unique ID for this set of audits telnet: data: # 'osfinger' grain, for multiplatform support CentOS Linux-6: # pkg name : tag - 'telnet': 'CIS-2.1.1' # Catch-all, if no osfinger match was found '*': # pkg name : tag - 'telnet': 'telnet-bad' # description/alert/trigger are currently ignored, but may be used in the future description: 'Telnet is evil' labels: - critical alert: email trigger: state # Must be installed, no version checking (yet) whitelist: rsh: data: CentOS Linux-6: # Use dict format to define specific version - 'rsh': tag: 'CIS-2.1.3' version: '4.3.2' # Dict format can also define ranges (only >= and <= supported) - 'rsh-client': tag: 'CIS-2.1.3' version: '>=4.3.2' # String format says "package must be installed, at any version" - 'rsh-server': 'CIS-2.1.4' CentOS Linux-7: - 'rsh': 'CIS-2.1.3' - 'rsh-server': 'CIS-2.1.4' '*': - 'rsh-client': 'CIS-5.1.2' - 'rsh-redone-client': 'CIS-5.1.2' - 'rsh-server': 'CIS-5.1.3' - 'rsh-redone-server': 'CIS-5.1.3' description: 'RSH is awesome' alert: email trigger: state """ import logging import fnmatch import copy import hubblestack.utils import hubblestack.utils.platform from distutils.version import LooseVersion log = logging.getLogger(__name__) def __virtual__(): if hubblestack.utils.platform.is_windows(): return False, 'This audit module only runs on linux' return True def apply_labels(__data__, labels): """ Filters out the tests whose label doesn't match the labels given when running audit and returns a new data structure with only labelled tests. """ labelled_data = {} if labels: labelled_data['pkg'] = {} for topkey in ('blacklist', 'whitelist'): if topkey in __data__.get('pkg', {}): labelled_test_cases=[] for test_case in __data__['pkg'].get(topkey, []): # each test case is a dictionary with just one key-val pair. key=test name, val=test data, description etc if isinstance(test_case, dict) and test_case: test_case_body = test_case.get(next(iter(test_case))) if set(labels).issubset(set(test_case_body.get('labels',[]))): labelled_test_cases.append(test_case) labelled_data['pkg'][topkey]=labelled_test_cases else: labelled_data = __data__ return labelled_data def audit(data_list, tags, labels, debug=False, **kwargs): """ Run the pkg audits contained in the YAML files processed by __virtual__ """ __data__ = {} for profile, data in data_list: _merge_yaml(__data__, data, profile) __data__ = apply_labels(__data__, labels) __tags__ = _get_tags(__data__) if debug: log.debug('pkg audit __data__:') log.debug(__data__) log.debug('pkg audit __tags__:') log.debug(__tags__) ret = {'Success': [], 'Failure': [], 'Controlled': []} for tag in __tags__: if fnmatch.fnmatch(tag, tags): for tag_data in __tags__[tag]: if 'control' in tag_data: ret['Controlled'].append(tag_data) continue name = tag_data['name'] audittype = tag_data['type'] # Blacklisted packages (must not be installed) if audittype == 'blacklist': if __mods__['pkg.version'](name): tag_data['failure_reason'] = "Found blacklisted package '{0}'" \ " installed on the system" \ .format(name) ret['Failure'].append(tag_data) else: ret['Success'].append(tag_data) # Whitelisted packages (must be installed) elif audittype == 'whitelist': if 'version' in tag_data: mod, _, version = tag_data['version'].partition('=') if not version: version = mod mod = '' if mod == '<': if (LooseVersion(__mods__['pkg.version'](name)) <= LooseVersion(version)): ret['Success'].append(tag_data) else: tag_data['failure_reason'] = "Could not find requisite package '{0}' with" \ " version less than or equal to '{1}' " \ "installed on the system" \ .format(name, version) ret['Failure'].append(tag_data) elif mod == '>': if (LooseVersion(__mods__['pkg.version'](name)) >= LooseVersion(version)): ret['Success'].append(tag_data) else: tag_data['failure_reason'] = "Could not find requisite package '{0}' " \ "with version greater than or equal to '{1}'" \ " installed on the system" \ .format(name, version) ret['Failure'].append(tag_data) elif not mod: # Just peg to the version, no > or < if __mods__['pkg.version'](name) == version: ret['Success'].append(tag_data) else: tag_data['failure_reason'] = "Could not find the version '{0}' of requisite" \ " package '{1}' installed on the system" \ .format(version, name) ret['Failure'].append(tag_data) else: # Invalid modifier log.error('Invalid modifier in version {0} for pkg {1} audit {2}' .format(tag_data['version'], name, tag)) tag_data = copy.deepcopy(tag_data) # Include an error in the failure tag_data['error'] = 'Invalid modifier {0}'.format(mod) tag_data['failure_reason'] = 'Invalid modifier in version {0} for pkg {1} audit' \ ' {2}. Seems like a bug in hubble profile.' \ .format(tag_data['version'], name, tag) ret['Failure'].append(tag_data) else: # No version checking if __mods__['pkg.version'](name): ret['Success'].append(tag_data) else: tag_data['failure_reason'] = "Could not find requisite package '{0}' installed" \ " on the system".format(name) ret['Failure'].append(tag_data) return ret def _merge_yaml(ret, data, profile=None): """ Merge two yaml dicts together at the pkg:blacklist and pkg:whitelist level """ if 'pkg' not in ret: ret['pkg'] = {} for topkey in ('blacklist', 'whitelist'): if topkey in data.get('pkg', {}): if topkey not in ret['pkg']: ret['pkg'][topkey] = [] for key, val in data['pkg'][topkey].items(): if profile and isinstance(val, dict): val['nova_profile'] = profile ret['pkg'][topkey].append({key: val}) return ret def _get_tags(data): """ Retrieve all the tags for this distro from the yaml """ ret = {} distro = __grains__.get('osfinger') for toplist, toplevel in data.get('pkg', {}).items(): # pkg:blacklist for audit_dict in toplevel: # pkg:blacklist:0 for audit_id, audit_data in audit_dict.items(): # pkg:blacklist:0:telnet tags_dict = audit_data.get('data', {}) # pkg:blacklist:0:telnet:data tags = None for osfinger in tags_dict: if osfinger == '*': continue osfinger_list = [finger.strip() for finger in osfinger.split(',')] for osfinger_glob in osfinger_list: if fnmatch.fnmatch(distro, osfinger_glob): tags = tags_dict.get(osfinger) break if tags is not None: break # If we didn't find a match, check for a '*' if tags is None: tags = tags_dict.get('*', []) # pkg:blacklist:0:telnet:data:Debian-8 if isinstance(tags, dict): # malformed yaml, convert to list of dicts tmp = [] for name, tag in tags.items(): tmp.append({name: tag}) tags = tmp for item in tags: for name, tag in item.items(): tag_data = {} # Whitelist could have a dictionary, not a string if isinstance(tag, dict): tag_data = copy.deepcopy(tag) tag = tag_data.pop('tag') if tag not in ret: ret[tag] = [] formatted_data = {'name': name, 'tag': tag, 'module': 'pkg', 'type': toplist} formatted_data.update(tag_data) formatted_data.update(audit_data) formatted_data.pop('data') ret[tag].append(formatted_data) return ret
6,384
766
<reponame>data-man/libfsm<filename>src/libfsm/minimise.c /* * Copyright 2020 <NAME> * * See LICENCE for the full copyright terms. */ #include <assert.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdio.h> #include <fsm/fsm.h> #include <fsm/pred.h> #include <fsm/walk.h> #include <fsm/alloc.h> #include <adt/edgeset.h> #include <adt/set.h> #include "internal.h" #define LOG_MAPPINGS 0 #define LOG_STEPS 0 #define LOG_TIME 0 #define LOG_INIT 0 #define LOG_ECS 0 #define LOG_PARTITIONS 0 #if LOG_TIME #include <sys/time.h> #endif #include "minimise_internal.h" int fsm_minimise(struct fsm *fsm) { int r = 0; struct fsm *dst = NULL; unsigned char labels[FSM_SIGMA_COUNT]; size_t label_count, orig_states, minimised_states; fsm_state_t *mapping = NULL; unsigned *shortest_end_distance = NULL; #if LOG_TIME struct timeval tv_pre, tv_post; #define TIME(T) if (0 != gettimeofday(&T, NULL)) { assert(0); } #define LOG_TIME_DELTA(NAME) \ fprintf(stderr, "%-8s %.3f msec\n", NAME, \ 1000.0 * (tv_post.tv_sec - tv_pre.tv_sec) \ + (tv_post.tv_usec - tv_pre.tv_usec)/1000.0); #else #define TIME(T) #define LOG_TIME_DELTA(NAME) #endif /* This should only be called with a DFA. */ assert(fsm != NULL); assert(fsm_all(fsm, fsm_isdfa)); /* The algorithm used below won't remove states without a path * to an end state, because it cannot prove they're * unnecessary, so they must be trimmed away first. */ if (fsm_trim(fsm, FSM_TRIM_START_AND_END_REACHABLE, &shortest_end_distance) < 0) { return 0; } if (fsm->statecount == 0) { r = 1; goto cleanup; } TIME(tv_pre); collect_labels(fsm, labels, &label_count); TIME(tv_post); LOG_TIME_DELTA("collect_labels"); if (label_count == 0) { r = 1; goto cleanup; } mapping = f_malloc(fsm->opt->alloc, fsm->statecount * sizeof(mapping[0])); if (mapping == NULL) { goto cleanup; } orig_states = fsm->statecount; TIME(tv_pre); r = build_minimised_mapping(fsm, labels, label_count, shortest_end_distance, mapping, &minimised_states); TIME(tv_post); LOG_TIME_DELTA("minimise"); if (!r) { goto cleanup; } /* Minimisation should never add states. */ assert(minimised_states <= orig_states); /* Use the mapping to consolidate the current states * into a new DFA, combining states that could not be * proven distinguishable. */ TIME(tv_pre); dst = fsm_consolidate(fsm, mapping, fsm->statecount); TIME(tv_post); LOG_TIME_DELTA("consolidate"); if (dst == NULL) { r = 0; goto cleanup; } fsm_move(fsm, dst); cleanup: if (mapping != NULL) { f_free(fsm->opt->alloc, mapping); } if (shortest_end_distance != NULL) { f_free(fsm->opt->alloc, shortest_end_distance); } return r; } /* Build a bit set of labels used, then write the set * into a sorted array. */ static void collect_labels(const struct fsm *fsm, unsigned char *labels, size_t *label_count) { size_t count = 0; uint64_t label_set[FSM_SIGMA_COUNT/64] = { 0, 0, 0, 0 }; int i; fsm_state_t id; for (id = 0; id < fsm->statecount; id++) { struct fsm_edge e; struct edge_iter ei; unsigned char label; for (edge_set_reset(fsm->states[id].edges, &ei); edge_set_next(&ei, &e); ) { assert(e.state < fsm->statecount); label = e.symbol; if (label_set[label/64] & (UINT64_C(1) << (label & 63))) { /* already set, ignore */ } else { label_set[label/64] |= (UINT64_C(1) << (label & 63)); count++; } } } *label_count = 0; for (i = 0; i < 256; i++) { if (label_set[i/64] & (UINT64_C(1) << (i & 63))) { labels[*label_count] = i; (*label_count)++; } } assert(*label_count == count); } /* Build a mapping for a minimised version of the DFA, using Moore's * algorithm (with a couple performance improvements). * * For a good description of the algorithm (albeit one that incorrectly * attributes it to Hopcroft) see pgs. 55-59 of Cooper & Torczon's * _Engineering a Compiler_. For another, see pg. 13-20 of <NAME> * Veen's thesis, _The Practical Performance of Automata Minimization * Algorithms_. * * Intuitively, the algorithm starts by dividing all of the states into * two sets, called Equivalence Classes (abbreviated EC below), * containing all non-final and final states respectively. Then, for * every EC, check whether any of its states' edges for the same label * lead to states in distinct ECs (and therefore observably different * results). If so, partition the EC into two ECs, containing the states * with matching and non-matching destination ECs. (Which EC is chosen * as matching doesn't affect correctness.) Repeat until no further * progress can be made, meaning the algorithm cannot prove anything * else is distinguishable via transitive final/non-final reachability. * Each EC represents a state in the minimised DFA mapping, and multiple * states in a single EC can be safely combined without affecting * observable behavior. * * When PARTITION_BY_END_STATE_DISTANCE is non-zero, instead of * starting with two ECs, do a pass grouping the states into ECs * according to their distance to the closest end state. See the * comments around it for further details. */ static int build_minimised_mapping(const struct fsm *fsm, const unsigned char *dfa_labels, size_t dfa_label_count, const unsigned *shortest_end_distance, fsm_state_t *mapping, size_t *minimized_state_count) { struct min_env env; int changed, res = 0; size_t i; fsm_state_t ec_offset; /* Alloc for each state, plus the dead state. */ size_t alloc_size = (fsm->statecount + 1) * sizeof(env.state_ecs[0]); env.fsm = fsm; env.dead_state = fsm->statecount; env.iter = 0; env.steps = 0; assert(fsm->statecount > 0); env.state_ecs = NULL; env.jump = NULL; env.ecs = NULL; env.dfa_labels = dfa_labels; env.dfa_label_count = dfa_label_count; env.state_ecs = f_malloc(fsm->opt->alloc, alloc_size); if (env.state_ecs == NULL) { goto cleanup; } env.jump = f_malloc(fsm->opt->alloc, alloc_size); if (env.jump == NULL) { goto cleanup; } env.ecs = f_malloc(fsm->opt->alloc, alloc_size); if (env.ecs == NULL) { goto cleanup; } env.ecs[INIT_EC_NOT_FINAL] = NO_ID; env.ecs[INIT_EC_FINAL] = NO_ID; env.ec_count = 2; env.done_ec_offset = env.ec_count; if (!populate_initial_ecs(&env, fsm, shortest_end_distance)) { goto cleanup; } #if LOG_INIT for (i = 0; i < env.ec_count; i++) { fprintf(stderr, "# --ec[%lu]: %d\n", i, env.ecs[i]); } #endif do { /* repeat until no further progress can be made */ size_t l_i, ec_i; changed = 0; dump_ecs(stderr, &env); /* Check all active ECs for potential partitions. */ for (ec_i = 0; ec_i < env.done_ec_offset; ec_i++) { int should_gather_EC_labels; struct min_label_iterator li; restart_EC: /* ECs were swapped; restart the new EC here */ { fsm_state_t next = env.ecs[ec_i]; if (next == NO_ID) { continue; /* 0 elements, skip */ } should_gather_EC_labels = (next & SMALL_EC_FLAG) != 0; next = MASK_EC_HEAD(next); if (env.jump[next] == NO_ID) { continue; /* only 1 element, skip */ } } init_label_iterator(&env, ec_i, should_gather_EC_labels, &li); while (li.i < li.limit) { size_t pcounts[2]; const fsm_state_t ec_src = ec_i; const fsm_state_t ec_dst = env.ec_count; unsigned char label; l_i = li.i; li.i++; label = (li.has_labels_for_EC ? li.labels[l_i] : env.dfa_labels[l_i]); env.steps++; if (try_partition(&env, label, ec_src, ec_dst, pcounts)) { int should_restart_EC; #if LOG_PARTITIONS > 0 fprintf(stderr, "# partition: ec_i %lu/%u/%u, l_i %lu/%u%s, pcounts [ %lu, %lu ]\n", ec_i, env.done_ec_offset, env.ec_count, l_i, li.limit, li.has_labels_for_EC ? "*" : "", pcounts[0], pcounts[1]); #endif should_restart_EC = update_after_partition(&env, pcounts, ec_src, ec_dst); changed = 1; env.ec_count++; assert(env.done_ec_offset <= env.ec_count); if (should_restart_EC) { goto restart_EC; } } #if EXPENSIVE_INTEGRITY_CHECKS check_done_ec_offset(&env); #endif } } env.iter++; } while (changed); /* When all of the original input states are final, then the * initial not-final EC will be empty. Skip it in the mapping, * otherwise an unnecessary state will be created for it. */ ec_offset = (env.ecs[INIT_EC_NOT_FINAL] == NO_ID) ? 1 : 0; /* Build map condensing to unique states */ for (i = ec_offset; i < env.ec_count; i++) { fsm_state_t cur = MASK_EC_HEAD(env.ecs[i]); while (cur != NO_ID) { mapping[cur] = i - ec_offset; cur = env.jump[cur]; } } if (minimized_state_count != NULL) { *minimized_state_count = env.ec_count - ec_offset; } #if LOG_MAPPINGS for (i = 0; i < fsm->statecount; i++) { fprintf(stderr, "# minimised_mapping[%lu]: %u\n", i, mapping[i]); } #endif #if LOG_STEPS fprintf(stderr, "# done in %lu iteration(s), %lu step(s), %ld -> %ld states, label_count %lu\n", env.iter, env.steps, fsm->statecount, (size_t)(env.ec_count - ec_offset), env.dfa_label_count); #endif res = 1; /* fall through */ cleanup: f_free(fsm->opt->alloc, env.ecs); f_free(fsm->opt->alloc, env.state_ecs); f_free(fsm->opt->alloc, env.jump); return res; } static void dump_ecs(FILE *f, const struct min_env *env) { #if LOG_ECS size_t i = 0; fprintf(f, "# iter %ld, steps %lu\n", env->iter, env->steps); while (i < env->ec_count) { fsm_state_t cur = MASK_EC_HEAD(env->ecs[i]); fprintf(f, "M_EC[%lu]:", i); while (cur != NO_ID) { fprintf(f, " %u", cur); cur = env->jump[cur]; } fprintf(f, "\n"); i++; } #else (void)f; (void)env; #endif } #define PARTITION_BY_END_STATE_DISTANCE 1 #if PARTITION_BY_END_STATE_DISTANCE /* Use counting sort to construct a permutation vector -- this is an * array of offsets into in[N] such that in[pv[0..N]] would give the * values of in[] in ascending order (but don't actually rearrange in, * just get the offsets). This is O(n). */ static unsigned * build_permutation_vector(const struct fsm_alloc *alloc, size_t length, size_t max_value, unsigned *in) { unsigned *out = NULL; unsigned *counts = NULL; size_t i; out = f_malloc(alloc, length * sizeof(*out)); if (out == NULL) { goto cleanup; } counts = f_calloc(alloc, max_value + 1, sizeof(*out)); if (counts == NULL) { goto cleanup; } /* Count each distinct value */ for (i = 0; i < length; i++) { counts[in[i]]++; } /* Convert to cumulative counts, so counts[v] stores the upper * bound for where sorting would place each distinct value. */ for (i = 1; i <= max_value; i++) { counts[i] += counts[i - 1]; } /* Sweep backwards through the input array, placing each value * according to the cumulative count. Decrement the count so * progressively earlier instances of the same value will * receive earlier offsets in out[]. */ for (i = 0; i < length; i++) { const unsigned pos = length - i - 1; const unsigned value = in[pos]; const unsigned count = --counts[value]; out[count] = pos; } f_free(alloc, counts); return out; cleanup: if (out != NULL) { f_free(alloc, out); } if (counts != NULL) { f_free(alloc, counts); } return NULL; } #endif static int populate_initial_ecs(struct min_env *env, const struct fsm *fsm, const unsigned *shortest_end_distance) { int res = 0; size_t i; #if PARTITION_BY_END_STATE_DISTANCE /* Populate the initial ECs, partitioned by their shortest * distance to an end state. Where Moore or Hopcroft's algorithm * would typically start with two ECs, one for final states and * one for non-final states, these states can be further * partitioned into groups with equal shortest distances to an * end state (0 for the end states themselves). This eliminates * the worst case in `build_minimised_mapping`, where a very * deeply nested path to an end state requires several passes: * for example, an EC with 1000 states where only the last * reaches the end state and is distinguishable, then 999, then * 998, ... Using an initial partitioning based on the * shortest_end_distance puts the states with each distance into * their own ECs, replacing quadratic repetition. This initial * pass can be done in linear time. * * This end-distance-based partitioning is described in * _Efficient Deterministic Finite Automata Minimization Based * on Backward Depth Information_ by <NAME>. al. While * I'm not convinced their approach works as presented -- and * the pseudocode, diagrams, and test data tables in the paper * contain numerous errors -- their proposition that any two * states with different backwards depths to accept states must * be distinguishable appears to be valid. We use this * partitioning as a first pass, and then Moore's algorithm does * the rest. */ size_t count_ceil; unsigned *counts = NULL; unsigned *pv = NULL, *ranking = NULL; unsigned count_max = 0, sed_max = 0, sed_limit; assert(fsm != NULL); assert(shortest_end_distance != NULL); counts = f_calloc(fsm->opt->alloc, DEF_INITIAL_COUNT_CEIL, sizeof(counts[0])); if (counts == NULL) { goto cleanup; } count_ceil = DEF_INITIAL_COUNT_CEIL; /* Count unique shortest_end_distances, growing the * counts array as necessary, and track the max SED * present. */ for (i = 0; i < fsm->statecount; i++) { unsigned sed = shortest_end_distance[i]; #if LOG_INIT fprintf(stderr, "initial_ecs: %lu/%lu: sed %u\n", i, fsm->statecount, sed); #endif assert(sed != (unsigned)-1); if (sed >= count_ceil) { size_t ni; size_t nceil = 2 * count_ceil; unsigned *ncounts; while (sed >= nceil) { nceil *= 2; } ncounts = f_realloc(fsm->opt->alloc, counts, nceil * sizeof(counts[0])); if (ncounts == NULL) { goto cleanup; } /* zero the newly allocated region */ for (ni = count_ceil; ni < nceil; ni++) { ncounts[ni] = 0; } counts = ncounts; count_ceil = nceil; } counts[sed]++; if (sed > sed_max) { sed_max = sed; } if (counts[sed] > count_max) { count_max = counts[sed]; } } /* The upper limit includes the max value. */ sed_limit = sed_max + 1; /* Build a permutation vector of the counts, such * that counts[pv[i..N]] would return the values * in counts[] in ascending order. */ pv = build_permutation_vector(fsm->opt->alloc, sed_limit, count_max, counts); if (pv == NULL) { goto cleanup; } /* Build a permutation vector of the permutation vector, * converting it into the rankings for counts[]. This is an * old APL idiom[1], composing the grade-up operator (which * builds an ascending permutation vector) with itself. * * Using k syntax & ngn's k [2] : * * d:10?4 / bind d to: draw 10 values 0 <= x < 4 * d / print d's contents * 3 3 0 1 3 1 1 3 2 2 * <d / build permutation vector of d * 2 3 5 6 8 9 0 1 4 7 * d[<d] / d sliced by pv of d -> sorted d * 0 1 1 1 2 2 3 3 3 3 * d / print d's contents, again * 3 3 0 1 3 1 1 3 2 2 * <<d / pv of (pv of d): ranking vector of d * 6 7 0 1 8 2 3 9 4 5 * / see how (0) -> 0, (1 2 3) -> 1, * / (4 5) -> 2, (6 7 8 9) -> 3? * 9-<<d / subtract from the length to count * 3 2 9 8 1 7 6 0 5 4 / from the end, for descending ranks. * / now (0 1 2 3) -> 3, (4 5) -> 2, ... * dr:{(-1+#x)-<<x} / bind function: descending rank * dr d / put it all together * 3 2 9 8 1 7 6 0 5 4 * / one more example, to show the pattern * d:5 5 5 2 2 2 2 1 1 1 * dr d * 2 1 0 6 5 4 3 9 8 7 / (2 1 0) -> 5, (6 5 4 3) -> 2, (9 8 7) -> 1 * * [1]: http://www.sudleyplace.com/APL/Anatomy%20of%20An%20Idiom.pdf * [2]: https://bitbucket.org/ngn/k/src */ ranking = build_permutation_vector(fsm->opt->alloc, sed_limit, sed_limit, pv); if (ranking == NULL) { goto cleanup; } /* Reverse the ranking offsets -- count from the end, rather * than the start, so ECs with higher counts appear first. */ for (i = 0; i < sed_limit; i++) { ranking[i] = sed_max - ranking[i]; env->ecs[i] = NO_ID; } /* Assign the states to the ECs, ordered by descending ranking. * We want the largest ECs first, as they will need the most * processing. All ECs with less than 2 states are already done, * so they should be together at the end. */ for (i = 0; i < fsm->statecount; i++) { const unsigned sed = shortest_end_distance[i]; fsm_state_t ec; assert(sed < sed_limit); /* assign EC and link state at head of list */ ec = ranking[sed]; env->state_ecs[i] = ec; env->jump[i] = env->ecs[ec]; env->ecs[ec] = i; } /* Set done_ec_offset to the first EC with <2 states, if any. */ env->ec_count = sed_limit; env->done_ec_offset = env->ec_count; for (i = 0; i < sed_limit; i++) { const unsigned count = counts[shortest_end_distance[env->ecs[i]]]; if (count < 2) { env->done_ec_offset = i; break; } } /* The dead state is not a member of any EC. */ env->state_ecs[env->dead_state] = NO_ID; res = 1; cleanup: f_free(fsm->opt->alloc, counts); f_free(fsm->opt->alloc, pv); f_free(fsm->opt->alloc, ranking); return res; #else (void)shortest_end_distance; for (i = 0; i < fsm->statecount; i++) { const fsm_state_t ec = fsm_isend(fsm, i) ? INIT_EC_FINAL : INIT_EC_NOT_FINAL; env->state_ecs[i] = ec; /* link at head of the list */ env->jump[i] = env->ecs[ec]; env->ecs[ec] = i; #if LOG_INIT fprintf(stderr, "# --init[%lu]: ec %d, jump[]= %d\n", i, ec, env->jump[i]); #endif } /* The dead state is not a member of any EC. */ env->state_ecs[env->dead_state] = NO_ID; res = 1; return res; #endif } #if EXPENSIVE_INTEGRITY_CHECKS static void check_done_ec_offset(const struct min_env *env) { size_t i; /* All ECs after the done_ec_offset have less than two elements * (and cannot be partitioned further), all elements after the * first two but before the offset have two or more. The first * two are allowed to to have less, because for example the DFA * may start with only one end state. The done_ec_offset is used * to avoid redundantly scanning lots of small ECs that have * been split off from the initial sets, but it would not be * worth the added complexity to avoid checking ECs 0 and 1. */ for (i = 0; i < env->ec_count; i++) { const fsm_state_t head = MASK_EC_HEAD(env->ecs[i]); if (i >= done_ec_offset) { assert(head == NO_ID || env->jump[head] == NO_ID); } else if (i >= 2) { assert(env->jump[head] != NO_ID); } } } #endif static int update_after_partition(struct min_env *env, const size_t *partition_counts, fsm_state_t ec_src, fsm_state_t ec_dst) { int should_restart_EC = 0; assert(partition_counts[0] > 0); assert(partition_counts[1] > 0); /* ec_dst is at the end, so ecs[ec_dst] is in the * done group by default. If there's only one, * leave it there. */ if (partition_counts[1] == 1) { assert(env->done_ec_offset > 0); update_ec_links(env, ec_dst); } else { /* Otherwise, swap and increment the offset so that dst * is moved immediately before the done group, but * outside of it. */ const fsm_state_t ndst = env->done_ec_offset; const fsm_state_t tmp = env->ecs[ec_dst]; env->ecs[ec_dst] = env->ecs[ndst]; env->ecs[ndst] = tmp; assert(partition_counts[1] > 1); /* not 0 */ update_ec_links(env, ec_dst); update_ec_links(env, ndst); env->done_ec_offset++; } /* If the src EC only has one, swap it immediately before * the done group and decrement the offset, expanding it * to include the src EC. */ if (partition_counts[0] == 1 && env->done_ec_offset > 0) { fsm_state_t nsrc = env->done_ec_offset - 1; /* swap ec[nsrc] and ec[ec_src] */ const fsm_state_t tmp = env->ecs[ec_src]; env->ecs[ec_src] = env->ecs[nsrc]; env->ecs[nsrc] = tmp; update_ec_links(env, ec_src); update_ec_links(env, nsrc); assert(env->done_ec_offset > 0); env->done_ec_offset--; /* The src EC just got swapped with another, * so start over at the beginning of the labels * for the new EC. */ should_restart_EC = 1; } return should_restart_EC; } static void update_ec_links(struct min_env *env, fsm_state_t ec_dst) { size_t count = 0; fsm_state_t cur = env->ecs[ec_dst]; assert(cur != NO_ID); cur = MASK_EC_HEAD(cur); while (cur != NO_ID) { env->state_ecs[cur] = ec_dst; cur = env->jump[cur]; count++; } /* If the EC count is smaller than the threshold (and it isn't a * DFA with a very small number of labels overall), then set the * flag indicating that it should get smarter label checking. */ if (count <= SMALL_EC_THRESHOLD && env->dfa_label_count >= DFA_LABELS_THRESHOLD) { env->ecs[ec_dst] = SET_SMALL_EC_FLAG(env->ecs[ec_dst]); } } static void init_label_iterator(const struct min_env *env, fsm_state_t ec_i, int should_gather_EC_labels, struct min_label_iterator *li) { /* If the SMALL_EC flag was set for the EC (indicating that it has a * small number of states), then gather the labels actually used * by those states rather than checking all labels in the entire * DFA. */ if (should_gather_EC_labels) { fsm_state_t cur; size_t i; uint32_t label_set[FSM_SIGMA_COUNT/32]; memset(label_set, 0x00, sizeof(label_set)); cur = env->ecs[ec_i]; assert(cur != NO_ID); cur = MASK_EC_HEAD(cur); while (cur != NO_ID) { struct fsm_edge e; struct edge_iter ei; for (edge_set_reset(env->fsm->states[cur].edges, &ei); edge_set_next(&ei, &e); ) { const unsigned char label = e.symbol; label_set[label/32] |= ((uint32_t)1 << (label & 31)); } cur = env->jump[cur]; } li->has_labels_for_EC = 1; li->i = 0; li->limit = 0; i = 0; while (i < 256) { /* Check the bitset, skip forward 32 entries at a time * if they're all zero. */ if ((i & 31) == 0 && label_set[i/32] == 0) { i += 32; } else { if (label_set[i/32] & ((uint32_t)1 << (i & 31))) { li->labels[li->limit] = i; li->limit++; } i++; } } } else { /* check all labels in sequence */ li->has_labels_for_EC = 0; li->limit = env->dfa_label_count; li->i = 0; } } static fsm_state_t find_edge_destination(const struct fsm *fsm, fsm_state_t id, unsigned char label) { struct fsm_edge e; assert(id < fsm->statecount); if (edge_set_find(fsm->states[id].edges, label, &e)) { return e.state; } return fsm->statecount; /* dead state */ } static int try_partition(struct min_env *env, unsigned char label, fsm_state_t ec_src, fsm_state_t ec_dst, size_t partition_counts[2]) { fsm_state_t cur = MASK_EC_HEAD(env->ecs[ec_src]); fsm_state_t to, to_ec, first_ec, prev; #if EXPENSIVE_INTEGRITY_CHECKS /* Count states here, to compare against the partitioned * EC' counts later. */ size_t state_count = 0, psrc_count, pdst_count; while (cur != NO_ID) { cur = env->jump[cur]; state_count++; } cur = MASK_EC_HEAD(env->ecs[ec_src]); #endif memset(partition_counts, 0x00, 2*sizeof(partition_counts[0])); #if LOG_PARTITIONS > 1 fprintf(stderr, "# --- try_partition: checking '%c' for %u\n", label, ec_src); #endif /* There must be at least two states in this EC. * See where the current label leads on the first state. * Any states which has an edge to a different EC for * that label will be split into a new EC. * * Note that the ec_src EC is updated in place -- because this * is successively trying different labels on the same EC, it * can often do several partitions and make more progress in a * single pass, avoiding most of the theoretical overhead of the * fixpoint approach. */ to = find_edge_destination(env->fsm, cur, label); first_ec = env->state_ecs[to]; partition_counts[0] = 1; prev = cur; cur = env->jump[cur]; #if LOG_PARTITIONS > 1 fprintf(stderr, "# --- try_partition: first, %u, has to %d -> first_ec %d\n", cur, to, first_ec); #endif /* initialize the new EC -- empty */ env->ecs[ec_dst] = NO_ID; while (cur != NO_ID) { to = find_edge_destination(env->fsm, cur, label); to_ec = env->state_ecs[to]; #if LOG_PARTITIONS > 1 fprintf(stderr, "# --- try_partition: next, cur %u, has to %d -> to_ec %d\n", cur, to, to_ec); #endif if (to_ec == first_ec) { /* in same EC */ partition_counts[0]++; prev = cur; cur = env->jump[cur]; } else { /* unlink, split */ fsm_state_t next; #if LOG_PARTITIONS > 1 fprintf(stderr, "# try_partition: unlinking -- label '%c', src %u, dst %u, first_ec %d, cur %u -> to_ec %d\n", label, ec_src, ec_dst, first_ec, cur, to_ec); #endif /* Unlink this state from the current EC, * instead put it as the start of a new one * at ecs[ec_dst]. */ next = env->jump[cur]; env->jump[prev] = next; env->jump[cur] = env->ecs[ec_dst]; env->ecs[ec_dst] = cur; cur = next; partition_counts[1]++; } } #if EXPENSIVE_INTEGRITY_CHECKS /* Count how many states were split into each EC * and check that the sum matches the original count. */ psrc_count = 0; cur = env->ecs[ec_src]; if (cur != NO_ID) { cur = MASK_EC_HEAD(cur); while (cur != NO_ID) { cur = env->jump[cur]; psrc_count++; } } pdst_count = 0; cur = env->ecs[ec_dst]; if (cur != NO_ID) { cur = MASK_EC_HEAD(cur); while (cur != NO_ID) { cur = env->jump[cur]; pdst_count++; } } assert(state_count == psrc_count + pdst_count); #endif return partition_counts[1] > 0; }
10,387
1,025
<gh_stars>1000+ //================================================================================== // Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved. // /// \author AMD Developer Tools Team /// \file pdRemoteProcessDebugger.cpp /// //================================================================================== //------------------------------ pdRemoteProcessDebugger.cpp ------------------------------ // Infra: #include <AMDTBaseTools/Include/gtAssert.h> #include <AMDTOSWrappers/Include/osApplication.h> #include <AMDTOSWrappers/Include/osCallStack.h> #include <AMDTOSWrappers/Include/osChannel.h> #include <AMDTOSWrappers/Include/osDebugLog.h> #include <AMDTOSWrappers/Include/osDirectory.h> #include <AMDTOSWrappers/Include/osProcess.h> #include <AMDTOSWrappers/Include/osPipeSocketServer.h> #include <AMDTOSWrappers/Include/osTCPSocketClient.h> #include <AMDTOSWrappers/Include/osTCPSocketServer.h> #include <AMDTAPIClasses/Include/apDebugProjectSettings.h> #include <AMDTAPIClasses/Include/apExpression.h> #include <AMDTAPIClasses/Include/Events/apThreadCreatedEvent.h> #include <AMDTAPIClasses/Include/Events/apDebuggedProcessCreationFailureEvent.h> #include <AMDTAPIClasses/Include/Events/apEventsHandler.h> #include <AMDTAPIClasses/Include/Events/apDebuggedProcessTerminatedEvent.h> // The remote client is not used for the 64-bit Windows version of the process debugger: #if !((AMDT_BUILD_TARGET == AMDT_WINDOWS_OS) && (AMDT_ADDRESS_SPACE_TYPE == AMDT_64_BIT_ADDRESS_SPACE)) #include <AMDTRemoteClient/Include/CXLDaemonClient.h> #endif // Local: #include <src/pdStringConstants.h> #include <AMDTProcessDebugger/Include/pdRemoteProcessDebuggerCommandId.h> #include <src/pdRemoteProcessDebugger.h> #include <src/pdRemoteProcessDebuggerEventsListenerThread.h> #include <src/pdRemoteProcessDebuggerDebuggingServerWatcherThread.h> #include <src/pdRemoteProcessDebuggerTCPIPConnectionWaiterThread.h> // Remote Debugging Server: #include <AMDTRemoteDebuggingServer/Include/rdStringConstants.h> // TCP/IP timeout: #define PD_REMOTE_DEBUGGING_SERVER_TCP_IP_TIMEOUT OS_CHANNEL_INFINITE_TIME_OUT // The timeout for the communication channel with the remote agent (in milliseconds): #define PD_REMOTE_DEBUGGING_SERVER_TCP_IP_CONNECTION_WAIT_TIMEOUT_MS 1500 // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::pdRemoteProcessDebugger // Description: Constructor // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- pdRemoteProcessDebugger::pdRemoteProcessDebugger() : _pRemoteDebuggingServerAPIChannel(nullptr), _pRemoteDebuggingEventsAPIChannel(nullptr), _pEventsListenerThread(nullptr), _pServerWatcherThread(nullptr), _pDebuggedProcessCreationData(nullptr), _pRemoteDebuggedProcessCreationData(nullptr), _connectionMethod(PD_REMOTE_DEBUGGING_SERVER_NOT_CONNECTED), m_pDaemonClient(nullptr), m_daemonConnectionPort(0), m_pLocalLogFilePath(nullptr), _debuggedProcessExists(false), _debuggedProcessSuspended(false), _isDebugging64BitApplication(false), m_isSpiesAPIThreadRunning(false) { } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::~pdRemoteProcessDebugger // Description: Destructor // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- pdRemoteProcessDebugger::~pdRemoteProcessDebugger() { initialize(); StopEventListener(); if (_pServerWatcherThread != nullptr) { _pServerWatcherThread->stopMonitoringDebuggingServer(); delete _pServerWatcherThread; _pServerWatcherThread = nullptr; } if (_pRemoteDebuggingServerAPIChannel != nullptr) { delete _pRemoteDebuggingServerAPIChannel; _pRemoteDebuggingServerAPIChannel = nullptr; } if (_pRemoteDebuggingEventsAPIChannel != nullptr) { delete _pRemoteDebuggingEventsAPIChannel; _pRemoteDebuggingEventsAPIChannel = nullptr; } } void pdRemoteProcessDebugger::StopEventListener() { if (_pEventsListenerThread != nullptr) { _pEventsListenerThread->setEventsChannel(nullptr); _pEventsListenerThread->stopListening(); delete _pEventsListenerThread; _pEventsListenerThread = nullptr; } } //////////////////////////////////////////////////////////////////////////// /// \brief Do host debugger (gdb, VS, etc..) initialization prerequestics /// /// \param processCreationData a data needed for the process debugger creation and initailization /// \return true - success, false - failed /// \author <NAME> /// \date 21/01/2016 bool pdRemoteProcessDebugger::initializeDebugger(const apDebugProjectSettings& processCreationData) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger initializing debug session", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; bool connectionEstablished = false; m_isSpiesAPIThreadRunning = false; // We default to 32-bit apps: _isDebugging64BitApplication = false; // Is this truly a remote target, or is it "local" remote debugging - via a shared memory object? if (processCreationData.isRemoteTarget()) { const gtString& remoteTargetHostname = processCreationData.remoteTargetName(); GT_IF_WITH_ASSERT(!remoteTargetHostname.isEmpty()) { // Get the daemon connection port: gtUInt16 daemonConnectionPortNumber = processCreationData.remoteTargetDaemonConnectionPort(); osPortAddress daemonConnectionPort(remoteTargetHostname, daemonConnectionPortNumber); connectionEstablished = launchRemoteDebuggingServerOnRemoteMachine(daemonConnectionPort, processCreationData.remoteTargetConnectionPort(), processCreationData.remoteTargetEventsPort()); if (_pServerWatcherThread == nullptr) { _pServerWatcherThread = new pdRemoteProcessDebuggerDebuggingServerWatcherThread(); _pServerWatcherThread->execute(); } } } else // !processCreationData.isRemoteTarget() { // Open a pipe socket server to connect with the remote debugging server: gtString sharedMemObjectName = createSharedMemoryObjectPipeServer(); GT_IF_WITH_ASSERT(!sharedMemObjectName.isEmpty()) { gtString eventsPipeSharedMemObjName = createEventsSharedMemoryObjectPipeServer(); GT_IF_WITH_ASSERT(!eventsPipeSharedMemObjName.isEmpty()) { connectionEstablished = launchRemoteDebuggingServerOnLocalMachine(sharedMemObjectName, eventsPipeSharedMemObjName); } } } GT_IF_WITH_ASSERT(connectionEstablished && (_pRemoteDebuggingServerAPIChannel != nullptr) && (_pRemoteDebuggingEventsAPIChannel != nullptr)) { // Create and run the events listener thread, if it doesn't exist yet: if (_pEventsListenerThread == nullptr) { _pEventsListenerThread = new pdRemoteProcessDebuggerEventsListenerThread; _pEventsListenerThread->execute(); } // Set it to listen to the pipe we created: _pEventsListenerThread->setEventsChannel(_pRemoteDebuggingEventsAPIChannel); // Start listening to events: _pEventsListenerThread->startListening(); // Log the debugged process creation data: _pDebuggedProcessCreationData = new apDebugProjectSettings(processCreationData); *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_INITIALIZE_PROCESS_DEBUGGER_CMD; bool rcCreationData = _pDebuggedProcessCreationData->writeSelfIntoChannel(*_pRemoteDebuggingServerAPIChannel); GT_ASSERT(rcCreationData); *_pRemoteDebuggingServerAPIChannel >> retVal; if (retVal) { _pRemoteDebuggedProcessCreationData = new apDebugProjectSettings(processCreationData); _pRemoteDebuggedProcessCreationData->readSelfFromChannel(*_pRemoteDebuggingServerAPIChannel); } } if (!retVal) { // Launching the debugged process failed, close the connections we opened initialize(); } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended initializing debug session", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::launchDebuggedProcess // Description: Launch a process for a debug session. // Arguments: processCreationData - Contains the data of the process to be launched. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::launchDebuggedProcess() { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger launching debugged process", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT((nullptr != _pRemoteDebuggingServerAPIChannel) && (nullptr != _pRemoteDebuggingEventsAPIChannel)) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_LAUNCH_DEBUGGED_PROCESS_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; // Ask the remote debugging server if this is a 64-bit application: *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_IS_DEBUGGING_64_BIT_APPLICATION_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; if (retVal) { *_pRemoteDebuggingServerAPIChannel >> _isDebugging64BitApplication; } } if (!retVal) { // Launching the debugged process failed, close the connections we opened initialize(); } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended launching debugged process", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::doesSupportTwoStepLaunching // Description: Returns true iff the remote process debugger implements the // launchDebuggedProcessInSuspendedMode and // continueDebuggedProcessFromSuspendedCreation functions. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 11/4/2011 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::doesSupportTwoStepLaunching() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger support two step launch?", OS_DEBUG_LOG_EXTENSIVE); // TO_DO: when we support REAL remote debugging, this should be retrieved from the debugging server: return true; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::launchDebuggedProcessInSuspendedMode // Description: Creates the debugged process but does not start its run. When // this function returns, debuggedProcessId() has a valid value. // Arguments: const apDebugProjectSettings& processCreationData // Return Val: bool - Success / failure. // Author: <NAME> // Date: 11/4/2011 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::launchDebuggedProcessInSuspendedMode() { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger launching debugged process in suspended mode", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT((nullptr != _pRemoteDebuggingServerAPIChannel) && (nullptr != _pRemoteDebuggingEventsAPIChannel)) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_LAUNCH_DEBUGGED_PROCESS_IN_SUSPENDED_MODE_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; // Ask the remote debugging server if this is a 64-bit application: *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_IS_DEBUGGING_64_BIT_APPLICATION_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; if (retVal) { *_pRemoteDebuggingServerAPIChannel >> _isDebugging64BitApplication; } } if (!retVal) { // Launching the debugged process failed, close the connections we opened initialize(); } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended launching debugged process in suspended mode", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::continueDebuggedProcessFromSuspendedCreation // Description: Completes the debugged process launching after // launchDebuggedProcessInSuspendedMode, by starting the debugged // process run. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 11/4/2011 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::continueDebuggedProcessFromSuspendedCreation() { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger continue debugged process from suspended creation", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_CONTINUE_DEBUGGED_PROCESS_FROM_SUSPENDED_CREATION_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended continue debugged process from suspended creation", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::debuggedProcessExists // Description: Returns true iff a debugged process exists. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::debuggedProcessExists() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger debugged process exists?", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; /* // Uri, 18/8/09: This code causes slowdown as this function is queried very // often. It DOES work (and the other side is implementer in the remote // debugging server - but we use a caching mechanism instead. GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_DEBUGGED_PROCESS_EXISTS_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; } */ retVal = _debuggedProcessExists; return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::debuggedProcessCreationData // Description: Returns the data used for launching the debugged process. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- const apDebugProjectSettings* pdRemoteProcessDebugger::debuggedProcessCreationData() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get debugged process creation data", OS_DEBUG_LOG_EXTENSIVE); return _pDebuggedProcessCreationData; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::serverSideDebuggedProcessCreationData // Description: Returns the process creation data, as processed by the remote debugger // Author: <NAME> // Date: 29/8/2013 // --------------------------------------------------------------------------- const apDebugProjectSettings* pdRemoteProcessDebugger::serverSideDebuggedProcessCreationData() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get server-side debugged process creation data", OS_DEBUG_LOG_EXTENSIVE); return _pRemoteDebuggedProcessCreationData; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::terminateDebuggedProcess // Description: Terminates the debugged process. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::terminateDebuggedProcess() { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger terminating debugged process", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_TERMINATE_DEBUGGED_PROCESS_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended terminating debugged process", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::isDebugging64BitApplication // Description: Query whether the debugged application is a 64-bit application. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 21/9/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::isDebugging64BitApplication(bool& is64Bit) const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger is debugged process 64 bit?", OS_DEBUG_LOG_EXTENSIVE); bool retVal = true; is64Bit = _isDebugging64BitApplication; return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::amountOfDebuggedProcessThreads // Description: Returns the amount of debugged process threads. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- int pdRemoteProcessDebugger::amountOfDebuggedProcessThreads() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get amount of debugged process thread", OS_DEBUG_LOG_EXTENSIVE); int retVal = 0; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_AMOUNT_OF_DEBUGGED_PROCESS_THREADS_CMD; gtInt32 retValAsInt32 = 0; *_pRemoteDebuggingServerAPIChannel >> retValAsInt32; retVal = (int)retValAsInt32; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended getting amount of debugged process threads", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::getThreadId // Description: Gets an OS thread Id from the internal thread index. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::getThreadId(int threadIndex, osThreadId& threadId) const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get thread id", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_GET_THREAD_ID_CMD; *_pRemoteDebuggingServerAPIChannel << (gtInt32)threadIndex; *_pRemoteDebuggingServerAPIChannel >> retVal; if (retVal) { gtUInt64 threadIdAsUInt64 = (gtUInt64)OS_NO_THREAD_ID; *_pRemoteDebuggingServerAPIChannel >> threadIdAsUInt64; threadId = (osThreadId)threadIdAsUInt64; } } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended getting thread id", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::setSpiesAPIThreadId // Description: Sets the spy API thread Id // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::setSpiesAPIThreadId(osThreadId spiesAPIThreadId) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger set server API thread id", OS_DEBUG_LOG_EXTENSIVE); GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_SET_SPY_API_THREAD_ID_CMD; *_pRemoteDebuggingServerAPIChannel << (gtUInt64)spiesAPIThreadId; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended set server API thread id", OS_DEBUG_LOG_EXTENSIVE); } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::spiesAPIThreadIndex // Description: Gets the internal index of the spies API thread. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- int pdRemoteProcessDebugger::spiesAPIThreadIndex() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get server API thread index", OS_DEBUG_LOG_EXTENSIVE); int retVal = -1; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_SPIES_API_THREAD_INDEX_CMD; gtInt32 threadIndexAsInt32 = -1; *_pRemoteDebuggingServerAPIChannel >> threadIndexAsInt32; retVal = (int)threadIndexAsInt32; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended getting server API thread index", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::mainThreadId // Description: Gets the Thread Id of the debugged application's main thread. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- osThreadId pdRemoteProcessDebugger::mainThreadId() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get main thread id", OS_DEBUG_LOG_EXTENSIVE); osThreadId retVal = OS_NO_THREAD_ID; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_MAIN_THREAD_ID_CMD; gtUInt64 threadIdAsUInt64 = GT_UINT64_MAX; *_pRemoteDebuggingServerAPIChannel >> threadIdAsUInt64; retVal = (osThreadId)threadIdAsUInt64; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended getting main thread id", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::spiesAPIThreadId // Description: Gets the thread Id of the spies API thread // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- osThreadId pdRemoteProcessDebugger::spiesAPIThreadId() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get server API thread id", OS_DEBUG_LOG_EXTENSIVE); osThreadId retVal = OS_NO_THREAD_ID; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_SPIES_API_THREAD_ID_CMD; gtUInt64 threadIdAsUInt64 = GT_UINT64_MAX; *_pRemoteDebuggingServerAPIChannel >> threadIdAsUInt64; retVal = (osThreadId)threadIdAsUInt64; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended getting server API thread id", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::debuggedProcessId // Description: Returns the debugged process ID. // Author: <NAME> // Date: 16/9/2010 // --------------------------------------------------------------------------- osProcessId pdRemoteProcessDebugger::debuggedProcessId() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get debugged process id", OS_DEBUG_LOG_EXTENSIVE); osProcessId retVal = 0; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_DEBUGGED_PROCESS_ID_CMD; gtUInt64 processIdAsUInt64 = GT_UINT64_MAX; *_pRemoteDebuggingServerAPIChannel >> processIdAsUInt64; retVal = (osThreadId)processIdAsUInt64; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended getting debugged process id", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::isSpiesAPIThreadRunning // Description: Queries whether the spies API thread is running // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::isSpiesAPIThreadRunning() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get is server API thread running", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; // If the debugged process doesn't exist, it certainly can't be connected: if (_debuggedProcessExists) { retVal = m_isSpiesAPIThreadRunning; // If we did not yet detect the Spies API thread as running, query again: if (!m_isSpiesAPIThreadRunning) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get is server API thread running from remote debugging server", OS_DEBUG_LOG_EXTENSIVE); GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_IS_SPY_API_THREAD_RUNNING_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; } // If there was a change: if (retVal) { // Update the cache member: ((pdRemoteProcessDebugger*)this)->m_isSpiesAPIThreadRunning = retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended getting is server API thread running from remote debugging server", OS_DEBUG_LOG_EXTENSIVE); } } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended getting is server API thread running", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::suspendDebuggedProcess // Description: Suspends the debugged process // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::suspendDebuggedProcess() { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger suspending debugged process", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_SUSPEND_DEBUGGED_PROCESS_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended suspending debugged process", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::resumeDebuggedProcess // Description: Resumes the debugged process run // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::resumeDebuggedProcess() { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger resuming debugged process", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_RESUME_DEBUGGED_PROCESS_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended resuming debugged process", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::isDebuggedProcssSuspended // Description: Queries whether the debugged process is suspended // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::isDebuggedProcssSuspended() { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger is debugged process suspended?", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; /* // Uri, 18/8/09: This code causes slowdown as this function is queried very // often. It DOES work (and the other side is implementer in the remote // debugging server - but we use a caching mechanism instead. GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_IS_DEBUGGED_PROCESS_SUSPENDED_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; } */ retVal = _debuggedProcessSuspended; return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::suspendDebuggedProcessThread // Description: Suspends a debugged process thread // Return Val: bool - Success / failure. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::suspendDebuggedProcessThread(osThreadId threadId) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger suspending debugged process thread", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_SUSPEND_DEBUGGED_PROCESS_THREAD_CMD; *_pRemoteDebuggingServerAPIChannel << (gtUInt64)threadId; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended suspending debugged process thread", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::resumeDebuggedProcessThread // Description: Resume a debugged process thread // Return Val: bool - Success / failure. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::resumeDebuggedProcessThread(osThreadId threadId) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger resuming debugged process thread", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_RESUME_DEBUGGED_PROCESS_THREAD_CMD; *_pRemoteDebuggingServerAPIChannel << (gtUInt64)threadId; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended resuming debugged process thread", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::getDebuggedThreadCallStack // Description: Gets the debugged thread's current calls stack // Return Val: bool - Success / failure. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::getDebuggedThreadCallStack(osThreadId threadId, osCallStack& callStack, bool hideSpyDLLsFunctions) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get thread call stack", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_GET_DEBUGGED_THREAD_CALL_STACK_CMD; *_pRemoteDebuggingServerAPIChannel << (gtUInt64)threadId; *_pRemoteDebuggingServerAPIChannel << hideSpyDLLsFunctions; *_pRemoteDebuggingServerAPIChannel >> retVal; if (retVal) { callStack.readSelfFromChannel(*_pRemoteDebuggingServerAPIChannel); } } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended getting thread call stack", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::fillCallsStackDebugInfo // Description: Fills a calls stack's debug info // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::fillCallsStackDebugInfo(osCallStack& callStack, bool hideSpyDLLsFunctions) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger filling call stack debug info", OS_DEBUG_LOG_EXTENSIVE); GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_FILL_CALL_STACK_DEBUG_INFO_CMD; bool rcStack = callStack.writeSelfIntoChannel(*_pRemoteDebuggingServerAPIChannel); *_pRemoteDebuggingServerAPIChannel << hideSpyDLLsFunctions; GT_ASSERT(rcStack); rcStack = callStack.readSelfFromChannel(*_pRemoteDebuggingServerAPIChannel); GT_ASSERT(rcStack); } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended filling call stack debug info", OS_DEBUG_LOG_EXTENSIVE); } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::fillThreadCreatedEvent // Description: Fills a thread created event // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::fillThreadCreatedEvent(apThreadCreatedEvent& eve) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger filling thread created event", OS_DEBUG_LOG_EXTENSIVE); GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_FILL_THERAD_CREATED_EVENT_CMD; bool rcEvent = eve.writeSelfIntoChannel(*_pRemoteDebuggingServerAPIChannel); GT_ASSERT(rcEvent); rcEvent = eve.readSelfFromChannel(*_pRemoteDebuggingServerAPIChannel); GT_ASSERT(rcEvent); } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended filling thread created event", OS_DEBUG_LOG_EXTENSIVE); } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::canGetCallStacks // Description: Query whether this process debugger can get debugged process // calls stacks by itself (without the API // Author: <NAME> // Date: 25/1/2010 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::canGetCallStacks() { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger can get call stacks?", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; // Any process debugger may be implemented on the debugging server side, so // we need to query the remote debugging server: GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_CAN_GET_CALL_STACKS_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended querying can get call stacks", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::canMakeThreadExecuteFunction // Description: Returns whether this process debugger implementation supports // the "make thread execute function" mechanism. // Author: <NAME> // Date: 2/11/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::canMakeThreadExecuteFunction(const osThreadId& threadId) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger can make thread execute function?", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; // Any process debugger may be implemented on the debugging server side, so // we need to query the remote debugging server: GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_CAN_MAKE_THREAD_EXECUTE_FUNCTION_CMD; *_pRemoteDebuggingServerAPIChannel << (gtUInt64)threadId; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended querying can make thread execute function", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::makeThreadExecuteFunction // Description: Makes a debugged process thread execute a given function // Return Val: bool - Success / failure. // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::makeThreadExecuteFunction(const osThreadId& threadId, osProcedureAddress64 funcAddress) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger making thread execute function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_MAKE_THREAD_EXECUTE_FUNCTION_CMD; *_pRemoteDebuggingServerAPIChannel << (gtUInt64)threadId; *_pRemoteDebuggingServerAPIChannel << (gtUInt64)funcAddress; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended making thread execute function", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::functionExecutionMode // Description: // Return Val: pdProcessDebugger::FunctionExecutionMode // Author: <NAME> // Date: 12/2/2010 // --------------------------------------------------------------------------- pdProcessDebugger::FunctionExecutionMode pdRemoteProcessDebugger::functionExecutionMode() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get function execution mode", OS_DEBUG_LOG_EXTENSIVE); FunctionExecutionMode retVal = pdProcessDebugger::functionExecutionMode(); GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_FUNCTION_EXECUTION_MODE_CMD; gtUInt32 executionModeAsUInt32 = (gtUInt32)retVal; *_pRemoteDebuggingServerAPIChannel >> executionModeAsUInt32; retVal = (FunctionExecutionMode)executionModeAsUInt32; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended getting function execution mode", OS_DEBUG_LOG_EXTENSIVE); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::afterAPICallIssued // Description: Run after an API Call is issued // Author: <NAME> // Date: 11/8/2009 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::afterAPICallIssued() { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger after API call issued", OS_DEBUG_LOG_EXTENSIVE); GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_AFTER_API_CALL_ISSUED_CMD; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended after API call issued", OS_DEBUG_LOG_EXTENSIVE); } // --------------------------------------------------------------------------- // Name: pdProcessDebugger::setLocalLogFileDirectory // Description: Sets the log file path for acquiring remote files. // Note that is is not passed to the remote debugger, as the path // is (by definition) on the local machine. // Author: <NAME> // Date: 23/10/2013 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::setLocalLogFileDirectory(const osFilePath& localLogFilePath) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger setting local log file path", OS_DEBUG_LOG_EXTENSIVE); if (nullptr != m_pLocalLogFilePath) { delete m_pLocalLogFilePath; m_pLocalLogFilePath = nullptr; } m_pLocalLogFilePath = new osFilePath(localLogFilePath); GT_ASSERT(nullptr != m_pLocalLogFilePath); } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::remoteToLocalFilePath // Description: Pulls in a file from a remote host. For Daemon connection, // It then copies over the file using the daemon. // Author: <NAME> // Date: 30/9/2013 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::remoteToLocalFilePath(osFilePath& io_filePath, bool useCache) const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger remote to local file path", OS_DEBUG_LOG_EXTENSIVE); GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_TO_LOCAL_FILE_PATH_CMD; *_pRemoteDebuggingServerAPIChannel << useCache; // Send the original file path: io_filePath.writeSelfIntoChannel(*_pRemoteDebuggingServerAPIChannel); // Get the (possibly modified) file path back: io_filePath.readSelfFromChannel(*_pRemoteDebuggingServerAPIChannel); } if (nullptr != m_pDaemonClient) { bool getFile = true; // Search for the file path in the cache, if requested: if (useCache) { gtMap<gtString, osFilePath>::const_iterator findIter = m_remoteToLocalFilePathCache.find(io_filePath.asString()); gtMap<gtString, osFilePath>::const_iterator endIter = m_remoteToLocalFilePathCache.end(); if (findIter != endIter) { // We have a cache hit! OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger remote to local file path cache hit", OS_DEBUG_LOG_EXTENSIVE); getFile = false; io_filePath = findIter->second; } } if (getFile) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger remote to local file path getting via daemon", OS_DEBUG_LOG_EXTENSIVE); GT_IF_WITH_ASSERT(m_pDaemonClient->IsInitialized(m_daemonConnectionPort)) { // Construct the local file path: osFilePath localFilePath(osFilePath::OS_TEMP_DIRECTORY); if (nullptr != m_pLocalLogFilePath) { localFilePath = *m_pLocalLogFilePath; localFilePath.reinterpretAsDirectory(); } else // nullptr == m_pLocalLogFilePath { GT_IF_WITH_ASSERT(nullptr != _pDebuggedProcessCreationData) { localFilePath = _pDebuggedProcessCreationData->logFilesFolder().directoryPath(); localFilePath.reinterpretAsDirectory(); } } // Copy the file name and extension: localFilePath.setFromOtherPath(io_filePath, false, true, true); // Get the file: bool rcFl = m_pDaemonClient->GetRemoteFile(io_filePath.asString(), localFilePath.asString(), false, nullptr, nullptr); if (rcFl) { // Add this to the cache (we add files to the cache even if we didn't request them there, since // it's a fairly "cheap" operation): ((pdRemoteProcessDebugger*)this)->m_remoteToLocalFilePathCache[io_filePath.asString()] = localFilePath; io_filePath = localFilePath; } } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger remote to local file path finished getting via daemon", OS_DEBUG_LOG_EXTENSIVE); } } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger remote to local file path ended", OS_DEBUG_LOG_EXTENSIVE); } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::onEvent // Description: Called when a debugged process event occurs: // Author: <NAME> // Date: 12/8/2009 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::onEvent(const apEvent& eve, bool& vetoEvent) { // Unused parameters (void)vetoEvent; apEvent::EventType eveType = eve.eventType(); switch (eveType) { case apEvent::AP_DEBUGGED_PROCESS_TERMINATED: { // The debugged process was terminated, kill the debugging server: GT_IF_WITH_ASSERT(_pServerWatcherThread != nullptr) { _pServerWatcherThread->stopMonitoringDebuggingServer(); } } break; default: { // Do nothing } break; } } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::onEventRegistration // Description: Called when a debugged process event is about to be registered, // we use it to update our status and remove duplicate termination events // Author: <NAME> // Date: 18/8/2009 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::onEventRegistration(apEvent& eve, bool& vetoEvent) { apEvent::EventType eveType = eve.eventType(); switch (eveType) { case apEvent::AP_DEBUGGED_PROCESS_TERMINATED: { // Don't let this event get thrown twice: if (!_debuggedProcessExists) { vetoEvent = true; } else { // Note the debugged process doesn't exist: delete m_pLocalLogFilePath; m_pLocalLogFilePath = nullptr; m_remoteToLocalFilePathCache.clear(); _debuggedProcessExists = false; _debuggedProcessSuspended = false; m_isSpiesAPIThreadRunning = false; if (nullptr != _pEventsListenerThread) { _pEventsListenerThread->stopListening(); } // If the daemon connection exists, we can close it now: cleanupDaemonConnection(); } } break; case apEvent::AP_DEBUGGED_PROCESS_CREATION_FAILURE: { if (nullptr != _pEventsListenerThread) { _pEventsListenerThread->stopListening(); } // If the daemon connection exists, we can close it now: cleanupDaemonConnection(); } break; case apEvent::AP_DEBUGGED_PROCESS_CREATED: { // Note the debugged process exists: m_remoteToLocalFilePathCache.clear(); _debuggedProcessExists = true; _debuggedProcessSuspended = false; m_isSpiesAPIThreadRunning = false; } break; case apEvent::AP_BREAKPOINT_HIT: { _debuggedProcessSuspended = true; } break; case apEvent::AP_DEBUGGED_PROCESS_RUN_SUSPENDED: { _debuggedProcessSuspended = true; } break; case apEvent::AP_DEBUGGED_PROCESS_RUN_RESUMED: { _debuggedProcessSuspended = false; } break; case apEvent::AP_BEFORE_KERNEL_DEBUGGING_EVENT: case apEvent::AP_AFTER_KERNEL_DEBUGGING_EVENT: { // These need to pass to the remote debugging server at registration time: passDebugEventToRemoteDebuggingServer(eve); } break; case apEvent::AP_THREAD_TERMINATED: { // If a thread stopped running, it may have been the API thread. Mark as not running it so that it is updated on the next query: m_isSpiesAPIThreadRunning = false; } break; default: { // Do nothing } break; } } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::isRemoteDebuggingServerAlive // Description: Checks if the local / remote RDS exists and returns the answer. // The answer is whether AT LEAST ONE of the requested RDSes running. // Author: <NAME> // Date: 16/10/2013 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::isRemoteDebuggingServerAlive(bool checkLocal, bool checkRemote) { bool retVal = false; bool rcLoc = false; bool rcRem = false; // Local RDS: if (checkLocal) { // If we have a local server, we have a server watcher thread: if (nullptr != _pServerWatcherThread) { // Is the thread currently monitoring anything? rcLoc = _pServerWatcherThread->isMonitoringRemoteDebuggingServer(); } } // Remote RDS: if (checkRemote) { // Sanity check: if (nullptr != m_pDaemonClient) { // If we've connected: if (m_pDaemonClient->IsInitialized(m_daemonConnectionPort)) { // Request the status: DaemonSessionStatus rdsStatus = dssSessionStatusCount; bool rcStat = m_pDaemonClient->GetSessionStatus(romDEBUG, rdsStatus); if (rcStat && (dssAlive == rdsStatus)) { // The remote target RDS is running: rcRem = true; } } } } retVal = (checkLocal && rcLoc) || (checkRemote && rcRem); return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::passDebugEventToRemoteDebuggingServer // Description: Used to pass debug events to the remote debugging server, usually // these are events from the spy event listener thread that are // relevant to the process debugger. // Author: <NAME> // Date: 26/6/2011 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::passDebugEventToRemoteDebuggingServer(const apEvent& eve) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger passing debugged process event to remote debugging server", OS_DEBUG_LOG_EXTENSIVE); GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_HANDLE_DEBUG_EVENT; *_pRemoteDebuggingServerAPIChannel << (const osTransferableObject&)eve; bool retVal = false; *_pRemoteDebuggingServerAPIChannel >> retVal; GT_ASSERT(retVal); } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger ended passing debugged process event to remote debugging server", OS_DEBUG_LOG_EXTENSIVE); } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::createSharedMemoryObjectPipeServer // Description: Creates a shared memory object pipe server used for debugging commands, and // returns its file path as a string (or an empty string on failure) // Author: <NAME> // Date: 12/8/2009 // --------------------------------------------------------------------------- gtString pdRemoteProcessDebugger::createSharedMemoryObjectPipeServer() { gtString retVal; // Get the temp directory and the current time and date, to construct the shared memory object name: osFilePath tempDir(osFilePath::OS_TEMP_DIRECTORY); osTime now; now.setFromCurrentTime(); gtString dateStr; gtString timeStr; now.dateAsString(dateStr, osTime::UNDERSCORE_SAPERATOR, osTime::LOCAL); now.timeAsString(timeStr, osTime::UNDERSCORE_SAPERATOR, osTime::LOCAL); // Create the shared object's full path: gtString uniqueSharedObjectName = tempDir.asString(); uniqueSharedObjectName.append(osFilePath::osPathSeparator); uniqueSharedObjectName.append(PD_STR_remoteProcessDebuggerSharedMemoryObject); uniqueSharedObjectName.append('-'); uniqueSharedObjectName.append(dateStr); uniqueSharedObjectName.append('-'); uniqueSharedObjectName.append(timeStr); // Create the pipe server: osPipeSocketServer* pPipeSocketServer = new osPipeSocketServer(uniqueSharedObjectName); GT_IF_WITH_ASSERT(pPipeSocketServer != nullptr) { // Open it: bool rcPipeServer = pPipeSocketServer->open(); GT_IF_WITH_ASSERT(rcPipeServer) { // Return the success values: _pRemoteDebuggingServerAPIChannel = pPipeSocketServer; _connectionMethod = PD_REMOTE_DEBUGGING_SHARED_MEMORY_OBJECT; retVal = uniqueSharedObjectName; } } return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::createEventsSharedMemoryObjectPipeServer // Description: Creates a shared memory object pipe server used for events, and // returns its file path as a string (or an empty string on failure) // Author: <NAME> // Date: 12/8/2009 // --------------------------------------------------------------------------- gtString pdRemoteProcessDebugger::createEventsSharedMemoryObjectPipeServer() { gtString retVal; // Get the temp directory and the current time and date, to construct the shared memory object name: osFilePath tempDir(osFilePath::OS_TEMP_DIRECTORY); osTime now; now.setFromCurrentTime(); gtString dateStr; gtString timeStr; now.dateAsString(dateStr, osTime::UNDERSCORE_SAPERATOR, osTime::LOCAL); now.timeAsString(timeStr, osTime::UNDERSCORE_SAPERATOR, osTime::LOCAL); // Create the shared object's full path: gtString uniqueSharedObjectName = tempDir.asString(); uniqueSharedObjectName.append(osFilePath::osPathSeparator); uniqueSharedObjectName.append(PD_STR_remoteProcessDebuggerEventsSharedMemoryObject); uniqueSharedObjectName.append('-'); uniqueSharedObjectName.append(dateStr); uniqueSharedObjectName.append('-'); uniqueSharedObjectName.append(timeStr); // Create the pipe server: osPipeSocketServer* pPipeSocketServer = new osPipeSocketServer(uniqueSharedObjectName); GT_IF_WITH_ASSERT(pPipeSocketServer != nullptr) { // Open it: bool rcPipeServer = pPipeSocketServer->open(); GT_IF_WITH_ASSERT(rcPipeServer) { _pRemoteDebuggingEventsAPIChannel = pPipeSocketServer; retVal = uniqueSharedObjectName; } } return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::launchRemoteDebuggingServerOnLocalMachine // Description: Launches the remote debugging server on the local machine using the // given shared memory object names and starts a thread to watch it. // Return Val: bool - Success / failure. // Author: <NAME> // Date: 12/8/2009 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::launchRemoteDebuggingServerOnLocalMachine(const gtString& sharedMemObj, const gtString& eventsSharedMemObj) { // Unused parameters: (void)sharedMemObj; (void)eventsSharedMemObj; bool retVal = false; #if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS // Currently, the only supported local debugging server is the 64-bit debugging server: osFilePath remoteDebuggingServerExecutable; bool rcPath = true; bool isDllsDirSet = osGetCurrentApplicationDllsPath(remoteDebuggingServerExecutable); if (!isDllsDirSet) { rcPath = osGetCurrentApplicationPath(remoteDebuggingServerExecutable); } GT_IF_WITH_ASSERT(rcPath) { remoteDebuggingServerExecutable.setFileName(PD_STR_remoteDebuggingServer64ExecutableFileName); // The first command line argument must be the executable path: gtString commandLineArgs = remoteDebuggingServerExecutable.asString(); commandLineArgs.append('\"').prepend('\"'); gtString workDir; osDirectory executableDir; remoteDebuggingServerExecutable.getFileDirectory(executableDir); workDir = executableDir.directoryPath().asString(); // Initialize the output structs: STARTUPINFO startupInfo = {0}; PROCESS_INFORMATION processInfo = {0}; // Set the environment variables used by the server process: osEnvironmentVariable debuggingMode, sharedMemObjName, eventsSharedMemObjName, debugLogSeverity; debuggingMode._name = RD_STR_DebuggingModeEnvVar; debuggingMode._value = RD_STR_DebuggingModeSharedMemoryObject; sharedMemObjName._name = RD_STR_SharedMemoryObjectNameEnvVar; sharedMemObjName._value = sharedMemObj; eventsSharedMemObjName._name = RD_STR_EventsSharedMemoryObjectNameEnvVar; eventsSharedMemObjName._value = eventsSharedMemObj; debugLogSeverity._name = RD_STR_DebugLogSeverityEnvVar; debugLogSeverity._value = osDebugLogSeverityToString(osDebugLog::instance().loggedSeverity()); osSetCurrentProcessEnvVariable(debuggingMode); osSetCurrentProcessEnvVariable(sharedMemObjName); osSetCurrentProcessEnvVariable(eventsSharedMemObjName); osSetCurrentProcessEnvVariable(debugLogSeverity); // Create the server process: int rc = CreateProcess(nullptr, // Specify the path in the Command line arguments (LPWSTR)commandLineArgs.asCharArray(), // Command line arguments nullptr, // Default process security attributes nullptr, // Default thread security attributes FALSE, // Don't inherit handles CREATE_NEW_CONSOLE, // Don't debug this process - if we try to, the command will fail. // Also, this is a console app - run it without a visible console. nullptr, // Environment (LPWSTR)workDir.asCharArray(), // Work dir &startupInfo, // Pointer to STARTUPINFO structure. &processInfo); // Pointer to PROCESS_INFORMATION structure. retVal = (rc != 0); if (!retVal) { DWORD errCode = ::GetLastError(); gtString rdsErr = L"Could not launch Remote Debugging Server. Error code:"; rdsErr.appendFormattedString(L"%#x", errCode); GT_ASSERT_EX(retVal, rdsErr.asCharArray()); } // Clear the environment variables: osRemoveCurrentProcessEnvVariable(RD_STR_DebuggingModeEnvVar); osRemoveCurrentProcessEnvVariable(RD_STR_SharedMemoryObjectNameEnvVar); osRemoveCurrentProcessEnvVariable(RD_STR_EventsSharedMemoryObjectNameEnvVar); osRemoveCurrentProcessEnvVariable(RD_STR_DebugLogSeverityEnvVar); GT_IF_WITH_ASSERT(retVal) { osPipeSocketServer* pSocketServer = (osPipeSocketServer*)_pRemoteDebuggingServerAPIChannel; GT_IF_WITH_ASSERT(pSocketServer != nullptr) { // Wait for a client connection, so we will be synchronized with the debugging server: pSocketServer->waitForClientConnection(); } osPipeSocketServer* pEventsSocketServer = (osPipeSocketServer*)_pRemoteDebuggingEventsAPIChannel; GT_IF_WITH_ASSERT(pEventsSocketServer != nullptr) { // Wait for a client connection, so we will be synchronized with the debugging server: pEventsSocketServer->waitForClientConnection(); } // Create the server watcher thread if needed: if (_pServerWatcherThread == nullptr) { _pServerWatcherThread = new pdRemoteProcessDebuggerDebuggingServerWatcherThread; _pServerWatcherThread->execute(); } // Monitor the debugging server: _pServerWatcherThread->monitorLocalMachineDebuggingServer(processInfo.dwProcessId); } } #endif return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::launchRemoteDebuggingServerOnRemoteMachine // Description: Connects to the CodeXL daemon on the remote machine, and establishes // two connections with the target machine // Author: <NAME> // Date: 7/8/2013 // --------------------------------------------------------------------------- bool pdRemoteProcessDebugger::launchRemoteDebuggingServerOnRemoteMachine(const osPortAddress& daemonConnectionPort, gtUInt16 remoteDebuggingConnectionPortNumber, gtUInt16 remoteDebuggingEventsPortNumber) { bool retVal = false; // This flag indicates whether the handshake result is match (true) or mismatch (false). bool isHandshakeMatch = false; // This flag indicates whether the handshake execution succeeded. bool isHandshakeSucesss = false; // This var will hold the handshake error message (if any). gtString handshakeErrMsg; #if ((AMDT_BUILD_TARGET == AMDT_WINDOWS_OS) && (AMDT_ADDRESS_SPACE_TYPE == AMDT_64_BIT_ADDRESS_SPACE)) // This should not be called in the 64-bit windows version of this project! GT_ASSERT(false); #else // !((AMDT_BUILD_TARGET == AMDT_WINDOWS_OS) && (AMDT_ADDRESS_SPACE_TYPE == AMDT_64_BIT_ADDRESS_SPACE)) // Clean up any previous connections: CXLDaemonClient::Close(); bool rcDae = CXLDaemonClient::Init(daemonConnectionPort, LONG_MAX); CXLDaemonClient* pClient = CXLDaemonClient::GetInstance(); GT_IF_WITH_ASSERT(nullptr != pClient) { GT_IF_WITH_ASSERT(rcDae) { osPortAddress daemonConnectionPortBuffer; rcDae = pClient->ConnectToDaemon(daemonConnectionPortBuffer); GT_IF_WITH_ASSERT(rcDae) { // First, do the handshake: rcDae = isHandshakeSucesss = pClient->PerformHandshake(isHandshakeMatch, handshakeErrMsg); GT_IF_WITH_ASSERT(rcDae) { if (isHandshakeMatch) { // If successful, open two TCP servers for the RDS to connect to: osTCPSocketServer tcpConnectionServer; bool rcCon = tcpConnectionServer.open(); GT_IF_WITH_ASSERT(rcCon) { osPortAddress remoteDebuggingServerConnectionPort(remoteDebuggingConnectionPortNumber, false); rcCon = tcpConnectionServer.bind(remoteDebuggingServerConnectionPort); GT_IF_WITH_ASSERT(rcCon) { rcCon = tcpConnectionServer.listen(1); GT_ASSERT(rcCon); } } osTCPSocketServer tcpEventsServer; bool rcEve = tcpEventsServer.open(); GT_IF_WITH_ASSERT(rcEve) { osPortAddress remoteDebuggingServerEventsPort(remoteDebuggingEventsPortNumber, false); rcEve = tcpEventsServer.bind(remoteDebuggingServerEventsPort); GT_IF_WITH_ASSERT(rcEve) { rcEve = tcpEventsServer.listen(1); GT_ASSERT(rcEve); } } // If both succeeded: if (rcCon && rcEve) { // Wait for a connection on both channels: osTCPSocketServerConnectionHandler* pTCPConnection = new osTCPSocketServerConnectionHandler; pdRemoteProcessDebuggerTCPIPConnectionWaiterThread connectionWaiterThread(*this, tcpConnectionServer, *pTCPConnection); connectionWaiterThread.execute(); osTCPSocketServerConnectionHandler* pTCPEventsConnection = new osTCPSocketServerConnectionHandler; pdRemoteProcessDebuggerTCPIPConnectionWaiterThread eventConnectionWaiterThread(*this, tcpEventsServer, *pTCPEventsConnection); eventConnectionWaiterThread.execute(); // Prepare the environment variables that the remote daemon should set for the RDS. osEnvironmentVariable conTypeVar(RD_STR_DebuggingModeEnvVar, RD_STR_DebuggingModeTCPIPConnection); osEnvironmentVariable conVar; conVar._name = RD_STR_TCPIPConnectionPortEnvVar; conVar._value = daemonConnectionPortBuffer.hostName(); conVar._value.appendFormattedString(L":%u", remoteDebuggingConnectionPortNumber); osEnvironmentVariable eveVar; eveVar._name = RD_STR_EventsTCPIPConnectionPortEnvVar; eveVar._value = daemonConnectionPortBuffer.hostName(); eveVar._value.appendFormattedString(L":%u", remoteDebuggingEventsPortNumber); osEnvironmentVariable logLvlVar; logLvlVar._name = RD_STR_DebugLogSeverityEnvVar; logLvlVar._value = osDebugLogSeverityToString(osDebugLog::instance().loggedSeverity()); std::vector<osEnvironmentVariable> envVars; envVars.push_back(conTypeVar); envVars.push_back(conVar); envVars.push_back(eveVar); envVars.push_back(logLvlVar); rcDae = pClient->LaunchRDS(L"", envVars); GT_IF_WITH_ASSERT(rcDae) { // Save the pointer to the remote client. m_pDaemonClient = pClient; // Wait until both connections are established: rcCon = rcCon && rcEve && connectionWaiterThread.waitForConnection(PD_REMOTE_DEBUGGING_SERVER_TCP_IP_CONNECTION_WAIT_TIMEOUT_MS) && connectionWaiterThread.wasConnectionSuccessful(); rcEve = rcCon && rcEve && eventConnectionWaiterThread.waitForConnection(PD_REMOTE_DEBUGGING_SERVER_TCP_IP_CONNECTION_WAIT_TIMEOUT_MS) && eventConnectionWaiterThread.wasConnectionSuccessful(); GT_IF_WITH_ASSERT(rcCon && rcEve) { _pRemoteDebuggingServerAPIChannel = pTCPConnection; _pRemoteDebuggingServerAPIChannel->setReadOperationTimeOut(PD_REMOTE_DEBUGGING_SERVER_TCP_IP_TIMEOUT); _pRemoteDebuggingServerAPIChannel->setWriteOperationTimeOut(PD_REMOTE_DEBUGGING_SERVER_TCP_IP_TIMEOUT); _pRemoteDebuggingEventsAPIChannel = pTCPEventsConnection; _pRemoteDebuggingEventsAPIChannel->setReadOperationTimeOut(PD_REMOTE_DEBUGGING_SERVER_TCP_IP_TIMEOUT); _pRemoteDebuggingEventsAPIChannel->setWriteOperationTimeOut(PD_REMOTE_DEBUGGING_SERVER_TCP_IP_TIMEOUT); _connectionMethod = PD_REMOTE_DEBUGGING_TCP_IP_CONNECTION; m_daemonConnectionPort = daemonConnectionPort; retVal = true; } else { // Close and delete the connections: pTCPConnection->close(); delete pTCPConnection; pTCPEventsConnection->close(); delete pTCPEventsConnection; } } } } } } } } #endif // ((AMDT_BUILD_TARGET == AMDT_WINDOWS_OS) && (AMDT_ADDRESS_SPACE_TYPE == AMDT_64_BIT_ADDRESS_SPACE)) // If we failed to start debugging, notify the system. if (!retVal) { GT_IF_WITH_ASSERT(nullptr != pClient) { // Make sure that our session is closed. bool isTerminationSuccess = pClient->TerminateWholeSession(); GT_ASSERT_EX(isTerminationSuccess, L"Unable to terminate remote session after faililng to start a remote debugging sessison properly."); } if (isHandshakeSucesss && !isHandshakeMatch) { // It is a handshake failure. apDebuggedProcessCreationFailureEvent processCreationFailedEvent(apDebuggedProcessCreationFailureEvent::REMOTE_HANDSHAKE_MISMATCH, L"", L"", handshakeErrMsg); apEventsHandler::instance().registerPendingDebugEvent(processCreationFailedEvent); } else { // It is some other failure. apDebuggedProcessCreationFailureEvent processCreationFailedEvent(apDebuggedProcessCreationFailureEvent::COULD_NOT_CREATE_PROCESS, L"", L"", L""); apEventsHandler::instance().registerPendingDebugEvent(processCreationFailedEvent); } } return retVal; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::closeSharedMemoryObjectConnections // Description: Closes the shared memory object connections: // Author: <NAME> // Date: 12/8/2009 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::closeSharedMemoryObjectConnections() { osPipeSocketServer* pServerConnection = (osPipeSocketServer*)_pRemoteDebuggingServerAPIChannel; osPipeSocketServer* pEventsConnection = (osPipeSocketServer*)_pRemoteDebuggingEventsAPIChannel; // Close and destroy the server connection: if (pServerConnection != nullptr) { pServerConnection->close(); delete _pRemoteDebuggingServerAPIChannel; _pRemoteDebuggingServerAPIChannel = nullptr; } // Close and destroy the events connection: if (pEventsConnection != nullptr) { pEventsConnection->close(); delete _pRemoteDebuggingEventsAPIChannel; _pRemoteDebuggingEventsAPIChannel = nullptr; } // Mark that we have disconnected: _connectionMethod = PD_REMOTE_DEBUGGING_SERVER_NOT_CONNECTED; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::closeTCPIPConnections // Description: Closes the TCP/IP connections // Author: <NAME> // Date: 29/8/2013 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::closeTCPIPConnections() { osTCPSocketServerConnectionHandler* pServerConnection = (osTCPSocketServerConnectionHandler*)_pRemoteDebuggingServerAPIChannel; osTCPSocketServerConnectionHandler* pEventsConnection = (osTCPSocketServerConnectionHandler*)_pRemoteDebuggingEventsAPIChannel; // Close and destroy the server connection: if (pServerConnection != nullptr) { pServerConnection->close(); delete _pRemoteDebuggingServerAPIChannel; _pRemoteDebuggingServerAPIChannel = nullptr; } // Close and destroy the events connection: if (pEventsConnection != nullptr) { StopEventListener(); pEventsConnection->close(); delete _pRemoteDebuggingEventsAPIChannel; _pRemoteDebuggingEventsAPIChannel = nullptr; } // Close the daemon connection if it was open: cleanupDaemonConnection(); // Mark that we have disconnected: _connectionMethod = PD_REMOTE_DEBUGGING_SERVER_NOT_CONNECTED; } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::cleanupDaemonConnection // Description: Cleans up the daemon connection // Author: <NAME> // Date: 7/10/2013 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::cleanupDaemonConnection() { // Clean up any remote daemon connection: if (m_pDaemonClient != nullptr) { // Close the connection: GT_ASSERT(m_pDaemonClient->IsInitialized(m_daemonConnectionPort)); bool rcTerm = m_pDaemonClient->TerminateWholeSession(); GT_ASSERT(rcTerm); // Do not delete the daemon client, as it is a singleton: // delete m_pDaemonClient; m_pDaemonClient = nullptr; // Close the daemon itself: CXLDaemonClient::Close(); } } // --------------------------------------------------------------------------- // Name: pdRemoteProcessDebugger::initialize // Description: Close all open connections and reset the process debugger // Author: <NAME> // Date: 12/8/2009 // --------------------------------------------------------------------------- void pdRemoteProcessDebugger::initialize() { switch (_connectionMethod) { case PD_REMOTE_DEBUGGING_SERVER_NOT_CONNECTED: { // We are not connected, do nothing: } break; case PD_REMOTE_DEBUGGING_SHARED_MEMORY_OBJECT: { // Close the shared memory object connection: closeSharedMemoryObjectConnections(); } break; case PD_REMOTE_DEBUGGING_TCP_IP_CONNECTION: { // Close the shared memory object connection: closeTCPIPConnections(); } break; default: { // Unknown connection method GT_ASSERT(false); } break; } delete _pDebuggedProcessCreationData; _pDebuggedProcessCreationData = nullptr; delete _pRemoteDebuggedProcessCreationData; _pRemoteDebuggedProcessCreationData = nullptr; // If the server watcher thread is active, kill the debugging server: GT_IF_WITH_ASSERT(_pServerWatcherThread != nullptr) { _pServerWatcherThread->stopMonitoringDebuggingServer(); } delete m_pLocalLogFilePath; m_pLocalLogFilePath = nullptr; m_remoteToLocalFilePathCache.clear(); _debuggedProcessExists = false; _debuggedProcessSuspended = false; _isDebugging64BitApplication = false; m_isSpiesAPIThreadRunning = false; _connectionMethod = PD_REMOTE_DEBUGGING_SERVER_NOT_CONNECTED; } bool pdRemoteProcessDebugger::canGetHostVariables() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger can get host variables function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_CAN_GET_HOST_VARIABLES_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; } if (retVal) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger can get host variables function exit with result true", OS_DEBUG_LOG_EXTENSIVE); } else { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger can get host variables function exit with result false", OS_DEBUG_LOG_EXTENSIVE); } return retVal; } bool pdRemoteProcessDebugger::getHostLocals(osThreadId threadId, int callStackFrameIndex, int evaluationDepth, bool onlyNames, gtVector<apExpression>& o_locals) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get host locals function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_GET_HOST_LOCALS_CMD; *_pRemoteDebuggingServerAPIChannel << (gtUInt64)threadId; *_pRemoteDebuggingServerAPIChannel << (gtInt32)callStackFrameIndex; *_pRemoteDebuggingServerAPIChannel << (gtInt32)evaluationDepth; *_pRemoteDebuggingServerAPIChannel << onlyNames; *_pRemoteDebuggingServerAPIChannel >> retVal; if (retVal) { gtInt32 outputVectorSize = 0; *_pRemoteDebuggingServerAPIChannel >> outputVectorSize; o_locals.resize(outputVectorSize); for (gtInt32 i = 0; i < outputVectorSize; i++) { bool rcVar = o_locals[i].readSelfFromChannel(*_pRemoteDebuggingServerAPIChannel); GT_ASSERT(rcVar); retVal = retVal && rcVar; } } } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get host locals function exit", OS_DEBUG_LOG_EXTENSIVE); return retVal; } bool pdRemoteProcessDebugger::getHostExpressionValue(osThreadId threadId, int callStackFrameIndex, const gtString& expressionText, int evaluationDepth, apExpression& o_exp) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get host expression value function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_GET_HOST_EXPRESSION_VALUE_CMD; *_pRemoteDebuggingServerAPIChannel << (gtUInt64)threadId; *_pRemoteDebuggingServerAPIChannel << (gtInt32)callStackFrameIndex; *_pRemoteDebuggingServerAPIChannel << expressionText; *_pRemoteDebuggingServerAPIChannel << (gtInt32)evaluationDepth; *_pRemoteDebuggingServerAPIChannel >> retVal; if (retVal) { retVal = o_exp.readSelfFromChannel(*_pRemoteDebuggingServerAPIChannel); } } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get host expression value exit", OS_DEBUG_LOG_EXTENSIVE); return retVal; } bool pdRemoteProcessDebugger::canPerformHostDebugging() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger can perform host debugging function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_CAN_PERFORM_HOST_DEBUGGING; *_pRemoteDebuggingServerAPIChannel >> retVal; } if (retVal) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger can perform host debugging function exit with retVal true", OS_DEBUG_LOG_EXTENSIVE); } else { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger can perform host debugging function exit with retVal false", OS_DEBUG_LOG_EXTENSIVE); } return retVal; } bool pdRemoteProcessDebugger::isAtAPIOrKernelBreakpoint(osThreadId threadId) const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger is API or kernel breakpoint function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; if (_debuggedProcessExists) { if (((osSocket*)_pRemoteDebuggingServerAPIChannel)->isOpen()) { GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_IS_API_OR_KERNEL_BP_CMD; *_pRemoteDebuggingServerAPIChannel << (gtUInt64)threadId; *_pRemoteDebuggingServerAPIChannel >> retVal; } } else { apDebuggedProcessTerminatedEvent eve(0); apEventsHandler::instance().registerPendingDebugEvent(eve); } if (retVal) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger is API or kernel breakpoint function exit with retVal true", OS_DEBUG_LOG_EXTENSIVE); } else { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger is API or kernel breakpoint function exit with retVal false", OS_DEBUG_LOG_EXTENSIVE); } } return retVal; } apBreakReason pdRemoteProcessDebugger::hostBreakReason() const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger host breakpoint reason function", OS_DEBUG_LOG_EXTENSIVE); apBreakReason retVal = apBreakReason::AP_FOREIGN_BREAK_HIT; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_HOST_BREAK_REASON_CMD; gtInt32 breakReasonAsInt32 = -1; *_pRemoteDebuggingServerAPIChannel >> breakReasonAsInt32; retVal = (apBreakReason)breakReasonAsInt32; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger host breakpoint reason exit", OS_DEBUG_LOG_EXTENSIVE); return retVal; } bool pdRemoteProcessDebugger::getHostBreakpointLocation(osFilePath& bpFile, int& bpLine) const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger host breakpoint location function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_HOST_BREAKPOINT_LOCATION_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; if (retVal) { bpFile.readSelfFromChannel(*_pRemoteDebuggingServerAPIChannel); gtInt32 lineNumAsInt32 = -1; *_pRemoteDebuggingServerAPIChannel >> lineNumAsInt32; bpLine = (int)lineNumAsInt32; } } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger host breakpoint location exit", OS_DEBUG_LOG_EXTENSIVE); return retVal; } bool pdRemoteProcessDebugger::setHostSourceBreakpoint(const osFilePath& fileName, int lineNumber) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger cset host source breakpoint function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_SET_HOST_BP_CMD; fileName.writeSelfIntoChannel(*_pRemoteDebuggingServerAPIChannel); *_pRemoteDebuggingServerAPIChannel << (gtInt32)lineNumber; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger cset host source breakpoint function exit", OS_DEBUG_LOG_EXTENSIVE); return retVal; } bool pdRemoteProcessDebugger::deleteHostSourceBreakpoint(const osFilePath& fileName, int lineNumber) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger cset host source breakpoint function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_DELETE_HOST_BP_CMD; fileName.writeSelfIntoChannel(*_pRemoteDebuggingServerAPIChannel); *_pRemoteDebuggingServerAPIChannel << (gtInt32)lineNumber; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger cset host source breakpoint function exit", OS_DEBUG_LOG_EXTENSIVE); return retVal; } bool pdRemoteProcessDebugger::setHostFunctionBreakpoint(const gtString& funcName) { (void)funcName; return false; } bool pdRemoteProcessDebugger::performHostStep(osThreadId threadId, StepType stepType) { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger cset host source breakpoint function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_PERFORM_HOST_STEP_CMD; *_pRemoteDebuggingServerAPIChannel << (gtUInt64)threadId; *_pRemoteDebuggingServerAPIChannel << (gtInt32)stepType; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger cset host source breakpoint function exit", OS_DEBUG_LOG_EXTENSIVE); return retVal; } bool pdRemoteProcessDebugger::suspendHostDebuggedProcess() { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger suspend host debugged process function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_SUSPEND_HOST_DEBUGGED_PROCESS; *_pRemoteDebuggingServerAPIChannel >> retVal; } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger suspend host debugged process function exit", OS_DEBUG_LOG_EXTENSIVE); return retVal; } bool pdRemoteProcessDebugger::getBreakpointTriggeringThreadIndex(int& index) const { OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get host BP triggering index function", OS_DEBUG_LOG_EXTENSIVE); bool retVal = false; GT_IF_WITH_ASSERT(_pRemoteDebuggingServerAPIChannel != nullptr) { *_pRemoteDebuggingServerAPIChannel << (gtInt32)PD_REMOTE_GET_BP_TRIGGERING_THREAD_INDEX_CMD; *_pRemoteDebuggingServerAPIChannel >> retVal; if (retVal) { gtInt32 indexAsInt32 = -1; *_pRemoteDebuggingServerAPIChannel >> indexAsInt32; index = (int)indexAsInt32; } } OS_OUTPUT_DEBUG_LOG(L"pdRemoteProcessDebugger get host BP triggering index function exit", OS_DEBUG_LOG_EXTENSIVE); return retVal; }
33,002
3,765
<gh_stars>1000+ /** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.plsql.ast; import java.util.List; import org.junit.Assert; import org.junit.Test; import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst; public class ASTCompoundConditionTest extends AbstractPLSQLParserTst { @Test public void testParseType() { ASTInput input = plsql.parse("BEGIN SELECT COUNT(1) INTO MY_TABLE FROM USERS_TABLE WHERE user_id = 1 AnD user_id = 2; END;"); List<ASTCompoundCondition> compoundConditions = input.findDescendantsOfType(ASTCompoundCondition.class); Assert.assertFalse(compoundConditions.isEmpty()); Assert.assertEquals("AND", compoundConditions.get(0).getType()); } }
286
460
<filename>trunk/win/UploadMessage.py #!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from subprocess import call import ftplib import os import sys import urllib PYTHON = 'C:\Python25\python.exe ' S3FUNNEL = PYTHON + '"' + os.getcwd() + '\\bin\\s3funnelcmd" download.bumptop.com ' def usage(): print """ usage: UploadMessage.py upload a file as message.txt: > python UploadBumptop.py path/of/message.txt upload a file as message.txt: > python UploadBumptop.py path/of/vip_message.txt delete message.txt > python UploadBumpTop.py delete_message delete vip_message.txt > python UploadBumpTop.py delete_vip_message """ def main(argv=None): if argv is None: argv = sys.argv if len(argv) != 2: usage() elif os.path.basename(sys.argv[1]) == 'delete_message': call(S3FUNNEL + ' DELETE message.txt') elif os.path.basename(sys.argv[1]) == 'delete_vip_message': call(S3FUNNEL + ' DELETE vip_message.txt') elif os.path.basename(sys.argv[1]) != 'message.txt' and os.path.basename(sys.argv[1]) != 'vip_message.txt': print "Error: File must be called message.txt or vip_message.txt" else: call(S3FUNNEL + ' PUT %s' % sys.argv[1]) if __name__ == '__main__': main()
777
320
<reponame>trathborne/nvchecker # MIT licensed # Copyright (c) 2020-2021 lilydjwg <<EMAIL>>, et al. # Copyright (c) 2017 <NAME> <<EMAIL>>, et al. from flaky import flaky import pytest pytestmark = [pytest.mark.asyncio, pytest.mark.needs_net] @flaky(max_runs=10) async def test_apt(get_version): assert await get_version("sigrok-firmware-fx2lafw", { "source": "apt", "mirror": "http://deb.debian.org/debian/", "suite": "sid", }) == "0.1.7-1" @flaky(max_runs=10) async def test_apt_srcpkg(get_version): ver = await get_version("test", { "source": "apt", "srcpkg": "golang-github-dataence-porter2", "mirror": "http://deb.debian.org/debian/", "suite": "sid", }) assert ver.startswith("0.0~git20150829.56e4718-") @flaky(max_runs=10) async def test_apt_strip_release(get_version): assert await get_version("sigrok-firmware-fx2lafw", { "source": "apt", "mirror": "http://deb.debian.org/debian/", "suite": "sid", "strip_release": 1, }) == "0.1.7" @flaky(max_runs=10) async def test_apt_deepin(get_version): assert await get_version("sigrok-firmware-fx2lafw", { "source": "apt", "mirror": "https://community-packages.deepin.com/deepin", "suite": "apricot", }) == "0.1.6-1" @flaky(max_runs=10) async def test_apt_multiversions(get_version): ver = await get_version("ms-teams", { "source": "apt", "mirror": "https://packages.microsoft.com/repos/ms-teams", "pkg": "teams", "suite": "stable", "repo": "main", "arch": "amd64", }) assert ver.startswith("1.4.00.")
793
340
#!/bin/python3 import sys def is_kaprekar(num): if num < 4: if num == 1: return True else: return False num_sq = pow(num, 2) num_sq_str = str(num_sq) left = num_sq_str[:len(num_sq_str)//2] right = num_sq_str[len(num_sq_str)//2:] #print("left = {} right = {}".format(left, right)) if int(left) + int(right) == num: return True else: return False def kaprekarNumbers(p, q): out = [] for num in range(p, q + 1): if is_kaprekar(num): out.append(num) return out if __name__ == "__main__": p = int(input().strip()) q = int(input().strip()) result = kaprekarNumbers(p, q) if result: print (" ".join(map(str, result))) else: print("INVALID RANGE")
430
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.recoveryservicesbackup.models; import com.azure.resourcemanager.recoveryservicesbackup.fluent.models.OperationStatusInner; import java.time.OffsetDateTime; /** An immutable client-side representation of OperationStatus. */ public interface OperationStatus { /** * Gets the id property: ID of the operation. * * @return the id value. */ String id(); /** * Gets the name property: Name of the operation. * * @return the name value. */ String name(); /** * Gets the status property: Operation status. * * @return the status value. */ OperationStatusValues status(); /** * Gets the startTime property: Operation start time. Format: ISO-8601. * * @return the startTime value. */ OffsetDateTime startTime(); /** * Gets the endTime property: Operation end time. Format: ISO-8601. * * @return the endTime value. */ OffsetDateTime endTime(); /** * Gets the error property: Error information related to this operation. * * @return the error value. */ OperationStatusError error(); /** * Gets the properties property: Additional information associated with this operation. * * @return the properties value. */ OperationStatusExtendedInfo properties(); /** * Gets the inner com.azure.resourcemanager.recoveryservicesbackup.fluent.models.OperationStatusInner object. * * @return the inner object. */ OperationStatusInner innerModel(); }
588
1,338
<reponame>Kirishikesan/haiku<gh_stars>1000+ #include "PrintTestView.hpp" PrintTestView::PrintTestView(BRect frame) : Inherited(frame, "", B_FOLLOW_ALL, B_WILL_DRAW | B_FULL_UPDATE_ON_RESIZE) { } void PrintTestView::Draw(BRect updateRect) { StrokeRoundRect(Bounds().InsetByCopy(20,20), 10, 10); BFont font(be_bold_font); font.SetSize(Bounds().Height()/10); font.SetShear(Bounds().Height()/10); font.SetRotation(Bounds().Width()/10); SetFont(&font, B_FONT_ALL); DrawString("OpenBeOS", 8, BPoint(Bounds().Width()/2,Bounds().Height()/2)); }
232