text
stringlengths
8
6.88M
// // SnappaUtil.h // Snappa // // Created by Sam Edson on 7/13/15. // Copyright (c) 2015 Sam Edson. All rights reserved. // #ifndef __Snappa__SnappaUtil__ #define __Snappa__SnappaUtil__ #include <stdio.h> #include <string> #include <vector> class SnappaUtil { public: static std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems); static std::vector<std::string> split(const std::string &s, char delim); static time_t stringToTime( const std::string& s ); }; #endif /* defined(__Snappa__SnappaUtil__) */
#include "game.h" #include <sdl.h> int main(int argc, char* args[]) { Game game(new Engine()); game.Startup(); while (!game.Quit()) { game.Update(); } game.Shutdown(); return 0; }
#include "naive_dictionary.hpp" #include "tools.hpp" naive_dictionary::naive_dictionary(const std::initializer_list<std::string>& init) : m_set(init.begin(), init.end()) { } void naive_dictionary::init(const std::vector<std::string>& word_list) { m_set = std::set<std::string>(word_list.begin(), word_list.end()); } result_t naive_dictionary::search(const std::string& query) const { std::lock_guard l(m); std::string best; int distance = std::numeric_limits<int>::max(); for (const auto& word : m_set) { int d = levenshtein(query, word); if (d < distance) { best = word; distance = d; } } return {best, distance}; } void naive_dictionary::insert(const std::string& w) { std::lock_guard l(m); m_set.insert(w); } void naive_dictionary::erase(const std::string& w) { std::lock_guard l(m); m_set.erase(w); }
#include <iostream> #include <glad/glad.h> #include <GLFW/glfw3.h> int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(800, 800, "OpenGL Hello World", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); gladLoadGL(); glViewport(0, 0, 800, 800); glClearColor(0.07F, 0.13f, 0.17f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); return 0; }
#include "sx/ResFileHelper.h" #include <boost/filesystem.hpp> namespace sx { ResFileType ResFileHelper::Type(const std::string& filepath) { ResFileType type = RES_FILE_UNKNOWN; auto ext = boost::filesystem::extension(filepath); std::transform(ext.begin(), ext.end(), ext.begin(), tolower); if (ext == ".png" || ext == ".jpg" || ext == ".bmp" || ext == ".ppm" || ext == ".pvr" || ext == ".pkm" || ext == ".dds" || ext == ".hdr") { type = RES_FILE_IMAGE; } else if (ext == ".raw3d" || ext == ".vdb") { type = RES_FILE_IMAGE3D; } else if (ext == ".json") { type = RES_FILE_JSON; } else if (ext == ".param" || ext == ".obj" || ext == ".m3d" || ext == ".x" || ext == ".xml" || ext == ".mdl" || ext == ".bsp" || ext == ".dae" || ext == ".fbx" || ext == ".ply") { type = RES_FILE_MODEL; } else if (ext == ".bin") { type = RES_FILE_BIN; } else if (ext == ".lua") { type = RES_FILE_SCRIPT; } // shader else if (ext == ".shader") { type = RES_FILE_SHADER; } else if (ext == ".asset") { type = RES_FILE_ASSET; } // script else if (ext == ".py") { type = RES_FILE_PYTHON; } else if (ext == ".lua") { type = RES_FILE_LUA; } // quake else if (ext == ".wad") { type = RES_FILE_WAD; } else if (ext == ".map") { type = RES_FILE_MAP; } return type; } }
/* moveniu is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. moveniu is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with moveniu. If not, see <http://www.gnu.org/licenses/>. */ #ifndef UTILS_NONCOPYABLE_H_ #define UTILS_NONCOPYABLE_H_ namespace utils { struct NonCopyable { NonCopyable() = default; NonCopyable(NonCopyable const&) = delete; NonCopyable& operator=(NonCopyable const&) = delete; }; struct NonMovable { NonMovable() = default; NonMovable(NonMovable&&) = delete; NonMovable& operator=(NonMovable&&) = delete; }; struct NonMovableOrCopyable : private NonCopyable, NonMovable { NonMovableOrCopyable() = default; }; } #endif
#pragma once #include <cstddef> #include "parameter_is_shared.hpp" #include "sum_template_parameters.hpp" namespace detail { template<typename Function, typename Integers, typename... Args> struct sizeof_shared_parameters_impl; template<typename Function, unsigned int... Integers, typename... Args> struct sizeof_shared_parameters_impl<Function, integer_series<Integers...>, Args...> { static const std::size_t value = sum_template_parameters< (parameter_is_shared<Integers,Function,Args...>::value ? sizeof(Args) : 0)... >::value; }; } // end detail template<typename Function, typename... Args> struct sizeof_shared_parameters : detail::sizeof_shared_parameters_impl< Function, typename make_integer_series<sizeof...(Args)>::type, Args... > {}; // unit tests namespace detail { namespace sizeof_shared_parameters_detail { struct has_shared { void operator()(shared<int> &x) {} }; static_assert(sizeof_shared_parameters<has_shared,int>::value == sizeof(int), "error with has_shared"); struct doesnt_have_shared { void operator()(int x) {} }; static_assert(sizeof_shared_parameters<doesnt_have_shared,int>::value == 0u, "error with doesnt_have_shared"); struct has_template { template<typename T> void operator()(T x) {} }; static_assert(sizeof_shared_parameters<has_template,int>::value == 0u, "error with has_template"); struct bar {}; struct foo { void operator()(int x, bar y, shared<bar> &z) {} }; static_assert(sizeof_shared_parameters<foo,int,bar,bar>::value == sizeof(bar), "error with foo"); void baz(int x, shared<bar> &y, const shared<int> &z) {} static_assert(sizeof_shared_parameters<decltype(baz),int,bar,int>::value == sizeof(bar) + sizeof(int), "error with baz"); struct test1_struct { float x, y, z; }; void test1(double x, float y, shared<int> &z, shared<test1_struct> &w); static_assert(sizeof_shared_parameters<decltype(test1),double,float,int,test1_struct>::value == sizeof(int) + sizeof(test1_struct), "error with test1"); } // end sizeof_shared_parameters_detail } // end detail
#include "precompiled.h" #include "component/poscomponent.h" #include "component/jscomponent.h" using namespace component; REGISTER_COMPONENT_TYPE(PosComponent, 1); #pragma warning(disable: 4355) // disable warning for using 'this' as an initializer PosComponent::PosComponent(entity::Entity* entity, const string& name, const desc_type& desc) : Component(entity, name, desc), parent(this) { D3DXQUATERNION q; D3DXQuaternionRotationYawPitchRoll(&q, D3DXToRadian(desc.rotation.y), D3DXToRadian(desc.rotation.x), D3DXToRadian(desc.rotation.z)); D3DXMatrixTransformation(&m_transform, NULL, NULL, &desc.scale, NULL, &q, &desc.position); parent = desc.parentName; } PosComponent::~PosComponent() { if(m_scriptObject) destroyScriptObject(); } void PosComponent::acquire() { Component::acquire(); } void PosComponent::release() { Component::release(); parent.release(); } // TODO: optimization - store pos/rot/scale so you don't have to decompose on every call void PosComponent::setPos(const D3DXVECTOR3& new_pos) { if(parent) { INFO("WARNING: tried to set position on an acquired child PosComponent"); return; } D3DXVECTOR3 scale, pos; D3DXQUATERNION rot; D3DXMatrixDecompose(&scale, &rot, &pos, &getTransform()); if(m_setter) { D3DXMATRIX new_transform; D3DXMatrixTransformation(&new_transform, NULL, NULL, &scale, NULL, &rot, &new_pos); m_setter(m_transform, new_transform); } else D3DXMatrixTransformation(&m_transform, NULL, NULL, &scale, NULL, &rot, &new_pos); } D3DXVECTOR3 PosComponent::getPos() { D3DXVECTOR3 scale, pos; D3DXQUATERNION rot; D3DXMatrixDecompose(&scale, &rot, &pos, &getTransform()); return pos; } void PosComponent::setRot(const D3DXVECTOR3& new_rot) { if(parent) { INFO("WARNING: tried to set rotation on an acquired child PosComponent"); return; } D3DXVECTOR3 scale, pos; D3DXQUATERNION rot, new_qrot; D3DXMatrixDecompose(&scale, &rot, &pos, &getTransform()); D3DXQuaternionRotationYawPitchRoll(&new_qrot, D3DXToRadian(new_rot.y), D3DXToRadian(new_rot.x), D3DXToRadian(new_rot.z)); if(m_setter) { D3DXMATRIX new_transform; D3DXMatrixTransformation(&new_transform, NULL, NULL, &scale, NULL, &new_qrot, &pos); m_setter(m_transform, new_transform); } else D3DXMatrixTransformation(&m_transform, NULL, NULL, &scale, NULL, &new_qrot, &pos); } void PosComponent::setRot(const D3DXQUATERNION& new_qrot) { if(parent) { INFO("WARNING: tried to set rotation on an acquired child PosComponent"); return; } D3DXVECTOR3 scale, pos; D3DXQUATERNION rot; D3DXMatrixDecompose(&scale, &rot, &pos, &getTransform()); if(m_setter) { D3DXMATRIX new_transform; D3DXMatrixTransformation(&new_transform, NULL, NULL, &scale, NULL, &new_qrot, &pos); m_setter(m_transform, new_transform); } else D3DXMatrixTransformation(&m_transform, NULL, NULL, &scale, NULL, &new_qrot, &pos); } D3DXVECTOR3 PosComponent::getRot() { D3DXVECTOR3 rot; MatrixToYawPitchRoll(&getTransform(), &rot); return rot; } D3DXQUATERNION PosComponent::getRotQuat() { D3DXVECTOR3 scale, pos; D3DXQUATERNION rot; D3DXMatrixDecompose(&scale, &rot, &pos, &getTransform()); return rot; } void PosComponent::setScale(const D3DXVECTOR3& new_scale) { if(parent) { INFO("WARNING: tried to set scale on an acquired child PosComponent"); return; } D3DXVECTOR3 scale, pos; D3DXQUATERNION rot; D3DXMatrixDecompose(&scale, &rot, &pos, &getTransform()); if(m_setter) { D3DXMATRIX new_transform; D3DXMatrixTransformation(&new_transform, NULL, NULL, &new_scale, NULL, &rot, &pos); m_setter(m_transform, new_transform); } else D3DXMatrixTransformation(&m_transform, NULL, NULL, &new_scale, NULL, &rot, &pos); } D3DXVECTOR3 PosComponent::getScale() { D3DXVECTOR3 scale, pos; D3DXQUATERNION rot; D3DXMatrixDecompose(&scale, &rot, &pos, &getTransform()); return scale; } void PosComponent::setTransform(const D3DXMATRIX& new_transform) { if(parent) { INFO("WARNING: tried to set transform on an acquired child PosComponent"); return; } if(m_setter) { //getTransform(); // maybe update the current transform? m_setter(m_transform, new_transform); } else m_transform = new_transform; } D3DXMATRIX PosComponent::getTransform() { if(m_getter) { D3DXMATRIX new_transform; m_getter(new_transform, m_transform); m_transform = new_transform; } if(parent) { return m_transform * parent->getTransform(); } return m_transform; } PosComponent::get_set_type PosComponent::setGetFunction(const component::PosComponent::get_set_type &getter) { get_set_type old_getter = m_getter; m_getter = getter; return old_getter; } PosComponent::get_set_type PosComponent::setSetFunction(const component::PosComponent::get_set_type &setter) { get_set_type old_setter = m_setter; m_setter = setter; return old_setter; } JSObject* PosComponent::createScriptObject() { return jscomponent::createComponentScriptObject(this); } void PosComponent::destroyScriptObject() { jscomponent::destroyComponentScriptObject(this); m_scriptObject = NULL; }
#include<bits/stdc++.h> using namespace std; using ll=long long; unordered_map<ll,int> mp; int main(){ int n; scanf("%d",&n); ll a; for(int i=0;i<n;i++){ scanf("%I64d",&a); mp[a]++; } ll ans=0; for(int i=-10;i<0;i++){ if(mp.count(i)&&mp.count(-i)){ ans+=(ll)mp[i]*mp[-i]; } } if(mp.count(0)){ ans+=(ll)mp[0]*(mp[0]-1)/2; } cout<<ans; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #ifdef SVG_SUPPORT #include "modules/svg/src/svgpch.h" #ifdef SVG_SUPPORT_EDITABLE #include "modules/display/vis_dev.h" #include "modules/doc/frm_doc.h" #include "modules/svg/src/AttrValueStore.h" #include "modules/svg/src/SVGUtils.h" #include "modules/svg/src/SVGDynamicChangeHandler.h" #include "modules/svg/src/SVGEditable.h" #include "modules/svg/src/SVGCanvas.h" #include "modules/svg/src/SVGElementStateContext.h" #include "modules/svg/src/SVGTextElementStateContext.h" #include "modules/svg/src/SVGManagerImpl.h" SVGEditableCaret::SVGEditableCaret(SVGEditable *edit) : m_edit(edit) , m_pos(0, 0, 0, 0) , m_glyph_pos(0, 0, 0, 0) , m_line(0) , m_on(FALSE) , m_update_pos_lock(0) , m_update_pos_needed(FALSE) , m_prefer_first(FALSE) { } SVGEditableCaret::~SVGEditableCaret() { m_timer.Stop(); } void SVGEditableCaret::LockUpdatePos(BOOL lock) { if (lock) m_update_pos_lock++; else { m_update_pos_lock--; if (m_update_pos_lock == 0 && m_update_pos_needed) { UpdatePos(m_prefer_first); } } } void SVGEditableCaret::PlaceFirst(HTML_Element* edit_root) { OP_ASSERT(!edit_root || SVGUtils::IsEditable(edit_root)); SVGCaretPoint new_cp; if (edit_root) { HTML_Element* editable_elm = m_edit->FindEditableElement(edit_root, TRUE, FALSE); if (edit_root->IsAncestorOf(editable_elm)) new_cp.elm = editable_elm; } Set(new_cp); } OP_STATUS SVGEditableCaret::Init(BOOL create_line_if_empty, HTML_Element* edit_root) { OP_ASSERT(SVGUtils::IsEditable(edit_root)); PlaceFirst(edit_root); if (create_line_if_empty && !m_point.IsValid()) { // We have nothing to put the caret on. Create a empty textelement. HTML_Element *first_text_elm = m_edit->NewTextElement(UNI_L(""), 0); if (!first_text_elm) return OpStatus::ERR_NO_MEMORY; first_text_elm->UnderSafe(m_edit->GetDocument(), edit_root); m_point.elm = first_text_elm; } Invalidate(); m_on = FALSE; UpdatePos(); return OpStatus::OK; } void SVGEditableCaret::Invalidate() { HTML_Element* elm = m_point.elm; while (elm && (elm->IsText() || elm->IsMatchingType(Markup::SVGE_TBREAK, NS_SVG))) elm = elm->Parent(); // Invalidating the element the caret is on // FIXME: Might be possible to only invalidate the caret area if (SVGDocumentContext* doc_ctx = AttrValueStore::GetSVGDocumentContext(elm)) SVGDynamicChangeHandler::RepaintElement(doc_ctx, elm); } BOOL SVGEditableCaret::UpdatePos(BOOL prefer_first) { if (!m_point.IsValid()) { PlaceFirst(); if (!m_point.IsValid()) return FALSE; } // FIX: m_prefer_first is still not used from all places calling updatepos. m_prefer_first = prefer_first; m_update_pos_needed = TRUE; if (m_update_pos_lock > 0) { // Update is locked or the document is dirty and the caret // will be update very soon (after the reflow) return FALSE; } Invalidate(); if (m_point.ofs > m_point.elm->GetTextContentLength()) { //OP_ASSERT(0); // If this happens, something has changed the textcontent without // our knowledge (probably DOM). m_point.ofs = m_point.elm->GetTextContentLength(); } Invalidate(); m_update_pos_needed = FALSE; SVGEditableListener* listener = m_edit->GetListener(); if (listener) listener->OnCaretMoved(); return TRUE; } void SVGEditableCaret::MoveWord(BOOL forward) { INT32 SeekWord(const uni_char* str, INT32 start, INT32 step, INT32 max_len); // widgets/OpEdit.cpp if (!m_point.IsValid()) return; SVGEditPoint ep = m_edit->ToEdit(m_point); SVGEditPoint new_ep = ep; if (!forward) { if (m_point.ofs != 0) // Jump within current element new_ep.ofs = ep.ofs + SeekWord(ep.elm->TextContent(), ep.ofs, -1, ep.elm->GetTextContentLength()); if (new_ep.ofs == ep.ofs) // Jump to previous element m_edit->GetNearestCaretPos(ep.elm, new_ep, FALSE, FALSE); } else { if (m_point.ofs < ep.elm->GetTextContentLength()) // Jump within current element new_ep.ofs = ep.ofs + SeekWord(ep.elm->TextContent(), ep.ofs, 1, ep.elm->GetTextContentLength()); if (new_ep.ofs == ep.ofs) { // Jump to next element if (m_edit->GetNearestCaretPos(ep.elm, new_ep, TRUE, FALSE)) { new_ep.ofs = SeekWord(new_ep.elm->TextContent(), 0, 1, new_ep.elm->GetTextContentLength()); } } } Place(m_edit->ToCaret(new_ep), TRUE, FALSE); } BOOL SVGEditableCaret::CheckElementOffset(SVGEditPoint& ep, BOOL forward) { if (SVGEditable::IsXMLSpacePreserve(ep.elm)) // No need to go looking for words, just check bounds on the text element return ep.IsValidTextOffset(); else { // Test if we can place the caret at new_ofs. const uni_char* word; int word_ofs; return m_edit->FindWordStartAndOffset(ep, word, word_ofs, forward); } } void SVGEditableCaret::Move(BOOL forward, BOOL force_stop_on_break /* = FALSE */) { SVGEditPoint ep = m_edit->ToEdit(m_point); ep.ofs += (forward ? 1 : -1); // Test if we can place the caret at the new offset. if ((forward || m_point.ofs > 0) && CheckElementOffset(ep, forward)) { Place(m_edit->ToCaret(ep), TRUE, forward); } else { // We couldn't. Search for the nearest caretpos in other elements. SVGEditPoint nearest_ep; BOOL moved = m_edit->GetNearestCaretPos(m_point.elm, nearest_ep, forward, FALSE, FALSE); if (!moved) return; OP_ASSERT(nearest_ep.IsValid()); // When moving forward, we don't want to stop on the first // break that we discover, since then we will remain on the // same line as previously, so look for the next editable // element, and place the caret there BOOL passed_break = FALSE; if (!force_stop_on_break && forward && !nearest_ep.IsText()) { SVGEditPoint next_ep; if (m_edit->GetNearestCaretPos(nearest_ep.elm, next_ep, forward, FALSE, FALSE)) { passed_break = TRUE; nearest_ep = next_ep; } } if (forward && !passed_break && nearest_ep.ofs == 0 && nearest_ep.IsText() && !m_point.elm->IsMatchingType(Markup::SVGE_TBREAK, NS_SVG)) nearest_ep.ofs = 1; Place(m_edit->ToCaret(nearest_ep), !forward || (!force_stop_on_break && !passed_break), forward); } } static BOOL GetTextAreaBoundraries(HTML_Element* element, SVGNumber& start, SVGNumber& end) { SVGProxyObject* proxy = NULL; SVGLengthObject* len = NULL; AttrValueStore::GetProxyObject(element, Markup::SVGA_WIDTH, &proxy); if (proxy && proxy->GetRealObject() && proxy->GetRealObject()->Type() == SVGOBJECT_LENGTH) { len = static_cast<SVGLengthObject*>(proxy->GetRealObject()); } else return FALSE; // 'auto' SVGValueContext vcxt; // FIXME: Need correct setup SVGLengthObject* xl = NULL; AttrValueStore::GetLength(element, Markup::SVGA_X, &xl); if (xl) start = SVGUtils::ResolveLength(xl->GetLength(), SVGLength::SVGLENGTH_X, vcxt); end = start + SVGUtils::ResolveLength(len->GetLength(), SVGLength::SVGLENGTH_X, vcxt); return TRUE; } void SVGEditableCaret::FindBoundrary(SVGLineInfo* lineinfo, SVGNumber boundrary_max) { HTML_Element* editroot = m_edit->GetEditRoot(); SVGDocumentContext* doc_ctx = AttrValueStore::GetSVGDocumentContext(editroot); SVGMatrix ctm; RETURN_VOID_IF_ERROR(SVGUtils::GetElementCTM(editroot, doc_ctx, &ctm)); SVGNumber test_start_x = m_pos.x; SVGNumber test_end_x = boundrary_max; SelectionBoundaryPoint pt; SVGNumberPair curr_testpos((test_start_x + test_end_x) / 2, m_pos.y - lineinfo->height / 2); SVGNumber diff = (curr_testpos.x - test_start_x).abs(); SVGNumber limit = lineinfo->height / 8; // FIXME: Pretty random int old_line = m_line; // FindTextPosition overwrites m_line while (diff > limit) { SVGNumberPair testpos = ctm.ApplyToCoordinate(curr_testpos); if (g_svg_manager_impl->FindTextPosition(doc_ctx, testpos, pt) == OpBoolean::IS_TRUE && pt.GetElement() && pt.GetElement()->Type() == HE_TEXT) { // Hit something SVGCaretPoint new_cp; new_cp.elm = pt.GetElement(); new_cp.ofs = pt.GetElementCharacterOffset(); Set(new_cp); StickToPreceding(); test_start_x = curr_testpos.x; } else { // Missed test_end_x = curr_testpos.x; } curr_testpos.x = (test_start_x + test_end_x) / 2; diff = (curr_testpos.x - test_start_x).abs(); } m_line = old_line; } void SVGEditableCaret::Place(Placement place) { if (!m_point.elm) return; BOOL is_multiline = m_edit->IsMultiLine(); OpVector<SVGLineInfo>* lineinfo = NULL; SVGElementContext* elm_ctx = AttrValueStore::AssertSVGElementContext(m_edit->GetEditRoot()); SVGTextRootContainer* text_root_cont = elm_ctx ? elm_ctx->GetAsTextRootContainer() : NULL; if (is_multiline && text_root_cont) { lineinfo = static_cast<SVGTextAreaElement*>(text_root_cont)->GetLineInfo(); } switch(place) { case PLACE_START: PlaceFirst(m_edit->GetEditRoot()); break; case PLACE_LINESTART: case PLACE_LINEEND: { SVGNumber line_start_min, line_end_max; if (is_multiline && lineinfo && GetTextAreaBoundraries(m_edit->GetEditRoot(), line_start_min, line_end_max)) { SVGLineInfo* li = lineinfo->Get(m_line); SVGNumber boundrary = place == PLACE_LINESTART ? // Potential optimization (for short lines) SVGNumber::max_of(line_start_min, m_pos.x - li->width) : SVGNumber::min_of(line_end_max, m_pos.x + li->width); FindBoundrary(li, boundrary); break; } else if (place == PLACE_LINESTART) { PlaceFirst(m_edit->GetEditRoot()); break; } // Fall-through to handle non-multiline PLACE_LINEEND the same as PLACE_END } case PLACE_END: { SVGEditPoint ep; ep.elm = m_edit->FindEditableElement(m_edit->GetEditRoot()->LastChildActual(), FALSE, TRUE); if (ep.IsText()) { ep.ofs = ep.elm->GetTextContentLength(); Set(m_edit->ToCaret(ep)); } } break; case PLACE_LINEPREVIOUS: case PLACE_LINENEXT: { if (!is_multiline || !lineinfo) // 'Single line' text or broken layout break; SVGDocumentContext* doc_ctx = AttrValueStore::GetSVGDocumentContext(m_edit->GetEditRoot()); SVGMatrix ctm; RETURN_VOID_IF_ERROR(SVGUtils::GetElementCTM(m_edit->GetEditRoot(), doc_ctx, &ctm)); SVGLineInfo* li = lineinfo->Get(m_line); BOOL use_fallback = TRUE; if(li) { SVGNumberPair newpos(m_pos.x, m_pos.y); if (place == PLACE_LINENEXT) { newpos.y += li->height / 2; } else { newpos.y -= (li->height * 3)/2; } SelectionBoundaryPoint pt; int old_line = m_line; // FindTextPosition overwrites m_line newpos = ctm.ApplyToCoordinate(newpos); OP_BOOLEAN result = g_svg_manager_impl->FindTextPosition(doc_ctx, newpos, pt); m_line = old_line; if (result == OpBoolean::IS_TRUE && pt.GetElement() != m_edit->GetEditRoot() && m_edit->GetEditRoot()->IsAncestorOf(pt.GetElement())) { SVGCaretPoint new_cp; new_cp.elm = pt.GetElement(); new_cp.ofs = pt.GetElementCharacterOffset(); if (new_cp.IsText()) { Set(new_cp); StickToPreceding(); } use_fallback = FALSE; } } if(use_fallback) { // No hit - try some other methods if ((place == PLACE_LINEPREVIOUS && m_line > 0) || (place == PLACE_LINENEXT && m_line+1 < (int)lineinfo->GetCount())) { SVGLineInfo* target_li = lineinfo->Get(m_line + (place == PLACE_LINENEXT ? 1 : -1)); if (target_li && (target_li->forced_break || (place == PLACE_LINEPREVIOUS && (unsigned int)m_line >= lineinfo->GetCount()))) { // There _should_ be a line to place on // Try finding a break HTML_Element* elm = m_point.elm; do { elm = m_edit->FindEditableElement(elm, place == PLACE_LINENEXT, FALSE); } while (elm && !elm->IsMatchingType(Markup::SVGE_TBREAK, NS_SVG)); if (elm && elm->IsMatchingType(Markup::SVGE_TBREAK, NS_SVG)) { SVGCaretPoint new_cp; new_cp.elm = elm; Set(new_cp); if (place == PLACE_LINENEXT) { SVGEditPoint new_ep; new_ep.elm = m_edit->FindEditableElement(m_point.elm, place == PLACE_LINENEXT, FALSE); if (new_ep.elm) Place(m_edit->ToCaret(new_ep), FALSE, FALSE); } else { StickToPreceding(); } } } } } } break; } } void SVGEditableCaret::Place(const SVGCaretPoint& cp, BOOL allow_snap, BOOL snap_forward) { if (!cp.IsValid()) { OP_ASSERT(0); PlaceFirst(); return; } OP_ASSERT(cp.ofs >= 0); // if (ofs < 0) // Just to be sure. // ofs = 0; Set(cp); if (allow_snap) StickToPreceding(); UpdatePos(!snap_forward); RestartBlink(); } void SVGEditableCaret::Set(const SVGCaretPoint& cp) { OP_ASSERT(!cp.IsValid() || cp.IsText() || cp.elm->IsMatchingType(Markup::SVGE_TBREAK, NS_SVG)); m_point = cp; } void SVGEditableCaret::StickToPreceding() { if (m_point.IsText() && m_point.elm->GetTextContentLength() == 0) return; // Stay inside dummyelements if (m_point.ofs == 0) { SVGEditPoint new_ep; new_ep.elm = m_edit->FindEditableElement(m_point.elm, FALSE, FALSE, FALSE); if (new_ep.IsText()) { const uni_char* word; int word_ofs; new_ep.ofs = new_ep.elm->GetTextContentLength(); // Check if it is possible to place in this element. if (m_edit->FindWordStartAndOffset(new_ep, word, word_ofs, TRUE)) { Place(m_edit->ToCaret(new_ep)); } } } } void SVGEditableCaret::StickToDummy() { if (m_point.IsText() && m_point.elm->GetTextContentLength() == m_point.ofs) { SVGCaretPoint new_cp; new_cp.elm = m_edit->FindElementAfterOfType(m_point.elm, HE_TEXT); if (new_cp.elm && new_cp.elm->GetTextContentLength() == 0) { Place(new_cp); } } } void SVGEditableCaret::Paint(SVGCanvas* canvas) { if(m_on && canvas && OpStatus::IsSuccess(canvas->SaveState())) { canvas->EnableStroke(SVGCanvasState::USE_COLOR); canvas->SetStrokeColor(0xFF000000); canvas->SetLineWidth(0.5); canvas->SetVectorEffect(SVGVECTOREFFECT_NON_SCALING_STROKE); canvas->DrawLine(m_glyph_pos.x, m_glyph_pos.y, m_glyph_pos.x, m_glyph_pos.y+m_glyph_pos.height); canvas->RestoreState(); } } void SVGEditableCaret::BlinkNow() { m_on = !m_on; Invalidate(); } void SVGEditableCaret::RestartBlink() { StopBlink(); if (!m_edit->IsFocused()) return; m_on = TRUE; Invalidate(); m_timer.SetTimerListener(this); m_timer.Start(500); } void SVGEditableCaret::StopBlink() { m_timer.Stop(); if(m_on) { m_on = FALSE; Invalidate(); } } void SVGEditableCaret::OnTimeOut(OpTimer* timer) { timer->Start(500); BlinkNow(); } #endif // SVG_SUPPORT_EDITABLE #endif // SVG_SUPPORT
/** Copyright (c) 2016 Mozart Alexander Louis. All rights reserved. */ #ifndef __AUDIO_UTILS_HXX__ #define __AUDIO_UTILS_HXX__ #include "fmod_studio.hpp" #include "globals.hxx" /** * Map of audio instance pointers that use a a string to reference them. */ using AudioMap = unordered_map<string, FMOD::Studio::EventInstance *>; /** * Manages all audio for this game. Uses that FMOD and FMOD Studio library to play audio.FMOD * provides a powerful low level interface combined with FMOD Studio, which provides advanced * audio manipulation. */ class AudioUtils { public: /** * Constructor. */ AudioUtils(); /** * Destructor. */ virtual ~AudioUtils(); /** * Caches audio instances from the FMOD bank. This enables faster loading * of audio. */ void preloadAudio(const string &path); /** * Plays audio by name. */ void playAudio(const char *name, bool persist = true); /** * Plays audio and set a specified parameter to `value`. */ void playAudioWithParam(const char *name, const char *param, float value, bool persist = true); /** * Get the name of the audio that is currently playing. */ string getCurrentlyPlaying(); /** * Pause audio. */ void pauseAudio(const char *name); /** * Resume audio. */ void resumeAudio(const char *name); /** * Stops audio. */ void stopAudio(const char *name, bool clean = false); /** * Sets a audio parameter tat is created in FMOD Studio. */ void setAudioParam(const char *name, const char *param, float value); /** * Stops all audio instances. */ void stopAll(bool release = false); /** * Pauses the main output thread */ void pauseMixer() const; /** * Resumes the main output thread */ void resumeMixer() const; /** * Setter for `audio_enabled_` */ void setEnabled(bool enable); /** * Gets `audio_enabled_` */ bool getEnabled() const; /** * Updates the main mixer thread to sync with game play. */ void update() const; /** * Gets singleton instance of `AudioUtils`. */ static AudioUtils *getInstance(); private: /** * Finds `name`s audio-id inside the `audio_instance_map_`. */ void findAudioInstance(string name); /** * Initializes FMOD and load the master bank. */ void initAudioEngine(); /** * Gets and audio instance using the `event_path`. */ FMOD::Studio::EventInstance *getEvent(const char *event_path, bool preload = false) const; // Whether audio should play or not. bool audio_enabled_; // FMOD low level system. FMOD::System *low_level_system_; // FMOD Studio instance. FMOD::Studio::System *fmod_system_; // A key/pair string to audio instance map. Holds all of the audio instance pointers. AudioMap audio_instance_map_; // `AudioMap` iterator used to find audio instances. AudioMap::iterator audio_instance_map_iter_; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) string MASTER_FILE = "file:///android_asset/audio/Evermaze.bank"; string MASTER_STRINGS_FILE = "file:///android_asset/audio/Evermaze.strings.bank"; #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) string MASTER_FILE = FileUtils::getInstance()->fullPathForFilename("audio/Evermaze.bank"); string MASTER_STRINGS_FILE = FileUtils::getInstance()->fullPathForFilename("audio/Evermaze.strings.bank"); #else string MASTER_FILE = "audio/Evermaze.bank"; string MASTER_STRINGS_FILE = "audio/Evermaze.strings.bank"; #endif // Singleton instance of `AudioUtils`. static AudioUtils *m_instance_; }; #endif // __AUDIO_UTILS_HXX__
#include "pch.h" GameServer::GameServer() { } GameServer::~GameServer() { } BOOL GameServer::Begin() { m_ServerConnector = new CServerConnector(); return TRUE; } BOOL GameServer::End() { delete m_ServerConnector; return TRUE; }
#include "clickablelabel.h" ClickableLabel::ClickableLabel(QWidget* parent, Qt::WindowFlags f) : QLabel(parent) { } ClickableLabel::~ClickableLabel() { } void ClickableLabel::mousePressEvent(QMouseEvent* e) { emit clicked(true); }
#ifndef _QMC5883_HPP_ #define _QMC5883_HPP_ #include <Wire.h> #define QMC_ADDRESS ((uint8_t)0x0D) #define OSR_512 ((uint8_t)0b00000000) #define OSR_256 ((uint8_t)0b01000000) #define OSR_128 ((uint8_t)0b10000000) #define OSR_64 ((uint8_t)0b11000000) #define RNG_2G ((uint8_t)0b00000000) #define RNG_8G ((uint8_t)0b00010000) #define ODR_10HZ ((uint8_t)0b00000000) #define ODR_50HZ ((uint8_t)0b00000100) #define ODR_100HZ ((uint8_t)0b00001000) #define ODR_200HZ ((uint8_t)0b00001100) #define MODE_STANDBY ((uint8_t)0b00000000) #define MODE_CONTINOUS ((uint8_t)0b00000001) class Kompas { public: static Kompas& getInstance() { static Kompas instance; return instance; } void measure(int16_t& x, int16_t& y); void avgMeasure(uint8_t samples, int16_t& x, int16_t& y); float measureAngle(); float avgAngle(uint8_t samples); float avgRadian(uint8_t samples); private: Kompas(); Kompas(const Kompas &); void writeRegister(uint8_t reg, uint8_t value); float azimuth(int16_t a,int16_t b); static void readyInterrupt(); volatile bool readyState = false; }; #endif // _QMC5883_HPP_
// #include <boost/multiprecision/cpp_int.hpp> // using boost::multiprecision::cpp_int; #include <bits/stdc++.h> using namespace std; // ¯\_(ツ)_/¯ #define f first #define s second #define mp make_pair #define pb push_back #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define debug(x) cout << '>' << #x << ':' << x << endl; #define all(v) v.begin(), v.end() #define sz(x) ((int)(x).size()) #define endl " \n" #define newl cout<<"\n" #define MAXN 100005 #define MOD 1000000007LL #define EPS 1e-13 #define INFI 1000000000 // 10^9 #define INFLL 1000000000000000000ll //10^18 // ¯\_(ツ)_/¯ #define ll long long int #define ull unsigned long long int #define ld long double #define vll vector<long long> #define vvll vector<vll> #define pll pair<long long, long long> #define fast_io() \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); ll tc, n, m, k; // knightwalk on chessboard. vll dx = {-2, -1, 1, 2, 2, 1, -1, -2}; vll dy = {-1, -2, -2, -1, 1, 2, 2, 1}; bool check(pll& v) { return (v.f >= 0 && v.f < n && v.s >= 0 && v.s < m); } void dfs(pll u, vvll& adjgraph, pll& dest) { rep(i, 0, 8) { pll v = {u.f+dx[i], u.s+dy[i]}; // not maintaining visited, pruning works only because all paths takes 1 cost if(check(v) && adjgraph[v.f][v.s] > adjgraph[u.f][u.s] + 1 && adjgraph[dest.f][dest.s] > adjgraph[u.f][u.s] + 1 ) { adjgraph[v.f][v.s] = adjgraph[u.f][u.s] + 1; dfs(v, adjgraph, dest); } } } int main() { fast_io(); #ifndef ONLINE_JUDGE freopen("../input.txt", "r", stdin); freopen("../output.txt", "w", stdout); #endif cin>>tc; while(tc--) { cin>>n; m = n; ll x, y, tx, ty; cin>>x>>y>>tx>>ty; pll start = {--x, --y}; pll dest = {--tx, --ty}; vvll adjgraph(n, vll(m, INFI)); adjgraph[start.f][start.s] = 0; ll ans = 0; if(start.f == dest.f && start.s == dest.s) { ans = 0; } else { dfs(start, adjgraph, dest); } ans = adjgraph[dest.f][dest.s]; cout<<ans; newl; } return 0; } /* 2 6 4 5 1 1 20 5 7 15 20 */
#pragma once #define _CRT_SECURE_NO_WARNINGS #ifndef _STDAFX_H #define _STDAFX_H #include <WS2tcpip.h> #include <Windows.h> #pragma comment(lib,"ws2_32.lib") #include <string> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <stack> #include <list> #include <map> #include <io.h> #include <conio.h> #include <mutex> #include <thread> #include "libMag.h" #include "paraParser.h" #include "register.h" #include "csCommunication.h" typedef int(*FUNADDR)(...); #endif // ! _STDAFX_H
#pragma once #include "pch.h" #include "VertexBuffer.h" #include "ConstantBuffer.h" #include "Shaders.h" #include "Timer.h" struct PS_FADE_BUFFER { XMFLOAT3 color; float alpha; }; class Transition { private: // Device ID3D11DeviceContext* m_dContext; // Constant Buffers ConstBuffer<PS_FADE_BUFFER> m_fadeCBuffer; // Shaders Shaders m_shaders; // Timer Timer m_timer; bool m_fadeIn; bool m_animationDone; Transition() { m_dContext = nullptr; m_fadeIn = false; m_animationDone = true; m_fadeCBuffer.m_data.color = { 0.f, 0.f, 0.f }; m_fadeCBuffer.m_data.alpha = 0.f; } public: static Transition& get() { static Transition handlerInstance; return handlerInstance; } Transition(Transition const&) = delete; void operator=(Transition const&) = delete; ~Transition() {} void initialize(ID3D11Device* device, ID3D11DeviceContext* dContext) { m_dContext = dContext; m_fadeCBuffer.init(device, dContext); ShaderFiles shaderFiles; shaderFiles.vs = L"Shader Files\\FullscreenQuadVS.hlsl"; shaderFiles.ps = L"Shader Files\\TransitionPS.hlsl"; m_shaders.initialize(device, dContext, shaderFiles); } void fadeIn(XMFLOAT3 color) { m_fadeCBuffer.m_data.color = color; m_fadeIn = true; m_animationDone = false; } void fadeOut() { m_fadeIn = false; m_animationDone = false; } void update(float dt) { if (m_fadeIn) { if (m_fadeCBuffer.m_data.alpha < 1.f) m_fadeCBuffer.m_data.alpha += dt * 2; else { m_fadeCBuffer.m_data.alpha = 1.f; m_animationDone = true; } } else { if (m_fadeCBuffer.m_data.alpha > 0.f) m_fadeCBuffer.m_data.alpha -= dt * 2; else { m_fadeCBuffer.m_data.alpha = 0.f; m_animationDone = true; } } } bool isAnimationDone() const { return m_animationDone; } void render() { m_fadeCBuffer.upd(); m_dContext->PSSetConstantBuffers(0, 1, m_fadeCBuffer.GetAddressOf()); m_shaders.setShaders(); m_dContext->Draw(4, 0); } };
#include <cstdio> #include <cstdlib> #include <ctime> #include <unistd.h> #include <iostream> #include <vector> #include <ostream> #include <queue> #include <set> #include <algorithm> #include <cmath> using namespace std; #include "common.h" #include "marshal.h" #include "update.h" Mapa mapa; Stav stav; // vzdy som hrac cislo 0 Teren viditelnyTeren; Teren objavenyTeren; vector<Prikaz> prikazy; set<Bod> starts; bool rob_banikov = true; int vlacik = 0; int pocet_banikov = 0, pocet_banikov_old = 0; bool vitaz = false; int kovacX = -1, kovacY = -1; bool vlacik_cesty(int x, int y){ for ( auto it = starts.begin(); it != starts.end(); ++it ){ if(it->x == x || it->y == y) return true; } return false; } void bfs(const Teren& teren, Bod start, Teren& vzdialenost) { int inf = teren.w() * teren.h() * 2; vzdialenost.vyprazdni(teren.w(), teren.h(), inf); queue<Bod> Q; vzdialenost.set(start, 0); Q.push(start); while (!Q.empty()) { Bod p = Q.front(); Q.pop(); for (int d = 0; d < 4; d++) { Bod n(p.x + DX[d], p.y + DY[d]); if (teren.get(n) == MAPA_OKRAJ) continue; if (teren.get(n) == MAPA_START) continue; if (vzdialenost.get(n) != inf) continue; vzdialenost.set(n, vzdialenost.get(p) + 1); if (teren.get(n) == MAPA_VOLNO) Q.push(n); } } } // main() zavola tuto funkciu, ked nacita mapu void inicializuj() { Bod start2, start1 = Bod(-1, -1); fprintf(stderr, "INIT\n"); objavenyTeren.vyprazdni(mapa.w, mapa.h, MAPA_NEVIEM); for (int y = 0; y < mapa.h; y++) for (int x = 0; x < mapa.w; x++) { if (mapa.pribliznyTeren.get(x, y) == MAPA_START){ objavenyTeren.set(x, y, MAPA_START); starts.insert(Bod(x, y)); if(start1.x == -1) start1 = Bod(x, y); else start2 = Bod(x, y); } } cerr << "koniec initu\n"; FOREACH(it, stav.manici) { if (it->ktorehoHraca == 0 && it->typ == MANIK_KOVAC) { kovacX = it->x; kovacY = it->y; } } if(abs(start1.x - start2.x) + abs(start1.y - start2.y) < 50) { rob_banikov = false; vlacik = 1; } } // pomocna funkcia co ked uz vieme kam ten manik chce ist tak ho tam posle static void chodKuMiestu(const Manik &m, Bod ciel) { Teren vzdialenost; bfs(objavenyTeren, ciel, vzdialenost); int smer = -1; for (int d = 0; d < 4; d++) { Bod n(m.x + DX[d], m.y + DY[d]); if (priechodne(objavenyTeren.get(n)) && vzdialenost.get(n) < vzdialenost.get(m.pozicia())) { smer = d; } } if(smer != -1){ prikazy.push_back(Prikaz(m.id, PRIKAZ_CHOD, Bod(m.x + DX[smer], m.y + DY[smer]))); objavenyTeren.set(Bod(m.x + DX[smer], m.y + DY[smer]), MAPA_START); }else{ for (int d = 0; d < 4; d++) { Bod n(m.x + DX[d], m.y + DY[d]); if (priechodne(objavenyTeren.get(n)) && abs(n.x - ciel.x) + abs(n.y - ciel.y) <= abs(m.x - ciel.x) + abs(m.y - ciel.y)) { smer = d; } } if(smer != -1){ prikazy.push_back(Prikaz(m.id, PRIKAZ_CHOD, Bod(m.x + DX[smer], m.y + DY[smer]))); objavenyTeren.set(Bod(m.x + DX[smer], m.y + DY[smer]), MAPA_START); } else { if(m.x > ciel.x) { if(priechodne(objavenyTeren.get(m.x-1, m.y))){ prikazy.push_back(Prikaz(m.id, PRIKAZ_CHOD, m.x-1, m.y)); } else { prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, m.x-1, m.y)); } } else if(m.x < ciel.x) { if(priechodne(objavenyTeren.get(m.x+1, m.y))){ prikazy.push_back(Prikaz(m.id, PRIKAZ_CHOD, m.x+1, m.y)); } else { prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, m.x+1, m.y)); } } else { if(m.y > ciel.y) { if(priechodne(objavenyTeren.get(m.x, m.y-1))){ prikazy.push_back(Prikaz(m.id, PRIKAZ_CHOD, m.x, m.y-1)); } else { prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, m.x, m.y-1)); } } else if(m.y < ciel.y) { if(priechodne(objavenyTeren.get(m.x, m.y+1))){ prikazy.push_back(Prikaz(m.id, PRIKAZ_CHOD, m.x, m.y+1)); } else { prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, m.x, m.y+1)); } } } } } } void coRobiVlacik(const Manik &m) { for (int d = 0; d < 4; d++) { int nx = m.x + DX[d], ny = m.y + DY[d]; FOREACH(it, stav.manici) if(it->ktorehoHraca != 0 && it->x == nx && it->y == ny && (vitaz || it->typ != MANIK_KOVAC)){ prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, nx, ny)); return; } // ak som hned vedla kovaca a mam mu co dat, dam mu to. if (nx == kovacX && ny == kovacY && m.zlato) { prikazy.push_back(Prikaz(m.id, PRIKAZ_DAJ_ZLATO, nx, ny, m.zlato)); return; } if (nx == kovacX && ny == kovacY && m.zelezo) { prikazy.push_back(Prikaz(m.id, PRIKAZ_DAJ_ZELEZO, nx, ny, m.zelezo)); return; } } // ak som uz vytazil vela surovin, idem nazad za kovacom. if ((m.zlato + m.zelezo >= 60) && kovacX != -1) { chodKuMiestu(m, Bod(kovacX, kovacY)); return; } vector <Bod> possible; int bestdist = mapa.w * mapa.h; for ( auto it = starts.begin(); it != starts.end(); ++it ){ if(abs(it->x-m.x)+abs(it->y-m.y) < bestdist){ possible.clear(); possible.push_back(Bod(it->x, it->y)); bestdist = abs(it->x-m.x)+abs(it->y-m.y); }else if(abs(it->x-m.x)+abs(it->y-m.y) == bestdist) possible.push_back(Bod(it->x, it->y)); } if (!possible.empty()) { Bod bestp = possible[rand()%possible.size()]; if (abs(bestp.x - m.x) + abs(bestp.y - m.y) == 1) { FOREACH(it, stav.manici) if(it->ktorehoHraca != 0 && it->x == bestp.x && it->y == bestp.y ){ if(vitaz || it->typ != MANIK_KOVAC) prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, bestp)); return; } starts.erase(Bod(bestp.x, bestp.y)); } // inak sa k nemu priblizim chodKuMiestu(m, bestp); return; } } void coRobiKovac(const Manik &m) { // hlupy klient proste furt stavia banikov kolko moze... kovacX = m.x; kovacY = m.y; int d = rand() % 4; int vyrabam = rand()%7; if(rob_banikov){ if(pocet_banikov_old < 3 || vyrabam < 4) { for(int i = 0; i < 4; i++){ int counter = 0; FOREACH(it, stav.manici) { if (it->x == (m.x + DX[(i+d)%4]) && it->y == (m.y + DY[(i+d)%4])) { counter++; break; } } if(!counter){ prikazy.push_back(Prikaz(m.id, PRIKAZ_KUJ, m.x + DX[(i+d)%4], m.y + DY[(i+d)%4], MANIK_BANIK)); } } } else { for(int i = 0; i < 4; i++){ int counter = 0; FOREACH(it, stav.manici) { if (it->x == (m.x + DX[(i+d)%4]) && it->y == (m.y + DY[(i+d)%4])) { counter++; break; } } if(!counter){ prikazy.push_back(Prikaz(m.id, PRIKAZ_KUJ, m.x + DX[(i+d)%4], m.y + DY[(i+d)%4], MANIK_STRAZNIK)); } } } } else if(vyrabam < 2 || vlacik) { vector <Bod> possible; int bestdist = mapa.w * mapa.h; for ( auto it = starts.begin(); it != starts.end(); ++it ){ if(abs(it->x-m.x)+abs(it->y-m.y) < bestdist){ possible.clear(); possible.push_back(Bod(it->x, it->y)); bestdist = abs(it->x-m.x)+abs(it->y-m.y); }else if(abs(it->x-m.x)+abs(it->y-m.y) == bestdist) possible.push_back(Bod(it->x, it->y)); } bestdist = mapa.w * mapa.h; if (!possible.empty()) { Bod bestp = possible[rand()%possible.size()]; int d = rand() % 4; for(int i = 0; i < 4; i++){ if (abs(bestp.x-(m.x + DX[(i+d)%4]))+abs(bestp.y-(m.y + DY[(i+d)%4]) < bestdist)) { prikazy.push_back(Prikaz(m.id, PRIKAZ_KUJ, (m.x + DX[(i+d)%4]), (m.y + DY[(i+d)%4]), MANIK_MLATIC)); //vlacik--; break; } } } } else if(vyrabam < 5){ for(int i = 0; i < 4; i++){ int counter = 0; FOREACH(it, stav.manici) { if (it->x == (m.x + DX[(i+d)%4]) && it->y == (m.y + DY[(i+d)%4])) { counter++; break; } } if(!counter){ prikazy.push_back(Prikaz(m.id, PRIKAZ_KUJ, m.x + DX[(i+d)%4], m.y + DY[(i+d)%4], MANIK_SEKAC)); } } } else { for(int i = 0; i < 4; i++){ int counter = 0; FOREACH(it, stav.manici) { if (it->x == (m.x + DX[(i+d)%4]) && it->y == (m.y + DY[(i+d)%4])) { counter++; break; } } if(!counter){ prikazy.push_back(Prikaz(m.id, PRIKAZ_KUJ, m.x + DX[(i+d)%4], m.y + DY[(i+d)%4], MANIK_STRAZNIK)); } } } } void coRobiUtok(const Manik &m) { for (int d = 0; d < 4; d++) { int nx = m.x + DX[d], ny = m.y + DY[d]; FOREACH(it, stav.manici) if(it->ktorehoHraca != 0 && it->x == nx && it->y == ny &&(vitaz || it->typ != MANIK_KOVAC)){ prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, nx, ny)); return; } // ak som hned vedla kovaca a mam mu co dat, dam mu to. if (nx == kovacX && ny == kovacY && m.zlato) { prikazy.push_back(Prikaz(m.id, PRIKAZ_DAJ_ZLATO, nx, ny, m.zlato)); return; } if (nx == kovacX && ny == kovacY && m.zelezo) { prikazy.push_back(Prikaz(m.id, PRIKAZ_DAJ_ZELEZO, nx, ny, m.zelezo)); return; } } // ak som uz vytazil vela surovin, idem nazad za kovacom. if ((m.zlato + m.zelezo >= 60) && kovacX != -1) { chodKuMiestu(m, Bod(kovacX, kovacY)); return; } Teren vzdialenost; bfs(objavenyTeren, m.pozicia(), vzdialenost); vector <Bod> possible; int bestdist = mapa.w * mapa.h; FOREACH(it, stav.manici){ if(it->ktorehoHraca != 0 && (vitaz || it->typ != MANIK_KOVAC)){ if (vzdialenost.get(it->x, it->y) < bestdist) { possible.clear(); possible.push_back(Bod(it->x, it->y)); bestdist = vzdialenost.get(it->x, it->y); } else if (vzdialenost.get(it->x, it->y) == bestdist){ possible.push_back(Bod(it->x, it->y)); } } } if (!possible.empty()) { Bod bestp = possible[rand()%possible.size()]; if (abs(bestp.x - m.x) + abs(bestp.y - m.y) == 1) { prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, bestp)); return; } // inak sa k nemu priblizim chodKuMiestu(m, bestp); return; } bestdist = 0; // ak nie, tak idem za najblizsim sutrom a snad niekde nieco najdem... for (int y = 0; y < mapa.h; y++) for (int x = 0; x < mapa.w; x++) { //if (objavenyTeren.get(x, y) == MAPA_VOLNO){ if (vzdialenost.get(x, y) > bestdist) { possible.clear(); possible.push_back(Bod(x, y)); bestdist = vzdialenost.get(x, y); } else if (vzdialenost.get(x, y) == bestdist){ possible.push_back(Bod(x, y)); } //} } if (!possible.empty()) { Bod bestp = possible[rand()%possible.size()]; // inak sa k nemu priblizim chodKuMiestu(m, bestp); return; } } void coRobiObrana(const Manik &m) { for (int d = 0; d < 4; d++) { int nx = m.x + DX[d], ny = m.y + DY[d]; FOREACH(it, stav.manici) if(it->ktorehoHraca != 0 && it->x == nx && it->y == ny){ if(vitaz || it->typ != MANIK_KOVAC) prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, nx, ny)); return; } // ak som hned vedla kovaca a mam mu co dat, dam mu to. if (nx == kovacX && ny == kovacY && m.zlato) { prikazy.push_back(Prikaz(m.id, PRIKAZ_DAJ_ZLATO, nx, ny, m.zlato)); return; } if (nx == kovacX && ny == kovacY && m.zelezo) { prikazy.push_back(Prikaz(m.id, PRIKAZ_DAJ_ZELEZO, nx, ny, m.zelezo)); return; } } // ak som uz vytazil vela surovin, idem nazad za kovacom. if ((m.zlato + m.zelezo >= 60) && kovacX != -1) { chodKuMiestu(m, Bod(kovacX, kovacY)); return; } Teren vzdialenost; bfs(objavenyTeren, m.pozicia(), vzdialenost); vector <Bod> possible; int bestdist = 20; FOREACH(it, stav.manici){ if(it->ktorehoHraca != 0 && (vitaz || it->typ != MANIK_KOVAC) && (it->y-kovacY)*(it->y-kovacY)+(it->x-kovacX)*(it->x-kovacX) <= 50){ if (vzdialenost.get(it->x, it->y) < bestdist) { possible.clear(); possible.push_back(Bod(it->x, it->y)); bestdist = vzdialenost.get(it->x, it->y); } else if (vzdialenost.get(it->x, it->y) == bestdist){ possible.push_back(Bod(it->x, it->y)); } } } if (!possible.empty()) { Bod bestp = possible[rand()%possible.size()]; if (abs(bestp.x - m.x) + abs(bestp.y - m.y) == 1) { prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, bestp)); return; } // inak sa k nemu priblizim chodKuMiestu(m, bestp); return; } bestdist = mapa.w * mapa.h; // ak nie, tak idem za najblizsim sutrom a snad niekde nieco najdem... for (int y = 0; y < mapa.h; y++) for (int x = 0; x < mapa.w; x++) { if ((objavenyTeren.get(x,y) != MAPA_START || (x == m.x && y == m.y)) && !vlacik_cesty(x,y) && y%3 != 0 && (x-1)%11 != 0 && (y-kovacY)*(y-kovacY)+(x-kovacX)*(x-kovacX) >= 18 && (y-kovacY)*(y-kovacY)+(x-kovacX)*(x-kovacX) <= 36){ if (vzdialenost.get(x, y) < bestdist) { possible.clear(); possible.push_back(Bod(x, y)); bestdist = vzdialenost.get(x, y); } else if (vzdialenost.get(x, y) == bestdist){ possible.push_back(Bod(x, y)); } } } if (!possible.empty()) { Bod bestp = possible[rand()%possible.size()]; // inak sa k nemu priblizim chodKuMiestu(m, bestp); return; } } void coRobiBanik(const Manik &m) { for (int d = 0; d < 4; d++) { int nx = m.x + DX[d], ny = m.y + DY[d]; // ak som hned vedla zlata alebo zeleza, tazim. if (objavenyTeren.get(nx, ny) == MAPA_ZLATO || objavenyTeren.get(nx, ny) == MAPA_ZELEZO) { prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, nx, ny)); return; } // ak som hned vedla kovaca a mam mu co dat, dam mu to. if (nx == kovacX && ny == kovacY && m.zlato) { prikazy.push_back(Prikaz(m.id, PRIKAZ_DAJ_ZLATO, nx, ny, m.zlato)); return; } if (nx == kovacX && ny == kovacY && m.zelezo) { prikazy.push_back(Prikaz(m.id, PRIKAZ_DAJ_ZELEZO, nx, ny, m.zelezo)); return; } } // ak som uz vytazil vela surovin, idem nazad za kovacom. if ((m.zlato + m.zelezo >= min(stav.cas/20+1,100)) && kovacX != -1) { chodKuMiestu(m, Bod(kovacX, kovacY)); return; } // ak vidime nejake zlato alebo zelezo, idem k nemu. Teren vzdialenost; bfs(objavenyTeren, m.pozicia(), vzdialenost); int bestdist = 6; vector <Bod> possible; for (int y = 0; y < mapa.h; y++) for (int x = 0; x < mapa.w; x++) { if (objavenyTeren.get(x, y) == MAPA_ZLATO || objavenyTeren.get(x, y) == MAPA_ZELEZO) { if (vzdialenost.get(x, y) < bestdist) { possible.clear(); possible.push_back(Bod(x, y)); bestdist = vzdialenost.get(x, y); } else if (vzdialenost.get(x, y) == bestdist){ possible.push_back(Bod(x, y)); } } } if (!possible.empty()) { chodKuMiestu(m, possible[rand()%possible.size()]); return; } bestdist = mapa.w * mapa.h; // ak nie, tak idem za najblizsim sutrom a snad niekde nieco najdem... for (int y = 0; y < mapa.h; y++) for (int x = 0; x < mapa.w; x++) { if (objavenyTeren.get(x, y) == MAPA_SUTER && (y%3 == 0 || (x-1)%11 == 0 || (y-kovacY)*(y-kovacY)+(x-kovacX)*(x-kovacX) <= 36 || vlacik_cesty(x,y))){ if (vzdialenost.get(x, y) < bestdist) { possible.clear(); possible.push_back(Bod(x, y)); bestdist = vzdialenost.get(x, y); } else if (vzdialenost.get(x, y) == bestdist){ possible.push_back(Bod(x, y)); } } } if (!possible.empty()) { Bod bestp = possible[rand()%possible.size()]; if (abs(bestp.x - m.x) + abs(bestp.y - m.y) == 1) { prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, bestp)); return; } // inak sa k nemu priblizim chodKuMiestu(m, bestp); return; } /*if ((m.zlato + m.zelezo > 0) && kovacX != -1) { chodKuMiestu(m, Bod(kovacX, kovacY)); return; }*/ bestdist = mapa.w * mapa.h; FOREACH(it, stav.manici){ if(it->typ == MANIK_BANIK && it->id != m.id){ if (vzdialenost.get(it->x, it->y) < bestdist) { possible.clear(); possible.push_back(Bod(it->x, it->y)); bestdist = vzdialenost.get(it->x, it->y); } else if (vzdialenost.get(it->x, it->y) == bestdist){ possible.push_back(Bod(it->x, it->y)); } } } if (!possible.empty()) { Bod bestp = possible[rand()%possible.size()]; if (abs(bestp.x - m.x) + abs(bestp.y - m.y) == 1) { prikazy.push_back(Prikaz(m.id, PRIKAZ_UTOC, bestp)); return; } // inak sa k nemu priblizim chodKuMiestu(m, bestp); return; } } // main() zavola tuto funkciu, ked chce vediet, ake prikazy chceme vykonat, // co tato funkcia rozhodne pomocou: prikazy.push_back(Prikaz(...)); void zistiTah() { // (sem patri vas kod) int skore_max = 0; for(int i = 1; i < stav.hraci.size(); i++){ if(stav.hraci[i].skore > skore_max){ skore_max = zistiSkore(stav, i); } } if(skore_max-200 > zistiSkore(stav, 0)) vitaz = false; else vitaz = true; fprintf(stderr, "zistiTah zacina %d\n", stav.cas); // zapamatame si teren co vidime a doteraz sme nevideli for (int y = 0; y < mapa.h; y++) for (int x = 0; x < mapa.w; x++) { if (viditelnyTeren.get(x, y) != MAPA_NEVIEM) { objavenyTeren.set(x, y, viditelnyTeren.get(x, y)); } } FOREACH(it, stav.manici) { if(it->ktorehoHraca == 0){ if(it->typ == MANIK_KOVAC || it->typ == MANIK_STRAZNIK) objavenyTeren.set(it->x, it->y, MAPA_START); starts.erase(Bod(it->x, it->y)); } else { if(it->typ == MANIK_KOVAC){ starts.insert(Bod(it->x, it->y)); } } } // kazdemu nasmu manikovi povieme co ma robit (na to mame pomocne funkcie) pocet_banikov = 0; FOREACH(it, stav.manici) { if (it->ktorehoHraca != 0) continue; switch (it->typ) { case MANIK_KOVAC: coRobiKovac(*it); break; case MANIK_BANIK: coRobiBanik(*it); pocet_banikov++; break; case MANIK_MLATIC: coRobiVlacik(*it); break; case MANIK_SEKAC: coRobiUtok(*it); break; case MANIK_STRAZNIK: coRobiObrana(*it); break; } } if(pocet_banikov >= 50) rob_banikov = false; pocet_banikov_old = pocet_banikov; fprintf(stderr, "prikazov %d\n", (int)prikazy.size()); } int main() { // v tejto funkcii su vseobecne veci, nemusite ju menit (ale mozte). unsigned int seed = time(NULL) * getpid(); srand(seed); nacitaj(cin, mapa); fprintf(stderr, "START pid=%d, seed=%u\n", getpid(), seed); inicializuj(); while (cin.good()) { vector<int> zakodovanyTeren; nacitaj(cin, zakodovanyTeren); dekodujViditelnyTeren(zakodovanyTeren, viditelnyTeren); nacitaj(cin, stav); prikazy.clear(); zistiTah(); uloz(cout, prikazy); cout << ".\n" << flush; // bodka a flush = koniec odpovede } return 0; }
/* * 2013+ Copyright (c) Ruslan Nigatullin <euroelessar@yandex.ru> * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef COCAINE_SERVICE_NETWORKREQUEST_H #define COCAINE_SERVICE_NETWORKREQUEST_H #include <vector> #include <string> #include <utility> namespace ioremap { namespace swarm { class network_request_data; class network_reply_data; template <typename T> class shared_data_ptr { public: explicit shared_data_ptr(T *data) : m_data(data) { if (m_data) ++m_data->refcnt; } shared_data_ptr() : m_data(NULL) {} shared_data_ptr(const shared_data_ptr &other) : m_data(other.m_data) { if (m_data) ++m_data->refcnt; } ~shared_data_ptr() { if (m_data && --m_data->refcnt == 0) delete m_data; } shared_data_ptr &operator =(const shared_data_ptr &other) { shared_data_ptr tmp(other); std::swap(tmp.m_data, m_data); return *this; } T *operator ->() { detach(); return m_data; } const T *operator ->() const { return m_data; } T &operator *() { detach(); return *m_data; } const T &operator *() const { return *m_data; } T *data() { detach(); return m_data; } T *data() const { return m_data; } T *constData() { return m_data; } private: void detach() { if (m_data && m_data->refcnt != 1) { shared_data_ptr tmp(new T(*m_data)); std::swap(tmp.m_data, m_data); } } T *m_data; }; typedef std::pair<std::string, std::string> headers_entry; class network_request { public: network_request(); network_request(const network_request &other); ~network_request(); network_request &operator =(const network_request &other); // Request URL const std::string &get_url() const; void set_url(const std::string &url); // Follow Location from 302 HTTP replies bool get_follow_location() const; void set_follow_location(bool follow_location); // Timeout in ms long get_timeout() const; void set_timeout(long timeout); // List of headers const std::vector<headers_entry> &get_headers() const; bool has_header(const std::string &name) const; std::string get_header(const std::string &name) const; std::string get_header(const char *name) const; void set_headers(const std::vector<headers_entry> &headers); void set_header(const headers_entry &header); void set_header(const std::string &name, const std::string &value); void add_header(const headers_entry &header); void add_header(const std::string &name, const std::string &value); // If-Modified-Since, UTC bool has_if_modified_since() const; time_t get_if_modified_since() const; std::string get_if_modified_since_string() const; void set_if_modified_since(const std::string &time); void set_if_modified_since(time_t time); // TheVoid specific arguments void set_http_version(int major_version, int minor_version); int get_http_major_version() const; int get_http_minor_version() const; void set_method(const std::string &method); std::string get_method() const; void set_content_length(size_t length); bool has_content_length() const; size_t get_content_length() const; void set_content_type(const std::string &type); bool has_content_type() const; std::string get_content_type() const; bool is_keep_alive() const; private: shared_data_ptr<network_request_data> m_data; }; class network_reply { public: enum status_type { ok = 200, created = 201, accepted = 202, no_content = 204, multiple_choices = 300, moved_permanently = 301, moved_temporarily = 302, not_modified = 304, bad_request = 400, unauthorized = 401, forbidden = 403, not_found = 404, internal_server_error = 500, not_implemented = 501, bad_gateway = 502, service_unavailable = 503 }; network_reply(); network_reply(const network_reply &other); ~network_reply(); network_reply &operator =(const network_reply &other); // Original request network_request get_request() const; void set_request(const network_request &request); // HTTP code int get_code() const; void set_code(int code); // Errno int get_error() const; void set_error(int error); // Final URL from HTTP reply const std::string &get_url() const; void set_url(const std::string &url); // List of headers const std::vector<headers_entry> &get_headers() const; bool has_header(const std::string &name) const; std::string get_header(const std::string &name) const; std::string get_header(const char *name) const; void set_headers(const std::vector<headers_entry> &headers); void set_header(const headers_entry &header); void set_header(const std::string &name, const std::string &value); void add_header(const headers_entry &header); void add_header(const std::string &name, const std::string &value); // Reply data const std::string &get_data() const; void set_data(const std::string &data); // Last-Modified, UTC bool has_last_modified() const; time_t get_last_modified() const; std::string get_last_modified_string() const; void set_last_modified(const std::string &last_modified); void set_last_modified(time_t last_modified); // Content length void set_content_length(size_t length); bool has_content_length() const; size_t get_content_length() const; // Content type void set_content_type(const std::string &type); bool has_content_type() const; std::string get_content_type() const; private: shared_data_ptr<network_reply_data> m_data; }; } } #endif // COCAINE_SERVICE_NETWORKREQUEST_H
// Created on: 2016-04-07 // Copyright (c) 2016 OPEN CASCADE SAS // Created by: Oleg AGASHIN // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IMeshTools_ModelBuilder_HeaderFile #define _IMeshTools_ModelBuilder_HeaderFile #include <Message_Algorithm.hxx> #include <Standard_ErrorHandler.hxx> #include <Standard_Failure.hxx> #include <Standard_Type.hxx> #include <IMeshData_Model.hxx> struct IMeshTools_Parameters; //! Interface class represents API for tool building discrete model. //! //! The following statuses should be used by default: //! Message_Done1 - model has been successfully built. //! Message_Fail1 - empty shape. //! Message_Fail2 - model has not been build due to unexpected reason. class IMeshTools_ModelBuilder : public Message_Algorithm { public: //! Destructor. virtual ~IMeshTools_ModelBuilder() { } //! Exceptions protected method to create discrete model for the given shape. //! Returns nullptr in case of failure. Handle (IMeshData_Model) Perform ( const TopoDS_Shape& theShape, const IMeshTools_Parameters& theParameters) { ClearStatus (); try { OCC_CATCH_SIGNALS return performInternal (theShape, theParameters); } catch (Standard_Failure const&) { SetStatus (Message_Fail2); return NULL; } } DEFINE_STANDARD_RTTIEXT(IMeshTools_ModelBuilder, Message_Algorithm) protected: //! Constructor. IMeshTools_ModelBuilder() { } //! Creates discrete model for the given shape. //! Returns nullptr in case of failure. Standard_EXPORT virtual Handle (IMeshData_Model) performInternal ( const TopoDS_Shape& theShape, const IMeshTools_Parameters& theParameters) = 0; }; #endif
// Fill out your copyright notice in the Description page of Project Settings. #include "Hypoxia.h" #include "Hammer.h" #include "EngineUtils.h" #include "PhysicsEngine/DestructibleActor.h" #include "Components/DestructibleComponent.h" void AHammer::BeginPlay() { Super::BeginPlay(); //for (TActorIterator<ADestructibleActor> ActorItr(GetWorld()); ActorItr; ++ActorItr) { // ADestructibleActor *Mesh = *ActorItr; // if (ActorItr->ActorHasTag(Tags[0])) { // //Door = *ActorItr; // UE_LOG(LogTemp, Warning, TEXT("Child: %s"), *ActorItr->GetName()); // UE_LOG(LogTemp, Warning, TEXT("Parent: %s"), *GetName()); // break; // } //} } void AHammer::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit) { //UE_LOG(LogTemp, Warning, TEXT("I'm hit, I'm hit")); if (OtherActor->IsA(ADestructibleActor::StaticClass())) { UE_LOG(LogTemp, Warning, TEXT("I'm hit, I'm hit")); ADestructibleActor* Destruct = Cast<ADestructibleActor>(OtherActor); //UDestructibleComponent* CompDesc = Cast<UDestructibleComponent>(OtherComponent); //Destruct->GetDestructibleComponent()->SetSimulatePhysics(true); Destruct->GetDestructibleComponent()->ApplyDamage(1.0f, Hit.Location, NormalImpulse, 10000.0f); //Destruct->GetDestructibleComponent()->AddForce(FVector(0.0f, 0.0f, 5.0f)); } }
/* Programación Orientada a Objetos PROYECTO 3 Ana Elisa Estrada Lugo A01251091 05/06/2020 */ #include <iostream> #include <string> #include <sstream> #include <fstream> #include "Reserva.h" #include "Disco.h" #include "Libro.h" #include "Software.h" using namespace std; int main() { //Declaración de arreglos Reserva arrRes[60]; Material *arrMa[30]; Disco arrD[30]; Libro arrL[30]; Software arrS[30]; Fecha fecha,fecha2,fecha3; //Abrir archivos ifstream infoMa; infoMa.open("Material.txt"); ifstream infoRe; infoRe.open("Reserva.txt"); //Declaración variables string titulo,palabra,lineaMa, lineaRe; char letra; int k=0,dia,mes,anio,idMat,idCli,r=0,num,j=0,nL=0,nD=0,nS=0; //Leer datos de archivo material while(infoMa>>idMat>>titulo>>letra>>num>>palabra){ switch(letra){ case 'L': arrMa[nL] = &arrL[nL]; arrMa[nL]->setIdMaterial(idMat); //cout<<arrMa[r]->getIdMaterial()<<"\t"; arrMa[nL]->setTitulo(titulo); //cout<<arrMa[r]->getTitulo()<<"\t"; arrL[nL].setNumPag(num); //cout<<arrL[r].getNumPag()<<"\t"; arrL[nL].setAutor(palabra); //cout<<arrL[r].getAutor()<<endl; nL++; break; case 'D': arrMa[nD] = &arrD[nD]; arrMa[nD]->setIdMaterial(idMat); //cout<<arrMa[r]->getIdMaterial()<<"\t"; arrMa[nD]->setTitulo(titulo); //cout<<arrMa[r]->getTitulo()<<"\t"; arrD[nD].setDuracion(num); //cout<<arrD[r].getDuracion()<<"\t"; arrD[nD].setGenero(palabra); //cout<<arrD[r].getGenero()<<endl; nD++; break; case 'S': arrMa[nS] = &arrS[nS]; arrMa[nS]->setIdMaterial(idMat); //cout<<arrMa[r]->getIdMaterial()<<"\t"; arrMa[nS]->setTitulo(titulo); //cout<<arrMa[r]->getTitulo()<<"\t"; arrS[nS].setVersion(num); //cout<<arrS[r].getVersion()<<"\t"; arrS[nS].setSO(palabra); //cout<<arrS[r].getSO()<<endl; nS++; break; default: cout<<"Material no encontrado"<<endl; return 0; } r++; } //Leer datos de archivo reserva while(infoRe>>dia>>mes>>anio>>idMat>>idCli){ //Verificación fecha //cout<<dia<<"\t"; //cout<<mes<<"\t"; //cout<<anio<<"\t"; //Carga datos en clase fecha fecha.setFecha(dia,mes,anio); //Carga datos en el archivo arrRes[k].setFechaReservacion(fecha); //Verificación idMaterial arrRes[k].setIdMaterial(idMat); //cout<<arrRes[k].getIdMaterial()<<"\t"; //Verfificación idCliente arrRes[k].setIdCliente(idCli); //cout<<arrRes[k].getIdCliente()<<endl; k++;//Salta a la sig localidad del arrRe } char opcion; int id,idM,idC,idMaterial,valiMa; do{ cout<<endl; cout<<"MENÚ"<<endl; cout<<"a. Consultar lista de Materiales"<<endl; cout<<"b. Consultar la lista de reservaciones"<<endl; cout<<"c. Consultar las reservaciones de un material dado"<<endl; cout<<"d. Consultar las reservaciones de una fecha dada"<<endl; cout<<"e. Hacer una reservación"<<endl; cout<<"f. Terminar"<<endl; cout<<endl; cout<<"Teclea la letra de la opción deseada"<<"\t"; cin>>opcion; opcion=tolower(opcion); int z=0,n=0,day,year,month; switch(opcion){ case 'a': cout<<endl; for(int i=0;i<nL;i++){ arrL[i].muestraDatos(); cout<<endl; } for(int i=0;i<nD;i++){ arrD[i].muestraDatos(); cout<<endl; } for(int i=0;i<nS;i++){ arrS[i].muestraDatos(); cout<<endl; } break; case 'b': cout<<endl; cout<<"F inicio"<<"\t"<<"F terminación"<<"\t"<<"Nombre"<<"\t"<<"\t"<<"\t"<<"IdCliente"<<endl; for(int i=0;i<k;i++){ cout<<arrRes[i].getFechaReservacion()<<"\t"; id = arrRes[i].getIdMaterial(); for(int j=0;j<nL;j++){ idM = arrL[j].getIdMaterial(); if(id == idM){ cout<<arrRes[i].calculaFechaFinReserva(7)<<"\t"; cout<<arrL[j].getTitulo()<<"\t"; } } for(int j=0;j<nD;j++){ idM = arrD[j].getIdMaterial(); if(id == idM){ cout<<arrRes[i].calculaFechaFinReserva(2)<<"\t"; cout<<arrD[j].getTitulo()<<"\t"; } } for(int j=0;j<nS;j++){ idM = arrS[j].getIdMaterial(); if(id == idM){ cout<<arrRes[i].calculaFechaFinReserva(1)<<"\t"; cout<<arrS[j].getTitulo()<<"\t"; } } cout<<arrRes[i].getIdCliente()<<endl; } break; case 'c': cout<<endl; do{ cout<<"Teclea id del material"<<"\t"; cin>>idMaterial; for(int j=0;j<nL;j++){ idM = arrL[j].getIdMaterial(); if(idMaterial == idM) n=1; } for(int j=0;j<nD;j++){ idM = arrD[j].getIdMaterial(); if(idMaterial == idM) n=1; } for(int j=0;j<nS;j++){ idM = arrS[j].getIdMaterial(); if(idMaterial == idM) n=1; } }while(n==0); cout<<"F inicio"<<"\t"<<"F terminación"<<"\t"<<"Nombre"<<"\t"<<"\t"<<"\t"<<"IdCliente"<<endl; for(int i=0;i<k;i++){ idM = arrRes[i].getIdMaterial(); fecha = arrRes[i].getFechaReservacion(); if(idMaterial == idM){ cout<<arrRes[i].getFechaReservacion()<<"\t"; for(int j=0;j<nL;j++){ idM = arrL[j].getIdMaterial(); if(idMaterial == idM){ cout<<arrRes[i].calculaFechaFinReserva(7)<<"\t"; cout<<arrL[j].getTitulo()<<"\t";cout<<arrRes[i].getIdCliente()<<endl; z=1; } } for(int j=0;j<nD;j++){ idM = arrD[j].getIdMaterial(); if(idMaterial == idM){ cout<<arrRes[i].calculaFechaFinReserva(2)<<"\t"; cout<<arrD[j].getTitulo()<<"\t"; cout<<arrRes[i].getIdCliente()<<endl; z=1; } } for(int j=0;j<nS;j++){ idM = arrS[j].getIdMaterial(); if(idMaterial == idM){ cout<<arrRes[i].calculaFechaFinReserva(1)<<"\t"; cout<<arrS[j].getTitulo()<<"\t"; cout<<arrRes[i].getIdCliente()<<endl; z=1; } } } } if(z==0){ cout<<"-------------------------------------------------------"<<endl; cout<<"El material no está reservado"<<endl; } break; case 'd': cout<<endl; cout<<"Ingrese fecha deseada:"<<endl; cin>>fecha2; for(int i=0;i<k;i++){ fecha = arrRes[i].getFechaReservacion(); id = arrRes[i].getIdMaterial(); for(int j=0;j<nL;j++){ idM = arrL[j].getIdMaterial(); if(id == idM){ fecha3 = arrRes[i].calculaFechaFinReserva(7); } } for(int j=0;j<nD;j++){ idM = arrD[j].getIdMaterial(); if(id == idM){ fecha3 = arrRes[i].calculaFechaFinReserva(2); } } for(int j=0;j<nS;j++){ idM = arrS[j].getIdMaterial(); if(id == idM){ fecha3 = arrRes[i].calculaFechaFinReserva(1); } } if((fecha2>=fecha) && (fecha2<=fecha3)){ cout<<endl; cout<<"RESERVACIONES"<<endl; cout<<"Fecha"<<"\t"<<"\t"<<"Nombre"<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<<"IdCliente"<<endl; cout<<fecha2<<"\t"; for(int j=0;j<nL;j++){ idM = arrL[j].getIdMaterial(); if(id == idM) cout<<arrL[j].getTitulo()<<"\t"; } for(int j=0;j<nD;j++){ idM = arrD[j].getIdMaterial(); if(id == idM) cout<<arrD[j].getTitulo()<<"\t"; } for(int j=0;j<nS;j++){ idM = arrS[j].getIdMaterial(); if(id == idM) cout<<arrS[j].getTitulo()<<"\t"; } cout<<arrRes[i].getIdCliente()<<endl; z=1; } } if(z==0){ cout<<endl; cout<<"Fecha: "<<"\t"<<fecha2<<endl; cout<<"No hay nada reservado en fecha indicada "<<endl; } break; case 'e': cout<<endl; cout<<"Teclea id del cliente"<<"\t"; cin>>idC; cout<<"Teclea la fecha que desea reservar"<<endl; cout<<"Dia: "<<"\t"; cin>>day; cout<<"Mes: "<<"\t"; cin>>month; cout<<"Anio: "<<"\t"; cin>>year; fecha2.setFecha(day,month,year); do{ cout<<"Teclea id del material"<<"\t"; cin>>idMaterial; for(int j=0;j<nL;j++){ idM = arrL[j].getIdMaterial(); if(idMaterial == idM) n=1; } for(int j=0;j<nD;j++){ idM = arrD[j].getIdMaterial(); if(idMaterial == idM) n=1; } for(int j=0;j<nS;j++){ idM = arrS[j].getIdMaterial(); if(idMaterial == idM) n=1; } }while(n==0); for(int i=0;i<k;i++){ id = arrRes[i].getIdMaterial(); if(idMaterial == id){ fecha = arrRes[i].getFechaReservacion(); for(int j=0;j<nL;j++){ idM = arrL[j].getIdMaterial(); if(id == idM){ fecha3 = arrRes[i].calculaFechaFinReserva(7); } } for(int j=0;j<nD;j++){ idM = arrD[j].getIdMaterial(); if(id == idM){ fecha3 = arrRes[i].calculaFechaFinReserva(2); } } for(int j=0;j<nS;j++){ idM = arrS[j].getIdMaterial(); if(id == idM){ fecha3 = arrRes[i].calculaFechaFinReserva(1); } } if((fecha2>=fecha) && (fecha2<=fecha3)){ cout<<"Material reservado en fecha solicitada: "<<fecha2<<endl; cout<<"NO SE PUEDE HACER RESERVACIÓN"<<endl; z=1; } } } if(z==0){ cout<<endl; cout<<"Fecha: "<<"\t"<<fecha2<<endl; cout<<"Material disponible en fecha indicada "<<endl; cout<<"RESERVACIÓN REALIZADA"<<endl; ofstream infoReSalida; infoReSalida.open("Reserva.txt",ios::app); infoReSalida<<day<<" "<<month<<" "<<year<<" "<<idMaterial<<" "<<idC<<endl; infoReSalida.close(); } break; case 'f': cout<<endl; cout<<"PROGRAMA TERMINADO"<<endl; break; default: cout<<endl; cout<<"NO EXISTE LA OPCIÓN SELECCIONADA"<<endl; } }while(opcion != 'f'); infoMa.close(); infoRe.close(); return 0; }
class Solution { public: int josephus(int n, int k) { if(n==1) return 1; return (josephus(n-1,k)+k-1)%n+1; } };
#ifndef CORE_SRC_CONFIGURATION_H #define CORE_SRC_CONFIGURATION_H #include "ConfigurationReader.h" namespace edlprovider { namespace core { /*! * \brief The Configuration class provides the read values for the application to use. */ class Configuration { public: /*! * \brief Configuration constructor. */ Configuration(); /*! * \brief Loads the specified configuration file. * \param configPath The configuration file path to read. * \return True if the configuration is successfully read. */ bool load(const QString& configPath); /*! * \brief Gets the port to use in the soap service. * \return The configured port found in the configuration. */ quint16 getServicePort() const; /*! * \brief Gets the service host name to use in the soap service. * * If not specified local host is used. * * \return The host name found in the configuration. */ QString getServiceHostName() const; /*! * \brief Gets flag to automatically update the available EDL plugins. * \return The flag to enable/disable the automatic update of the EDL plugins. */ bool getPluginsAutoUpdate() const; private: common::util::ConfigurationReader configReader_; //!< The configuration reader to get the values from. }; } } #endif // CORE_SRC_CONFIGURATION_H
#pragma once #include <QString> class ConstantStrings { public: static const QString averageRatio; static const QString brainCount; static const QString neuronPerBrain; static const QString loopPerCompute; static const QString mutationFrequency; static const QString mutationIntensity; static const QString imageId; static const QString steps; static const QString brains; static const QString brain; static const QString age; static const QString winCount; static const QString loseCount; static const QString dna; static const QString dnaSize; };
#pragma once #include <windows.h> class Waitable { public: Waitable(HANDLE handle); virtual ~Waitable(); bool beWaited(); bool isSignaled(); HANDLE handle; }; class Semaphore: public Waitable { public: Semaphore(LONG initialCount, LONG maximumCount); bool dissipate(); bool accumulate(); }; class Event: public Waitable { public: Event(BOOL manualReset, BOOL initialState); bool happen(); bool over(); }; class Thread: private Waitable { protected: typedef void (Thread::*PWORK)(); PWORK pWork; Event eventStopping; Thread(DWORD stackSize, PWORK pWork); ~Thread(); public: void start(); void stop(); void join(); private: static DWORD WINAPI ThreadFunc(LPVOID param); Event eventStarting, eventDone, eventExiting; Semaphore accessible; };
#pragma once #include "FwdDecl.h" #include "d3d11.h" #include "WinWrappers/ComPtr.h" #include "Keng/GPU/RenderTarget/ISwapChain.h" namespace keng::graphics::gpu { class SwapChain : public core::RefCountImpl<ISwapChain> { public: SwapChain(Device& device, const SwapChainParameters& params, window_system::IWindow& window); ~SwapChain(); virtual void Present() override final; DeviceTexture& GetCurrentTexture(); const DeviceTexture& GetCurrentTexture() const; void CopyFromTexture(const DeviceTexture& texture); private: ComPtr<ID3D11Texture2D> GetBackBuffer(size_t index) const; DevicePtr m_device; TexturePtr m_currentTexture; ComPtr<IDXGISwapChain> m_swapchain; }; }
#include <iostream> bool checkNumber(int number) { if(1 == number || 2 == number || 3 == number) { return true; } else { for(int i = 2; i <= number/2; ++i ) { if(0 == number % i) { return false; } } } } int main() { int number; bool truefalse = true; std::cout<<"Mutqagrel tiv@ ->"; std::cin>>number; truefalse = checkNumber(number); if(truefalse) { std::cout<<number<<" parz tiv e \n"; } else { std::cout<<number<<" parz tiv che \n"; } return 0; }
#pragma once #include "../../Toolbox/Toolbox.h" #include "Texture2D.h" namespace ae { class FramebufferAttachement; /// \ingroup graphics /// <summary> /// 2D multisample data that can be link to a shader to be rendered. /// </summary> class AERO_CORE_EXPORT TextureMultisample : public Texture2D { public: /// <summary>Create an empty multisample texture 2D.</summary> /// <param name="_Width">The width of the texture.</param> /// <param name="_Height">The height of the texture.</param> /// <param name="_Format">Format of the texture : channels, type.</param> /// <param name="_SamplesCount">Number of sample for multi sample texture. 0 or 1 mean no multi sampling.</param> TextureMultisample( Uint32 _Width, Uint32 _Height, TexturePixelFormat _Format = TexturePixelFormat::DefaultTexture, Uint32 _SamplesCount = 0 ); /// <summary>Create an empty multisample texture with framebuffer attachement settings.</summary> /// <param name="_Width">The width of the texture.</param> /// <param name="_Height">The height of the texture.</param> /// <param name="_FramebufferAttachement">Settings to apply.</param> TextureMultisample( Uint32 _Width, Uint32 _Height, const FramebufferAttachement& _FramebufferAttachement ); /// <summary>Create an empty multisample texture 2D.</summary> /// <param name="_Width">The width of the texture.</param> /// <param name="_Height">The height of the texture.</param> /// <param name="_Format">Format of the texture : channels, type.</param> /// <param name="_SamplesCount">Number of sample for multi sample texture. 0 or 1 mean no multi sampling.</param> void Set( Uint32 _Width, Uint32 _Height, TexturePixelFormat _Format = TexturePixelFormat::DefaultTexture, Uint32 _SamplesCount = 0 ); /// <summary>Create an empty multisample texture 2D.</summary> /// <param name="_Width">The width of the texture.</param> /// <param name="_Height">The height of the texture.</param> /// <param name="_Format">Format of the texture : channels, type.</param> void Set( Uint32 _Width, Uint32 _Height, TexturePixelFormat _Format = TexturePixelFormat::DefaultTexture ) override; /// <summary>Create an empty texture with framebuffer attachement settings..</summary> /// <param name="_Width">The width of the texture.</param> /// <param name="_Height">The height of the texture.</param> /// <param name="_FramebufferAttachement">Settings to apply.</param> void Set( Uint32 _Width, Uint32 _Height, const FramebufferAttachement& _FramebufferAttachement ); /// <summary>Set the number of samples for the texture in case of 2D mutli sample texture.</summary> /// <param name="_SamplesCount">The number of samples for multi sample texture to apply.</param> void SetSamplesCount( Uint32 _SamplesCount ); /// <summary>The number of samples for the texture in case of 2D mutli sample texture.</summary> /// <returns>The number of samples for multi sample texture.</returns> Uint32 GetSamplesCount() const; /// <summary>Called by the framebuffer to attach the texture to it.</summary> void AttachToFramebuffer( const FramebufferAttachement& _Attachement ) const override; /// <summary> /// Function called by the editor. /// It allows the class to expose some attributes for user editing. /// Think to call all inherited class function too when overloading. /// </summary> virtual void ToEditor(); protected: /// <summary>Hide ToImage method of Texture2D, it is not supported for multisample texture..</summary> using Texture2D::ToImage; /// <summary>Create an empty texture.</summary> void SetupEmpty() override; protected: /// <summary>In case of multi sample 2D texture, the number of sample in the texture.</summary> Uint32 m_SampleCount; }; } // ae
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-1999 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "modules/dom/src/domenvironmentimpl.h" #include "modules/dom/src/domcore/implem.h" #include "modules/dom/src/domcore/text.h" #include "modules/dom/src/domhtml/htmlimplem.h" #include "modules/dom/src/domhtml/htmldoc.h" #include "modules/dom/src/domhtml/htmlelem.h" DOM_HTMLDOMImplementation::DOM_HTMLDOMImplementation() { } void DOM_HTMLDOMImplementation::InitializeL() { DOM_DOMImplementation::ConstructDOMImplementationL(*this, GetRuntime()); AddFunctionL(createHTMLDocument, "createHTMLDocument", "s-"); } /* static */ OP_STATUS DOM_HTMLDOMImplementation::Make(DOM_HTMLDOMImplementation *&implementation, DOM_EnvironmentImpl *environment) { DOM_Runtime *runtime = environment->GetDOMRuntime(); RETURN_IF_ERROR(DOM_Object::DOMSetObjectRuntime(implementation = OP_NEW(DOM_HTMLDOMImplementation, ()), runtime, runtime->GetObjectPrototype(), "DOMImplementation")); TRAPD(status, implementation->InitializeL()); return status; } int DOM_HTMLDOMImplementation::createHTMLDocument(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(implementation, DOM_TYPE_HTML_IMPLEMENTATION, DOM_HTMLDOMImplementation); DOM_CHECK_ARGUMENTS("s"); DOM_HTMLDocument *document; CALL_FAILED_IF_ERROR(DOM_HTMLDocument::Make(document, implementation, TRUE)); DOM_DocumentType *doctype; CALL_FAILED_IF_ERROR(DOM_DocumentType::Make(doctype, origining_runtime->GetEnvironment(), UNI_L("html"), NULL, NULL)); doctype->DOMChangeOwnerDocument(document); CALL_FAILED_IF_ERROR(document->InsertChild(doctype, document, origining_runtime)); DOM_HTMLElement *html; CALL_FAILED_IF_ERROR(DOM_HTMLElement::CreateElement(html, document, UNI_L("html"))); DOM_HTMLElement *head; CALL_FAILED_IF_ERROR(DOM_HTMLElement::CreateElement(head, document, UNI_L("head"))); DOM_HTMLElement *title; CALL_FAILED_IF_ERROR(DOM_HTMLElement::CreateElement(title, document, UNI_L("title"))); DOM_Text *title_text; CALL_FAILED_IF_ERROR(DOM_Text::Make(title_text, document, argv[0].value.string)); DOM_HTMLElement *body; CALL_FAILED_IF_ERROR(DOM_HTMLElement::CreateElement(body, document, UNI_L("body"))); CALL_FAILED_IF_ERROR(document->InsertChild(html, NULL, origining_runtime)); CALL_FAILED_IF_ERROR(html->InsertChild(head, NULL, origining_runtime)); CALL_FAILED_IF_ERROR(head->InsertChild(title, NULL, origining_runtime)); CALL_FAILED_IF_ERROR(title->InsertChild(title_text, NULL, origining_runtime)); CALL_FAILED_IF_ERROR(html->InsertChild(body, NULL, origining_runtime)); DOM_Object::DOMSetObject(return_value, document); return ES_VALUE; }
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: vector<vector<int>> generateMatrix(int n) { //基本思想:模拟旋转过程,从外往内按层模拟旋转输出,每一层输出四条边。 //对于这种螺旋遍历的方法,重要的是要确定上下左右四条边的位置,上边界和左边界都为layer也是层数,右边界和下边界都为n-layer。 vector<vector<int>> res(n, vector<int>(n, 0)); //cnt为填入的数字从1到n^2 int cnt = 1, layer = 0, i, m = n; //从外往内按层模拟旋转输出,每一层输出四条边 while (m > 0) { //输出上边界 for (i = layer; i < n - layer; i++) res[layer][i] = cnt++; //输出右边界 for (i = layer + 1; i < n - layer; i++) res[i][n - layer - 1] = cnt++; //输出下边界 for (i = n - layer - 2; i >= layer; i--) res[n - layer - 1][i] = cnt++; //输出左边界 for (i = n - layer - 2; i > layer; i--) res[i][layer] = cnt++; layer++; m -= 2; } return res; } }; int main() { Solution solute; int n = 5; vector<vector<int>> res; res = solute.generateMatrix(n); for (int i = 0; i < res.size(); i++) { for (int j = 0; j < res[i].size(); j++) cout << res[i][j] << " "; cout << endl; } return 0; }
#include "table.h" #include "system.h" /* Create a table to hold at most "size" entries. */ Table::Table(int size){ tableSize = size; tableLock = new Lock("tableLock"); table = (void**) new int[size]; for(int i = 0; i < size;i++){ table[i] = NULL; } } Table::~Table(){ for(int i = 0; i < tableSize; i++) { delete (int*)table[i]; } if (tableLock) delete tableLock; if(table) delete table; } int Table::getTableSize(){ return tableSize; } /* Allocate a table slot for "object", returning the "index" of the allocated entry; otherwise, return -1 if no free slots are available. */ int Table::Alloc(void *object) { int id = 0; tableLock->Acquire(); for(int i = 0; i < tableSize; i++) { if(table[i] == NULL){ table[i] = object; id = (i + 1); break; } } tableSize--; tableLock->Release(); return id; } /* Retrieve the object from table slot at "index", or NULL if that slot has not been allocated. */ void* Table::Get(int index) { void* f; tableLock->Acquire(); if(index > 0 && index < tableSize) f = table[(index - 1)]; else f = NULL; tableLock->Release(); return f; } /* Free the table slot at index. */ void Table::Release(int index) { tableLock->Acquire(); if(index > 0 && index < tableSize) { table[(index - 1)] = NULL; tableSize++; } else { // leave like this now, may need ASSERT(FALSE) printf("index bigger or less than the table"); ASSERT(FALSE); } tableLock->Release(); } void Table::ReleaseAll(){ tableLock->Acquire(); for(int i = 0; i <tableSize; i++) table[i] = NULL; tableLock->Release(); } bool Table::AnyExist(){ int anyExist = 0; tableLock->Acquire(); for (int i = 0; i < tableSize; i++ ){ if (table[i] != NULL) anyExist++; } ASSERT(anyExist != 0); tableLock->Release(); return anyExist; }
// // Created by Brady Bodily on 4/19/17. // #ifndef ITAK_USERIPLIST_HPP #define ITAK_USERIPLIST_HPP #include "UserIP.hpp" #include <iostream> #include <fstream> #include <string> #include <vector> class UserIPList { private: std::vector<UserIP> AllIPs; public: UserIPList(std::ifstream* fin); void PrintFromIndex(int index); UserIP GetAddressFromIndex(int index); UserIP GetAddressByIP(std::string IP); void PrintAll(); int size(){return AllIPs.size();}; }; #endif //ITAK_USERIPLIST_HPP
#include <cassert> #include <cmath> using namespace std; #include "gaussianbasisfunction.h" #include "kmeans.h" GaussianBasisFunction::GaussianBasisFunction(double _mean, double _variance) : mean(_mean), variance(_variance) { } QVector<double> GaussianBasisFunction::sample(QVector<double> xs) const { QVector<double> samples(xs.size()); for(int i = 0; i < xs.size(); i++) { samples[i] = exp(-1.0/(2*variance)*pow(xs[i] - mean, 2.0)); } return samples; }
// // Created by OLD MAN on 2020/1/8. // //将一个数组中的值按逆序重新存放。例如,原来的顺序为 8,6,5,4,1。要求改为 1,4,5,6,8。 // //输入格式\ //输入为两行:第一行数组中元素的个数 n(1<n<100),第二行是 n 个整数(整数范围为 [−100,100]),每两个整数之间用空格分隔。 // //输出格式\ //输出为一行:输出逆序后数组的整数,每两个整数之间用空格分隔。 #include <iostream> using namespace std; int main(){ int n; cin>>n; int a[n]; for (int i = 0; i < n; ++i) { cin>>a[i]; } for (int j = n-1; j >= 0; --j) { cout<<a[j]<<" "; } }
#include<malloc.h> #include<assert.h> #include<stdio.h> template<class T> class Vector { typedef int ptrdiff_t; //Vector的嵌套型别定义(参考vector源码) typedef T value_type;//存储的数据类型 typedef value_type* pointer;//可以指向存储的数据的指针 typedef value_type* iterator;//迭代器(与指针相同) typedef size_t size_type;//数据size的类型 typedef value_type& reference;//数据的引用类型 typedef ptrdiff_t difference_type;//表示两个迭代器之间的距离,C++内置定义typedef int ptrdiff_t; public: Vector()//默认构造函数 :_start(nullptr) , _finish(nullptr) , _end(nullptr) , _size(0) , _capacity(0) {} Vector(size_type n, value_type value)//第一个参数代表要存放数据数量,第二个参数表示要存放的值 { //申请空间并安装好迭代器 _size = n; _capacity = n; _start = new value_type[_capacity]; assert(_start); _end = _start + _capacity; _finish = _start + _size; //放入数据 iterator ptr = _start; while (n--) { *ptr++ = value; } } Vector(iterator start, iterator end)//数组的头和尾,前闭后开 { //申请空间并安装好迭代器 _capacity = end - start; _size = _capacity; _start = new value_type[_capacity]; assert(_start); _end = _start + _capacity; _finish = _start + _size; //放入数据 iterator ptr = _start; size_t i = 0; for (ptr = _start; (ptr + i) != _finish; ++i) { ptr[i] = start[i]; } } Vector(Vector<T>& v)//拷贝构造函数 { //申请空间并安装迭代器 _capacity = v.capacity(); _size = v.size(); _start = new value_type[_capacity]; assert(_start); _end = _start + _capacity; _finish = _start + _size; //放入数据 iterator ptr = v.begin(); iterator ptr_me = _start; size_type i = 0; while ((ptr + i) != v.end()) { ptr_me[i] = ptr[i]; i += 1; } } const size_type capacity()const { return this->_capacity; } const size_type size()const { return this->_size; } iterator begin()const { return this->_start; } const iterator cbegin()const { return this->_start; } iterator end()const { return this->_end; } const iterator cend()const { return this->_end; } iterator rbegin()const { return (_end - 1); } const iterator crbegin()const { return (_end - 1); } iterator rend()const { return _start; } const iterator crend()const { return _start; } const size_type max_size()const { return _capacity; } const bool empty()const { return _size == 0; } void resize(size_type size,value_type value = 0) { if (size <= _size) _size = size; else { while (((_start + _size) != (_start + size)) && ((_start + _size) != _end)) { _start[_size] = value; _size += 1; } _size = size; } } void reserve(size_type capacity) { //判断新容量是否大于旧容量 if (capacity <= _capacity) return; //保存旧空间信息 size_type old_capacity = _capacity; size_type old_size = _size; iterator old_start = _start; iterator old_end = _end; iterator old_finish = _finish; //开辟新空间并安装迭代器 _capacity = capacity; _start = new value_type[_capacity]; _end = _start + _capacity; _finish = _start + _size; //复制旧空间的数据 size_type i = 0; while (_start + i != _start + _size) { _start[i] = old_start[i]; i += 1; } //释放旧空间 delete[] old_start; old_start = nullptr; old_end = nullptr; } void InsertPop(value_type value);//尾插 //~Vector();//析构函数 const size_t at(value_type value)const { iterator = _start; size_t count = 0; while ((*(_start + count) != value) && (_start + count != end)) { count += 1; } if ((_start + count) == _end) return -1; return count; } value_type front()const { return *_start; } value_type back()const { return *(_end - 1); } value_type operator[](size_type i)const { return *(_start + i); } void push_back(value_type value) { if (!has_space()) reserve(_capacity * 2+1); *(_start + _size) = value; _size += 1; } void pop_back() { _size -= 1; } void insert(size_type pos, const value_type value)//固定位置插入单个数据 { if (!has_space()) reserve(_capacity * 2 + 1); if (pos >= _size) { printf("所插入位置之前还有空位置,将为您尾插入可使用的第一个位置!\n"); push_back(value); } else { iterator ptr = _start + _size - 1; size_type num = _size - pos; while (num--) { move(ptr, ptr + 1); } *(_start + pos) = value; } } void insert(size_type pos, const size_type n, value_type value)//从固定位置向后插入固定数目的固定数据 { //准备空间 while ((_size + n) >= _capacity) { reserve(_capacity * 2 + 1); } //先将pos位置之后的所有数据存在另外的一块空间内 size_type temp_size = _size - pos; iterator temp_start = new value_type[temp_size]; iterator temp_end = temp_start + temp_size; size_t i = 0; while ((temp_start + i) != (temp_end)) { temp_start[i] = _start[pos + i]; i += 1; } //从真实空间的pos位置开始向后插入需要的数据 size_t temp_n = n; while (temp_n--) { _start[pos] = value; _size += 1; pos += 1; } //将临时空间内的数据补齐 i = 0; while ((temp_start + i) != temp_end) { _start[_size - n + i] = temp_start[i]; i += 1; } //释放临时空间 delete temp_start; temp_start = nullptr; temp_end = nullptr; } void insert(size_type pos, value_type* start, value_type* end) { //准备空间 size_t size = end - start; while (_size + size >= _capacity) { reserve(_capacity * 2 + 1); } //用临时空间保存pos位置向后的数据 size_type temp_size = _size - pos; iterator temp_start = new value_type[temp_size]; iterator temp_end = temp_start + temp_size; size_t i = 0; while ((temp_start + i) != (temp_end)) { temp_start[i] = _start[pos + i]; i += 1; } //将要插入的数据进行插入 size_t temp_pos = pos; while (start + temp_pos != end) { _start[temp_pos] = start[temp_pos]; _size += 1; temp_pos += 1; } //将临时空间内的数据补齐 i = 0; while ((temp_start + i) != temp_end) { _start[_size - size +i] = temp_start[i]; i += 1; } //释放临时空间 delete temp_start; temp_start = nullptr; temp_end = nullptr; } void swap(Vector<value_type>& v)//未完成实现 { //交换size与capacity size_t temp = _size; _size = v.size_change(); v.size_change() = temp; temp = _capacity; _capacity = v.capacity_change(); v.capacity_change() = temp; //交换指针 iterator temp_ptr = _start; _start = v.start_change(); v.start_change() = temp_ptr; temp_ptr = _end; _end = v.end_change(); v.end_change() = temp_ptr; temp_ptr = _finish; _finish = v.finish_change(); v.finish_change() = _finish; } void earse(size_t pos)//删除某一个数据 { if (_size <= pos) { printf("%d位置没有数据!\n", pos); return; } while ((pos + 1) != _size) { move(_start + pos + 1, _start + pos); pos += 1; } _size -= 1; } void earse(size_t pos_start, size_t pos_end)//删除某一段数据(前闭后开) { if (pos_start > pos_end) assert(0); else if (pos_start == pos_end) { earse(pos_start); return; } if (pos_start >= _size) { printf("所选区域不存在数据!\n"); return; } if (pos_end >= _size - 1) { _size = _size - (pos_end - pos_start); } else { size_t pos_temp_end = pos_end; while ((_start + pos_temp_end ) != (_start + _size)) { move(_start + pos_temp_end , _start + pos_temp_end - (pos_end - pos_start)); pos_temp_end += 1; } _size = _size - (pos_end - pos_start); } } protected: const bool has_space()const { return _size != _capacity; } void move(const iterator pos1, iterator pos2) { *pos2 = *pos1; } size_t& size_change() { return _size; } size_t& capacity_change() { return _capacity; } iterator& start_change() { return _start; } iterator& finish_change() { return _finish; } iterator& end_change() { return _end; } void clear() { _size = 0; _finish = _start; } private: iterator _start;//表示目前使用空间的头 iterator _finish;//表示目前使用空间的尾 iterator _end;//表示目前可用空间的尾 size_type _capacity;//表示所维护的空间总的容量 size_type _size;//表示已经使用容量的大小 };
////////////////////////////////////////////////////////////////////// // Interpolate.cpp // // 插值类 CInterpolate 的实现代码 // // 周长发编制, 2002/8 ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Interpolate.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // 基本构造函数 ////////////////////////////////////////////////////////////////////// CInterpolate::CInterpolate() { } ////////////////////////////////////////////////////////////////////// // 析构函数 ////////////////////////////////////////////////////////////////////// CInterpolate::~CInterpolate() { } ////////////////////////////////////////////////////////////////////// // 将字符串转化为结点的值 // // 参数: // 1. CString s - 数字和分隔符构成的字符串 // 2. int n - 结点的个数 // 3. double dblNodes[] - 一维数组,长度为n,返回结点的值 // 4. const CString& sDelim - 数字之间的分隔符,默认为空格 // // 返回值:int 型,转换成功的结点的个数 ////////////////////////////////////////////////////////////////////// int CInterpolate::GetNodesFromString(CString s, int n, double dblNodes[], const CString& sDelim /*= " "*/) { // 将结点值初始化为0 memset(dblNodes, 0, n*sizeof(double)); // 构造根据指定的分界符将字符串分解为不同的子串的对象 CTokenizer tk(s, sDelim); CString sElement; // 分解字符串,给结点赋值 int i = 0; while (tk.Next(sElement)) { sElement.TrimLeft(); sElement.TrimRight(); double v = atof(sElement); dblNodes[i++] = v; if (i == n) break; } return i; } ////////////////////////////////////////////////////////////////////// // 一元全区间不等距插值 // // 参数: // 1. int n - 结点的个数 // 2. double x[] - 一维数组,长度为n,存放给定的n个结点的值x(i), // 要求x(0)<x(1)<...<x(n-1) // 3. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 4. double t - 存放指定的插值点的值 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueLagrange(int n, double x[], double y[], double t) { int i,j,k,m; double z,s; // 初值 z=0.0; // 特例处理 if (n<1) return(z); if (n==1) { z=y[0]; return(z); } if (n==2) { z=(y[0]*(t-x[1])-y[1]*(t-x[0]))/(x[0]-x[1]); return(z); } // 开始插值 i=0; while ((x[i]<t)&&(i<n)) i=i+1; k=i-4; if (k<0) k=0; m=i+3; if (m>n-1) m=n-1; for (i=k;i<=m;i++) { s=1.0; for (j=k;j<=m;j++) { if (j!=i) // 拉格朗日插值公式 s=s*(t-x[j])/(x[i]-x[j]); } z=z+s*y[i]; } return(z); } ////////////////////////////////////////////////////////////////////// // 一元全区间等距插值 // // 参数: // 1. int n - 结点的个数 // 2. double x0 - 存放等距n个结点中第一个结点的值 // 3. double xStep - 等距结点的步长 // 4. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 5. double t - 存放指定的插值点的值 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueLagrange(int n, double x0, double xStep, double y[], double t) { int i,j,k,m; double z,s,xi,xj; float p,q; // 初值 z=0.0; // 特例处理 if (n<1) return(z); if (n==1) { z=y[0]; return(z); } if (n==2) { z=(y[1]*(t-x0)-y[0]*(t-x0-xStep))/xStep; return(z); } // 开始插值 if (t>x0) { p=(t-x0)/xStep; i=(int)p; q=(float)i; if (p>q) i=i+1; } else i=0; k=i-4; if (k<0) k=0; m=i+3; if (m>n-1) m=n-1; for (i=k;i<=m;i++) { s=1.0; xi=x0+i*xStep; for (j=k; j<=m; j++) { if (j!=i) { xj=x0+j*xStep; // 拉格朗日插值公式 s=s*(t-xj)/(xi-xj); } } z=z+s*y[i]; } return(z); } ////////////////////////////////////////////////////////////////////// // 一元三点不等距插值 // // 参数: // 1. int n - 结点的个数 // 2. double x[] - 一维数组,长度为n,存放给定的n个结点的值x(i) // 3. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 4. double t - 存放指定的插值点的值 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueLagrange3(int n, double x[], double y[], double t) { int i,j,k,m; double z,s; // 初值 z=0.0; // 特例处理 if (n<1) return(z); if (n==1) { z=y[0]; return(z); } if (n==2) { z=(y[0]*(t-x[1])-y[1]*(t-x[0]))/(x[0]-x[1]); return(z); } // 开始插值 if (t<=x[1]) { k=0; m=2; } else if (t>=x[n-2]) { k=n-3; m=n-1; } else { k=1; m=n; while (m-k!=1) { i=(k+m)/2; if (t<x[i-1]) m=i; else k=i; } k=k-1; m=m-1; if (fabs(t-x[k])<fabs(t-x[m])) k=k-1; else m=m+1; } z=0.0; for (i=k;i<=m;i++) { s=1.0; for (j=k;j<=m;j++) { if (j!=i) // 抛物线插值公式 s=s*(t-x[j])/(x[i]-x[j]); } z=z+s*y[i]; } return(z); } ////////////////////////////////////////////////////////////////////// // 一元三点等距插值 // // 参数: // 1. int n - 结点的个数 // 2. double x0 - 存放等距n个结点中第一个结点的值 // 3. double xStep - 等距结点的步长 // 4. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 5. double t - 存放指定的插值点的值 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueLagrange3(int n, double x0, double xStep, double y[], double t) { int i,j,k,m; double z,s,xi,xj; // 初值 z=0.0; // 特例处理 if (n<1) return(z); if (n==1) { z=y[0]; return(z); } if (n==2) { z=(y[1]*(t-x0)-y[0]*(t-x0-xStep))/xStep; return(z); } // 开始插值 if (t<=x0+xStep) { k=0; m=2; } else if (t>=x0+(n-3)*xStep) { k=n-3; m=n-1; } else { i=(int)((t-x0)/xStep)+1; if (fabs(t-x0-i*xStep)>=fabs(t-x0-(i-1)*xStep)) { k=i-2; m=i; } else { k=i-1; m=i+1; } } z=0.0; for (i=k;i<=m;i++) { s=1.0; xi=x0+i*xStep; for (j=k;j<=m;j++) { if (j!=i) { xj=x0+j*xStep; // 抛物线插值公式 s=s*(t-xj)/(xi-xj); } } z=z+s*y[i]; } return(z); } ////////////////////////////////////////////////////////////////////// // 连分式不等距插值 // // 参数: // 1. int n - 结点的个数 // 2. double x[] - 一维数组,长度为n,存放给定的n个结点的值x(i) // 3. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 4. double t - 存放指定的插值点的值 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValuePqs(int n, double x[], double y[], double t) { int i,j,k,m,l; double z,h,b[8]; // 初值 z=0.0; // 特例处理 if (n<1) return(z); if (n==1) { z=y[0]; return(z); } // 连分式插值 if (n<=8) { k=0; m=n; } else if (t<x[4]) { k=0; m=8; } else if (t>x[n-5]) { k=n-8; m=8; } else { k=1; j=n; while (j-k!=1) { i=(k+j)/2; if (t<x[i-1]) j=i; else k=i; } k=k-4; m=8; } b[0]=y[k]; for (i=2;i<=m;i++) { h=y[i+k-1]; l=0; j=1; while ((l==0)&&(j<=i-1)) { if (fabs(h-b[j-1])+1.0==1.0) l=1; else h=(x[i+k-1]-x[j+k-1])/(h-b[j-1]); j=j+1; } b[i-1]=h; if (l!=0) b[i-1]=1.0e+35; } z=b[m-1]; for (i=m-1;i>=1;i--) z=b[i-1]+(t-x[i+k-1])/z; return(z); } ////////////////////////////////////////////////////////////////////// // 连分式等距插值 // // 参数: // 1. int n - 结点的个数 // 2. double x0 - 存放等距n个结点中第一个结点的值 // 3. double xStep - 等距结点的步长 // 4. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 5. double t - 存放指定的插值点的值 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValuePqs(int n, double x0, double xStep, double y[], double t) { int i,j,k,m,l; double z,hh,xi,xj,b[8]; // 初值 z=0.0; // 特例处理 if (n<1) return(z); if (n==1) { z=y[0]; return(z); } // 连分式插值 if (n<=8) { k=0; m=n; } else if (t<(x0+4.0*xStep)) { k=0; m=8; } else if (t>(x0+(n-5)*xStep)) { k=n-8; m=8; } else { k=(int)((t-x0)/xStep)-3; m=8; } b[0]=y[k]; for (i=2;i<=m;i++) { hh=y[i+k-1]; l=0; j=1; while ((l==0)&&(j<=i-1)) { if (fabs(hh-b[j-1])+1.0==1.0) l=1; else { xi=x0+(i+k-1)*xStep; xj=x0+(j+k-1)*xStep; hh=(xi-xj)/(hh-b[j-1]); } j=j+1; } b[i-1]=hh; if (l!=0) b[i-1]=1.0e+35; } z=b[m-1]; for (i=m-1;i>=1;i--) z=b[i-1]+(t-(x0+(i+k-1)*xStep))/z; return(z); } ////////////////////////////////////////////////////////////////////// // 埃尔米特不等距插值 // // 参数: // 1. int n - 结点的个数 // 2. double x[] - 一维数组,长度为n,存放给定的n个结点的值x(i) // 3. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 4. double dy[] - 一维数组,长度为n,存放给定的n个结点的函数导数值y'(i), // y'(i) = f'(x(i)), i=0,1,...,n-1 // 5. double t - 存放指定的插值点的值 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueHermite(int n, double x[], double y[], double dy[], double t) { int i,j; double z,p,q,s; // 初值 z=0.0; // 循环插值 for (i=1;i<=n;i++) { s=1.0; for (j=1;j<=n;j++) { if (j!=i) s=s*(t-x[j-1])/(x[i-1]-x[j-1]); } s=s*s; p=0.0; for (j=1;j<=n;j++) { if (j!=i) p=p+1.0/(x[i-1]-x[j-1]); } q=y[i-1]+(t-x[i-1])*(dy[i-1]-2.0*y[i-1]*p); z=z+q*s; } return(z); } ////////////////////////////////////////////////////////////////////// // 埃尔米特等距插值 // // 参数: // 1. int n - 结点的个数 // 2. double x0 - 存放等距n个结点中第一个结点的值 // 3. double xStep - 等距结点的步长 // 4. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 4. double dy[] - 一维数组,长度为n,存放给定的n个结点的函数导数值y'(i), // y'(i) = f'(x(i)), i=0,1,...,n-1 // 5. double t - 存放指定的插值点的值 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueHermite(int n, double x0, double xStep, double y[], double dy[], double t) { int i,j; double z,s,p,q; // 初值 z=0.0; // 循环插值 for (i=1;i<=n;i++) { s=1.0; q=x0+(i-1)*xStep; for (j=1;j<=n;j++) { p=x0+(j-1)*xStep; if (j!=i) s=s*(t-p)/(q-p); } s=s*s; p=0.0; for (j=1;j<=n;j++) { if (j!=i) p=p+1.0/(q-(x0+(j-1)*xStep)); } q=y[i-1]+(t-q)*(dy[i-1]-2.0*y[i-1]*p); z=z+q*s; } return(z); } ////////////////////////////////////////////////////////////////////// // 埃特金不等距逐步插值 // // 参数: // 1. int n - 结点的个数 // 2. double x[] - 一维数组,长度为n,存放给定的n个结点的值x(i) // 3. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 4. double t - 存放指定的插值点的值 // 5. double eps - 控制精度参数,默认值为0.000001 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueAitken(int n, double x[], double y[], double t, double eps /*= 0.000001*/) { int i,j,k,m,l; double z,xx[10],yy[10]; // 初值 z=0.0; // 特例处理 if (n<1) return(z); if (n==1) { z=y[0]; return(z); } // 开始插值 m=10; if (m>n) m=n; if (t<=x[0]) k=1; else if (t>=x[n-1]) k=n; else { k=1; j=n; while ((k-j!=1)&&(k-j!=-1)) { l=(k+j)/2; if (t<x[l-1]) j=l; else k=l; } if (fabs(t-x[l-1])>fabs(t-x[j-1])) k=j; } j=1; l=0; for (i=1;i<=m;i++) { k=k+j*l; if ((k<1)||(k>n)) { l=l+1; j=-j; k=k+j*l; } xx[i-1]=x[k-1]; yy[i-1]=y[k-1]; l=l+1; j=-j; } i=0; do { i=i+1; z=yy[i]; for (j=0;j<=i-1;j++) z=yy[j]+(t-xx[j])*(yy[j]-z)/(xx[j]-xx[i]); yy[i]=z; } while ((i!=m-1)&&(fabs(yy[i]-yy[i-1])>eps)); return(z); } ////////////////////////////////////////////////////////////////////// // 埃特金等距逐步插值 // // 参数: // 1. int n - 结点的个数 // 2. double x0 - 存放等距n个结点中第一个结点的值 // 3. double xStep - 等距结点的步长 // 4. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 5. double t - 存放指定的插值点的值 // 6. double eps - 控制精度参数,默认值为0.000001 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueAitken(int n, double x0, double xStep, double y[], double t, double eps /*= 0.000001*/) { int i,j,k,m,l; double z,xx[10],yy[10]; // 初值 z=0.0; // 特例处理 if (n<1) return(z); if (n==1) { z=y[0]; return(z); } // 开始插值 m=10; if (m>n) m=n; if (t<=x0) k=1; else if (t>=x0+(n-1)*xStep) k=n; else { k=1; j=n; while ((k-j!=1)&&(k-j!=-1)) { l=(k+j)/2; if (t<x0+(l-1)*xStep) j=l; else k=l; } if (fabs(t-(x0+(l-1)*xStep))>fabs(t-(x0+(j-1)*xStep))) k=j; } j=1; l=0; for (i=1;i<=m;i++) { k=k+j*l; if ((k<1)||(k>n)) { l=l+1; j=-j; k=k+j*l; } xx[i-1]=x0+(k-1)*xStep; yy[i-1]=y[k-1]; l=l+1; j=-j; } i=0; do { i=i+1; z=yy[i]; for (j=0;j<=i-1;j++) z=yy[j]+(t-xx[j])*(yy[j]-z)/(xx[j]-xx[i]); yy[i]=z; } while ((i!=m-1)&&(fabs(yy[i]-yy[i-1])>eps)); return(z); } ////////////////////////////////////////////////////////////////////// // 光滑不等距插值 // // 参数: // 1. int n - 结点的个数 // 2. double x[] - 一维数组,长度为n,存放给定的n个结点的值x(i) // 3. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 4. double t - 存放指定的插值点的值 // 5. double s[] - 一维数组,长度为5,其中s(0),s(1),s(2),s(3)返回三次多项式的系数, // s(4)返回指定插值点t处的函数近似值f(t)(k<0时)或任意值(k>=0时) // 6. int k - 控制参数,若k>=0,则只计算第k个子区间[x(k), x(k+1)]上的三次多项式的系数 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueAkima(int n, double x[], double y[], double t, double s[], int k /*= -1*/) { int kk,m,l; double u[5],p,q; // 初值 s[4]=0.0; s[0]=0.0; s[1]=0.0; s[2]=0.0; s[3]=0.0; // 特例处理 if (n<1) return s[4]; if (n==1) { s[0]=y[0]; s[4]=y[0]; return s[4]; } if (n==2) { s[0]=y[0]; s[1]=(y[1]-y[0])/(x[1]-x[0]); if (k<0) s[4]=(y[0]*(t-x[1])-y[1]*(t-x[0]))/(x[0]-x[1]); return s[4]; } // 插值 if (k<0) { if (t<=x[1]) kk=0; else if (t>=x[n-1]) kk=n-2; else { kk=1; m=n; while (((kk-m)!=1)&&((kk-m)!=-1)) { l=(kk+m)/2; if (t<x[l-1]) m=l; else kk=l; } kk=kk-1; } } else kk=k; if (kk>=n-1) kk=n-2; u[2]=(y[kk+1]-y[kk])/(x[kk+1]-x[kk]); if (n==3) { if (kk==0) { u[3]=(y[2]-y[1])/(x[2]-x[1]); u[4]=2.0*u[3]-u[2]; u[1]=2.0*u[2]-u[3]; u[0]=2.0*u[1]-u[2]; } else { u[1]=(y[1]-y[0])/(x[1]-x[0]); u[0]=2.0*u[1]-u[2]; u[3]=2.0*u[2]-u[1]; u[4]=2.0*u[3]-u[2]; } } else { if (kk<=1) { u[3]=(y[kk+2]-y[kk+1])/(x[kk+2]-x[kk+1]); if (kk==1) { u[1]=(y[1]-y[0])/(x[1]-x[0]); u[0]=2.0*u[1]-u[2]; if (n==4) u[4]=2.0*u[3]-u[2]; else u[4]=(y[4]-y[3])/(x[4]-x[3]); } else { u[1]=2.0*u[2]-u[3]; u[0]=2.0*u[1]-u[2]; u[4]=(y[3]-y[2])/(x[3]-x[2]); } } else if (kk>=(n-3)) { u[1]=(y[kk]-y[kk-1])/(x[kk]-x[kk-1]); if (kk==(n-3)) { u[3]=(y[n-1]-y[n-2])/(x[n-1]-x[n-2]); u[4]=2.0*u[3]-u[2]; if (n==4) u[0]=2.0*u[1]-u[2]; else u[0]=(y[kk-1]-y[kk-2])/(x[kk-1]-x[kk-2]); } else { u[3]=2.0*u[2]-u[1]; u[4]=2.0*u[3]-u[2]; u[0]=(y[kk-1]-y[kk-2])/(x[kk-1]-x[kk-2]); } } else { u[1]=(y[kk]-y[kk-1])/(x[kk]-x[kk-1]); u[0]=(y[kk-1]-y[kk-2])/(x[kk-1]-x[kk-2]); u[3]=(y[kk+2]-y[kk+1])/(x[kk+2]-x[kk+1]); u[4]=(y[kk+3]-y[kk+2])/(x[kk+3]-x[kk+2]); } } s[0]=fabs(u[3]-u[2]); s[1]=fabs(u[0]-u[1]); if ((s[0]+1.0==1.0)&&(s[1]+1.0==1.0)) p=(u[1]+u[2])/2.0; else p=(s[0]*u[1]+s[1]*u[2])/(s[0]+s[1]); s[0]=fabs(u[3]-u[4]); s[1]=fabs(u[2]-u[1]); if ((s[0]+1.0==1.0)&&(s[1]+1.0==1.0)) q=(u[2]+u[3])/2.0; else q=(s[0]*u[2]+s[1]*u[3])/(s[0]+s[1]); s[0]=y[kk]; s[1]=p; s[3]=x[kk+1]-x[kk]; s[2]=(3.0*u[2]-2.0*p-q)/s[3]; s[3]=(q+p-2.0*u[2])/(s[3]*s[3]); if (k<0) { p=t-x[kk]; s[4]=s[0]+s[1]*p+s[2]*p*p+s[3]*p*p*p; } return s[4]; } ////////////////////////////////////////////////////////////////////// // 光滑等距插值 // // 参数: // 1. int n - 结点的个数 // 2. double x0 - 存放等距n个结点中第一个结点的值 // 3. double xStep - 等距结点的步长 // 4. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 5. double t - 存放指定的插值点的值 // 5. double s[] - 一维数组,长度为5,其中s(0),s(1),s(2),s(3)返回三次多项式的系数, // s(4)返回指定插值点t处的函数近似值f(t)(k<0时)或任意值(k>=0时) // 6. int k - 控制参数,若k>=0,则只计算第k个子区间[x(k), x(k+1)]上的三次多项式的系数 // // 返回值:double 型,指定的查指点t的函数近似值f(t) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueAkima(int n, double x0, double xStep, double y[], double t, double s[], int k /*= -1*/) { int kk,m,l; double u[5],p,q; // 初值 s[4]=0.0; s[0]=0.0; s[1]=0.0; s[2]=0.0; s[3]=0.0; // 特例处理 if (n<1) return s[4]; if (n==1) { s[0]=y[0]; s[4]=y[0]; return s[4]; } if (n==2) { s[0]=y[0]; s[1]=(y[1]-y[0])/xStep; if (k<0) s[4]=(y[1]*(t-x0)-y[0]*(t-x0-xStep))/xStep; return s[4]; } // 插值 if (k<0) { if (t<=x0+xStep) kk=0; else if (t>=x0+(n-1)*xStep) kk=n-2; else { kk=1; m=n; while (((kk-m)!=1)&&((kk-m)!=-1)) { l=(kk+m)/2; if (t<x0+(l-1)*xStep) m=l; else kk=l; } kk=kk-1; } } else kk=k; if (kk>=n-1) kk=n-2; u[2]=(y[kk+1]-y[kk])/xStep; if (n==3) { if (kk==0) { u[3]=(y[2]-y[1])/xStep; u[4]=2.0*u[3]-u[2]; u[1]=2.0*u[2]-u[3]; u[0]=2.0*u[1]-u[2]; } else { u[1]=(y[1]-y[0])/xStep; u[0]=2.0*u[1]-u[2]; u[3]=2.0*u[2]-u[1]; u[4]=2.0*u[3]-u[2]; } } else { if (kk<=1) { u[3]=(y[kk+2]-y[kk+1])/xStep; if (kk==1) { u[1]=(y[1]-y[0])/xStep; u[0]=2.0*u[1]-u[2]; if (n==4) u[4]=2.0*u[3]-u[2]; else u[4]=(y[4]-y[3])/xStep; } else { u[1]=2.0*u[2]-u[3]; u[0]=2.0*u[1]-u[2]; u[4]=(y[3]-y[2])/xStep; } } else if (kk>=(n-3)) { u[1]=(y[kk]-y[kk-1])/xStep; if (kk==(n-3)) { u[3]=(y[n-1]-y[n-2])/xStep; u[4]=2.0*u[3]-u[2]; if (n==4) u[0]=2.0*u[1]-u[2]; else u[0]=(y[kk-1]-y[kk-2])/xStep; } else { u[3]=2.0*u[2]-u[1]; u[4]=2.0*u[3]-u[2]; u[0]=(y[kk-1]-y[kk-2])/xStep; } } else { u[1]=(y[kk]-y[kk-1])/xStep; u[0]=(y[kk-1]-y[kk-2])/xStep; u[3]=(y[kk+2]-y[kk+1])/xStep; u[4]=(y[kk+3]-y[kk+2])/xStep; } } s[0]=fabs(u[3]-u[2]); s[1]=fabs(u[0]-u[1]); if ((s[0]+1.0==1.0)&&(s[1]+1.0==1.0)) p=(u[1]+u[2])/2.0; else p=(s[0]*u[1]+s[1]*u[2])/(s[0]+s[1]); s[0]=fabs(u[3]-u[4]); s[1]=fabs(u[2]-u[1]); if ((s[0]+1.0==1.0)&&(s[1]+1.0==1.0)) q=(u[2]+u[3])/2.0; else q=(s[0]*u[2]+s[1]*u[3])/(s[0]+s[1]); s[0]=y[kk]; s[1]=p; s[3]=xStep; s[2]=(3.0*u[2]-2.0*p-q)/s[3]; s[3]=(q+p-2.0*u[2])/(s[3]*s[3]); if (k<0) { p=t-(x0+kk*xStep); s[4]=s[0]+s[1]*p+s[2]*p*p+s[3]*p*p*p; } return s[4]; } ////////////////////////////////////////////////////////////////////// // 第一种边界条件的三次样条函数插值、微商与积分 // // 参数: // 1. int n - 结点的个数 // 2. double x[] - 一维数组,长度为n,存放给定的n个结点的值x(i) // 3. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 4. double dy[] - 一维数组,长度为n,调用时,dy(0)存放给定区间的左端点处的一阶导数值, // dy(n-1)存放给定区间的右端点处的一阶导数值。返回时,存放n个给定点处的 // 一阶导数值y'(i),i=0,1,...,n-1 // 5. double ddy[] - 一维数组,长度为n,返回时,存放n个给定点处的二阶导数值y''(i), // i=0,1,...,n-1 // 6. int m - 指定插值点的个数 // 7. double t[] - 一维数组,长度为m,存放m个指定的插值点的值。 // 要求x(0)<t(j)<x(n-1), j=0,1,…,m-1 // 8. double z[] - 一维数组,长度为m,存放m个指定的插值点处的函数值 // 9. double dz[] - 一维数组,长度为m,存放m个指定的插值点处的一阶导数值 // 10. double ddz[] - 一维数组,长度为m,存放m个指定的插值点处的二阶导数值 // // 返回值:double 型,指定函数的x(0)到x(n-1)的定积分值 ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueSpline1(int n, double x[], double y[], double dy[], double ddy[], int m, double t[], double z[], double dz[], double ddz[]) { int i,j; double h0,h1,alpha,beta,g,*s; // 初值 s=new double[n]; s[0]=dy[0]; dy[0]=0.0; h0=x[1]-x[0]; for (j=1;j<=n-2;j++) { h1=x[j+1]-x[j]; alpha=h0/(h0+h1); beta=(1.0-alpha)*(y[j]-y[j-1])/h0; beta=3.0*(beta+alpha*(y[j+1]-y[j])/h1); dy[j]=-alpha/(2.0+(1.0-alpha)*dy[j-1]); s[j]=(beta-(1.0-alpha)*s[j-1]); s[j]=s[j]/(2.0+(1.0-alpha)*dy[j-1]); h0=h1; } for (j=n-2;j>=0;j--) dy[j]=dy[j]*dy[j+1]+s[j]; for (j=0;j<=n-2;j++) s[j]=x[j+1]-x[j]; for (j=0;j<=n-2;j++) { h1=s[j]*s[j]; ddy[j]=6.0*(y[j+1]-y[j])/h1-2.0*(2.0*dy[j]+dy[j+1])/s[j]; } h1=s[n-2]*s[n-2]; ddy[n-1]=6.*(y[n-2]-y[n-1])/h1+2.*(2.*dy[n-1]+dy[n-2])/s[n-2]; g=0.0; for (i=0;i<=n-2;i++) { h1=0.5*s[i]*(y[i]+y[i+1]); h1=h1-s[i]*s[i]*s[i]*(ddy[i]+ddy[i+1])/24.0; g=g+h1; } for (j=0;j<=m-1;j++) { if (t[j]>=x[n-1]) i=n-2; else { i=0; while (t[j]>x[i+1]) i=i+1; } h1=(x[i+1]-t[j])/s[i]; h0=h1*h1; z[j]=(3.0*h0-2.0*h0*h1)*y[i]; z[j]=z[j]+s[i]*(h0-h0*h1)*dy[i]; dz[j]=6.0*(h0-h1)*y[i]/s[i]; dz[j]=dz[j]+(3.0*h0-2.0*h1)*dy[i]; ddz[j]=(6.0-12.0*h1)*y[i]/(s[i]*s[i]); ddz[j]=ddz[j]+(2.0-6.0*h1)*dy[i]/s[i]; h1=(t[j]-x[i])/s[i]; h0=h1*h1; z[j]=z[j]+(3.0*h0-2.0*h0*h1)*y[i+1]; z[j]=z[j]-s[i]*(h0-h0*h1)*dy[i+1]; dz[j]=dz[j]-6.0*(h0-h1)*y[i+1]/s[i]; dz[j]=dz[j]+(3.0*h0-2.0*h1)*dy[i+1]; ddz[j]=ddz[j]+(6.0-12.0*h1)*y[i+1]/(s[i]*s[i]); ddz[j]=ddz[j]-(2.0-6.0*h1)*dy[i+1]/s[i]; } delete[] s; return(g); } ////////////////////////////////////////////////////////////////////// // 第二种边界条件的三次样条函数插值、微商与积分 // // 参数: // 1. int n - 结点的个数 // 2. double x[] - 一维数组,长度为n,存放给定的n个结点的值x(i) // 3. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 4. double dy[] - 一维数组,长度为n,返回时,存放n个给定点处的一阶导数值y'(i), // i=0,1,...,n-1 // 5. double ddy[] - 一维数组,长度为n,返回时,存放n个给定点处的二阶导数值y''(i), // i=0,1,...,n-1,调用时,ddy(0)存放给定区间的左端点处的二阶导数值, // ddy(n-1)存放给定区间的右端点处的二阶导数值 // 6. int m - 指定插值点的个数 // 7. double t[] - 一维数组,长度为m,存放m个指定的插值点的值。 // 要求x(0)<t(j)<x(n-1), j=0,1,…,m-1 // 8. double z[] - 一维数组,长度为m,存放m个指定的插值点处的函数值 // 9. double dz[] - 一维数组,长度为m,存放m个指定的插值点处的一阶导数值 // 10. double ddz[] - 一维数组,长度为m,存放m个指定的插值点处的二阶导数值 // // 返回值:double 型,指定函数的x(0)到x(n-1)的定积分值 ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueSpline2(int n, double x[], double y[], double dy[], double ddy[], int m, double t[], double z[], double dz[], double ddz[]) { int i,j; double h0,h1,alpha,beta,g,*s; // 初值 s=new double[n]; dy[0]=-0.5; h0=x[1]-x[0]; s[0]=3.0*(y[1]-y[0])/(2.0*h0)-ddy[0]*h0/4.0; for (j=1;j<=n-2;j++) { h1=x[j+1]-x[j]; alpha=h0/(h0+h1); beta=(1.0-alpha)*(y[j]-y[j-1])/h0; beta=3.0*(beta+alpha*(y[j+1]-y[j])/h1); dy[j]=-alpha/(2.0+(1.0-alpha)*dy[j-1]); s[j]=(beta-(1.0-alpha)*s[j-1]); s[j]=s[j]/(2.0+(1.0-alpha)*dy[j-1]); h0=h1; } dy[n-1]=(3.0*(y[n-1]-y[n-2])/h1+ddy[n-1]*h1/2.0-s[n-2])/(2.0+dy[n-2]); for (j=n-2;j>=0;j--) dy[j]=dy[j]*dy[j+1]+s[j]; for (j=0;j<=n-2;j++) s[j]=x[j+1]-x[j]; for (j=0;j<=n-2;j++) { h1=s[j]*s[j]; ddy[j]=6.0*(y[j+1]-y[j])/h1-2.0*(2.0*dy[j]+dy[j+1])/s[j]; } h1=s[n-2]*s[n-2]; ddy[n-1]=6.*(y[n-2]-y[n-1])/h1+2.*(2.*dy[n-1]+dy[n-2])/s[n-2]; g=0.0; for (i=0;i<=n-2;i++) { h1=0.5*s[i]*(y[i]+y[i+1]); h1=h1-s[i]*s[i]*s[i]*(ddy[i]+ddy[i+1])/24.0; g=g+h1; } for (j=0;j<=m-1;j++) { if (t[j]>=x[n-1]) i=n-2; else { i=0; while (t[j]>x[i+1]) i=i+1; } h1=(x[i+1]-t[j])/s[i]; h0=h1*h1; z[j]=(3.0*h0-2.0*h0*h1)*y[i]; z[j]=z[j]+s[i]*(h0-h0*h1)*dy[i]; dz[j]=6.0*(h0-h1)*y[i]/s[i]; dz[j]=dz[j]+(3.0*h0-2.0*h1)*dy[i]; ddz[j]=(6.0-12.0*h1)*y[i]/(s[i]*s[i]); ddz[j]=ddz[j]+(2.0-6.0*h1)*dy[i]/s[i]; h1=(t[j]-x[i])/s[i]; h0=h1*h1; z[j]=z[j]+(3.0*h0-2.0*h0*h1)*y[i+1]; z[j]=z[j]-s[i]*(h0-h0*h1)*dy[i+1]; dz[j]=dz[j]-6.0*(h0-h1)*y[i+1]/s[i]; dz[j]=dz[j]+(3.0*h0-2.0*h1)*dy[i+1]; ddz[j]=ddz[j]+(6.0-12.0*h1)*y[i+1]/(s[i]*s[i]); ddz[j]=ddz[j]-(2.0-6.0*h1)*dy[i+1]/s[i]; } delete[] s; return(g); } ////////////////////////////////////////////////////////////////////// // 第三种边界条件的三次样条函数插值、微商与积分 // // 参数: // 1. int n - 结点的个数 // 2. double x[] - 一维数组,长度为n,存放给定的n个结点的值x(i) // 3. double y[] - 一维数组,长度为n,存放给定的n个结点的函数值y(i), // y(i) = f(x(i)), i=0,1,...,n-1 // 4. double dy[] - 一维数组,长度为n,返回时,存放n个给定点处的一阶导数值y'(i), // i=0,1,...,n-1 // 5. double ddy[] - 一维数组,长度为n,返回时,存放n个给定点处的二阶导数值y''(i), // i=0,1,...,n-1 // 6. int m - 指定插值点的个数 // 7. double t[] - 一维数组,长度为m,存放m个指定的插值点的值。 // 要求x(0)<t(j)<x(n-1), j=0,1,…,m-1 // 8. double z[] - 一维数组,长度为m,存放m个指定的插值点处的函数值 // 9. double dz[] - 一维数组,长度为m,存放m个指定的插值点处的一阶导数值 // 10. double ddz[] - 一维数组,长度为m,存放m个指定的插值点处的二阶导数值 // // 返回值:double 型,指定函数的x(0)到x(n-1)的定积分值 ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueSpline3(int n, double x[], double y[], double dy[], double ddy[], int m, double t[], double z[], double dz[], double ddz[]) { int i,j; double h0,y0,h1,y1,alpha,beta,u,g,*s; // 初值 s=new double[n]; h0=x[n-1]-x[n-2]; y0=y[n-1]-y[n-2]; dy[0]=0.0; ddy[0]=0.0; ddy[n-1]=0.0; s[0]=1.0; s[n-1]=1.0; for (j=1;j<=n-1;j++) { h1=h0; y1=y0; h0=x[j]-x[j-1]; y0=y[j]-y[j-1]; alpha=h1/(h1+h0); beta=3.0*((1.0-alpha)*y1/h1+alpha*y0/h0); if (j<n-1) { u=2.0+(1.0-alpha)*dy[j-1]; dy[j]=-alpha/u; s[j]=(alpha-1.0)*s[j-1]/u; ddy[j]=(beta-(1.0-alpha)*ddy[j-1])/u; } } for (j=n-2;j>=1;j--) { s[j]=dy[j]*s[j+1]+s[j]; ddy[j]=dy[j]*ddy[j+1]+ddy[j]; } dy[n-2]=(beta-alpha*ddy[1]-(1.0-alpha)*ddy[n-2])/ (alpha*s[1]+(1.0-alpha)*s[n-2]+2.0); for (j=2;j<=n-1;j++) dy[j-2]=s[j-1]*dy[n-2]+ddy[j-1]; dy[n-1]=dy[0]; for (j=0;j<=n-2;j++) s[j]=x[j+1]-x[j]; for (j=0;j<=n-2;j++) { h1=s[j]*s[j]; ddy[j]=6.0*(y[j+1]-y[j])/h1-2.0*(2.0*dy[j]+dy[j+1])/s[j]; } h1=s[n-2]*s[n-2]; ddy[n-1]=6.*(y[n-2]-y[n-1])/h1+2.*(2.*dy[n-1]+dy[n-2])/s[n-2]; g=0.0; for (i=0;i<=n-2;i++) { h1=0.5*s[i]*(y[i]+y[i+1]); h1=h1-s[i]*s[i]*s[i]*(ddy[i]+ddy[i+1])/24.0; g=g+h1; } for (j=0;j<=m-1;j++) { h0=t[j]; while (h0>=x[n-1]) h0=h0-(x[n-1]-x[0]); while (h0<x[0]) h0=h0+(x[n-1]-x[0]); i=0; while (h0>x[i+1]) i=i+1; u=h0; h1=(x[i+1]-u)/s[i]; h0=h1*h1; z[j]=(3.0*h0-2.0*h0*h1)*y[i]; z[j]=z[j]+s[i]*(h0-h0*h1)*dy[i]; dz[j]=6.0*(h0-h1)*y[i]/s[i]; dz[j]=dz[j]+(3.0*h0-2.0*h1)*dy[i]; ddz[j]=(6.0-12.0*h1)*y[i]/(s[i]*s[i]); ddz[j]=ddz[j]+(2.0-6.0*h1)*dy[i]/s[i]; h1=(u-x[i])/s[i]; h0=h1*h1; z[j]=z[j]+(3.0*h0-2.0*h0*h1)*y[i+1]; z[j]=z[j]-s[i]*(h0-h0*h1)*dy[i+1]; dz[j]=dz[j]-6.0*(h0-h1)*y[i+1]/s[i]; dz[j]=dz[j]+(3.0*h0-2.0*h1)*dy[i+1]; ddz[j]=ddz[j]+(6.0-12.0*h1)*y[i+1]/(s[i]*s[i]); ddz[j]=ddz[j]-(2.0-6.0*h1)*dy[i+1]/s[i]; } delete[] s; return(g); } ////////////////////////////////////////////////////////////////////// // 二元三点插值 // // 参数: // 1. int n - x方向上给定结点的点数 // 2. double x[] - 一维数组,长度为n,存放给定n x m 个结点x方向上的n个值x(i) // 3. int m - y方向上给定结点的点数 // 4. double y[] - 一维数组,长度为m,存放给定n x m 个结点y方向上的m个值y(i) // 5. double z[] - 一维数组,长度为n x m,存放给定的n x m个结点的函数值z(i,j), // z(i,j) = f(x(i), y(j)), i=0,1,...,n-1, j=0,1,...,m-1 // 6. double u - 存放插值点x坐标 // 7. double v - 存放插值点y坐标 // // 返回值:double 型,指定函数值f(u, v) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueTqip(int n, double x[], int m, double y[], double z[], double u, double v) { int nn,mm,ip,iq,i,j,k,l; double b[3],h,w; // 初值 nn=3; // 特例 if (n<=3) { ip=0; nn=n; } else if (u<=x[1]) ip=0; else if (u>=x[n-2]) ip=n-3; else { i=1; j=n; while (((i-j)!=1)&&((i-j)!=-1)) { l=(i+j)/2; if (u<x[l-1]) j=l; else i=l; } if (fabs(u-x[i-1])<fabs(u-x[j-1])) ip=i-2; else ip=i-1; } mm=3; if (m<=3) { iq=0; mm=m; } else if (v<=y[1]) iq=0; else if (v>=y[m-2]) iq=m-3; else { i=1; j=m; while (((i-j)!=1)&&((i-j)!=-1)) { l=(i+j)/2; if (v<y[l-1]) j=l; else i=l; } if (fabs(v-y[i-1])<fabs(v-y[j-1])) iq=i-2; else iq=i-1; } for (i=0;i<=nn-1;i++) { b[i]=0.0; for (j=0;j<=mm-1;j++) { k=m*(ip+i)+(iq+j); h=z[k]; for (k=0;k<=mm-1;k++) { if (k!=j) h=h*(v-y[iq+k])/(y[iq+j]-y[iq+k]); } b[i]=b[i]+h; } } w=0.0; for (i=0;i<=nn-1;i++) { h=b[i]; for (j=0;j<=nn-1;j++) { if (j!=i) h=h*(u-x[ip+j])/(x[ip+i]-x[ip+j]); } w=w+h; } return(w); } ////////////////////////////////////////////////////////////////////// // 二元全区间插值 // // 参数: // 1. int n - x方向上给定结点的点数 // 2. double x[] - 一维数组,长度为n,存放给定n x m 个结点x方向上的n个值x(i) // 3. int m - y方向上给定结点的点数 // 4. double y[] - 一维数组,长度为m,存放给定n x m 个结点y方向上的m个值y(i) // 5. double z[] - 一维数组,长度为n x m,存放给定的n x m个结点的函数值z(i,j), // z(i,j) = f(x(i), y(j)), i=0,1,...,n-1, j=0,1,...,m-1 // 6. double u - 存放插值点x坐标 // 7. double v - 存放插值点y坐标 // // 返回值:double 型,指定函数值f(u, v) ////////////////////////////////////////////////////////////////////// double CInterpolate::GetValueLagrange2(int n, double x[], int m, double y[], double z[], double u, double v) { int ip,ipp,i,j,l,iq,iqq,k; double h,w,b[10]; // 特例 if (u<=x[0]) { ip=1; ipp=4; } else if (u>=x[n-1]) { ip=n-3; ipp=n; } else { i=1; j=n; while (((i-j)!=1)&&((i-j)!=-1)) { l=(i+j)/2; if (u<x[l-1]) j=l; else i=l; } ip=i-3; ipp=i+4; } if (ip<1) ip=1; if (ipp>n) ipp=n; if (v<=y[0]) { iq=1; iqq=4; } else if (v>=y[m-1]) { iq=m-3; iqq=m; } else { i=1; j=m; while (((i-j)!=1)&&((i-j)!=-1)) { l=(i+j)/2; if (v<y[l-1]) j=l; else i=l; } iq=i-3; iqq=i+4; } if (iq<1) iq=1; if (iqq>m) iqq=m; for (i=ip-1;i<=ipp-1;i++) { b[i-ip+1]=0.0; for (j=iq-1;j<=iqq-1;j++) { h=z[m*i+j]; for (k=iq-1;k<=iqq-1;k++) { if (k!=j) h=h*(v-y[k])/(y[j]-y[k]); } b[i-ip+1]=b[i-ip+1]+h; } } w=0.0; for (i=ip-1;i<=ipp-1;i++) { h=b[i-ip+1]; for (j=ip-1;j<=ipp-1;j++) { if (j!=i) h=h*(u-x[j])/(x[i]-x[j]); } w=w+h; } return(w); }
// Copyright Oliver Kowalke 2013. // 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_TASKS_DETAIL_WORKER_OBJECT_H #define BOOST_TASKS_DETAIL_WORKER_OBJECT_H #include <boost/assert.hpp> #include <boost/bind.hpp> #include <boost/config.hpp> #include <boost/thread/thread.hpp> #include <boost/task/detail/worker_base.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace tasks { namespace detail { template< typename Allocator > class worker_object : public worker_base { public: typedef typename Allocator::template rebind< worker_object< Allocator > >::other allocator_t; private: allocator_t alloc_; static void destroy_( allocator_t & alloc, worker_object * p) { alloc.destroy( p); alloc.deallocate( p, 1); } worker_object( worker_object const&); // = delete worker_object & operator=( worker_object const&); // = delete protected: void deallocate_object() { destroy_( alloc_, this); } public: worker_object( allocator_t const& alloc) BOOST_NOEXCEPT : alloc_( alloc) { thrd_ = thread( bind( & worker_base::start_worker_, this) ); } ~worker_object() BOOST_NOEXCEPT {} }; }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_TASKS_DETAIL_WORKER_OBJECT_H
#include "valid_tracker.h" #include "utils.h" #include <algorithm> void ValidTracker::reset() { valid.clear(); std::vector<int> permutation(validNumbers.begin(), validNumbers.end()); std::random_shuffle(permutation.begin(), permutation.end()); std::copy(permutation.begin(), permutation.end(), std::inserter(valid, valid.begin())); } int ValidTracker::numValid() const { return valid.size(); } int ValidTracker::oneValid() const { return *valid.begin(); } int ValidTracker::otherValid() const { return *++valid.begin(); } const std::unordered_set<int>& ValidTracker::allValid() const { return valid; } bool ValidTracker::isValid(int number) const { return valid.find(number) != valid.end(); } static bool validCondition(int number, int guess, const Response& response) { Response correct = findResponse(number, guess); return correct.bulls == response.bulls && correct.cows == response.cows; } void ValidTracker::update(int guess, Response response) { std::unordered_set<int>::iterator it = valid.begin(); while (it != valid.end()) { if (!validCondition(*it, guess, response)) it = valid.erase(it); else it++; } } int ValidTracker::numValidAfterUpdate(int guess, Response response) const { int cnt = 0; for (int num : valid) { if (validCondition(num, guess, response)) ++cnt; } return cnt; } ValidTracker ValidTracker::afterUpdate(int guess, Response response) const { ValidTracker tracker; for (int num : valid) { if (validCondition(num, guess, response)) tracker.valid.insert(num); } return tracker; } int ValidTracker::worstSplitSize(int guess) const { std::vector<int> cnts(validResponses.size()); for (int number : valid) { ++cnts[responseToIndex(findResponse(number, guess))]; } return *std::max_element(cnts.begin(), cnts.end()); } std::vector<ValidTracker> ValidTracker::split(int guess) const { std::vector<ValidTracker> splits(validResponses.size()); for (int number : valid) { splits[responseToIndex(findResponse(number, guess))].valid.insert(number); } return splits; }
#include <iostream.h> /* * Á´±í½á¹¹ * */ struct Node { int data; Node* next; }; class LinkList { public: LinkList() { Construct(); } virtual bool Construct(void); bool AddTo(int); bool Display(void) const; //bool Insert(); bool Delete(int); bool Destroy(void); const Node* GetHead(void) const; virtual ~LinkList() {} private: Node* head; }; bool LinkList::Construct() { Node* ptr = new Node; if(ptr != NULL) { ptr->data = 0; ptr->next = NULL; head = ptr; cout<< "Add item 0" << " @ " << head << " - " << head->next <<endl; return true; } return false; } bool LinkList::AddTo(int value) { Node* ptr = new Node; if(ptr != NULL) { ptr->data = value; ptr->next = head; head = ptr; cout<< "Add item " << value << " @ " << ptr << " - " << ptr->next <<endl; return true; } return false; } bool LinkList::Display() const { Node* ptr = new Node; if(head != NULL) { ptr = head; try { while(ptr != NULL) { cout<< "See item " << ptr->data << " @ " << ptr << " - " << ptr->next <<endl; ptr = ptr->next; } } catch(...) { cout<< "\nAn error occured!" <<endl; return false; } return true; } return false; } bool LinkList::Delete(int value) { Node* ptr = new Node; if(head != NULL) { if(head->data == value) { head = head->next; } ptr = head; try { while(ptr != NULL) { if(ptr->next->data == value) { ptr->next = ptr->next->next; break; } else { ptr = ptr->next; } } } catch(...) { cout<< "\nAn error occured!" <<endl; return false; } return true; } return false; } const Node* LinkList::GetHead() const { return head; } //////////////////////////////////////////////////////////////////////////////////////// void main() { int a[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; LinkList* lnklst = new LinkList(); if(lnklst->GetHead() != NULL) { for(int i=0; i<9; i++) { lnklst->AddTo(a[i]); } } cout<< "------------------------------------" <<endl; lnklst->Delete(0); lnklst->Display(); }
vector<int> Solution::flip(string A) { //1 based indexing int n = A.size(); int start = 0, end = -1; int sum = 0, maxSum = INT_MIN; int ansStart = 0, ansEnd = INT_MAX; for (int i = 0; i < n; i++) { if (A[i] == '1') sum--; else sum++; if (sum < 0) { start = i + 1; sum = 0; } else { if (sum > maxSum) { maxSum = sum; ansStart = start + 1; ansEnd = i + 1; } } } vector<int> ans; if (ansEnd == INT_MAX) return ans; ans.push_back(ansStart); ans.push_back(ansEnd); return ans; }
#pragma once #cmakedefine HAS_EXPERIMENTAL_FILESYSTEM #ifdef HAS_EXPERIMENTAL_FILESYSTEM # include <experimental/filesystem> namespace std_fs_impl = std::experimental::filesystem; #else # include <filesystem> namespace std_fs_impl = std::filesystem; #endif #cmakedefine KG_PLATFORM_WIN #cmakedefine KG_PLATFORM_GTK
#pragma once #include <boost/core/demangle.hpp> #include <iomanip> #include <vector> #include "basis.hpp" namespace spacetime { template <class DblTreeIn, class DblTreeOut> auto GenerateSigma(const DblTreeIn &Lambda_in, const DblTreeOut &Lambda_out) { using OutNodeVector = std::vector<typename DblTreeOut::T0 *>; for (const auto &psi_out : Lambda_out.Project_0()->Bfs()) for (auto elem : psi_out->node()->support()) { if (!elem->has_data()) elem->set_data(new OutNodeVector()); elem->template data<OutNodeVector>()->push_back(psi_out->node()); } auto Sigma = std::make_shared<datastructures::DoubleTreeVector< typename DblTreeIn::T0, typename DblTreeOut::T1>>( std::get<0>(Lambda_in.root()->nodes()), std::get<1>(Lambda_out.root()->nodes())); Sigma->Project_0()->Union(Lambda_in.Project_0()); Sigma->Project_1()->Union(Lambda_out.Project_1()); OutNodeVector PI; for (const auto &psi_in_labda_0 : Sigma->Project_0()->Bfs()) { // NOTE: The code below is sigma as described in followup3.pdf. We chose // to enlarge sigma in order to create a `cheap` transpose of a spacetime // bilinear form. To do this, we must add the `diagonal` to Sigma. // std::vector<Time::Element1D *> children; // children.reserve(psi_in_labda_0->node()->support().size() * // DblTreeIn::T0::N_children); // for (auto elem : psi_in_labda_0->node()->support()) // for (auto child : elem->children()) children.push_back(child); // std::sort(children.begin(), children.end()); // auto last = std::unique(children.begin(), children.end()); // children.erase(last, children.end()); PI.clear(); for (auto child : psi_in_labda_0->node()->support()) { if (!child->has_data()) continue; PI.insert(PI.end(), child->template data<OutNodeVector>()->begin(), child->template data<OutNodeVector>()->end()); } // Remove duplicates from PI. std::sort(PI.begin(), PI.end()); PI.erase(std::unique(PI.begin(), PI.end()), PI.end()); for (auto mu : PI) psi_in_labda_0->FrozenOtherAxis()->Union(Lambda_out.Fiber_1(mu)); } for (const auto &psi_out : Lambda_out.Project_0()->Bfs()) for (auto elem : psi_out->node()->support()) { if (!elem->has_data()) continue; auto data = elem->template data<OutNodeVector>(); elem->reset_data(); delete data; } Sigma->ComputeFibers(); #ifdef VERBOSE std::cerr << std::left; std::cerr << "GenerateSigma(" << boost::core::demangle(typeid(DblTreeIn).name()) << ", " << boost::core::demangle(typeid(DblTreeIn).name()) << std::endl; std::cerr << " Lambda_in: #bfs = " << std::setw(10) << Lambda_in.Bfs().size() << "#container = " << Lambda_in.container().size() << std::endl; std::cerr << " Lambda_out: #bfs = " << std::setw(10) << Lambda_out.Bfs().size() << "#container = " << Lambda_out.container().size() << std::endl; std::cerr << " Sigma: #bfs = " << std::setw(10) << Sigma->Bfs().size() << "#container = " << Sigma->container().size() << std::endl; std::cerr << std::right; #endif return Sigma; } template <class DblTreeIn, class DblTreeOut> auto GenerateTheta(const DblTreeIn &Lambda_in, const DblTreeOut &Lambda_out) { return GenerateSigma(Lambda_out, Lambda_in); // auto Theta = std::make_shared<datastructures::DoubleTreeVector< // typename DblTreeOut::T0, typename DblTreeIn::T1>>( // std::get<0>(Lambda_out.root()->nodes()), // std::get<1>(Lambda_in.root()->nodes())); // Theta->Project_0()->Union(Lambda_out.Project_0()); // Theta->Project_1()->Union(Lambda_in.Project_1()); // // for (const auto &psi_in_labda_1 : Theta->Project_1()->Bfs()) { // auto fiber_labda_0 = Lambda_in.Fiber_0(psi_in_labda_1->node()); // auto fiber_labda_0_nodes = fiber_labda_0->Bfs(); // for (const auto &psi_in_labda_0 : fiber_labda_0_nodes) // for (auto elem : psi_in_labda_0->node()->support()) // elem->set_marked(true); // // psi_in_labda_1->FrozenOtherAxis()->Union( // Lambda_out.Project_0(), [](const auto &psi_out_labda_0) { // for (auto elem : psi_out_labda_0->node()->support()) // if (elem->marked()) return true; // return false; // }); // // for (const auto &psi_in_labda_0 : fiber_labda_0_nodes) // for (auto elem : psi_in_labda_0->node()->support()) // elem->set_marked(false); // } // Theta->ComputeFibers(); // //#ifdef VERBOSE // std::cerr << std::left; // std::cerr << "GenerateTheta(" // << boost::core::demangle(typeid(DblTreeIn).name()) << ", " // << boost::core::demangle(typeid(DblTreeIn).name()) << std::endl; // std::cerr << " Lambda_in: #bfs = " << std::setw(10) // << Lambda_in.Bfs().size() // << "#container = " << Lambda_in.container().size() << std::endl; // std::cerr << " Lambda_out: #bfs = " << std::setw(10) // << Lambda_out.Bfs().size() // << "#container = " << Lambda_out.container().size() << // std::endl; // std::cerr << " Theta: #bfs = " << std::setw(10) << Theta->Bfs().size() // << "#container = " << Theta->container().size() << std::endl; // std::cerr << std::right; //#endif // return Theta; } } // namespace spacetime
// // tertura.cpp // opengl2 // // Created by Tiago Rezende on 4/2/13. // // #include "genTexture.h" #include <fstream> GenTexture::GenTexture() { fbo.allocate(512, 512, GL_RGBA); //camera.enableOrtho(); camera.setAspectRatio(1); camera.setPosition(0, 0, -1); camera.setFov(45.0); camera.lookAt(ofVec3f(0,0,0)); } void GenTexture::applySequence() { // faz setup do FBO para renderização e chama um por um dos "shaders" fbo.begin(); camera.begin(); //ofClear(0, 0, 0); for (ShaderSeq::const_iterator i = sequence.begin(); i!=sequence.end(); i++) { (*i)->apply(); } camera.end(); fbo.end(); } void GenTexture::addShader(GenTextureShader *shader) { sequence.push_back(shader); } GenTexture::~GenTexture() {} ofTexture& GenTexture::getTexture() { return fbo.getTextureReference(); } GenTextureFragShader::GenTextureFragShader(const std::string &fn): filename(fn) { } void GenTextureFragShader::setup() { ofMesh mesh; mesh.addTexCoord(ofVec2f(0, 0)); mesh.addVertex(ofVec3f(-1, -1, 0)); mesh.addTexCoord(ofVec2f(512, 0)); mesh.addVertex(ofVec3f(1, -1, 0)); mesh.addTexCoord(ofVec2f(0, 512)); mesh.addVertex(ofVec3f(-1, 1, 0)); mesh.addTexCoord(ofVec2f(512, 512)); mesh.addVertex(ofVec3f(1, 1, 0)); vbo.setMesh(mesh, GL_STATIC_DRAW); if(!shader.load(ofToDataPath("shaders/simple.vert"), ofToDataPath("shaders/"+filename))) { ofLog(OF_LOG_ERROR, "error loading shader %s", filename.c_str()); } if(!shader.linkProgram()) { ofLog(OF_LOG_ERROR, "error linking shader with %s", filename.c_str()); }; // shader uniforms from ShaderToy //shader.setUniform3f("iResolution", 512, 512, 0); } void GenTextureFragShader::apply() { shader.setUniform3f("iResolution", 512, 512, 0); shader.setUniform1f("iGlobalTime", ofGetElapsedTimef()); shader.setUniform4f("iMouse", 256, 256, 0, 0); shader.setUniform4f("iChannelTime", 0, 0, 0, 0); shader.setUniform4f("iDate", 0, 0, 0, 0); shader.begin(); vbo.draw(GL_TRIANGLE_STRIP, 0, 4); shader.end(); } GenTextureImageShader::GenTextureImageShader(ofImage &image):img(image) { } void GenTextureImageShader::apply() { ofTexture &tex = img.getTextureReference(); tex.bind(); ofRect(-1, -1, 1, 1); tex.unbind(); }
// // Created by gurumurt on 10/18/18. // #ifndef OPENCLDISPATCHER_KERNELGRAPHS_H #define OPENCLDISPATCHER_KERNELGRAPHS_H #endif //OPENCLDISPATCHER_KERNELGRAPHS_H #include "headers.h" #include "globals.h" #include "../include/Importkernel.h" #include <iostream> // std::cout #include <utility> // std::pair #include <boost/graph/breadth_first_search.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/properties.hpp> #include <boost/pending/indirect_cmp.hpp> #include <boost/range/irange.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/topological_sort.hpp> using namespace boost; using namespace std; struct primitives{ string name, src; }bitmap, logical, materialize, arith,source1; cl_event evdp; vector<primitives> KernelArray; void initialize_primitives(){ source1.name = "Source data"; KernelArray.push_back(source1); bitmap.name = "selection_block"; bitmap.src = readKernelFile("kernels/mapper/selection_block.cl"); KernelArray.push_back(bitmap); logical.name = "logical_block"; logical.src = readKernelFile("kernels/mapper/logical_block.cl"); KernelArray.push_back(logical); materialize.name = "materialize_block"; materialize.src = readKernelFile("kernels/mapper/materialize_block.cl"); KernelArray.push_back(materialize); arith.name = "arithmetic_block"; arith.src = readKernelFile("kernels/mapper/arithmetic_block.cl"); KernelArray.push_back(arith); }; void compilekernels(size_t dev = 0){ cl_device_id d = device[dev][0]; for(primitives kern : KernelArray){ add_kernel(kern.name,d,kern.src); } } void kernelGraphs(){ initialize_primitives(); typedef adjacency_list<vecS, vecS, bidirectionalS,size_t> Graph; Graph kernelGraph; typedef pair<size_t,size_t> kernelEdges; typedef graph_traits<Graph>::vertex_descriptor kernelVertex; kernelVertex select1,select2,logical1,material,ari,sou; size_t N = 6; sou = add_vertex(0,kernelGraph); select1 = add_vertex(1,kernelGraph); select2 = add_vertex(1,kernelGraph); logical1 = add_vertex(2,kernelGraph); material = add_vertex(3,kernelGraph); ari = add_vertex(4,kernelGraph); add_edge(sou,select1,kernelGraph); add_edge(sou,select2,kernelGraph); add_edge(select1,logical1,kernelGraph); add_edge(select2,logical1,kernelGraph); add_edge(logical1,material,kernelGraph); add_edge(material,ari,kernelGraph); //Make order for the kernels typedef std::list<kernelVertex> MakeOrder; MakeOrder make_order; topological_sort(kernelGraph, std::front_inserter(make_order)); // std::cout << "make ordering: "; // for (MakeOrder::iterator i = make_order.begin(); // i != make_order.end(); ++i) // std::cout <<KernelArray[kernelGraph[*i]].name << " "; // std::cout << std::endl; // // // exit(0); std::vector<int> time(N, 0); int maxdist = 0; for (MakeOrder::iterator i = make_order.begin(); i != make_order.end(); ++i) { if (in_degree (*i, kernelGraph ) > 0) { Graph::in_edge_iterator j, j_end; for (boost::tie(j, j_end) = in_edges(*i,kernelGraph); j != j_end; ++j) maxdist = std::max(time[source(*j, kernelGraph)], maxdist); time[*i]=maxdist+1; } } cout<<"maxdist : "<<maxdist+2<<endl; //Compiled execution compilekernels(); int concurrentTime = 0; Graph::vertex_iterator iv, iend; short prevTime = 0; vector<cl_event> relatedEvents,temp; for (boost::tie(iv, iend) = vertices(kernelGraph); iv != iend; ++iv){ std::cout << "time_slot[" << KernelArray[kernelGraph[*iv]].name << "] = " << time[*iv] << std::endl; //enqueue the kernel and get a event as return argument vector<string> args,params; //Starting events if(time[*iv] == 0) relatedEvents.push_back(*queueExecution(device[0][0],KernelArray[kernelGraph[*iv]].name,args,params)); if(prevTime != time[*iv]){ temp = relatedEvents; relatedEvents.clear(); relatedEvents.push_back(*queueExecution(device[0][0],KernelArray[kernelGraph[*iv]].name,args,params,100,&temp[0])); } } executeGraph(device[0][0]); }
template < class Executor, bool Symmetric, class BaseLhs, class TypesLhs, class BaseRhs = BaseLhs, class TypesRhs = TypesLhs, typename ResultType = void > class StaticDispatcher { typedef typename TL::DerivedToFront<TypesLhs>::Result TList; typedef typename TL::Head<TList>::Result Head; typedef typename TL::Tail<TList>::Result Tail; template<bool swapArgs, class SomeLhs, class SomeRhs> struct InvocationTraits { static void DoDispatch(SomeLhs& lhs, SomeRhs& rhs, Executor& exec) { exec.Fire(lhs, rhs); } }; template<class SomeLhs, class SomeRhs> struct InvocationTraits<true, SomeLhs, SomeRhs> { static void DoDispatch(SomeLhs& lhs, SomeRhs& rhs, Executor& exec) { exec.Fire(rhs, lhs); } }; public: static ResultType Go(BaseLhs& lhs, BaseRhs& rhs, Executor exec) { if (Head *p1 = dynamic_cast<Head*>(&lhs)) { return StaticDispatcher<Executor, BaseLhs, NullType, BaseRhs, TypesRhs>::DispatchRhs(*p1, rhs, exec); } else { return StaticDispatcher<Executor, BaseLhs, Tail, BaseRhs, TypesRhs>::Go( lhs, rhs, exec); } } template<class Lhs> static ResultType DispatchRhs(SomeLhs& lhs, BaseRhs& rhs, Executor exec) { typedef typename TypesRhs::Head Head; typedef typename TypesRhs::Tail Tail; if (Head *p2 = dynamic_cast<Head*>(&rhs)) { enum { swapArgs = Symmetric && typeaname IndexOf<Head, TypesRhs>::Result < typename IndexOf<BaseLhs, TypesLhs>::Result }; typedef InvocationTraits<swapArgs, BaseLhs, Head> CallTraits; return typename CallTraits::DoDispatch(lhs, *p2l); } else { return StaticDispatcher<Executor, SomeLhs, NullType, BaseRhs, Tail>::DispatchRhs(lhs, rhs, exec); } } }; template < class Executor, bool Symmetric, class BaseLhs, class BaseRhs, class TypesRhs, typename ResultType > class StaticDispatcher<Executor, Symmetric, BaseLhs, NullType, BaseRhs, TypesRhs, ResultType> { public: static void Go(BaseLhs& lhs, BaseRhs& rhs, Executor exec) { exec.OnError(lhs, rhs); } }; template < class Executor, class BaseLhs, class TypesLhs, class BaseRhs, class TypesRhs, typename ResultType > class StaticDispatcher<Executor, Symmetric, BaseLhs, TypesLhs, BaseRhs, NullType, ResultType> { public: static void DispatchRhs(BaseLhs& lhs, BaseRhs& rhs, Executor exec) { exec.OnError(lhs, rhs); } };
/* * @Author: shaoDong * @Version: 1.0 * @DateTime: 2018-07-16 10:31:04 * @Description: 反转字符串中的元音字符,使用set 结构 */ #include <iostream> #include <set> #include <string> using namespace std; // 编译使用g++ reverseVowel.cpp -o reverseVowel -std=c++11 set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; string doReverse(string str) { int i = 0, j = str.length(); char temp; while(i < j) { // find 返回结果为迭代器,不是布尔类型 if(vowels.find(str[i]) == vowels.end()) { i++; } else if(vowels.find(str[j]) == vowels.end()) { j--; } else { temp = str[i]; str[i] = str[j]; str[j] = temp; i++; j--; } } return str; } int main(int argc, char const *argv[]) { /* code */ string str; cin>>str; string res = doReverse(str); cout<<res<<endl; return 0; }
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "Direct3D9Renderer/RenderTarget/RenderPass.h" #include <Renderer/IRenderer.h> #include <Renderer/IAllocator.h> #include <cstring> // For "memcpy()" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Direct3D9Renderer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] RenderPass::RenderPass(Renderer::IRenderer& renderer, uint32_t numberOfColorAttachments, const Renderer::TextureFormat::Enum* colorAttachmentTextureFormats, Renderer::TextureFormat::Enum depthStencilAttachmentTextureFormat, uint8_t numberOfMultisamples) : IRenderPass(renderer), mNumberOfColorAttachments(numberOfColorAttachments), mDepthStencilAttachmentTextureFormat(depthStencilAttachmentTextureFormat), mNumberOfMultisamples(numberOfMultisamples) { RENDERER_ASSERT(renderer.getContext(), mNumberOfColorAttachments < 8, "Invalid number of Direct3D 9 color attachments") memcpy(mColorAttachmentTextureFormats, colorAttachmentTextureFormats, sizeof(Renderer::TextureFormat::Enum) * mNumberOfColorAttachments); } //[-------------------------------------------------------] //[ Protected virtual Renderer::RefCount methods ] //[-------------------------------------------------------] void RenderPass::selfDestruct() { RENDERER_DELETE(getRenderer().getContext(), RenderPass, this); } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Direct3D9Renderer
/* * ============================================================================ * Name : DeviceInfoUtility.h * Author : Vinod Kumar K V (mailto:vin2kalks@gmail.com) * Version : 1.0.0b * Date Createed : 23/02/2007 * Date Modified : 23/02/2007 * Copyright : Copyright (c) 1999 - 2007 vin2ktalks. * (http://vin2ktalks.googlepages.com/) * Description : The class to get the IMEI number of the device. * Please note that in order to use this class the * user has to link against etel3rdparty.lib, as the * CTelephony which is used in this class needs it. * ============================================================================ */ #ifndef __DEVICEINFOUTILITY_H__ #define __DEVICEINFOUTILITY_H__ // INCLUDES // System Includes #include <e32base.h> // CBase, link against euser.lib #include <Etel3rdParty.h> // For CTelephony link against etel3rdparty.lib // User includes // CONSTANTS const TInt KIMEINumberLength(15); // TYPEDEFS /** * Typedef to represent the IMEI number. */ typedef TBuf<CTelephony::KPhoneManufacturerIdSize> TManufacturer; typedef TBuf<CTelephony::KPhoneModelIdSize> TModel; typedef TBuf<CTelephony::KPhoneSerialNumberSize> TSerialNumber; typedef TBuf<CTelephony::KNetworkCountryCodeSize> TCountryCode; typedef TBuf<CTelephony::KNetworkIdentitySize> TNetworkId; typedef TBuf<CTelephony::KIMSISize> TSubscriberId; // FORWARD DECLARATIONS // CLASS DECLARATION /** * \class CDeviceInfoUtility * * \author Vinod Kumar K V * * \date 14/02/2007 * * \brief The class to get the IMEI number of the device. * * \par Please note that in order to use this class the * user has to link against etel3rdparty.lib, as the * CTelephony which is used in this class needs it. */ class CDeviceInfoUtility : public CActive { public: // Constructors and destructor /** * Create new CDeviceInfoUtility object. * \return a pointer to the created instance of CDeviceInfoUtility */ static CDeviceInfoUtility* NewL(); /** * Create new CDeviceInfoUtility object. * \return a pointer to the created instance of CDeviceInfoUtility */ static CDeviceInfoUtility* NewLC(); /** * Destroy the object and release all memory of the objects. */ virtual ~CDeviceInfoUtility(); private: // Default constructors /** * Default constructor */ CDeviceInfoUtility(); /** * Second-phase constructor. */ void ConstructL(); protected: // From CActive /** * Handles an active object's request completion event. */ void DoCancel(); /** * Implements cancellation of an outstanding request. */ void RunL(); /** * Handles a leave occurring in the request completion event handler RunL(). * \prarm aError The default implementation returns aError. * \return The error codes. */ TInt RunError(TInt aError); private: // New functions enum TDevInfoUtilityType { EDevInfoUtilityTypeNone, EDevInfoUtilityTypePhoneInfo, EDevInfoUtilityTypeNetworkInfo, EDevInfoUtilityTypeSubscriberInfo }; void GetInfo(CDeviceInfoUtility::TDevInfoUtilityType aDevInfoUtilityType); public: // New functions void GetPhoneInfo(TManufacturer& aManufacturer, TModel& aModel, TSerialNumber& aSerialNumber); void GetNetworkInfo(TUint& aCellId, TUint& aLocationAreaCode, TNetworkId& aNetworkId,TCountryCode& aCountryCode); void GetSubscriberInfo(TSubscriberId& aSubscriberId); private: // Member data /** * The object to provide the simple interface to get * the phone's telephony informations. * Owned by CDeviceInfoUtility. */ CTelephony* iTelephony; /** * Controls a single scheduling loop in the current active scheduler * Owned by CDeviceInfoUtility object. */ CActiveSchedulerWait* iActiveSchedulerWait; /** * To store the state of the Active Object. */ TDevInfoUtilityType iDevInfoUtilityType; /** * Defines the mobile phone identity. */ CTelephony::TPhoneIdV1Pckg iPhoneIdV1Pckg; CTelephony::TNetworkInfoV1Pckg iNetworkInfoV1Pckg; CTelephony::TSubscriberIdV1Pckg iSubscriberIdV1Pckg; /** * Defines the mobile phone identity. */ CTelephony::TPhoneIdV1 iPhoneIdV1; CTelephony::TNetworkInfoV1 iNetworkInfoV1; CTelephony::TSubscriberIdV1 iSubscriberIdV1; TManufacturer iManufacturer; TModel iModel; TSerialNumber iSerialNumber; TUint iCellId; TUint iLocationAreaCode; TNetworkId iNetworkId; TCountryCode iCountryCode; TSubscriberId iSubscriberId; }; #endif // __DEVICEINFOUTILITY_H__ // End of File
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); screen = new Screen(this); connect(ui->pushButton_shot,SIGNAL(clicked()),this,SLOT(on_screenbtn_clicked())); connect(ui->pushButton_sava,SIGNAL(clicked()),this,SLOT(on_btn_save_clicked())); connect(screen,SIGNAL(sendpic(QPixmap *)),this,SLOT(on_drawImg(QPixmap *))); screen->hide(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_screenbtn_clicked() { if(ui->checkBox->isChecked()){ this->showMinimized(); } QScreen *scrPix = QGuiApplication::primaryScreen(); QPixmap pixmap = scrPix->grabWindow(0); //截屏 delete screen; screen = new Screen(this); //screen->stack.push(pixmap); connect(screen,SIGNAL(sendpic(QPixmap *)),this,SLOT(on_drawImg(QPixmap *))); /*每次按下截图按钮都要重新生成一次截屏对象,便于更改 * 信号槽机制好像还是绑定了对象的,我以为只要是一种类就可以只声明一次就够了,后来发现不继续绑定信号槽就会失效,因为原对象消失了 */ screen->setPixmap(pixmap); screen->setWindowFlags (Qt::Window); //使Screen对象全屏显示 screen->showFullScreen (); screen->show(); } void MainWindow::on_drawImg(QPixmap *p) { editPixmap=*p; ui->label_pic->setPixmap(editPixmap); //qDebug()<<"p_size:"<<sizeof(*p)<<endl; //qDebug()<<"editPixmap_size:"<<sizeof(editPixmap)<<endl; } void MainWindow::on_btn_save_clicked() { QFileDialog fileDialog; QString fileName = fileDialog.getSaveFileName(this,"Save Image","","(*.jpg *.bmp *.png)"); if(fileName == "") { return; } editPixmap.save(fileName,"JPG"); QMessageBox::warning(this,"tip","Save File Success!"); }
// class Solution { // public: // int lengthOfLongestSubstring(string s) { // int n = s.size(); // if( n == 0) return 0; // vector <int> cnt(400,0); // int i(0), j(0); // // cout << i << j; // cnt[s[0]]++; // int ans=1; // while(j!=n-1) { // if(!cnt[s[j+1]]) { // j++; // cnt[s[j]]++; // ans = max(ans, j-i+1); // cout << ans<< endl; // } // else { // cnt[s[i]]--; // i++; // } // } // return ans; // } // }; // Using Set : #pragma GCC optimize("Ofast") #include <algorithm> #include <bitset> #include <deque> #include <iostream> #include <iterator> #include <string> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <unordered_map> #include <unordered_set> using namespace std; void abhisheknaiidu() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } int main(int argc, char* argv[]) { abhisheknaiidu(); string s = "bbbbbb"; int ans = 0; int n = s.length(); if(n == 0) cout << "0" << endl; set <int> set; set.insert(s[0]); int end = 0; for(int start=0; start<n; start++) { while( end + 1 < n && !set.count(s[end+1])) { end++; set.insert(s[end]); } ans = max(ans, end - start + 1); cout << ans << endl; set.erase(s[start]); } for(char x: set) cout << x << " "; cout << ans << endl; return 0; }
#pragma once #include "pch.h" #include "Exceptions.h" using namespace std; struct OrderMsg { OrderMsg(const string& symbol, int quantity) : symbol_(symbol), quantity_ {quantity} {}; // TODO Rename or override with << const string& ToString() const { return symbol_; }; // TODO implement static OrderMsg Parse(const string& line) { throw runtime_error("Not Implemented"); return OrderMsg("", 0); }; private: string symbol_; int quantity_; };
// KEGIESDoc.h : CKEGIESDoc // #pragma once #include "resource.h" #include "myDocument.h" class CKEGIESDoc : public CDocument { public: myDocumentPtr m_doc; protected: // serialization CKEGIESDoc(); DECLARE_DYNCREATE(CKEGIESDoc) public: virtual BOOL OnNewDocument(); virtual BOOL OnOpenDocument(LPCTSTR lpszPathName); virtual void OnCloseDocument(); virtual void Serialize(CArchive& ar); public: virtual ~CKEGIESDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif public: CObj* objItem; public: BOOL openLastDoc(); static DWORD StartThread (LPVOID param); protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnToolbarStartthread(); afx_msg void OnExtLoadobj(); afx_msg void OnToolConvert(); afx_msg void OnTimer(UINT nIDEvent); };
/* Linked List Reverse Printing Challenge Using whatever programming techniques you know, write the cleanest possible function you can think of to print a singly linked list in reverse. The format for the node should be a struct containing an integer value, val, and a next pointer to the following node. */ #include <iostream> using namespace std; struct node { int val; node *next; }; void Print_Reverse( node *list ) { if( list != 0 ) { Print_Reverse( list->next ); cout << list->val << endl; } } int main() { node root; node a1; node a2; node a3; node *ptr1 = &root; // node *ptr2 = &a1; root.val = 10; a1.val = 11; a2.val = 12; a3.val = 13; root.next = &a1; a1.next = &a2; a2.next = &a3; a3.next = nullptr; Print_Reverse(ptr1); return 0; }
#include <iostream> #include <vector> int gcd(int a, int b) { while (b) { a %= b; std::swap(a, b); } return a; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); int n; std::cin >> n; int data[100]; while (n--) { int nn; std::cin >> nn; for (int i = 0; i < nn; ++i) { std::cin >> data[i]; } std::size_t sum{}; for (int i = 0; i < nn - 1; ++i) { for (int j = i + 1; j < nn; ++j) { sum += gcd(data[i], data[j]); } } std::cout << sum << '\n'; } return 0; }
// // Copyright (C) 1995-2008 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // @author Arjan van Leeuwen (arjanl) // #ifndef MAILBOX_COMMAND_H #define MAILBOX_COMMAND_H #include "adjunct/m2/src/backend/imap/commands/ImapCommandItem.h" #include "adjunct/m2/src/backend/imap/commands/MiscCommands.h" #include "adjunct/m2/src/backend/imap/imap-folder.h" #include "adjunct/m2/src/backend/imap/imap-protocol.h" #include "adjunct/m2/src/engine/index.h" #include "adjunct/m2/src/engine/offlinelog.h" class IMAP4; namespace ImapCommands { /** @brief Superclass for all commands that require one mailbox to operate on */ class MailboxCommand : public ImapCommandItem { public: /** Constructor * @param mailbox Mailbox to apply action on */ MailboxCommand(ImapFolder* mailbox) : m_mailbox(mailbox) {} ImapFolder* GetMailbox() const { return m_mailbox; } protected: ImapFolder* m_mailbox; }; /** @brief CREATE command (creating a mailbox) */ class Create : public MailboxCommand { public: Create(ImapFolder* mailbox) : MailboxCommand(mailbox) {} OP_STATUS OnFailed(IMAP4& protocol, const OpStringC8& failed_msg); ProgressInfo::ProgressAction GetProgressAction() const { return ProgressInfo::CREATING_FOLDER; } protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.AppendFormat("CREATE %s", m_mailbox->GetQuotedName().CStr()); } }; /** @brief All steps needed to safely delete a mailbox. Use this instead of using Delete directly */ class DeleteMailbox : public MailboxCommand { public: DeleteMailbox(ImapFolder* mailbox) : MailboxCommand(mailbox) {} BOOL IsMetaCommand(IMAP4& protocol) const { return TRUE; } ImapCommandItem* GetExpandedQueue(IMAP4& protocol); }; /** @brief DELETE command (deleting a mailbox) */ class Delete : public MailboxCommand { public: Delete(ImapFolder* mailbox) : MailboxCommand(mailbox) {} ProgressInfo::ProgressAction GetProgressAction() const { return ProgressInfo::DELETING_FOLDER; } ImapFolder* NeedsUnselectedMailbox() const { return m_mailbox; } OP_STATUS OnSuccessfulComplete(IMAP4& protocol) { return protocol.GetBackend().RemoveFolder(m_mailbox); } protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.AppendFormat("DELETE %s", m_mailbox->GetQuotedName().CStr()); } }; /** @brief EXPUNGE command */ class Expunge : public MailboxCommand { public: Expunge(ImapFolder* mailbox) : MailboxCommand(mailbox) {} BOOL IsSaveable() const { return TRUE; } OP_STATUS WriteToOfflineLog(OfflineLog& offline_log) { return offline_log.EmptyTrash(FALSE); } ProgressInfo::ProgressAction GetProgressAction() const { return ProgressInfo::EMPTYING_TRASH; } ImapFolder* NeedsSelectedMailbox() const { return m_mailbox; } protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.Append("EXPUNGE"); } }; /** @brief RENAME command (renaming a mailbox) */ class Rename : public MailboxCommand { public: Rename(ImapFolder* mailbox) : MailboxCommand(mailbox) {} ProgressInfo::ProgressAction GetProgressAction() const { return ProgressInfo::RENAMING_FOLDER; } ImapFolder* NeedsUnselectedMailbox() const { return m_mailbox; } OP_STATUS OnSuccessfulComplete(IMAP4& protocol); protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.AppendFormat("RENAME %s %s", m_mailbox->GetOldName().CStr(), m_mailbox->GetNewName().CStr()); } private: OP_STATUS ReSubscribeMailbox(ImapFolder* mailbox, IMAP4& protocol); }; /** @brief SELECT command (creating a mailbox) */ class Select : public MailboxCommand { public: Select(ImapFolder* mailbox) : MailboxCommand(mailbox), m_is_quick_resync(FALSE) {} OP_STATUS OnFailed(IMAP4& protocol, const OpStringC8& failed_msg); ProgressInfo::ProgressAction GetProgressAction() const { return ProgressInfo::CHECKING_FOLDER; } OP_STATUS PrepareToSend(IMAP4& protocol); OP_STATUS OnSuccessfulComplete(IMAP4& protocol); protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol); BOOL m_is_quick_resync; }; /** @brief Like Select, but used when synchronizing a mailbox */ class SelectSync : public Select { public: SelectSync(ImapFolder* mailbox) : Select(mailbox) { m_mailbox->IncreaseSyncCount(); } ~SelectSync() { m_mailbox->DecreaseSyncCount(); } }; /** @brief EXAMINE command, like Select but read-only */ class Examine : public Select { public: Examine(ImapFolder* mailbox) : Select(mailbox) {} OP_STATUS OnSuccessfulComplete(IMAP4& protocol) { return OpStatus::OK; } protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.AppendFormat("EXAMINE %s", m_mailbox->GetQuotedName().CStr()); } }; /** @brief UNSELECT command, unselects a mailbox. * Is replaced with suitable other commands if UNSELECT is not available. */ class Unselect : public MailboxCommand { public: Unselect(ImapFolder* mailbox) : MailboxCommand(mailbox) {} BOOL IsUnnecessary(const IMAP4& protocol) const { return protocol.GetCurrentFolder() != m_mailbox; } OP_STATUS OnFailed(IMAP4& protocol, const OpStringC8& failed_msg) { protocol.SetCurrentFolder(0); return OpStatus::OK; } OP_STATUS OnSuccessfulComplete(IMAP4& protocol) { protocol.SetCurrentFolder(0); return OpStatus::OK; } BOOL IsMetaCommand(IMAP4& protocol) const { return !(protocol.GetCapabilities() & ImapFlags::CAP_UNSELECT); } ImapCommandItem* GetExpandedQueue(IMAP4& protocol); protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.Append("UNSELECT"); } }; /** @brief CLOSE command, closes a mailbox */ class Close : public MailboxCommand { public: Close(ImapFolder* mailbox) : MailboxCommand(mailbox) {} BOOL IsUnnecessary(const IMAP4& protocol) const { return protocol.GetCurrentFolder() != m_mailbox; } OP_STATUS OnSuccessfulComplete(IMAP4& protocol) { protocol.SetCurrentFolder(0); return OpStatus::OK; } protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.Append("CLOSE"); } }; /** @brief meta-command for synchronizing a mailbox */ class Sync : public MailboxCommand { public: Sync(ImapFolder* mailbox) : MailboxCommand(mailbox) { m_mailbox->IncreaseSyncCount(); } ~Sync() { m_mailbox->DecreaseSyncCount(); } BOOL IsUnnecessary(const IMAP4& protocol) const { return m_mailbox->IsScheduledForMultipleSync(); } BOOL IsMetaCommand(IMAP4& protocol) const { return TRUE; } ImapCommandItem* GetExpandedQueue(IMAP4& protocol); }; /** @brief STATUS command (can be used to synchronize mailbox) */ class StatusSync : public MailboxCommand { public: StatusSync(ImapFolder* mailbox) : MailboxCommand(mailbox) { mailbox->IncreaseSyncCount(); } ~StatusSync() { m_mailbox->DecreaseSyncCount(); } OP_STATUS OnSuccessfulComplete(IMAP4& protocol); OP_STATUS OnFailed(IMAP4& protocol, const OpStringC8& failed_msg) { return m_mailbox->MarkUnselectable(); } ProgressInfo::ProgressAction GetProgressAction() const { return ProgressInfo::CHECKING_FOLDER; } protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return (protocol.GetCapabilities() & ImapFlags::CAP_QRESYNC) ? command.AppendFormat("STATUS %s (MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN HIGHESTMODSEQ)", m_mailbox->GetQuotedName().CStr()) : command.AppendFormat("STATUS %s (MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)", m_mailbox->GetQuotedName().CStr()); } }; /** @brief SUBSCRIBE command (subscribing to a mailbox) */ class Subscribe : public MailboxCommand { public: Subscribe(ImapFolder* mailbox) : MailboxCommand(mailbox) {} OP_STATUS OnSuccessfulComplete(IMAP4& protocol) { return AddDependency(OP_NEW(ImapCommands::Lsub, ()), protocol); } ProgressInfo::ProgressAction GetProgressAction() const { return ProgressInfo::FOLDER_SUBSCRIBE; } protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.AppendFormat("SUBSCRIBE %s", m_mailbox->GetQuotedName().CStr()); } }; /** @brief UNSUBSCRIBE command (unsubscribing from mailbox) */ class Unsubscribe : public MailboxCommand { public: Unsubscribe(ImapFolder* mailbox) : MailboxCommand(mailbox) {} OP_STATUS OnSuccessfulComplete(IMAP4& protocol) { return AddDependency(OP_NEW(ImapCommands::Lsub, ()), protocol); } ProgressInfo::ProgressAction GetProgressAction() const { return ProgressInfo::FOLDER_UNSUBSCRIBE; } ImapFolder* NeedsUnselectedMailbox() const { return m_mailbox; } protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.AppendFormat("UNSUBSCRIBE %s", m_mailbox->GetQuotedName().CStr()); } }; /** @brief special SUBSCRIBE command used when renaming a mailbox */ class SubscribeRenamed : public Subscribe { public: SubscribeRenamed(ImapFolder* mailbox) : Subscribe(mailbox) {} OP_STATUS OnSuccessfulComplete(IMAP4& protocol) { return OpStatus::OK; } protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.AppendFormat("SUBSCRIBE %s", m_mailbox->GetNewName().CStr()); } }; /** @brief special UNSUBSCRIBE command used when renaming a mailbox */ class UnsubscribeRenamed : public Unsubscribe { public: UnsubscribeRenamed(ImapFolder* mailbox) : Unsubscribe(mailbox) {} OP_STATUS OnSuccessfulComplete(IMAP4& protocol) { return m_mailbox->ApplyNewName(); } protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.AppendFormat("UNSUBSCRIBE %s", m_mailbox->GetOldName().CStr()); } }; /** @brief NOOP command (can be used to synchronize mailbox) */ class NoopSync : public MailboxCommand { public: NoopSync(ImapFolder* mailbox) : MailboxCommand(mailbox) { m_mailbox->IncreaseSyncCount(); } ~NoopSync() { m_mailbox->DecreaseSyncCount(); } BOOL IsUnnecessary(const IMAP4& protocol) const { return Suc() != NULL; } ImapFolder* NeedsSelectedMailbox() const { return m_mailbox; } protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.Append("NOOP"); } }; /** @brief APPEND command (to append a single message) */ class Append : public MailboxCommand { public: /** Constructor * @param message_id Message to append */ Append(ImapFolder* mailbox, message_gid_t message_id) : MailboxCommand(mailbox), m_message_id(message_id), m_continuation(FALSE) {} OP_STATUS PrepareContinuation(IMAP4& protocol, const OpStringC8& response_text) { m_continuation = TRUE; return OpStatus::OK; } BOOL IsSaveable() const { return TRUE; } OP_STATUS WriteToOfflineLog(OfflineLog& offline_log) { return offline_log.InsertMessage(m_message_id, m_mailbox->GetIndexId()); } ProgressInfo::ProgressAction GetProgressAction() const { return ProgressInfo::APPENDING_MESSAGE; } BOOL RemoveIfCausesDisconnect(IMAP4& protocol) const { return TRUE; } BOOL IsContinuation() const { return m_continuation; } void ResetContinuation() { m_continuation = FALSE; } ImapFolder* NeedsUnselectedMailbox() const { return m_mailbox; } OP_STATUS OnSuccessfulComplete(IMAP4& protocol); OP_STATUS OnAppendUid(IMAP4& protocol, unsigned uid_validity, unsigned uid); protected: OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol); OpString8 m_raw_message; message_gid_t m_message_id; BOOL m_continuation; }; /** @brief Append a message to the sent messages */ class AppendSent : public Append { public: AppendSent(ImapFolder* mailbox, message_gid_t message_id) : Append(mailbox, message_id), m_got_uid(FALSE) {} OP_STATUS OnSuccessfulComplete(IMAP4& protocol); OP_STATUS OnAppendUid(IMAP4& protocol, unsigned uid_validity, unsigned uid); protected: BOOL m_got_uid; }; }; #endif // MAILBOX_COMMAND_H
#include<bits/stdc++.h> using namespace std; main() { long long int l, h, i, limit, value, count = 0, g=0, c=0, temp; while(scanf("%lld %lld",&l,&h)==2) { if(l==0 && h==0)break; temp = 0, g=0, c=0; if(l>h) { temp = l; l = h; h =temp; } for(i=l; i<=h; i++) { limit =0; value = i; while(limit!=1) { if(value%2==0) { limit = value/2; count++; value = limit; } else { limit = (3*value)+1; count++; value = limit; } } if(count>c) { g=i; c=count; } count = 0; } printf("Between %lld and %lld, %lld generates the longest sequence of %lld values.\n",l,h,g,c); } return 0; }
#include<iostream> #include<vector> #include<algorithm> #include<set> #include<map> using namespace std; class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { //基本思想:双指针,与algo里面的set_intersection算法一致 vector<int> res; multiset<int> s1,s2; for(auto num:nums1) s1.insert(num); for(auto num:nums2) s2.insert(num); multiset<int>::iterator iter1=s1.begin(),iter2=s2.begin(); while(iter1!=s1.end()&&iter2!=s2.end()) { if(*iter1==*iter2) { res.push_back(*iter1); iter1++; iter2++; } else if(*iter1>*iter2) iter2++; else iter1++; } return res; } }; class Solution1 { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { //基本思想:哈希表HashMap,与algo里面的set_intersection算法一致 vector<int> res; map<int,int> s1,s2; for(auto num:nums1) s1[num]++; for(auto num:nums2) s2[num]++; map<int,int>::iterator iter1=s1.begin(),iter2=s2.begin(); while(iter1!=s1.end()&&iter2!=s2.end()) { if(iter1->first==iter2->first) { int cnt=min(iter1->second,iter2->second); while(cnt--) res.push_back(iter1->first); iter1++; iter2++; } else if(iter1->first>iter2->first) iter2++; else iter1++; } return res; } }; int main() { Solution solute; vector<int> nums1{1,2,2,1}; vector<int> nums2{2,2}; vector<int> nums=solute.intersect(nums1,nums2); for_each(nums.begin(),nums.end(),[](int n){cout<<n<<endl;}); return 0; }
#include "grille.hpp" #define WIDTH_BLOCKS 6 #define HEIGHT_BLOCKS 8 #define OFFSET_SCORE 180 #define SIZE_BLOCK 50 #define W_WIDTH ((WIDTH_BLOCKS) * (SIZE_BLOCK)) //20 * 6 #define W_HEIGHT ((HEIGHT_BLOCKS) * (SIZE_BLOCK) + (OFFSET_SCORE)) //20 * 8 struct retCheckGO { enum rettype { RET_OK, RET_STUCK }; enum rettype retcode; coord hint; }; Color getCouleur(enum couleur couleur); Grille *gen_new_grille(unsigned short width, unsigned short height); struct retCheckGO checkIfGameOver(Grille *grille); void drawCell(unsigned short x, unsigned short y, Grille *grille);
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// // Простой Калькулятор v 0.6. The Simply Calculator // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// #include<iostream> using namespace std; int main() { char userSelection = 'y'; do { cout << "Калькулятор. Введите первое число" << endl; float firstNum = 0; cin >> firstNum; cout << "Введите символ операции" << endl; char op = 0; cin >> op; if ((op == '+') || (op == '-') || (op == '*') || (op == '/')) { cout << "Введите второе число" << endl; float secondNum = 0; cin >> secondNum; switch (op) { case '*': cout << "Результат: " << firstNum * secondNum << endl; break; case '/': cout << "Результат: " << firstNum / secondNum << endl; break; case '+': cout << "Результат: " << firstNum + secondNum << endl; break; case '-': cout << "Результат: " << firstNum - secondNum << endl; break; default: cout << "Введите символ операции" << endl; break; } } else { cout << "Введите правильный оператор! +, -, *, /" << endl; return main(); } cout << "Нажмите y для повтора, n для выхода" << endl; cin >> userSelection; } while (userSelection != 'n'); return 0; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// // END FILE // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #define EIGEN2_SUPPORT #include "main.h" template<typename MatrixType> void eigen2support(const MatrixType& m) { typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; Index rows = m.rows(); Index cols = m.cols(); MatrixType m1 = MatrixType::Random(rows, cols), m2 = MatrixType::Random(rows, cols), m3(rows, cols); Scalar s1 = ei_random<Scalar>(), s2 = ei_random<Scalar>(); // scalar addition VERIFY_IS_APPROX(m1.cwise() + s1, s1 + m1.cwise()); VERIFY_IS_APPROX(m1.cwise() + s1, MatrixType::Constant(rows,cols,s1) + m1); VERIFY_IS_APPROX((m1*Scalar(2)).cwise() - s2, (m1+m1) - MatrixType::Constant(rows,cols,s2) ); m3 = m1; m3.cwise() += s2; VERIFY_IS_APPROX(m3, m1.cwise() + s2); m3 = m1; m3.cwise() -= s1; VERIFY_IS_APPROX(m3, m1.cwise() - s1); VERIFY_IS_EQUAL((m1.corner(TopLeft,1,1)), (m1.block(0,0,1,1))); VERIFY_IS_EQUAL((m1.template corner<1,1>(TopLeft)), (m1.template block<1,1>(0,0))); VERIFY_IS_EQUAL((m1.col(0).start(1)), (m1.col(0).segment(0,1))); VERIFY_IS_EQUAL((m1.col(0).template start<1>()), (m1.col(0).segment(0,1))); VERIFY_IS_EQUAL((m1.col(0).end(1)), (m1.col(0).segment(rows-1,1))); VERIFY_IS_EQUAL((m1.col(0).template end<1>()), (m1.col(0).segment(rows-1,1))); m1.minor(0,0); } void test_eigen2support() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( eigen2support(Matrix<double,1,1>()) ); CALL_SUBTEST_2( eigen2support(MatrixXd(1,1)) ); CALL_SUBTEST_4( eigen2support(Matrix3f()) ); CALL_SUBTEST_5( eigen2support(Matrix4d()) ); CALL_SUBTEST_2( eigen2support(MatrixXf(200,200)) ); CALL_SUBTEST_6( eigen2support(MatrixXcd(100,100)) ); } }
#include "AABB.h" #include <Gizmos.h> #include "PhysicsMaterial.h" AABB::AABB(const vec2& pos, const vec2& vel, float width, float height, const vec4& colour, float mass, float friction, float elasticity, bool isKinematic) : RigidBody(eShapeType::AABB, pos, vel, 0, isKinematic, new PhysicsMaterial(friction, elasticity, eMaterial::NIL), mass), m_colour(colour) { m_moment = 1.f / 12.f * m_mass * width * height; m_extents = vec2(width * 0.5f, height * 0.5f); } AABB::AABB(const vec2 & pos, const vec2 & vel, float width, float height, const vec4& colour, PhysicsMaterial* material, bool isKinematic) : RigidBody(eShapeType::AABB, pos, vel, 0, isKinematic, material), m_colour(colour) { m_mass = width * height * material->getDensity(); m_moment = 1.f / 12.f * m_mass * width * height; m_extents = vec2(width * 0.5f, height * 0.5f); } AABB::~AABB() { } void AABB::DrawGizmo() { aie::Gizmos::add2DAABBFilled(m_position, m_extents, m_colour); } vec2array AABB::vertices() const { vec2array verts(4); verts[0] = min(); verts[1] = { min().x, max().y }; verts[2] = max(); verts[3] = { max().x, min().y }; return verts; } vec2array AABB::vextents() const { vec2array vextents(4); vextents[0] = -m_extents; vextents[1] = { -m_extents.x, m_extents.y }; vextents[2] = m_extents; vextents[3] = { m_extents.x, -m_extents.y }; return vextents; } vec2 AABB::projection(const vec2 & axis) const { //Based on SAT algorithm auto cacheVertices = vertices(); float min = glm::dot(axis, cacheVertices[0]); float max = min; for (int i = 0; i < vertices().size(); ++i) { float point = glm::dot(axis, cacheVertices[i]); if (point < min) min = point; else if (point > max) max = point; } return vec2(min, max); }
#include <bits/stdc++.h> #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define all(x) (x).begin(),(x).end() #define rall(x) (x).rbegin(),(x).rend() #define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() ); template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; using ll = long long; struct UnionFind { vector<int> par; UnionFind(int n) : par(n, -1){} void init(int n) {par.assign(n, -1);} //再帰的に辿ることで親を調べる int root(int x){ if(par[x] < 0) return x; else return par[x] = root(par[x]); } //親が同じならば同じ集合に属する bool same(int x, int y){ return root(x) == root(y); } bool merge(int x, int y){ x = root(x); y = root(y); if(x == y) return false; //新しい要素を加えた時に、rootに対して辺を張る(merge technique) if(par[x] > par[y]) swap(x, y); par[x] += par[y]; par[y] = x; return true; } //新しいノードを集合に加えた時に、-1をrootに加算するため、 //rootには、集合に属するノードの数に負符号を付加したものが保存されている。 int size(int x){ return -par[root(x)]; } }; int main(){ int h, w; cin >> h >> w; using P = pair<int ,int>; vector<vector<int>> colored(h+2, vector<int>(w+2)); map<P, int> index; int idx = 1; rep(i, h){ rep(j, w){ index[{i+1, j+1}] = idx; idx++; } } int q; cin >> q; UnionFind uf(h * w + 1); int dy[] = {1, -1, 0, 0}; int dx[] = {0, 0, 1, -1}; rep(i, q){ int query_type; cin >> query_type; if(query_type == 1){ int y, x; cin >> y >> x; colored[y][x] = true; rep(d, 4){ int ny = y + dy[d]; int nx = x + dx[d]; if(colored[ny][nx]) uf.merge(index[{y, x}], index[{ny, nx}]); } } else if(query_type == 2){ int ya, xa, yb, xb; cin >> ya >> xa >> yb >> xb; if(colored[ya][xa] && colored[yb][xb] && uf.same(index[{ya, xa}] , index[{yb, xb}])) cout << "Yes" << endl; else cout << "No" << endl; } } return 0; }
#pragma once namespace Hourglass { class PrimitiveRenderer; } class Health : public hg::IComponent { public: virtual int GetTypeID() const { return s_TypeID; } void LoadFromXML(tinyxml2::XMLElement* data); float GetValue() const { return m_Value; } void SetValue(float val) { m_Value = val; } void Init(); void Update(); bool RestoreHealth(float value); void SetInvulnerable( bool invulnerable ) { m_Invulnerable = invulnerable; } void OnMessage(hg::Message* msg); void DealDamage( float dmgVal ); hg::IComponent* MakeCopyDerived() const; float GetHealthRatio()const; static uint32_t s_TypeID; private: float m_Value; float m_maxValue; bool m_PlayingFlashEffect; float m_FlashEffectEndTime; Color m_MeshColor; // For flashing effect hg::RenderComponent* m_Renderer; char m_Invulnerable : 1; char m_InDirect : 1; };
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/TextInputPrice.g.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Animations.IResize.h> #include <Fuse.Binding.h> #include <Fuse.Controls.Panel.h> #include <Fuse.Drawing.ISurfaceDrawable.h> #include <Fuse.IActualPlacement.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.ITemplateSource.h> #include <Fuse.Node.h> #include <Fuse.Scripting.IScriptObject.h> #include <Fuse.Triggers.Actions.ICollapse.h> #include <Fuse.Triggers.Actions.IHide.h> #include <Fuse.Triggers.Actions.IShow.h> #include <Fuse.Visual.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.UX.IPropertyListener.h> namespace g{namespace Uno{namespace UX{struct Property1;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{struct TextInputPrice;} namespace g{ // public partial sealed class TextInputPrice :2 // { ::g::Fuse::Controls::Panel_type* TextInputPrice_typeof(); void TextInputPrice__ctor_7_fn(TextInputPrice* __this); void TextInputPrice__InitializeUX_fn(TextInputPrice* __this); void TextInputPrice__New4_fn(TextInputPrice** __retval); void TextInputPrice__get_PlaceholderText_fn(TextInputPrice* __this, uString** __retval); void TextInputPrice__set_PlaceholderText_fn(TextInputPrice* __this, uString* value); void TextInputPrice__SetPlaceholderText_fn(TextInputPrice* __this, uString* value, uObject* origin); void TextInputPrice__SetValue_fn(TextInputPrice* __this, uObject* value, uObject* origin); void TextInputPrice__get_Value_fn(TextInputPrice* __this, uObject** __retval); void TextInputPrice__set_Value_fn(TextInputPrice* __this, uObject* value); struct TextInputPrice : ::g::Fuse::Controls::Panel { static ::g::Uno::UX::Selector __selector0_; static ::g::Uno::UX::Selector& __selector0() { return TextInputPrice_typeof()->Init(), __selector0_; } static ::g::Uno::UX::Selector __selector1_; static ::g::Uno::UX::Selector& __selector1() { return TextInputPrice_typeof()->Init(), __selector1_; } uStrong<uString*> _field_PlaceholderText; uStrong<uObject*> _field_Value; uStrong< ::g::Uno::UX::Property1*> temp_PlaceholderText_inst; uStrong< ::g::Uno::UX::Property1*> temp_Value_inst; void ctor_7(); void InitializeUX(); uString* PlaceholderText(); void PlaceholderText(uString* value); void SetPlaceholderText(uString* value, uObject* origin); void SetValue(uObject* value, uObject* origin); uObject* Value(); void Value(uObject* value); static TextInputPrice* New4(); }; // } } // ::g
#pragma once #include <Tanker/Entry.hpp> #include <Tanker/Trustchain/Actions/DeviceRevocation.hpp> #include <Tanker/Trustchain/DeviceId.hpp> #include <Tanker/Trustchain/UserId.hpp> #include <Tanker/User.hpp> #include <gsl-lite.hpp> #include <tconcurrent/coroutine.hpp> #include <cstdint> #include <tuple> #include <vector> namespace Tanker { class BlockGenerator; class ContactStore; class UserKeyStore; class DeviceKeyStore; class UserAccessor; class Client; namespace Revocation { tc::cotask<void> ensureDeviceIsFromUser(Trustchain::DeviceId const& deviceId, Trustchain::UserId const& selfUserId, ContactStore const& contactStore); tc::cotask<User> getUserFromUserId(Trustchain::UserId const& selfUserId, ContactStore const& contactStore); tc::cotask<Crypto::SealedPrivateEncryptionKey> encryptForPreviousUserKey( UserKeyStore const& userKeyStore, User const& user, Crypto::PublicEncryptionKey const& publicEncryptionKey); tc::cotask<Trustchain::Actions::DeviceRevocation::v2::SealedKeysForDevices> encryptPrivateKeyForDevices( User const& user, Trustchain::DeviceId const& deviceId, Crypto::PrivateEncryptionKey const& encryptionPrivateKey); tc::cotask<void> revokeDevice(Trustchain::DeviceId const& deviceId, Trustchain::UserId const& userId, ContactStore const& contactStore, UserKeyStore const& userKeyStore, BlockGenerator const& blockGenerator, std::unique_ptr<Client> const& client); Crypto::PrivateEncryptionKey decryptPrivateKeyForDevice( std::unique_ptr<DeviceKeyStore> const& deviceKeyStore, Crypto::SealedPrivateEncryptionKey const& encryptedPrivateEncryptionKey); tc::cotask<void> onOtherDeviceRevocation( Trustchain::Actions::DeviceRevocation const& deviceRevocation, Entry const& entry, Trustchain::UserId const& selfUserId, Trustchain::DeviceId const& deviceId, ContactStore& contactStore, std::unique_ptr<DeviceKeyStore> const& deviceKeyStore, UserKeyStore& userKeyStore); } }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ group "desktop_util.mailto"; include "adjunct/desktop_util/mail/mailto.h"; // tests inspired by http://people.mozilla.org/~ctalbert/test-protocol-links.html // The attributes (to, cc, bcc, subject, body) are what you should get when parsing url // rev_url is the URL you should get when converting the attributes back into a mailto url table MailtoTests(const char*, const char*, const uni_char*, const uni_char*, const uni_char*, const uni_char*, const uni_char*) { // Simple: just a To address { /* url */ "mailto:noone@opera.com", /* rev_url */ "mailto:noone%40opera.com", /* to */ UNI_L("noone@opera.com"), /* cc */ 0, /* bcc */ 0, /* subject */ 0, /* body */ 0 }, // CC, BCC, subject and body { /* url */ "mailto:noone@opera.com?cc=bob@opera.com&bcc=bcc@opera.com&subject=subject&body=hello%20world", /* rev_url */ "mailto:noone%40opera.com?cc=bob%40opera.com&bcc=bcc%40opera.com&subject=subject&body=hello%20world", /* to */ UNI_L("noone@opera.com"), /* cc */ UNI_L("bob@opera.com"), /* bcc */ UNI_L("bcc@opera.com"), /* subject */ UNI_L("subject"), /* body */ UNI_L("hello world") }, // Multiple To addresses { /* url */ "mailto:addr1@opera.com,addr2@foo.com", /* rev+url */ "mailto:addr1%40opera.com%2Caddr2%40foo.com", /* to */ UNI_L("addr1@opera.com,addr2@foo.com"), /* cc */ 0, /* bcc */ 0, /* subject */ 0, /* body */ 0 }, // Multi-line body { /* url */ "mailto:addr1@opera.com,addr2@foo.com?cc=addr3@foo.com&subject=foo&body=this%20is%20the%20first%20line%0D%0Athis%20is%20the%20second%0D%0Athis%20is%20the%20third", /* rev_url */ "mailto:addr1%40opera.com%2Caddr2%40foo.com?cc=addr3%40foo.com&subject=foo&body=this%20is%20the%20first%20line%0D%0Athis%20is%20the%20second%0D%0Athis%20is%20the%20third", /* to */ UNI_L("addr1@opera.com,addr2@foo.com"), /* cc */ UNI_L("addr3@foo.com"), /* bcc */ 0, /* subject */ UNI_L("foo"), /* body */ UNI_L("this is the first line\r\nthis is the second\r\nthis is the third") }, // To addresses spread over two attributes { /* url */ "mailto:addr1@foo.com?to=addr2@foo.com&subject=hi%20world&body=more%20text%20here", /* rev_url */ "mailto:addr1%40foo.com%2Caddr2%40foo.com?subject=hi%20world&body=more%20text%20here", /* to */ UNI_L("addr1@foo.com,addr2@foo.com"), /* cc */ 0, /* bcc */ 0, /* subject */ UNI_L("hi world"), /* body */ UNI_L("more text here") }, // Special characters & and ? inside subject and body { /* url */ "mailto:noone@opera.com?cc=bob@opera.com&subject=subject%20%26%20ampersands&body=hello%20world%3F", /* rev_url */ "mailto:noone%40opera.com?cc=bob%40opera.com&subject=subject%20%26%20ampersands&body=hello%20world%3F", /* to */ UNI_L("noone@opera.com"), /* cc */ UNI_L("bob@opera.com"), /* bcc */ 0, /* subject */ UNI_L("subject & ampersands"), /* body */ UNI_L("hello world?") }, // UTF-8 in mailto { /* url */ "mailto:addr1@foo.com?cc=addr2@foo.com&subject=%20%E9%A6%99%20%E9%A6%99%20%E9%A6%99&body=crazy%20characters%20with%20every%E2%BC%ADthing%ED%8C%BDin%C5%92%20%E9%A3%82%20%20%E9%A6%99%20them%20and%20mixed%20up!", /* rev_url */ "mailto:addr1%40foo.com?cc=addr2%40foo.com&subject=%20%E9%A6%99%20%E9%A6%99%20%E9%A6%99&body=crazy%20characters%20with%20every%E2%BC%ADthing%ED%8C%BDin%C5%92%20%E9%A3%82%20%20%E9%A6%99%20them%20and%20mixed%20up!", /* to */ UNI_L("addr1@foo.com"), /* cc */ UNI_L("addr2@foo.com"), /* bcc */ 0, /* subject */ UNI_L("\x20\x9999\x20\x9999\x20\x9999"), /* body */ UNI_L("\x63\x72\x61\x7a\x79\x20\x63\x68\x61\x72\x61\x63\x74\x65\x72\x73\x20\x77\x69\x74\x68\x20\x65\x76\x65\x72\x79\x2f2d\x74\x68\x69\x6e\x67\xd33d\x69\x6e\x152\x20\x98c2\x20\x20\x9999\x20\x74\x68\x65\x6d\x20\x61\x6e\x64\x20\x6d\x69\x78\x65\x64\x20\x75\x70\x21") }, // Test to make sure '#', '=' and '&' before first '?', extra '?' and extra '=' don't mess up parsing. { /* url */ "mailto:#1=2&3=4?subject=?#=&body=line1", /* rev_url */ "mailto:%231%3D2%263%3D4?subject=%3F%23%3D&body=line1", /* to */ UNI_L("#1=2&3=4"), /* cc */ 0, /* bcc */ 0, /* subject */ UNI_L("?#="), /* body */ UNI_L("line1") }, // Test case-insensitivity { /* url */ "mailto:?tO=1&sUbJeCt=2&bOdY=3&cC=4&bCc=5", /* rev_url */ "mailto:1?cc=4&bcc=5&subject=2&body=3", /* to */ UNI_L("1"), /* cc */ UNI_L("4"), /* bcc */ UNI_L("5"), /* subject */ UNI_L("2"), /* body */ UNI_L("3") }, // Test case-insensitivity and examples of unnecessary percent-encoding an hname { /* url */ "mailto:?%74%4F=1&%73%55%62%4A%65%43%74=2&%62%4F%64%59=3&%63%43=4&%62%43%63=5", /* rev_url */ "mailto:1?cc=4&bcc=5&subject=2&body=3", /* to */ UNI_L("1"), /* cc */ UNI_L("4"), /* bcc */ UNI_L("5"), /* subject */ UNI_L("2"), /* body */ UNI_L("3") }, // Test that lowercase %HH still work. { /* url */ "mailto:%3y%?subject=%3y%&body=%3y%&cc=%3y%&bcc=%3y%", /* rev_url */ "mailto:%253y%25?cc=%253y%25&bcc=%253y%25&subject=%253y%25&body=%253y%25", /* to */ UNI_L("%3y%"), /* cc */ UNI_L("%3y%"), /* bcc */ UNI_L("%3y%"), /* subject */ UNI_L("%3y%"), /* body */ UNI_L("%3y%") }, // Test to see if smart duplicate hname handling is supported (won't be supported if RFC2368 duplicate hname handling is supported) { /* url */ "mailto:1t?to=&to=&to=2t&to=3t&to=&to=&subject=1&subject=2&subject=&body=&body=&body=line1&body=&body=line3&body=&cc=&cc=&cc=1&cc=&cc=&cc=2&cc=3&bcc=&bcc=&bcc=1&bcc=2&bcc=&bcc=&bcc=3", /* rev_url */ "mailto:1t%2C%202t%2C%203t?cc=1%2C%202%2C%203&bcc=1%2C%202%2C%203&body=line1%0D%0A%0D%0Aline3%0D%0A", /* to */ UNI_L("1t, 2t, 3t"), /* cc */ UNI_L("1, 2, 3"), /* bcc */ UNI_L("1, 2, 3"), /* subject */ 0, /* body */ UNI_L("line1") }, // Test to make sure that '+' is treated as '+' { /* url */ "mailto:+?subject=+&body=+&cc=+&bcc=+", /* rev_url */ "mailto:%2B?cc=%2B&bcc=%2B&subject=%2B&body=%2B", /* to */ UNI_L("+"), /* cc */ UNI_L("+"), /* bcc */ UNI_L("+"), /* subject */ UNI_L("+"), /* body */ UNI_L("+") }, // Test that UTF-8 %HH sequence emit the chars they represent { /* url */ "mailto:%E2%88%9A?subject=%E2%88%9A&body=%E2%88%9A&cc=%E2%88%9A&bcc=%E2%88%9A", /* rev_url */ "mailto:%E2%88%9A?cc=%E2%88%9A&bcc=%E2%88%9A&subject=%E2%88%9A&body=%E2%88%9A", /* to */ UNI_L("\xE2\x88\x9A"), /* cc */ UNI_L("\xE2\x88\x9A"), /* bcc */ UNI_L("\xE2\x88\x9A"), /* subject */ UNI_L("\xE2\x88\x9A"), /* body */ UNI_L("\xE2\x88\x9A") } } subtest StringsEqual(const OpStringC& string1, const OpStringC& string2) { if (string1.Compare(string2)) { output("Failed: \"%s\" is not equal to \"%s\": ", string1.CStr() ? ST_down(string1.CStr()) : "", string2.CStr() ? ST_down(string2.CStr()) : ""); return FALSE; } return TRUE; } subtest StringsEqual8(const OpStringC8& string1, const OpStringC8& string2) { if (string1.Compare(string2)) { output("\"%s\" is not equal to \"%s\": ", string1.CStr() ? string1.CStr() : "", string2.CStr() ? string2.CStr() : ""); return FALSE; } return TRUE; } test("url to mailto parts") { iterate(url_string, rev_url, to, cc, bcc, subject, body) from MailtoTests { MailTo mailto; verify(OpStatus::IsSuccess(mailto.Init(url_string))); verify(StringsEqual(mailto.GetTo(), to)); verify(StringsEqual(mailto.GetCc(), cc)); verify(StringsEqual(mailto.GetBcc(), bcc)); verify(StringsEqual(mailto.GetSubject(), subject)); verify(StringsEqual(mailto.GetBody(), body)); } } test("mailto parts to url") { iterate(url, rev_url, to, cc, bcc, subject, body) from MailtoTests { MailTo mailto; verify(OpStatus::IsSuccess(mailto.Init(to, cc, bcc, subject, body))); verify(StringsEqual8(mailto.GetRawMailTo(), rev_url)); } }
#include "VnaCalStandard.h" using namespace RsaToolbox; #include <QTextStream> /*! * \class RsaToolbox::VnaCalStandard * \ingroup VnaGroup * \brief \c %CalStandard represents an RF calibration standard and its * associated properties * * A \c %CalStandard can be one or two port, of different connector * types and genders, it can be VNA port-specific, it can be defined * by a touchstone file or by a lumped-element model, and is also * limited to a specific frequency range. * * A \c %CalStandard can be given a label (optional) to uniquely identify * it. * * \note In order to prevent ambiguity, Rohde \& Schwarz VNAs * require standards with two ports to order connector genders and vna * ports a specific way. For example, a mixed gender thru standard * must be defined such that: \code calStandard.gender1() == MALE_GENDER; calStandard.gender2() == FEMALE_GENDER; \endcode * Similarly, port specific standards must list the lower-numbered port * as \c port1 and the higher-numbered port as \c port2. While CalStandard * does not enforce this, failure to abide by these guidelines will cause * instrument errors when using the RsaToolbox::Vna CalKit interface. * * For a list of supported standard types, see RsaToolbox::CalStandardType. * * \sa RsaToolbox::CalStandardType, Connector, Vna::CalKit(), Vna::Calibration */ /*! * \brief Default constructor * * This constructor provides an uninitialized CalStandard object. * This object is of type RsaToolbox::UNKNOWN_STANDARD_TYPE. All * properties of the resulting object must be set after * construction. * \sa setType(), setConnector(), setPort() */ VnaCalStandard::VnaCalStandard() { clear(); } /*! * \brief Constructor for single-port calibration standard * * This constructor creates a single-port %CalStandard object with * \c connector type and gender. The properties of the \c type * standard are uninitialized and must be set afterward. See * \c setTouchstoneFile() or one of the set model * functions such as \c setOpenModel(). * * The following standards are single port: <tt><br> RsaToolbox::OPEN_STANDARD_TYPE<br> RsaToolbox::SHORT_STANDARD_TYPE<br> RsaToolbox::OFFSET_SHORT_STANDARD_TYPE<br> RsaToolbox::OFFSET_SHORT2_STANDARD_TYPE<br> RsaToolbox::OFFSET_SHORT3_STANDARD_TYPE<br> RsaToolbox::MATCH_STANDARD_TYPE<br> RsaToolbox::SLIDING_MATCH_STANDARD_TYPE<br> RsaToolbox::REFLECT_STANDARD_TYPE<br> </tt> * * \param type Type of calibration standard * \param connector Connector type and gender * \sa CalStandard::CalStandard(CalStandardType type, uint port) */ VnaCalStandard::VnaCalStandard(Type type, Connector connector) { clear(); _type = type; _connector1 = connector; } /*! * \brief Constructor for port-specific single-port calibration standard * * This constructor creates a single-port %CalStandard object that * can be used only with VNA port \c port. The properties of the * \c type standard are uninitialized and must be set afterward. * See \c setTouchstoneFile() or one of the set model * functions such as \c setOpenModel(). * * The following standards are single port: <tt><br> RsaToolbox::OPEN_STANDARD_TYPE<br> RsaToolbox::SHORT_STANDARD_TYPE<br> RsaToolbox::OFFSET_SHORT_STANDARD_TYPE<br> RsaToolbox::OFFSET_SHORT2_STANDARD_TYPE<br> RsaToolbox::OFFSET_SHORT3_STANDARD_TYPE<br> RsaToolbox::MATCH_STANDARD_TYPE<br> RsaToolbox::SLIDING_MATCH_STANDARD_TYPE<br> RsaToolbox::REFLECT_STANDARD_TYPE<br> </tt> * * \param type Type of calibration standard * \param port Intended VNA port * \sa CalStandard::CalStandard(CalStandardType type, Connector connector) */ VnaCalStandard::VnaCalStandard(Type type, uint port) { clear(); _type = type; _port1 = port; } /*! * \brief Constructor for a two-port calibration standard * * This constructor creates a two-port %CalStandard object with * connectors \c connector1 and \c connector2. The properties of the * \c type standard are uninitialized and must be set afterward. * See \c setTouchstoneFile() or one of the set model * functions such as \c setThruModel(). * * The following standards are two-port: <tt><br> RsaToolbox::THRU_STANDARD_TYPE<br> RsaToolbox::LINE_STANDARD_TYPE<br> RsaToolbox::LINE2_STANDARD_TYPE<br> RsaToolbox::LINE3_STANDARD_TYPE<br> RsaToolbox::ATTENUATION_STANDARD_TYPE<br> RsaToolbox::SYMMETRIC_NETWORK_STANDARD_TYPE<br> </tt> * * \param type Two-port standard type * \param connector1 First connector type and gender * \param connector2 Second connector type and gender * \sa CalStandard::CalStandard(CalStandardType type, uint port1, uint port2) */ VnaCalStandard::VnaCalStandard(Type type, Connector connector1, Connector connector2) { clear(); _type = type; _connector1 = connector1; _connector2 = connector2; } /*! * \brief Constructor for a port-specific two-port calibration standard * * This constructor creates a two-port %CalStandard object for use * between VNA ports \c port1 and \c port2. The properties of the * \c type standard are uninitialized and must be set afterward. * See \c setTouchstoneFile() or one of the set model * functions such as \c setThruModel(). * * The following standards are two-port: <tt><br> RsaToolbox::THRU_STANDARD_TYPE<br> RsaToolbox::LINE_STANDARD_TYPE<br> RsaToolbox::LINE2_STANDARD_TYPE<br> RsaToolbox::LINE3_STANDARD_TYPE<br> RsaToolbox::ATTENUATION_STANDARD_TYPE<br> RsaToolbox::SYMMETRIC_NETWORK_STANDARD_TYPE<br> </tt> * * \param type Two-port standard type * \param port1 Intended VNA port 1 connection * \param port2 Intended VNA port 2 connection */ VnaCalStandard::VnaCalStandard(Type type, uint port1, uint port2) { clear(); _type = type; _port1 = port1; _port2 = port2; } /*! * \brief Copy constructor * \param other Standard to copy */ VnaCalStandard::VnaCalStandard(const VnaCalStandard &other) : _type(other._type), _label(other._label), _port1(other._port1), _connector1(other._connector1), _port2(other._port2), _connector2(other._connector2), _isTouchstone(other._isTouchstone), _touchstone(other._touchstone), _isModel(other._isModel), _model(other._model) { } /*! * \brief Generates a user-friendly textualization of \c this * * An example is given below: \code Connector male35mm(mm_3_5_CONNECTOR, MALE_GENDER); CalStandard open(OPEN_STANDARD_TYPE, male35mm); open.displayText(); // "Open 3.5 mm Male" \endcode * * \return User-friendly textualization * \sa displayType() */ QString VnaCalStandard::displayText() const { QString text; QTextStream stream(&text); stream << displayType() << " "; if (isPortSpecific()) { if (isSinglePort()) stream << "(P" << _port1 << ")"; else stream << "(P" << _port1 << "P" << _port2 << ")"; } else { if (isSinglePort()) stream << _connector1.displayText(); else stream << _connector1.displayText() << "-" << _connector2.displayText(); } stream.flush(); return(text); } /*! * \brief Generates a user-friendly textualization of * \c this calibration standard type * * An example is given below: \code Connector male35mm(mm_3_5_CONNECTOR, MALE_GENDER); CalStandard open(OPEN_STANDARD_TYPE, male35mm); open.displayType(); // "Open" \endcode * * \return User-friendly textualization of \c type() * \sa type(), displayText() */ QString VnaCalStandard::displayType() const { switch(_type) { case Type::Open: return("Open"); case Type::Short: return("Short"); case Type::Match: return("Match"); case Type::Thru: return("Thru"); case Type::OffsetShort1: return("Offset Short 1"); case Type::OffsetShort2: return("Offset Short 2"); case Type::OffsetShort3: return("Offset Short 3"); case Type::SlidingMatch: return("Sliding Match"); case Type::Reflect: return("Reflection"); case Type::Line1: return("Line"); case Type::Line2: return("Line 2"); case Type::Line3: return("Line 3"); case Type::Attenuation: return("Attenuation"); case Type::SymmetricNetwork: return("Symmetric Network"); default: return("Unknown Standard"); } } /*! * \brief Compares type of \c this to \c type for equality * \param type Type to compare to * \return \c true if \c this is a standard of type \c type, * returns \c false otherwise */ bool VnaCalStandard::isType(Type type) const { return(_type == type); } /*! * \brief Compares type of \c this to \c type for inequality * \param type Type to compare to * \return \c true if \c this is not a standard of type \c type, * returns \c false otherwise */ bool VnaCalStandard::isNotType(Type type) const { return(!isType(type)); } /*! * \brief Tests gender of single-port calibration standard * \param gender Gender to compare to * \return \c true if \c this is a single-port standard of * gender \c gender, returns \c false otherwise */ bool VnaCalStandard::isGender(Connector::Gender gender) const { if (isPortSpecific()) return false; else return(isSinglePort() && _connector1.gender() == gender); } /*! * \brief Tests gender of two-port calibration standard * \param gender1 * \param gender2 * \return \c true if \c this is a two-port standard of * genders \c gender1 and \c gender2, returns \c false otherwise */ bool VnaCalStandard::isGender(Connector::Gender gender1, Connector::Gender gender2) const { if(isSinglePort() || isPortSpecific()) return false; if (_connector1.isGender(gender1) && _connector2.isGender(gender2)) return true; if (_connector1.isGender(gender2) && _connector2.isGender(gender1)) return true; return false; } /*! * \brief Tests for male gender single-port calibration standard * \return \c true if male, single-port calibration standard, * \c false otherwise */ bool VnaCalStandard::isMale() const { return(isSinglePort() && isNotPortSpecific() && isGender(Connector::Gender::Male)); } /*! * \brief Tests for female gender single-port calibration standard * \return \c true if female, single-port calibration standard, * \c false otherwise */ bool VnaCalStandard::isFemale() const { return(isSinglePort() && isNotPortSpecific() && isGender(Connector::Gender::Female)); } /*! * \brief Tests for a port-specific calibration standard * \return \c true if calibration standard is port-specific, * \c false otherwise */ bool VnaCalStandard::isPortSpecific() const { if (isSinglePort() && _port1 != 0) return true; if (isTwoPort() && _port1 != 0 && _port2 != 0) return true; //else return false; } /*! * \brief Tests for a single-port calibration standard for VNA port \c port * \return \c true if calibration standard is single-port and specific * to VNA port \c port, \c false otherwise */ bool VnaCalStandard::isPortSpecific(uint port) const { if (isSinglePort() && _port1 == port) return true; //else return false; } /*! * \brief Tests for a two-port calibration standard for VNA ports * \c port1 and \c port2 * * \return \c true if calibration standard is two-port and specific * to VNA ports \c port1 and \c port2, \c false otherwise */ bool VnaCalStandard::isPortSpecific(uint port1, uint port2) const { if (!isTwoPort() || !isPortSpecific()) return false; if (_port1 == port1 && _port2 == port2) return true; if (_port1 == port2 && _port2 == port1) return true; return false; } /*! * \brief Tests for a non-port-specific calibration standard * \return \c true if calibration standard is not * port-specific, \c false otherwise */ bool VnaCalStandard::isNotPortSpecific() const { return(!isPortSpecific()); } /*! * \brief Tests for a single-port calibration standard * \return \c true if calibration standard is single-port, * \c false otherwise */ bool VnaCalStandard::isSinglePort() const { return isSinglePort(_type); } bool VnaCalStandard::isSinglePort(Type type) { return (type != Type::Unknown) && !isTwoPort(type); } /*! * \brief Tests for a two-port calibration standard * \return \c true if calibration standard is two-port, * \c false otherwise */ bool VnaCalStandard::isTwoPort() const { return isTwoPort(_type); } bool VnaCalStandard::isTwoPort(Type type) { switch(type) { case Type::Thru: case Type::Line1: case Type::Line2: case Type::Line3: case Type::Attenuation: case Type::SymmetricNetwork: case Type::Isolation: return true; default: return false; } } /*! * \brief Compares \c this standard to \c other for equality * * Two standards are considered to be the same if: <br> * <tt>They are of the same type<br> * They have the same connections (either port-specific or * connector type)</tt> * * \param other Standard to compare * \return \c true if the standards are the same type, * \c false otherwise */ bool VnaCalStandard::isSameStandardAs(VnaCalStandard other) const { if (isNotType(other.type())) return false; if (isSinglePort()) { if (other.isTwoPort()) return false; if (isPortSpecific()) { if (other.isNotPortSpecific()) return false; if (port() != other.port()) return false; } else { if (other.isPortSpecific()) return false; if (gender() != other.gender()) return false; } } else { if (other.isSinglePort()) return false; if (isPortSpecific()) { if (other.isNotPortSpecific()) return false; if (other.isPortSpecific(port1(), port2()) == false) return false; } else { if (other.isPortSpecific()) return false; if (other.isGender(gender1(), gender2()) == false) return false; } } // else return true; } /*! * \brief Tests for an open calibration standard * \return \c true if is an open standard, \c false otherwise */ bool VnaCalStandard::isOpen() const { return(isType(Type::Open)); } /*! * \brief Tests for an open calibration standard that * is specific to VNA port \c port * \param port VNA port * \return true if is a \c port -specific open standard, * \c false otherwise */ bool VnaCalStandard::isOpen(uint port) const { return(isOpen() && isPortSpecific(port)); } /*! * \brief Tests for a male open calibration standard * \return \c true if is a male open standard, false otherwise */ bool VnaCalStandard::isMaleOpen() const { return(isOpen() && isMale()); } /*! * \brief Tests for a female open calibration standard * \return \c true if is a female open standard, false otherwise */ bool VnaCalStandard::isFemaleOpen() const { return(isOpen() && isFemale()); } /*! * \brief Tests for a short calibration standard * \return \c true if is a short standard, false otherwise */ bool VnaCalStandard::isShort() const { return(isType(Type::Short)); } /*! * \brief Tests for a short calibration standard that * is specific to VNA port \c port * \param port VNA port * \return true if is a \c port -specific short standard, * \c false otherwise */ bool VnaCalStandard::isShort(uint port) const { return(isShort() && isPortSpecific(port)); } /*! * \brief Tests for a male short calibration standard * \return \c true if is a male short standard, false otherwise */ bool VnaCalStandard::isMaleShort() const { return(isShort() && isMale()); } /*! * \brief Tests for a female short calibration standard * \return \c true if is a female short standard, false otherwise */ bool VnaCalStandard::isFemaleShort() const { return(isShort() && isFemale()); } bool VnaCalStandard::isOffsetShort1() const { return isType(Type::OffsetShort1); } bool VnaCalStandard::isMaleOffsetShort1() const { return isOffsetShort1() && isMale(); } bool VnaCalStandard::isFemaleOffsetShort1() const { return isOffsetShort1() && isFemale(); } bool VnaCalStandard::isOffsetShort2() const { return isType(Type::OffsetShort2); } bool VnaCalStandard::isMaleOffsetShort2() const { return isOffsetShort2() && isMale(); } bool VnaCalStandard::isFemaleOffsetShort2() const { return isOffsetShort2() && isFemale(); } bool VnaCalStandard::isOffsetShort3() const { return isType(Type::OffsetShort3); } bool VnaCalStandard::isMaleOffsetShort3() const { return isOffsetShort3() && isMale(); } bool VnaCalStandard::isFemaleOffsetShort3() const { return isOffsetShort3() && isFemale(); } /*! * \brief Tests for a match calibration standard * \return \c true if is a match standard, false otherwise */ bool VnaCalStandard::isMatch() const { return(isType(Type::Match)); } /*! * \brief Tests for a port-specific match calibration standard * for VNA port \c port * \param port * \return \c true if is a match standard for port \c port, * false otherwise */ bool VnaCalStandard::isMatch(uint port) const { return(isMatch() && isPortSpecific(port)); } /*! * \brief Tests for a male match calibration standard * \return \c true if is a male match standard, false otherwise */ bool VnaCalStandard::isMaleMatch() const { return(isMatch() && isMale()); } /*! * \brief Tests for a female match calibration standard * \return \c true if is a female match standard, false otherwise */ bool VnaCalStandard::isFemaleMatch() const { return(isMatch() && isFemale()); } /*! * \brief Tests for a thru calibration standard * \return \c true if is a thru standard, false otherwise */ bool VnaCalStandard::isThru() const { return(isType(Type::Thru)); } /*! * \brief Tests for a male-to-male thru calibration standard * \return \c true if is a male-to-male thru standard, false otherwise */ bool VnaCalStandard::isThruMM() const { return(isThru(Connector::Gender::Male, Connector::Gender::Male)); } /*! * \brief Tests for a male-to-female thru calibration standard * \return \c true if is a male-to-female thru standard, false otherwise */ bool VnaCalStandard::isThruMF() const { return(isThru(Connector::Gender::Male, Connector::Gender::Female)); } /*! * \brief Tests for a female-to-female thru calibration standard * \return \c true if is a female-to-female thru standard, false otherwise */ bool VnaCalStandard::isThruFF() const { return(isThru(Connector::Gender::Female, Connector::Gender::Female)); } /*! * \brief Tests for a port-specific thru calibration standard * for VNA ports \c port1 and \c port2 * \param port1 * \param port2 * \return \c true if is a thru standard for ports \c port1 and \c port2, * false otherwise */ bool VnaCalStandard::isThru(uint port1, uint port2) const { return(isThru() && isPortSpecific(port1, port2)); } /*! * \brief Tests for a \c gender1 -to- \c gender2 thru calibration standard * \param gender1 * \param gender2 * \return \c true if is a \c gender1 -to- \c gender2 thru standard, false otherwise */ bool VnaCalStandard::isThru(Connector::Gender gender1, Connector::Gender gender2) const { return(isThru() && isGender(gender1, gender2)); } /*! * \brief Indicates whether or not calibration standard is defined * by a touchstone file * \return \c true if defined by a touchstone file, \c false otherwise */ bool VnaCalStandard::isTouchstone() const { return(_isTouchstone); } /*! * \brief Indicates whether or not calibration standard is defined by * a lumped element model * \return \c true if defined by a lumped element model, * \c false otherwise */ bool VnaCalStandard::isModel() const { return(_isModel); } /*! * \brief Compares the lumped element model of two standards * * If the standards being compared are of a different type, * or either standard is not defined by a lumped element model, * this method returns \c false. * * If the standards are of the same type and are both defined by * model, the model parameters are compared for equality and * the result is returned. * * \param other Calibration standard to compare to * \return \c true if the two standards are the same type and * lumped element model, \c false otherwise */ bool VnaCalStandard::isSameModel(const VnaCalStandard &other) const { if (!isType(other.type())) return false; if (!isModel() || !other.isModel()) return false; if (_model != other.model()) return false; return true; } /*! * \brief Returns the \c type of the calibration standard * \return standard type */ VnaCalStandard::Type VnaCalStandard::type() const { return(_type); } /*! * \brief Returns the minimum frequency of the calibration * standard * \return Minimum frequency in Hertz */ double VnaCalStandard::minimumFrequency_Hz() const { return _model.minimumFrequency_Hz; } /*! * \brief Returns the maximum frequency of the calibration * standard * \return Maximum frequency in Hertz */ double VnaCalStandard::maximumFrequency_Hz() const { return _model.maximumFrequency_Hz; } /*! * \brief Returns the VNA port of a single-port, * port-specific calibration standard * \return VNA port */ uint VnaCalStandard::port() const { return(_port1); } /*! * \brief Returns VNA port \c port1 of a two-port, * port-specific calibration standard * \return VNA port 1 */ uint VnaCalStandard::port1() const { return(_port1); } /*! * \brief Returns VNA port \c port2 of a two-port, * port-specific calibration standard * \return VNA port 2 */ uint VnaCalStandard::port2() const { return(_port2); } /*! * \brief Returns the connector of a single-port * calibration standard * \return %Connector */ Connector &VnaCalStandard::connector() { return _connector1; } /*! * \brief Returns \c connector1 of a two-port, * calibration standard * \return %Connector 1 */ Connector &VnaCalStandard::connector1() { return _connector1; } /*! * \brief Returns \c connector2 of a two-port, * calibration standard * \return %Connector 2 */ Connector &VnaCalStandard::connector2() { return _connector2; } /*! * \brief Returns the connector gender of a single-port * calibration standard * \return Gender */ Connector::Gender VnaCalStandard::gender() const { return(_connector1.gender()); } /*! * \brief Returns the gender of \c connector1 of a two-port, * calibration standard * \return Gender of connector 1 */ Connector::Gender VnaCalStandard::gender1() const { return(_connector1.gender()); } /*! * \brief Returns the gender of \c connector2 of a two-port, * calibration standard * \return Gender of connector 2 */ Connector::Gender VnaCalStandard::gender2() const { return(_connector2.gender()); } /*! * \brief Returns the label of the calibration standard * \return Label */ QString VnaCalStandard::label() const { return(_label); } /*! * \brief Returns the path of the touchstone file * that defines the calibration standard * \return Path to touchstone file */ QString VnaCalStandard::touchstone() const { return(_touchstone); } /*! * \brief Sets the calibration standard type * \param type Calibration type * \sa RsaToolbox::CalStandardType */ void VnaCalStandard::setType(Type type) { _type = type; } /*! * \brief Sets a specific VNA port for a single-port calibration * standard * \param port VNA port */ void VnaCalStandard::setPort(uint port) { _port1 = port; } /*! * \brief Sets the Vna ports for a port-specific two-port * calibration standard * * \note The Vna requires a specific port order for two-port * calibration standards in order to prevent confusion. For * example, a Thru standard specific to Vna ports 3 and 4 * will always consider Vna port 3 the "first port" (port1) * of the calibration standard. This is automatically enforced * in a \c %VnaCalStandard object; reordering occurs * as necessary after a call to \c %setConnector. * * \param port1 The Vna port used with port 1 of the calibration standard * \param port2 The Vna port used with port 2 of the calibration standard */ void VnaCalStandard::setPorts(uint port1, uint port2) { _port1 = port1; _port2 = port2; sort(); } /*! * \brief Sets the connector for a single-port calibration standard * \param connector Connector type and gender */ void VnaCalStandard::setConnector(Connector connector) { _connector1 = connector; _port1 = 0; } /*! * \brief Sets the connectors for a two-port calibration standard * * \note The Vna requires a specific gender order for two-port * calibration standards in order to prevent confusion. For * example, a mixed gender thru standard is always written * as Male-Female. This is automatically enforced in a * \c %VnaCalStandard object; reordering occurs * as necessary after a call to \c %setConnector. * * \param connector1 Connector type and gender of port1 * \param connector2 Connector type and gender of port2 */ void VnaCalStandard::setConnectors(Connector connector1, Connector connector2) { setConnector1(connector1); setConnector2(connector2); sort(); } /*! * \brief Sets the label of the calibration standard * * The label is usually a unique identifier string, such as * the serial number of the standard. * * \param label Calibration standard label */ void VnaCalStandard::setLabel(QString label) { _label = label; } /*! * \brief Sets the path to the touchstone file that defines * the calibration standard to \c path. * \param path Path to the touchstone file */ void VnaCalStandard::setTouchstoneFile(QString path) { _isTouchstone = true; _touchstone = path; } VnaStandardModel &VnaCalStandard::model() { return _model; } VnaStandardModel VnaCalStandard::model() const { return _model; } void VnaCalStandard::setModel(const VnaStandardModel &model) { _isTouchstone = false; _isModel = true; _model = model; } /*! * \brief Resets the calibration standard to the default state. * * The resulting standard is of type UNKNOWN_STANDARD_TYPE. All * settings are lost. * */ void VnaCalStandard::clear() { _type = Type::Unknown; _label.clear(); _port1 = 0; _port2 = 0; _connector1 = Connector(); _connector2 = Connector(); _isModel = false; _model = VnaStandardModel(); _isTouchstone = false; _touchstone.clear(); } /*! * \brief Clears port-specific settings */ void VnaCalStandard::clearPorts() { _port1 = 0; _port2 = 0; } /*! * \brief Clears connector settings */ void VnaCalStandard::clearConnectors() { _port1 = 0; _connector1 = Connector(); _port2 = 0; _connector2 = Connector(); } /*! * \brief Sets the settings of the object on the left-hand side * of the = operator to that of the object on the right-hand side * \param other Object to take settings from */ void VnaCalStandard::operator =(const VnaCalStandard &other) { _type = other._type; _label = other._label; _port1 = other._port1; _connector1 = other._connector1; _port2 = other._port2; _connector2 = other._connector2; _isTouchstone = other._isTouchstone; _touchstone = other._touchstone; _isModel = other._isModel; _model = other._model; } QStringList VnaCalStandard::displayText(const QVector<VnaCalStandard> &standards) { QStringList displays; foreach (VnaCalStandard std, standards) { displays.append(std.displayText()); } return(displays); } // Private void VnaCalStandard::setConnector1(Connector connector1) { _connector1 = connector1; _port1 = 0; } void VnaCalStandard::setConnector2(Connector connector2) { _connector2 = connector2; _port2 = 0; } void VnaCalStandard::sort() { if (isSinglePort()) return; if (isNotPortSpecific()) { RsaToolbox::sort(_connector1, _connector2); } else { RsaToolbox::sort(_port1, _port2); } } /*! * \relates VnaCalStandard * \brief Sorts two connectors by gender * * \note The Vna requires a specific gender order for two-port * calibration standards in order to prevent confusion. For * example, a mixed gender thru standard is always written * as Male-Female. * * \param connector1 * \param connector2 */ void RsaToolbox::sort(Connector &connector1, Connector &connector2) { if (connector2.isMale() && !connector1.isMale()) { Connector temp = connector1; connector1 = connector2; connector2 = temp; } else if (connector1.isFemale() && !connector2.isFemale()) { Connector temp = connector1; connector1 = connector2; connector2 = temp; } } /*! * \relates VnaCalStandard * \brief Sorts two connector genders * * \note The Vna requires a specific gender order for two-port * calibration standards in order to prevent confusion. For * example, a mixed gender thru standard is always written * as Male-Female. * * \param gender1 * \param gender2 */ void RsaToolbox::sort(Connector::Gender &gender1, Connector::Gender &gender2) { if (gender2 == Connector::Gender::Male && gender2 != Connector::Gender::Male) { Connector::Gender temp = gender1; gender1 = gender2; gender2 = temp; } else if (gender1 == Connector::Gender::Female && gender2 != Connector::Gender::Female) { Connector::Gender temp = gender1; gender1 = gender2; gender2 = temp; } } /*! * \relates VnaCalStandard * \brief Sorts two connector genders * * \note The Vna requires a specific port order for two-port * calibration standards in order to prevent confusion. For * example, a Thru standard specific to Vna ports 3 and 4 * will always consider Vna port 3 the "first port" (port1) * of the calibration standard. * * \param port1 * \param port2 */ void RsaToolbox::sort(uint &port1, uint &port2) { if (port1 > port2) { uint temp = port1; port1 = port2; port2 = temp; } } /*! * \relates VnaCalStandard * \brief Equality operator for CalStandard objects * * The == operator compares each property of the %CalStandard objects * for equality. If any property is different, this function returns * \c false. If all properties are identical, this function returns * \c true. * * \param right Right-hand object * \param left Left-hand object * \return \c true if objects are equal; \c false otherwise * \sa RsaToolbox::operator!=(const CalStandard &right, const CalStandard &left) */ bool RsaToolbox::operator==(const VnaCalStandard &right, const VnaCalStandard &left) { if (!right.isSameStandardAs(left)) return false; // Sliding match has no values...? if (right.isType(VnaCalStandard::Type::SlidingMatch)) return true; // Attenuator has no values...? if (right.isType(VnaCalStandard::Type::Attenuation)) return true; // I don't think this is how touchstone works... if (right.isTouchstone() != left.isTouchstone()) return false; if (left.isModel() != left.isModel()) return false; if (right.model() != left.model()) return false; return true; } /*! * \relates VnaCalStandard * \brief Inequality operator for CalStandard objects * * The != operator compares each property of the %CalStandard objects * for inequality. If any property is different, this function returns * \c true. If all properties are identical, this function returns * \c false. * * \param right Right-hand object * \param left Left-hand object * \return \c true if objects are unequal; \c false otherwise * \sa RsaToolbox::operator==(const CalStandard &right, const CalStandard &left) */ bool RsaToolbox::operator!=(const VnaCalStandard &right, const VnaCalStandard &left) { return(!(right == left)); }
// Siva Sankar Kannan - 267605 - siva.kannan@student.tut.fi #include <iostream> #include <iomanip> #include <vector> #include <map> #include <string> #include "splitter.h" #include "fileread.h" #include "usercommands.h" //#include "global.h" using namespace std; // define function pointers /*--------------------------------------------------------------------------*/ typedef void (*no_arg_pfunctions)(const map <string, map <string, vector <product>>>& read_map); typedef void (*one_arg_pfunctions)(const map <string, map <string, vector <product>>>& read_map, const string&); typedef void (*two_arg_pfunctions)(const map <string, map <string, vector <product>>>& read_map, const string&, const string&); /*--------------------------------------------------------------------------*/ //void command_hint(int& error_counter) { // // presents the user with a hint on how to use the console if the user // // fails a third time in a row. // if (error_counter > 2) { // cout << "\ntype 'help <command>' to know more about the <command>." // << endl; // cout << "\ntype 'list' for the list of available commands.\n"; // error_counter = 0; // } //} /*--------------------------------------------------------------------------*/ // read the data in the file and store it in a suitable data structure // map <string, map <string, vector <product>>> read_map = read("products.txt"); /*--------------------------------------------------------------------------*/ int main() { // initialize the necessary variables /*----------------------------------------------------------------------*/ string input; vector <string> input_vector; Splitter ui; // int error_counter = 0; map <string, no_arg_pfunctions> no_arg_map; map <string, one_arg_pfunctions> one_arg_map; map <string, two_arg_pfunctions> two_arg_map; no_arg_pfunctions no_arg_pfunct; one_arg_pfunctions one_arg_pfunct; two_arg_pfunctions two_arg_pfunct; // add function entries in the respective dispatchers /*----------------------------------------------------------------------*/ no_arg_map["quit"] = quit; no_arg_map["chains"] = chains; // no_arg_map["all"] = all; // no_arg_map["list"] = list; one_arg_map["stores"] = stores; one_arg_map["cheapest"] = cheapest; // one_arg_map["syntax"] = syntax; // one_arg_map["help"] = help; two_arg_map["selection"] = selection; // read the data in the file and store it in a suitable data structure map <string, map <string, vector <product>>> read_map = read("products.txt"); /*----------------------------------------------------------------------*/ while (true) { // cout << endl << setfill('-') << setw(60) << "-" << endl; cout << "product search> "; // cout << setfill(' '); getline(cin, input); // use splitter class to work the user input ui.reset(); ui.set_string_to_split(input); ui.set_seperator(' '); ui.split(); input_vector = ui.fields(); /*------------------------------------------------------------------*/ // use switch case to pass control to the respective fields switch (ui.counter()) { // if command exists and format is right, run it // if command exists but wrong syntax, display the syntax /*------------------------------------------------------------------*/ case 0: cout << "Error: Not enough commands!" << endl; // command_hint(++error_counter); break; case 1: { auto i = no_arg_map.find(input_vector[0]); if (i != no_arg_map.end()) { no_arg_pfunct = no_arg_map[input_vector[0]]; (*no_arg_pfunct)(read_map); } else if (check_command(input_vector[0])) { cout << "Error: command format wrong.\n"; // one_arg_pfunct = one_arg_map["syntax"]; // (*one_arg_pfunct)(input_vector[0]); } else { cout << "Error: command not found! \n"; // command_hint(++error_counter); } } break; /*------------------------------------------------------------------*/ case 2: { auto i = one_arg_map.find(input_vector[0]); if (i != one_arg_map.end()) { one_arg_pfunct = one_arg_map[input_vector[0]]; (*one_arg_pfunct)(read_map, input_vector[1]); } else if (check_command(input_vector[0])) { cout << "Error: command format wrong.\n"; // one_arg_pfunct = one_arg_map["syntax"]; // (*one_arg_pfunct)(input_vector[0]); } else { cout << "Error: command not found! \n"; // command_hint(++error_counter); } } break; /*------------------------------------------------------------------*/ case 3: { auto i = two_arg_map.find(input_vector[0]); if (i != two_arg_map.end()) { two_arg_pfunct = two_arg_map[input_vector[0]]; (*two_arg_pfunct)(read_map, input_vector[1], input_vector[2]); } else if (check_command(input_vector[0])) { cout << "Error: command format wrong.\n"; // one_arg_pfunct = one_arg_map["syntax"]; // (*one_arg_pfunct)(input_vector[0]); } else { // command_hint(++error_counter); cout << "Error: command not found! n"; } } break; /*------------------------------------------------------------------*/ default: { if (check_command(input_vector[0])) { cout << "Error: command format wrong.\n"; // one_arg_pfunct = one_arg_map["syntax"]; // (*one_arg_pfunct)(input_vector[0]); } else { cout << "Error: command not found! \n"; // command_hint(++error_counter); } } break; } } return 0; }
#include "Logger.h" #include "CoinConf.h" #include "hiredis.h" #include "Util.h" #include "GameApp.h" #include <vector> #include "StrFunc.h" using namespace std; static CoinConf* instance = NULL; CoinConf* CoinConf::getInstance() { if(instance==NULL) { instance = new CoinConf(); } return instance; } CoinConf::CoinConf() { } CoinConf::~CoinConf() { } bool CoinConf::GetCoinConfigData() { memset(&m_coincfg, 0, sizeof(m_coincfg)); m_coincfg.level = GameConfigure()->m_nLevel; map<string, string> retVal; vector<string> fields = Util::explode("minmoney maxmoney ante tax maxlimit maxallin rase1 rase2 " "rase3 rase4 magiccoin check_round compare_round", " "); bool bRet = m_Redis.HMGET(StrFormatA("Flower_RoomConfig:%d", m_coincfg.level).c_str(), fields, retVal); if (bRet) { int *pVal[] = { &m_coincfg.minmoney, &m_coincfg.maxmoney, &m_coincfg.ante, &m_coincfg.tax, &m_coincfg.maxlimit, &m_coincfg.maxallin, &m_coincfg.rase1, &m_coincfg.rase2, &m_coincfg.rase3, &m_coincfg.rase4, &m_coincfg.magiccoin, &m_coincfg.check_round, &m_coincfg.compare_round }; for (size_t i = 0; i < fields.size(); i++) { if (retVal.find(fields[i]) != retVal.end()) { *(pVal[i]) = atoi(retVal[fields[i]].c_str()); } } } _LOG_DEBUG_("minmoney[%d] maxmoney[%d] ante[%d] tax[%d] maxlimit[%d] maxallin[%d] rase1[%d] rase2[%d] rase3[%d] rase4[%d] magiccoin[%d]\n", m_coincfg.minmoney, m_coincfg.maxmoney, m_coincfg.ante, m_coincfg.tax, m_coincfg.maxlimit, m_coincfg.maxallin, m_coincfg.rase1, m_coincfg.rase2, m_coincfg.rase3, m_coincfg.rase4, m_coincfg.magiccoin); return bRet; }
// // Transform.cpp // closedFrameworks // // Created by William Meaton on 12/05/2016. // Copyright © 2016 WillMeaton.uk. All rights reserved. // #include "Transform.hpp" Transform::Transform(){ } Transform::Transform(const Math::Vector2D& pos): position(pos){ } Math::Vector2D& Transform::getPos(){ return position; }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef pair<int, int> P; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} const int mod = 1000000007; struct mint { ll x; // typedef long long ll; mint(ll x=0):x((x%mod+mod)%mod){} mint operator-() const { return mint(-x);} mint& operator+=(const mint a) { if ((x += a.x) >= mod) x -= mod; return *this; } mint& operator-=(const mint a) { if ((x += mod-a.x) >= mod) x -= mod; return *this; } mint& operator*=(const mint a) { (x *= a.x) %= mod; return *this; } mint operator+(const mint a) const { mint res(*this); return res+=a; } mint operator-(const mint a) const { mint res(*this); return res-=a; } mint operator*(const mint a) const { mint res(*this); return res*=a; } mint pow(ll t) const { if (!t) return 1; mint a = pow(t>>1); a *= a; if (t&1) a *= *this; return a; } // for prime mod mint inv() const { return pow(mod-2); } mint& operator/=(const mint a) { return (*this) *= a.inv(); } mint operator/(const mint a) const { mint res(*this); return res/=a; } }; struct combination { vector<mint> fact, ifact; combination(int n):fact(n+1),ifact(n+1) { assert(n < mod); fact[0] = 1; for (int i = 1; i <= n; ++i) fact[i] = fact[i-1]*i; ifact[n] = fact[n].inv(); for (int i = n; i >= 1; --i) ifact[i-1] = ifact[i]*i; } mint operator()(int n, int k) { if (k < 0 || k > n) return 0; return fact[n]*ifact[k]*ifact[n-k]; } }; /* 全方位木DP N個の頂点を持つ木に1~Nの数字を書く場合のパターン数を求める * 頂点kに1を書く。 * 既に数字を書かれている頂点と隣接している頂点から2以降の数字を書いていく。 頂点kごとにパターン数を出力する。(1<=N<=2*10^5) 頂点kを固定とし、k=1の場合単体をO(N)で求める方法を考える 子を頂点とする部分木の頂点の総和をAx, パターン数をBxとすると、 親を頂点とする部分木の頂点の総和は、A1 + A2 + ... + An + 1 親を頂点とする部分木のパターン数は、B1 * B2 * ... * Bn * (S) S = (A1 + A2 + ... An)! / (A1! * A2! * ... * An!) で求めることができるので、子⇒親方向へと計算すると求めることができる。 この計算を全てのkで行うとO(N^2)となり間に合わない。 よってこの計算結果を、k=2~Nの場合に置いても流用する必要がある。。。 計算の手順は 1.頂点1をrootとするパターン数をdfsにより求める。このとき、各頂点の子側の部分木をDPに保存しておく。    このときDPの値としては、頂点1のみ正しい答えが求まっているが、    頂点1以外においては親側の部分木の評価を行う必要がある。 2.再度頂点1から探索するが、このとき行きがけ順で下記の処理を行う。    a. 親側の頂点のパターン数から、自分の部分木が存在しないときのパターン数を求める。    b. その後、そのパターン数を元にDPに足し合わせる。 パターン数の結合と分解を各探索で繰り返すので、 パターン数を扱うデータ構造DPの演算子を別途定義すると、計算が高速化できる。 */ const int MAX_N = 200050; vector<int> root[MAX_N]; combination cb(MAX_N); struct DP{ mint pat; int t; DP (mint pat=1, int t=0) : pat(pat), t(t){} DP& operator+=(const DP& a){ t += a.t; pat *= a.pat; pat *= cb(t, a.t); return *this; } DP operator-(const DP& a) const { DP tmp = *this; tmp.pat /= a.pat; tmp.pat /= cb(tmp.t, a.t); tmp.t -= a.t; return tmp; } DP addroot() const { DP tmp = *this; tmp.t++; return tmp; } }; DP dp[MAX_N]; DP dfs(int v, int parent){ DP ans; for(auto next : root[v]){ if (next != parent){ ans += dfs(next, v); } } //cout << v << endl; //cout << ans.pat.x << ";" << ans.t << endl; dp[v] = ans; return ans.addroot(); } DP dfs_inv(int v, int parent){ for(auto next : root[v]){ if (next != parent){ //parentのスコアから自分を引いた数を求める // cout << v << ":::"<<endl; // cout << dp[v].pat.x << ":"<< dp[v].t << endl; // cout << dp[next].pat.x << ":" << dp[next].t << endl; DP tmp = dp[v] - dp[next].addroot(); // cout << tmp.pat.x << ":" << tmp.t << endl; // cout << endl; dp[next] += tmp.addroot(); dfs_inv(next, v); } } } int main(){ int n; cin >> n; vector<P> ab(n); rep(i, n-1) cin >> ab[i].first >> ab[i].second; rep(i, n-1) { root[ab[i].first-1].push_back(ab[i].second-1); root[ab[i].second-1].push_back(ab[i].first-1); } dfs(0, -1); // rep(i, n){ // cout << dp[i].pat.x << ":" << dp[i].t <<endl; // } dfs_inv(0, -1); rep(i, n){ //cout << dp[i].pat.x << ":" << dp[i].t << endl; cout << dp[i].pat.x << endl; } }
#include "Model.h" #include "Window.h" // ベクトル struct vec { float x, y, z; }; bool Model::FileLoad(const char *name, GLuint &nv, GLfloat(*&pos)[3], GLfloat(*&norm)[3], GLuint &nf, GLuint(*&face)[3], bool normalize){ //OBJファイル読み込み std::ifstream file(name, std::ios::binary); // ファイルが開けなかったら戻る if (file.fail()) { std::cerr << "Error: Can't open OBJ file: " << name << std::endl; return false; } // 一行読み込み用のバッファ std::string line; // データの数と座標値の最小値・最大値 float xmin, xmax, ymin, ymax, zmin, zmax; xmax = ymax = zmax = -(xmin = ymin = zmin = FLT_MAX); // 頂点位置の一時保存 std::vector<vec> _pos; std::vector<faceData> _face; // データを読み込む while (std::getline(file, line)) { std::istringstream str(line); std::string op; str >> op; if (op == "v") { // 頂点位置 vec v; // 頂点位置はスペースで区切られているので str >> v.x >> v.y >> v.z; // 位置の最大値と最小値を求める (AABB) xmin = min(xmin, v.x); xmax = max(xmax, v.x); ymin = min(ymin, v.y); ymax = max(ymax, v.y); zmin = min(zmin, v.z); zmax = max(zmax, v.z); // 頂点データを保存する _pos.push_back(v); } else if (op == "f") { // 面データ faceData f; // 頂点座標番号を取り出す for (int i = 0; i < 3; ++i) { // 1行をスペースで区切って個々の要素の最初の数値を取り出す std::string s; str >> s; f.p[i] = atoi(s.c_str()); } //std::cout << vx << " " << vy << " " << vz << std::endl; // 面データを保存する _face.push_back(f); } } // ファイルの読み込みチェック if (file.bad()) { // うまく読み込めなかった std::cerr << "Warning: Can't read OBJ file: " << name << std::endl; } file.close(); // メモリの確保 pos = norm = NULL; face = NULL; nv = _pos.size(); nf = _face.size(); try { pos = new GLfloat[nv][3]; norm = new GLfloat[nv][3]; face = new GLuint[nf][3]; } catch (std::bad_alloc e) { delete[] pos; delete[] norm; delete[] face; pos = norm = NULL; face = NULL; return false; } // 位置と大きさの正規化のための係数 GLfloat scale, cx, cy, cz; if (normalize) { const float sx(xmax - xmin); const float sy(ymax - ymin); const float sz(zmax - zmin); scale = sx; if (sy > scale) scale = sy; if (sz > scale) scale = sz; scale = (scale != 0.0f) ? 2.0f / scale : 1.0f; cx = (xmax + xmin) * 0.5f; cy = (ymax + ymin) * 0.5f; cz = (zmax + zmin) * 0.5f; } else { scale = 1.0f; cx = cy = cz = 0.0f; } // 図形の大きさと位置の正規化とデータのコピー for (std::vector<vec>::const_iterator it = _pos.begin(); it != _pos.end(); ++it) { const size_t v = it - _pos.begin(); pos[v][0] = (it->x - cx) * scale; pos[v][1] = (it->y - cy) * scale; pos[v][2] = (it->z - cz) * scale; } // 頂点法線の値を 0 にしておく std::fill(static_cast<GLfloat *>(&norm[0][0]), static_cast<GLfloat *>(&norm[nv][0]), 0.0f); // 面の法線の算出とデータのコピー for (std::vector<faceData>::const_iterator it = _face.begin(); it != _face.end(); ++it) { const size_t f(it - _face.begin()); // 頂点座標番号を取り出す const GLuint v0(face[f][0] = it->p[0] - 1); const GLuint v1(face[f][1] = it->p[1] - 1); const GLuint v2(face[f][2] = it->p[2] - 1); // v1 - v0, v2 - v0 を求める const GLfloat dx1(pos[v1][0] - pos[v0][0]); const GLfloat dy1(pos[v1][1] - pos[v0][1]); const GLfloat dz1(pos[v1][2] - pos[v0][2]); const GLfloat dx2(pos[v2][0] - pos[v0][0]); const GLfloat dy2(pos[v2][1] - pos[v0][1]); const GLfloat dz2(pos[v2][2] - pos[v0][2]); // 外積により面法線を求める const GLfloat nx(dy1 * dz2 - dz1 * dy2); const GLfloat ny(dz1 * dx2 - dx1 * dz2); const GLfloat nz(dx1 * dy2 - dy1 * dx2); // 面法線を頂点法線に積算する norm[v0][0] += nx; norm[v0][1] += ny; norm[v0][2] += nz; norm[v1][0] += nx; norm[v1][1] += ny; norm[v1][2] += nz; norm[v2][0] += nx; norm[v2][1] += ny; norm[v2][2] += nz; } // 頂点法線の正規化 for (GLuint v = 0; v < nv; ++v) { // 頂点法線の長さ GLfloat a(sqrt(norm[v][0] * norm[v][0] + norm[v][1] * norm[v][1] + norm[v][2] * norm[v][2])); // 頂点法線の正規化 if (a != 0.0) { norm[v][0] /= a; norm[v][1] /= a; norm[v][2] /= a; } } return true; } Model::Model() { } //モデルを読みこんでメッシュデータをメンバにポインタとして保持 Model::Model(const char *name, bool normalize){ GLuint nv, nf; GLfloat(*pos)[3], (*norm)[3]; GLuint(*face)[3]; if (FileLoad(name, nv, pos, norm, nf, face, normalize)){ m_Elements = new ShapeElements(nv, pos, norm, nf, face, GL_TRIANGLES); // 作業用に使ったメモリを解放する delete[] pos; delete[] norm; delete[] face; } else{ std::cout << "Model Open Error" << std::endl; } } Model::~Model() { Common::Delete(m_Elements); Common::Delete(m_Material); } void Model::Draw(){ //描画 m_Elements->Draw(); }
#ifndef STRING_HPP #define STRING_HPP class String: public Var { public: std::string str; String(std::string str); std::string toString(std::string str); }; #endif
#include "Game.h" #define stripeImageWidth 32 Game::Game() { Init(); } void Game::Init() { ps = ParticleSystem(Point3(0, 0, 0), Point3(0, 0.001, 0), 0.1, 1000); surrounding = Surrounding(); cueBall = CueBall(); cue = Cue(); quaffles.clear(); bludgers.clear(); for (int i = 0; i < 6; i++) { quaffles.push_back(Quaffle(i)); bludgers.push_back(Bludger(i)); } players.clear(); players.push_back(Player(1)); players.push_back(Player(2)); players.push_back(Player(3)); players.push_back(Player(4)); banner = Banner(Point2(BANNER_LENGTH, BANNER_HEIGHT), DRAWPARA); snitch = Snitch(); } Game::~Game() { } void Game::Display() { if (KeyBoardGame::isPause) return; glClearColor(color[BACKGROUND], color[BACKGROUND + 1], color[BACKGROUND + 2], 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); gluLookAt(KeyBoardGame::cameraLoc.axis[0], KeyBoardGame::cameraLoc.axis[1], KeyBoardGame::cameraLoc.axis[2], 0, 0, 0, 0, 1, 0); if (KeyBoardGame::isNewGame) { Init(); KeyBoardGame::isNewGame = false; } if (KeyBoardGame::isLight || KeyBoardGame::isCueBallLight) glEnable(GL_LIGHTING); else glDisable(GL_LIGHTING); if (KeyBoardGame::isLight) { glLightfv(GL_LIGHT0, GL_POSITION, posl); glLightfv(GL_LIGHT0, GL_AMBIENT, amb2); glLightfv(GL_LIGHT0, GL_SPECULAR, spec); glEnable(GL_LIGHT0); } else { glDisable(GL_LIGHT0); } glLightModelfv(GL_LIGHT_MODEL_AMBIENT, amb); glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); glMaterialfv(GL_FRONT, GL_SPECULAR, spec); glMateriali(GL_FRONT, GL_SHININESS, 128); vector<pair<Point3, Point2>> status(13); surrounding.Draw(); for (int i = 0; i < 6; i++) { quaffles[i].Draw(); bludgers[i].Draw(); } snitch.Draw(); cueBall.Draw(); cue.Draw(cueBall); if (KeyBoardGame::isCueDraw) { if (KeyBoardGame::bannerId == 0) banner.Draw(Point3(BANNER_POS_X, BANNER_POS_Y, BANNER_POS_Z), player1); else banner.Draw(Point3(BANNER_POS_X, BANNER_POS_Y, BANNER_POS_Z), player2); } for (int i = 0; i < 6; i++) { quaffles[i].Run(); bludgers[i].Run(); status[i + QUAFFLE_ID] = pair<Point3, Point2>(quaffles[i].center, quaffles[i].v); status[i + BLUDGER_ID] = pair<Point3, Point2>(bludgers[i].center, bludgers[i].v); } cueBall.Run(); status[CUEBALL_ID] = pair<Point3, Point2>(cueBall.center, cueBall.v); for (int i = 0; i < 6; i++) { quaffles[i].Collide(status); bludgers[i].Collide(status); } cueBall.Collide(status, players[KeyBoardGame::playerId], snitch); for (list<ParticleSystem>::iterator it = particle.begin(); it != particle.end(); it++) { it->Draw(); it->Run(); } snitch.Run(); while (particle.size() != 0 && particle.front().life == 0) particle.pop_front(); static char buf[256]; static string tmp; tmp = players[0].GetScore().c_str(); for (int i = 0; i < tmp.size(); i++) buf[i] = tmp[i]; buf[tmp.size()] = '\0'; String(buf).DrawString(48, ANSI_CHARSET, color + BLUE, "Comic Sans ms", Point3(0, 1.2, 0)); tmp = players[1].GetScore().c_str(); for (int i = 0; i < tmp.size(); i++) buf[i] = tmp[i]; buf[tmp.size()] = '\0'; String(buf).DrawString(48, ANSI_CHARSET, color + BLUE, "Comic Sans ms", Point3(0, 1.1, 0)); glPopMatrix(); glFlush(); glutSwapBuffers(); }
#include <iostream> #include "11_SeqList.h" using namespace std; template <typename T> TSeqList<T>::TSeqList(int capacity) { pArray = new T[capacity]; this->capacity = capacity; this->len = 0; } template <typename T> TSeqList<T>::~TSeqList() { delete[] pArray; pArray = NULL; len = 0; capacity = 0; } template <typename T> int TSeqList<T>::getLen() { return len; } template <typename T> int TSeqList<T>::getCapacity() { return capacity; } template <typename T> int TSeqList<T>::insert(T &t, int pos) { int i = 0, ret = 0; if (pos < 0) { ret = -1; printf("func insert() param err:%d\n", ret); goto End; } if (len == capacity) { ret = -2; printf("func insert() err:%d, list is full\n", ret); goto End; } if (pos > len) { pos = len; } for (i = len; i < pos; i--) { pArray[i] = pArray[i - 1]; } pArray[i] = t; len++; End: return ret; } template <typename T> int TSeqList<T>::get(int pos, T &t) { if (pos < 0) { printf("func get() param err:%d\n", -1); return -1; } t = pArray[pos]; return 0; } template <typename T> int TSeqList<T>::del(int pos, T &t) { int i = 0; if (pos < 0) { printf("func del() param err:%d\n", -1); return -1; } t = pArray[pos];//store the node which needs to be deleted for (i = pos + 1; i < len; i++) {//pos后面的元素前移 pArray[i - 1] = pArray[i]; } len--; return 0; }
DoublyLinkedListNode* sortedInsert(DoublyLinkedListNode* head, int data) { DoublyLinkedListNode *temp=head, *temp2, *newNode=(DoublyLinkedListNode *)malloc (sizeof(DoublyLinkedListNode)); newNode->next=NULL; newNode->prev=NULL; newNode->data=data; int cnt=0; while(temp!=NULL) { cnt++; if(temp->data >= data ) { if(cnt==1) { temp->prev=newNode; newNode->next=temp->next->prev; head=newNode; break; } temp2=temp->prev; temp->prev=newNode; newNode->next=temp2->next; newNode->prev=temp2; temp2->next=newNode; break; } if(temp->next==NULL) { temp->next=newNode; newNode->prev=temp->prev->next; break; } temp=temp->next; } return head; } //https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem?isFullScreen=false
// Copyright (c) 2018 Mozart Alexander Louis. All rights reserved. // Includes #include "app_delegate.hxx" #include "engines/firebase/firebase_engine.hxx" #include "engines/fmod/fmod_engine.hxx" #include "engines/language/language_engine.hxx" #include "scenes/intro/intro_scene.hxx" #include "utils/data/data_utils.hxx" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID or CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) #include "utils/archive/archive_utils.hxx" #endif AppDelegate::AppDelegate() = default; AppDelegate::~AppDelegate() = default; void AppDelegate::initGLContextAttrs() { // Set OpenGL context attributions, now can only set six attributions: // Red, Green, Blue, Alpha, Depth, Stencil GLContextAttrs gl_context_attrs = {8, 8, 8, 8, 24, 8, 0}; GLView::setGLContextAttrs(gl_context_attrs); } bool AppDelegate::applicationDidFinishLaunching() { initZipUtils(); initOpenGl(); initDirector(); initDatabase(); initFirebase(); copyLoadAssets(); createAndRunScene(); return true; } void AppDelegate::applicationDidEnterBackground() { Director::getInstance()->stopAnimation(); AudioUtils::getInstance()->pauseMixer(); // Destroy the instance of the language engine just in case the user changes the // system language LanguageEngine::destroyInstance(); } void AppDelegate::applicationWillEnterForeground() { Director::getInstance()->startAnimation(); AudioUtils::getInstance()->resumeMixer(); } void AppDelegate::initZipUtils() { // Set Up ZipUtils to use Key for sprites. ZipUtils::setPvrEncryptionKeyPart(0, 0x3a701f23); ZipUtils::setPvrEncryptionKeyPart(1, 0xa2af6677); ZipUtils::setPvrEncryptionKeyPart(2, 0x5248175b); ZipUtils::setPvrEncryptionKeyPart(3, 0xe404f08e); } void AppDelegate::initOpenGl() { const auto& director = Director::getInstance(); auto gl_view = director->getOpenGLView(); if (not gl_view) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC or CC_TARGET_PLATFORM == CC_PLATFORM_LINUX or \ CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) // gl_view = GLViewImpl::createWithRect(__APP_DELEGATE_NAME__, __APP_DELEGATE_RECT_MAIN__); // gl_view = GLViewImpl::createWithRect(__APP_DELEGATE_NAME__, __APP_DELEGATE_RECT_MAIN_LARGE__); // gl_view = GLViewImpl::createWithRect(__APP_DELEGATE_NAME__, __APP_DELEGATE_RECT_MAIN_SMALL__); // gl_view = GLViewImpl::createWithRect(__APP_DELEGATE_NAME__, __APP_DELEGATE_RECT_TABLET__); // gl_view = GLViewImpl::createWithRect(__APP_DELEGATE_NAME__, __APP_DELEGATE_RECT_TABLET_LARGE__); // gl_view = GLViewImpl::createWithRect(__APP_DELEGATE_NAME__, __APP_DELEGATE_RECT_TABLET_SMALL__); // gl_view = GLViewImpl::createWithRect(__APP_DELEGATE_NAME__, __APP_DELEGATE_RECT_GALAXY_S8__); gl_view = GLViewImpl::createWithRect(__APP_DELEGATE_NAME__, __APP_DELEGATE_RECT_GALAXY_S8_SMALL__); // gl_view = GLViewImpl::createWithRect(__APP_DELEGATE_NAME__, __APP_DELEGATE_RECT_LG_G6__); // gl_view = GLViewImpl::createWithRect(__APP_DELEGATE_NAME__, __APP_DELEGATE_RECT_LG_G6_SMALL__); #else gl_view = GLViewImpl::create(__APP_DELEGATE_NAME__); #endif } // Sets the internal resolution of the game. This allows to be played at the same resolution no matter what // device we are currently on. gl_view->setDesignResolutionSize(__APP_DELEGATE_RESOLUTION__.width, __APP_DELEGATE_RESOLUTION__.height, ResolutionPolicy::NO_BORDER); // Set the GLView director->setOpenGLView(gl_view); } void AppDelegate::initDirector() { const auto& director = Director::getInstance(); director->setAnimationInterval(1.0f / 144.0f); #ifdef COCOS2D_DEBUG director->setDisplayStats(true); #endif FileUtils::getInstance()->addSearchPath("data", true); FileUtils::getInstance()->addSearchPath("fonts"); } void AppDelegate::initDatabase() { DataUtils::initDatabase(); } void AppDelegate::initFirebase() { FirebaseEngine::getInstance(); } void AppDelegate::copyLoadAssets() { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID or CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) auto data = FileUtils::getInstance()->getDataFromFile( FileUtils::getInstance()->fullPathForFilename(__ARCHIVE_NAME__)); FileUtils::getInstance()->writeDataToFile(data, FileUtils::getInstance()->getWritablePath() + __ARCHIVE_NAME__); #endif } void AppDelegate::createAndRunScene() { Director::getInstance()->runWithScene(IntroScene::create(IntroScene::generateParams(), nullptr)); }
#include "stdafx.h" #include "Transform.h" Transform::Transform() :pParent(NULL), pFirstChild(NULL), pNextSibling(NULL) { bAutoUpdate = true; this->Reset(); if (this->bAutoUpdate) this->UpdateTransform(); } Transform::~Transform() { } void Transform::AddChild(Transform * pNewChild) { // 새로들어간 자식의 부모가 나면 리턴 if (pNewChild->pParent == this) return; // 이전 부모와 연결을 끊는다. pNewChild->ReleaseParent(); // 부모의 상대적인 좌표값으로 갱신하기 위해서 // 부모의 final 역행렬 값 Matrix matInvFinal; float temp; matInvFinal = this->matFinal.Inverse(temp); pNewChild->position = pNewChild->position.TransformCoord(matInvFinal); for (int i = 0; i < 2; i++) pNewChild->axis[i] = pNewChild->axis[i].TransformNormal(matInvFinal); pNewChild->scale.x = pNewChild->right.Length(); pNewChild->scale.y = pNewChild->up.Length(); pNewChild->pParent = this; Transform* pChild = this->pFirstChild; if (pChild == NULL) { this->pFirstChild = pNewChild; } else { while (pChild != NULL) { if (pChild->pNextSibling == NULL) { pChild->pNextSibling = pNewChild; break; } pChild = pChild->pNextSibling; } } this->UpdateTransform(); } void Transform::AttachTo(Transform * pParent) { } void Transform::ReleaseParent() { } void Transform::Reset(int resetFlag) { if (resetFlag & RESET_POSITION) { this->position.x = 0; this->position.y = 0; } if (resetFlag & RESET_ROTATION) { this->right = Vector2(1, 0); this->up = Vector2(0, 1); } if (resetFlag & RESET_SCALE) { this->scale = Vector2(1, 1); } } void Transform::SetWorldPosition(Vector2 position) { // 부모 존재하면 부모 기준으로 설정해야됨 if (this->pParent != NULL) { // 부모의 최종행렬 뒤집은거 Matrix matInvParentFinal; float temp; matInvParentFinal = pParent->matFinal.Inverse(temp); // 자식의 matFinal은 자식 월드 * 부모의 월드 // 따라서 부모이 역행렬로 제거 해야됨 // 계산 후 다시 부모 월드 곱하는거 // 부모의 역행렬값만큼 이동 position = position.TransformCoord(matInvParentFinal); } this->position.x = position.x; this->position.y = position.y; if (this->bAutoUpdate) this->UpdateTransform(); } void Transform::SetLocalPosition(Vector2 position) { this->position.x = position.x; this->position.y = position.y; if (this->bAutoUpdate) this->UpdateTransform(); } void Transform::MovePositionSelf(Vector2 delta) { // 이동 벡터 Vector2 move; // 자신의 이동 축을 얻는다 Vector2 moveAxis[2]; this->GetUnitAxis(moveAxis); move = move + moveAxis[0] * delta.x; move = move + moveAxis[1] * delta.y; Vector2 nowWorldPos = this->GetWorldPosition(); this->SetWorldPosition(nowWorldPos + move); } void Transform::MovePositionWorld(Vector2 delta) { Vector2 nowWorldPos = this->GetWorldPosition(); this->SetWorldPosition(nowWorldPos + delta); } void Transform::MovePositionLocal(Vector2 delta) { } void Transform::SetScale(Vector2 scale) { this->scale.x = scale.x; this->scale.y = scale.y; if (this->bAutoUpdate) this->UpdateTransform(); } void Transform::SetScaling(Vector2 deltaScale) { this->scale.x += deltaScale.x; this->scale.y += deltaScale.y; if (this->bAutoUpdate) this->UpdateTransform(); } // axis를 world 축으로 설정해주어햐함 void Transform::RotateWorld(float angle) { if (this->pParent) { Vector2 worldAxis[2]; this->GetUnitAxis(worldAxis); Matrix matRotateZ; matRotateZ = matRotateZ.Rotate(angle); Matrix matInvParentFinal; float temp; matInvParentFinal = this->pParent->matFinal.Inverse(temp); Matrix matRot = matRotateZ * matInvParentFinal; for (int i = 0; i < 2; i++) this->axis[i] = this->axis[i].TransformNormal(matRot); if (this->bAutoUpdate) this->UpdateTransform(); } else { RotateLocal(angle); } } void Transform::RotateSelf(float angle) { // 2D 라서 한방향만 회전하면 됨 z축으로 Matrix matRotateZ; matRotateZ = matRotateZ.Rotate(angle); for (int i = 0; i < 2; i++) this->axis[i] = this->axis[i].TransformNormal(matRotateZ); if (this->bAutoUpdate) this->UpdateTransform(); } void Transform::RotateLocal(float angle) { // 2D 라서 한방향만 회전하면 됨 z축으로 Matrix matRotateZ; matRotateZ = matRotateZ.Rotate(angle); for (int i = 0; i < 2; i++) this->axis[i] = this->axis[i].TransformNormal(matRotateZ); if (this->bAutoUpdate) this->UpdateTransform(); } void Transform::SetRotateWorld(const Matrix matWorldRotate) { } void Transform::SetRotateWorld(D3DXQUATERNION & worldRotate) { D3DXQUATERNION quatRot = worldRotate; D3DXMATRIX matRotate; D3DXMatrixRotationQuaternion(&matRotate, &quatRot); Matrix matRot = Matrix(matRotate); if (this->pParent) { Matrix matInvParentFinal; float temp; matInvParentFinal = this->pParent->matFinal.Inverse(temp); matRot = matRot * matInvParentFinal; } this->right = Vector2(1, 0); this->up = Vector2(0, 1); for (int i = 0; i < 2; i++) this->axis[i] = this->axis[i].TransformNormal(matRot); if (this->bAutoUpdate) this->UpdateTransform(); } void Transform::SetRotateLocal(const Matrix matLocalRotate) { } void Transform::LookPosition(Vector2 pos, Vector2 up) { } void Transform::ScaleLerp(Transform * from, Transform * to, float t) { t = Util::Clamp01(t); D3DXVECTOR3 fromScale = from->scale.ToDXVector3(); D3DXVECTOR3 toScale = to->scale.ToDXVector3(); if (FLOATZERO(t)) { this->SetScale(Vector2(from->scale.x, from->scale.y)); } else if (FLOATEQUAL(t, 1.0f)) { this->SetScale(Vector2(to->scale.x, to->scale.y)); } else { D3DXVECTOR3 result; D3DXVec3Lerp(&result, &fromScale, &toScale, t); Vector2 vec = Vector2(result.x, result.y); this->SetScale(vec); } } void Transform::RotateSlerp(Transform * from, Transform * to, float t) { // t 보간값 // 0 <= t <= 1 // 0에 가까우면 from에 가깝고 1에 가까우면 to에 가까움 // 0에 가까우면 많이 짤리게 되고 // 1에 가까우면 적게 짤리게 된다는거 // t 짤리는 비율 t = Util::Clamp01(t); D3DXQUATERNION fromQuat = from->GetWorldRotateQuaternion(); D3DXQUATERNION toQuat = to->GetWorldRotateQuaternion(); if (FLOATZERO(t)) { this->SetRotateWorld(fromQuat); } else if (FLOATEQUAL(t, 1.0f)) { this->SetRotateWorld(toQuat); } else { D3DXQUATERNION result; D3DXQuaternionSlerp(&result, &fromQuat, &toQuat, t); this->SetRotateWorld(result); } } void Transform::PositionLerp(Transform * from, Transform * to, float t) { // 선형보간 t = Util::Clamp01(t); D3DXVECTOR3 fromWorldPos = from->GetWorldPosition().ToDXVector3(); D3DXVECTOR3 toWorldPos = to->GetWorldPosition().ToDXVector3(); if (FLOATZERO(t)) { this->SetWorldPosition(from->GetWorldPosition()); } else if (FLOATEQUAL(t, 1.0f)) { this->SetWorldPosition(to->GetWorldPosition()); } else { D3DXVECTOR3 result; D3DXVec3Lerp(&result, &fromWorldPos, &toWorldPos, t); Vector2 vec = Vector2(result.x, result.y); this->SetWorldPosition(vec); } } void Transform::Interpolate(Transform * from, Transform * to, float t) { // 과제 // scale은 선형보간 // position은 선형보간 // rotate 구면보간 t = Util::Clamp01(t); Vector2 resultScale; Vector2 resultPosition; D3DXQUATERNION resultRotate; if (FLOATZERO(t)) { resultScale = from->scale; resultPosition = from->GetWorldPosition(); resultRotate = from->GetWorldRotateQuaternion(); } else if (FLOATEQUAL(t, 1.0f)) { resultScale = to->scale; resultPosition = to->GetWorldPosition(); resultRotate = to->GetWorldRotateQuaternion(); } else { D3DXVECTOR3 fromScale = from->scale.ToDXVector3(); D3DXVECTOR3 toScale = to->scale.ToDXVector3(); D3DXVECTOR3 fromPosition = from->GetWorldPosition().ToDXVector3(); D3DXVECTOR3 toPosition = to->GetWorldPosition().ToDXVector3(); D3DXQUATERNION fromQuat = from->GetWorldRotateQuaternion(); D3DXQUATERNION toQuat = to->GetWorldRotateQuaternion(); D3DXVECTOR3 tempScale; D3DXVECTOR3 tempPosition; D3DXQUATERNION tempQuat; D3DXVec3Lerp(&tempScale, &fromScale, &toScale, t); D3DXVec3Lerp(&tempPosition, &fromPosition, &toPosition, t); D3DXQuaternionSlerp(&tempQuat, &fromQuat, &toQuat, t); resultScale = Vector2(tempScale.x, tempScale.y); resultPosition = Vector2(tempPosition.x, tempPosition.y); resultRotate = tempQuat; } // auto 업데이트 끄고 값을 집어넣고 auto 업데이트 해줘야함 bool bPrevAutoUpdate = this->bAutoUpdate; bAutoUpdate = false; // -> SetScale // -> SetWorldPosition // -> SetRotateWorld this->SetScale(resultScale); this->SetWorldPosition(resultPosition); this->SetRotateWorld(resultRotate); this->bAutoUpdate = bPrevAutoUpdate; if (bAutoUpdate) this->UpdateTransform(); } void Transform::DefaultControl2() { float deltaTime = (float)Frame::Get()->GetFrameDeltaSec(); float deltaMove = 1000.0f * deltaTime; // c++ 에선 10.f 이렇게 써도 됨 float deltaAngle = 90.0f * D3DX_PI / 180.0f * deltaTime; if (Input::Get()->GetKey(VK_RBUTTON) == false) { if (Input::Get()->GetKey('A')) this->MovePositionSelf(Vector2(-deltaMove, 0)); else if (Input::Get()->GetKey('D')) this->MovePositionSelf(Vector2(deltaMove, 0)); if (Input::Get()->GetKey('W')) this->MovePositionSelf(Vector2(0, -deltaMove)); else if (Input::Get()->GetKey('S')) this->MovePositionSelf(Vector2(0, deltaMove)); if (Input::Get()->GetKey('Q')) this->RotateSelf(-deltaAngle); else if (Input::Get()->GetKey('E')) this->RotateSelf(deltaAngle); if (Input::Get()->GetKey('Z')) this->SetScaling(Vector2(0.1f, 0.1f)); if (Input::Get()->GetKey('X')) this->SetScaling(Vector2(-0.1f, -0.1f)); } } void Transform::UpdateTransform() { // 자신의 정보로 matLocal 행렬을 갱신 this->matLocal = Matrix::Identity(4); this->matFinal = Matrix::Identity(4); // scale 값을 가진 축 Vector2 scaledRight = this->right * this->scale.x; Vector2 scaledUp = this->up * this->scale.y; this->matLocal[0][0] = scaledRight.x; this->matLocal[0][1] = scaledRight.y; this->matLocal[1][0] = scaledUp.x; this->matLocal[1][1] = scaledUp.y; this->matLocal[3][0] = position.x; this->matLocal[3][1] = position.y; if (this->pParent == NULL) { this->matFinal = matLocal; } else { this->matFinal = matLocal * this->pParent->matFinal; } Transform* pChild = this->pFirstChild; while (pChild != NULL) { pChild->UpdateTransform(); pChild = pChild->pNextSibling; } } Matrix Transform::GetFinalMatrix() const { return matFinal; } Vector2 Transform::GetWorldPosition() const { Vector2 position = this->position; if (this->pParent) position = position.TransformCoord(pParent->matFinal); return position; } void Transform::GetUnitAxis(Vector2 * pVecArr) const { for (int i = 0; i < 2; i++) { pVecArr[i] = axis[i]; pVecArr[i] = pVecArr[i].Normalize(); } if (this->pParent) { Matrix matParentFinal = this->pParent->matFinal; for (int i = 0; i < 2; i++) { pVecArr[i] = pVecArr[i].TransformNormal(matParentFinal); } } } Vector2 Transform::GetUnitAxis(int axisNum) const { Vector2 result = this->axis[axisNum]; result = result.Normalize(); if (this->pParent) { Matrix matParentFinal = this->pParent->matFinal; result = result.TransformNormal(matParentFinal); } return result; } Vector2 Transform::GetUp() const { return this->GetUnitAxis(AXIS_Y); } Vector2 Transform::GetRight() const { return this->GetUnitAxis(AXIS_X); } Vector2 Transform::GetScale() const { return this->scale; } Matrix Transform::GetWorldRotateMatrix() { Matrix matRotate; matRotate = Matrix::Identity(4); Vector2 axis[2]; this->GetUnitAxis(axis); // 부모로 들어가면 정규화 필요 matRotate[0][0] = axis[0].x; matRotate[0][1] = axis[0].y; matRotate[1][0] = axis[1].x; matRotate[1][1] = axis[1].y; // 3차원이면 z값까지 처리 필요 return matRotate; } D3DXQUATERNION Transform::GetWorldRotateQuaternion() { D3DXQUATERNION quat; // 월드 축으로 받아오는 녀석으로 해야됨 // GetUnitAxis()를 월드축으로 받아와서 행렬로 변환 시켜서 // 그녀석을 matWorld라는 녀석에 집어넣어야함 D3DXMATRIX matWorld = this->GetWorldRotateMatrix().ToDXMatrix(); // quat 값으로 변환됨 (행렬중 회전값만 반환됨) D3DXQuaternionRotationMatrix(&quat, &matWorld); return quat; } void Transform::DrawInterface() { #ifdef IMGUI_USE ImGui::Begin("Transform"); { ImGui::Text("Postion"); ImGui::InputFloat("X", &position.x, 1.0f); ImGui::InputFloat("Y", &position.y, 1.0f); ImGui::Text("AxisX"); ImGui::InputFloat("X", &right.x, 1.0f); ImGui::InputFloat("Y", &right.y, 1.0f); ImGui::Text("AxisY"); ImGui::InputFloat("X", &up.x, 1.0f); ImGui::InputFloat("Y", &up.y, 1.0f); ImGui::Text("Scale"); ImGui::InputFloat("X", &scale.x, 1.0f); ImGui::InputFloat("Y", &scale.y, 1.0f); if (ImGui::Button("Reset")) this->Reset(); this->UpdateTransform(); } ImGui::End(); #endif // IMGUI_USE } void Transform::RenderGizmo(bool applyScale) { Vector2 worldPos = this->GetWorldPosition(); Vector2 axis[2]; // GetUnitAxis에서 normalize만 안하면됨 if (applyScale) { this->GetUnitAxis(axis); axis[0] = axis[0] * this->GetScale().x; axis[1] = axis[1] * this->GetScale().y; } else { this->GetUnitAxis(axis); } Vector2 xAxis = worldPos + axis[0] * 100; Vector2 yAxis = worldPos - axis[1] * 100; GIZMO->Line(worldPos, xAxis, 0xffff0000); GIZMO->Line(worldPos, yAxis, 0xff00ff00); }
#include "CTransform.h" using Mat4D::CMatrix4D; using Mat4D::CVector4D; CTransform::CTransform() { Position.Identity(); Scaling.Identity(); RotationX.Identity(); RotationY.Identity(); RotationZ.Identity(); FinalRotation.Identity(); } CTransform::~CTransform() { } void CTransform::SetRotationX(float angle) { RotationX = Mat4RotateX(angle); } void CTransform::RotateX( float angle ) { RotationX *= Mat4RotateX( angle ); } void CTransform::SetRotationY(float angle) { RotationY = Mat4RotateY(angle); } void CTransform::RotateY( float angle ) { RotationY *= Mat4RotateY( angle ); } void CTransform::SetRotationZ(float angle) { RotationZ = Mat4RotateZ(angle); } void CTransform::RotateZ( float angle ) { RotationZ *= Mat4RotateZ( angle ); } void CTransform::SetRotation(float x, float y, float z) { SetRotationX(x); SetRotationY(y); SetRotationZ(z); } void CTransform::SetRotation( Mat4D::CMatrix4D rotation ) { FinalRotation = rotation; } void CTransform::Rotate( float x, float y, float z ) { RotateX( x ); RotateY( y ); RotateZ( z ); } void CTransform::SetScale( float sx, float sy, float sz ) { Scaling = Mat4D::Scale( sx, sy, sz ); } void CTransform::SetScale( float s ) { SetScale( s, s, s ); } void CTransform::Scale( float sx, float sy, float sz ) { Scaling *= Mat4D::Scale( sx, sy, sz ); } void CTransform::Scale( float s ) { Scale( s, s, s ); } void CTransform::SetPosition(float x, float y, float z) { Position = Mat4Translate(x, y, z); } void CTransform::SetPosition(const CVector4D & position) { Position = Mat4Translate(position.x, position.y, position.z); } void CTransform::Move( float x, float y, float z ) { Position *= Mat4Translate( x, y, z ); } void CTransform::Move( const CVector4D & distance ) { Position *= Mat4Translate( distance.x, distance.y, distance.z ); } CMatrix4D CTransform::GetTransformed() { return Scaling * FinalRotation * RotationX * RotationY * RotationZ * Position; }
#ifndef TREEFACE_TEXTURE_POST_SURFACE_H #define TREEFACE_TEXTURE_POST_SURFACE_H #include "treeface/post/PostSurface.h" #include "treeface/gl/Texture.h" #include <treecore/RefCountHolder.h> namespace treeface { /// /// \brief post process rendering surface on a texture /// /// It holds a 2D texture, or one side of cube map texture, or one slice of a 2D /// texture array or 3D texture. /// class TexturePostSurface: public PostSurface { public: /// /// \brief create surface and also create an empty 2D texture /// /// \param width width in pixels /// \param height height in pixels /// \param levels number of mipmap levels /// \param internal_fmt texture data storage format /// /// \see Texture(GLsizei width, GLsizei height, GLsizei levels, GLInternalImageFormat internal_fmt) /// TexturePostSurface(GLsizei width, GLsizei height, GLsizei levels, GLInternalImageFormat internal_fmt); /// /// \brief create surface and assign a 2D texture with it /// \param texture texture to be assigned, must be a 2D texture. /// TexturePostSurface(Texture* texture); /// /// \brief create surface and assign one side of a cube map texture with it /// \param texture texture to be assigned, must be a cube map texture. /// \param side which side to be assigned /// TexturePostSurface(Texture* texture, GLTextureCubeSide side); /// /// \brief create surface and assign one slice of a 3D texture or 2D texture array /// \param texture texture to be assigned, must be a 3D texture or 2D texture array /// \param slice which slice to be assigned /// TexturePostSurface(Texture* texture, int32 slice); TREECORE_DECLARE_NON_COPYABLE(TexturePostSurface) TREECORE_DECLARE_NON_MOVABLE(TexturePostSurface) virtual ~TexturePostSurface(); Texture* get_texture() const noexcept; protected: struct Guts; void attach_to( Framebuffer* fbo, GLFramebufferAttachment attach ) override; Guts* m_guts; }; } // namespace treeface #endif // TREEFACE_TEXTURE_POST_SURFACE_H
#include<stdio.h> int a,b,c,s=0; main() { scanf("%d",&c); a=c; while(a!=0) { b=a%10; a=a/10; s=s*10+b; } if(c==s) { printf("YES"); } else printf("NO"); }
#include <cstdint> namespace rd { namespace ch1 { /* * converts a binary number (specified as a uint64_t number with * only ones and zeros) to a nonnegative integer * Example: * binary_to_decimal<11010>::value is replaced by 26 */ template <uint64_t input> struct binary_to_decimal { static uint64_t const value = (2 * binary_to_decimal<input / 10>::value) + (input % 10); }; /* recursion termination condition for binary_to_decimal */ template<> struct binary_to_decimal<0> { static uint64_t const value = 0; }; } }
#include "CCWebView.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxWebView.h" #include "CCEGLView.h" #include "CCDirector.h" #include "CCFileUtils.h" namespace cocos2d { namespace webview_plugin { CCWebViewDelegate *CCWebView::s_pWebViewDelegate = NULL; CCWebView::CCWebView(void* obj){ mWebView = obj; } CCWebView* CCWebView::create(bool fullScreenMode){ jobject obj = createWebViewJni(); CCWebView* webview = NULL; if(obj != NULL){ webview = new CCWebView((void*)obj); setJavascriptIfJni(obj, webview); setWebViewClientJni(obj, webview); webview->autorelease(); webview->retain(); } return webview; } void CCWebView::disableEffect(){ } void CCWebView::loadUrl(const char* url, bool transparent/* =false */){ if(mWebView != NULL){ loadUrlJni((jobject)mWebView, url, transparent); } } void CCWebView::loadHtml(const char *filepath, bool transparent/* =false */){ if(mWebView != NULL){ const char* base = "file:///android_asset/"; const char* suffix = ".html"; int len = strlen(base) + strlen(filepath) + strlen(suffix); char* buffer = new char[len]; sprintf(buffer, "%s%s%s", base, filepath, suffix); loadUrlJni((jobject)mWebView, buffer, transparent); delete [] buffer; } } void CCWebView::clearCache(){ if(mWebView != NULL){ clearCacheJni((jobject)mWebView); } } CCString* CCWebView::evaluateJS(const char* js){ if(mWebView != NULL){ evaluateJSJni((jobject)mWebView, js); } return NULL; } void CCWebView::setVisibility(bool enable){ if(mWebView != NULL){ setVisibilityJni((jobject)mWebView, enable); } } void CCWebView::setRect(int x, int y, int w, int h){ if(mWebView != NULL){ CCSize designSize = CCEGLView::sharedOpenGLView()->getDesignResolutionSize(); CCSize frameSize = CCEGLView::sharedOpenGLView()->getFrameSize(); float scale = frameSize.width / designSize.width; setRectJni((jobject)mWebView, scale * x, 1 + scale * y + (frameSize.height - designSize.height * scale) / 2, scale * w, scale * h); } } void CCWebView::destroy(){ if(mWebView != NULL){ destroyJni((jobject)mWebView); } } void CCWebView::handleCalledFromJS(const char *message){ CCWebViewDelegate *delegate = CCWebView::getWebViewDelegate(); if(delegate != NULL){ CCString *str = new CCString(message); str->autorelease(); delegate->callbackFromJS(this, str); } } bool CCWebView::handleShouldOverrideUrlLoading(const char *url) { CCWebViewDelegate *delegate = CCWebView::getWebViewDelegate(); if (delegate != NULL) { CCString *str = CCString::create(url); return delegate->shouldOverrideUrlLoading(this, str); } return false; } void CCWebView::handleOnPageFinished(const char *url) { CCWebViewDelegate *delegate = CCWebView::getWebViewDelegate(); if (delegate != NULL) { CCString *str = CCString::create(url); delegate->onPageFinished(this, str); } } void CCWebView::handleOnLoadError(const char *url) { CCWebViewDelegate *delegate = CCWebView::getWebViewDelegate(); if (delegate != NULL) { CCString *str = CCString::create(url); delegate->onLoadError(this, str); } } void CCWebView::setBannerModeEnable(bool enable) { if (mWebView != NULL) { setBannerModeEnableJni((jobject)mWebView, enable); } } void CCWebView::setCloseButton(const char* imageName, int x, int y, int w, int h) { if (mWebView != NULL) { std::string imagePath = CCFileUtils::sharedFileUtils()->fullPathForFilename(imageName); CCSize designSize = CCEGLView::sharedOpenGLView()->getDesignResolutionSize(); CCSize frameSize = CCEGLView::sharedOpenGLView()->getFrameSize(); float scale = frameSize.width / designSize.width; setCloseButtonJni((jobject)mWebView, this, imagePath.c_str(), scale * x, 1 + scale * y + (frameSize.height - designSize.height * scale) / 2, scale * w, scale * h); } } void CCWebView::setUrlSchemeNotFoundMessage(const char* message) { setUrlSchemeNotFoundMessageJni((jobject)mWebView, message); } }} // End of namespae cocos2d::webview_plugin
#pragma once #include "jsvalue.h" #include "../spatial/rect_size.h" #include <boost/filesystem.hpp> #include <cef/cef_app.h> #include <cef/cef_client.h> #include <functional> #include <list> namespace Browser { class Browser; class Application : public CefApp, boost::noncopyable { public: class IJSObjectifiable; Application(const std::function<void(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)>& onContextCreated); ~Application(); // CefApp methods: virtual CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler() override; private: IMPLEMENT_REFCOUNTING(Application); std::function<void(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)> _onContextCreated; CefRefPtr<CefRenderProcessHandler> _renderProcessHandler; }; }
#include "archiveextractor.h" ArchiveExtractor::ArchiveExtractor(QFileInfo& fileDest,QString& dir,QObject* parent) : QObject(parent), fileDest_(fileDest), dir_(dir) { } void ArchiveExtractor::run() { std::ifstream ifs(fileDest_.filePath().toStdString(), std::ios_base::in | std::ios_base::binary); boost::iostreams::filtering_streambuf<boost::iostreams::input> in__; in__.push(boost::iostreams::gzip_decompressor()); in__.push(ifs); std::ofstream file(dir_.toStdString() + "/bootstrap.dat", std::ios_base::out | std::ios_base::binary); boost::iostreams::copy(in__, file); emit finished(); }
class AK_107_kobra { weight = 3.8; }; class AK_107_GL_kobra { weight = 5.3; }; class AK_107_pso { weight = 4; }; class AK_107_GL_pso { weight = 5.5; }; class AK107_Kobra_DZ { weight = 3.8; }; class AK107_GL_Kobra_DZ { weight = 5.3; }; class AK107_PSO_DZ { weight = 4; }; class AK107_GL_PSO_DZ { weight = 5.5; }; class AK107_DZ { weight = 3; }; class AK107_GL_DZ { weight = 4.5; }; class AKS_74_U { weight = 2.7; }; class AKS_74_UN_kobra { weight = 3; }; class AKS_74_pso { weight = 3.6; }; class AKS_74_kobra { weight = 3; }; class AK74_Kobra_DZ { weight = 2.7; }; class AK74_Kobra_SD_DZ { weight = 2.72; }; class AK74_GL_Kobra_DZ { weight = 2.73; }; class AK74_GL_Kobra_SD_DZ { weight = 2.75; }; class AK_74 { weight = 3.1; }; class AK74_DZ { weight = 2.7; }; class AK74_SD_DZ { weight = 2.72; }; class AK74_GL_DZ { weight = 2.73; }; class AK_74_GL { weight = 2.73; }; class AK74_GL_SD_DZ { weight = 2.75; }; class AK74_PSO1_DZ { weight = 2.73; }; class AK74_PSO1_SD_DZ { weight = 2.75; }; class AK74_GL_PSO1_DZ { weight = 2.76; }; class AK74_GL_PSO1_SD_DZ { weight = 2.78; }; class AK_47_M { weight = 3.2; }; class AKM_DZ { weight = 2.7; }; class AKM_Kobra_DZ { weight = 2.9; }; class AKM_PSO1_DZ { weight = 3; }; class AK_47_S { weight = 3; }; class AKS_DZ { weight = 3; }; class AKS_GOLD { weight = 4.0; }; class AKS_74 { weight = 2.7; }; class AKS74U_DZ { weight = 2.7; }; class AKS74U_Kobra_DZ { weight = 2.9; }; class AKS74U_Kobra_SD_DZ { weight = 3.1; }; class AKS74U_SD_DZ { weight = 2.9; }; class AKS_74_GOSHAWK { weight = 3.5; }; class AKS_74_NSPU { weight = 3.5; }; class AK_74_GL_kobra { weight = 4.2; }; class L85A2_DZ { weight = 5; }; class L85A2_FL_DZ { weight = 5.2; }; class L85A2_MFL_DZ { weight = 5.2; }; class L85A2_SD_DZ { weight = 5.2; }; class L85A2_SD_FL_DZ { weight = 5.4; }; class L85A2_SD_MFL_DZ { weight = 5.4; }; class L85A2_CCO_DZ { weight = 5.2; }; class L85A2_CCO_FL_DZ { weight = 5.4; }; class L85A2_CCO_MFL_DZ { weight = 5.4; }; class L85A2_CCO_SD_DZ { weight = 5.4; }; class L85A2_CCO_SD_FL_DZ { weight = 5.6; }; class L85A2_CCO_SD_MFL_DZ { weight = 5.6; }; class L85A2_Holo_DZ { weight = 5.2; }; class L85A2_Holo_FL_DZ { weight = 5.4; }; class L85A2_Holo_MFL_DZ { weight = 5.4; }; class L85A2_Holo_SD_DZ { weight = 5.4; }; class L85A2_Holo_SD_FL_DZ { weight = 5.6; }; class L85A2_Holo_SD_MFL_DZ { weight = 5.6; }; class L85A2_ACOG_DZ { weight = 5.2; }; class L85A2_ACOG_FL_DZ { weight = 5.4; }; class L85A2_ACOG_MFL_DZ { weight = 5.4; }; class L85A2_ACOG_SD_DZ { weight = 5.4; }; class L85A2_ACOG_SD_FL_DZ { weight = 5.6; }; class L85A2_ACOG_SD_MFL_DZ { weight = 5.6; }; class BAF_L85A2_RIS_Holo { weight = 5.2; }; class BAF_L85A2_UGL_Holo { weight = 6.2; }; class BAF_L85A2_RIS_SUSAT { weight = 5.5; }; class BAF_L85A2_UGL_SUSAT { weight = 6.2; }; class BAF_L85A2_RIS_ACOG { weight = 5.5; }; class BAF_L85A2_UGL_ACOG { weight = 7.1; }; class BAF_L85A2_RIS_CWS { weight = 5.2; }; class BAF_L85A2_RIS_TWS_DZ { weight = 5.2; }; class FN_FAL { weight = 4.5; }; class FNFAL_DZ { weight = 4.5; }; class FNFAL_CCO_DZ { weight = 4.7; }; class FNFAL_Holo_DZ { weight = 4.7; }; class FN_FAL_ANPVS { weight=5.5; }; class FN_FAL_ANPVS4 { weight = 5.7; }; class FNFAL_ANPVS4_DZ { weight=5.5; }; class FN_FAL_ANPVS4_DZE { weight=5.5; }; class G36a { weight = 3.6; }; class G36 { weight = 3; }; class G36C { weight = 2.8; }; class G36C_camo { weight = 2.8; }; class G36_C_SD_camo { weight = 3.0; }; class G36C_DZ { weight = 2.8; }; class G36C_SD_DZ { weight = 3; }; class G36C_CCO_DZ { weight = 3; }; class G36C_CCO_SD_DZ { weight = 3.2; }; class G36C_Holo_DZ { weight = 3; }; class G36C_Holo_SD_DZ { weight = 3.2; }; class G36C_ACOG_DZ { weight = 3.1; }; class G36C_ACOG_SD_DZ { weight = 3.3; }; class G36_C_SD_eotech { weight = 3.6; }; class G36A_camo { weight = 3.6; }; class G36A_Camo_DZ { weight = 3.6; }; class G36C_Camo_DZ { weight = 2.8; }; class G36K { weight = 3; }; class G36K_camo { weight = 3; }; class G36K_Camo_DZ { weight = 3; }; class G36K_Camo_SD_DZ { weight = 3.2; }; class LeeEnfield { weight = 4; }; class LeeEnfield_DZ { weight = 4; }; class M16A2GL { weight = 5.2; }; class M16A4 { weight = 3.8; }; class M16A4_DZ { weight = 3.8; }; class M16A4_FL_DZ { weight = 4; }; class M16A4_GL_DZ { weight = 4; }; class M16A4_GL_FL_DZ { weight = 4.2; }; class M16A4_CCO_DZ { weight = 4; }; class M16A4_CCO_FL_DZ { weight = 4.2; }; class M16A4_GL_CCO_DZ { weight = 4.2; }; class M16A4_GL_CCO_FL_DZ { weight = 4.4; }; class M16A4_Holo_DZ { weight = 4; }; class M16A4_Holo_FL_DZ { weight = 4.2; }; class M16A4_GL_Holo_DZ { weight = 4.2; }; class M16A4_GL_Holo_FL_DZ { weight = 4.4; }; class M16A4_ACOG_DZ { weight = 3.8; }; class M16A4_ACOG_FL_DZ { weight = 4.2; }; class M16A4_GL_ACOG_DZ { weight = 4.2; }; class M16A4_GL_ACOG_FL_DZ { weight = 4.4; }; class M16A2_GL_DZ { weight = 5.2; }; class M16A4_ACG { weight = 3.8; }; class M16A4_GL { weight = 5.2; }; class M16A2 { weight = 3.8; }; class M16A2_DZ { weight = 3.8; }; class M16A4_ACG_GL { weight = 5.2; }; class M4A1_AIM_SD_camo { weight = 3; }; class M4A1_Aim_camo { weight = 3; }; class M4A1_Aim { weight = 3; }; class M4A1_CCO_DZ { weight = 3; }; class M4A1 { weight = 3; }; class M4A1_DZ { weight = 3; }; class M4A1_FL_DZ { weight = 3.2; }; class M4A1_SD_DZ { weight = 3.2; }; class M4A1_SD_FL_DZ { weight = 3.4; }; class M4A1_GL_DZ { weight = 3.2; }; class M4A1_GL_FL_DZ { weight = 3.4; }; class M4A1_GL_SD_DZ { weight = 3.4; }; class M4A1_GL_SD_FL_DZ { weight = 3.6; }; class M4A1_CCO_FL_DZ { weight = 3.4; }; class M4A1_CCO_SD_DZ { weight = 3.4; }; class M4A1_CCO_SD_FL_DZ { weight = 3.6; }; class M4A1_GL_CCO_DZ { weight = 3.4; }; class M4A1_GL_CCO_FL_DZ { weight = 3.6; }; class M4A1_GL_CCO_SD_DZ { weight = 3.6; }; class M4A1_GL_CCO_SD_FL_DZ { weight = 3.8; }; class M4A1_Holo_DZ { weight = 3.2; }; class M4A1_Holo_FL_DZ { weight = 3.4; }; class M4A1_Holo_SD_DZ { weight = 3.4; }; class M4A1_Holo_SD_FL_DZ { weight = 3.6; }; class M4A1_GL_Holo_DZ { weight = 3.4; }; class M4A1_GL_Holo_FL_DZ { weight = 3.6; }; class M4A1_GL_Holo_SD_DZ { weight = 3.6; }; class M4A1_GL_Holo_SD_FL_DZ { weight = 3.8; }; class M4A1_ACOG_DZ { weight = 3.2; }; class M4A1_ACOG_FL_DZ { weight = 3.4; }; class M4A1_ACOG_SD_DZ { weight = 3.4; }; class M4A1_ACOG_SD_FL_DZ { weight = 3.6; }; class M4A1_GL_ACOG_DZ { weight = 3.4; }; class M4A1_GL_ACOG_FL_DZ { weight = 3.6; }; class M4A1_GL_ACOG_SD_DZ { weight = 3.6; }; class M4A1_GL_ACOG_SD_FL_DZ { weight = 3.8; }; class M4A1_HWS_GL_Camo { weight = 4.5; }; class M4A1_HWS_GL_SD_Camo { weight = 4.5; }; class M4A1_HWS_GL { weight = 4.5; }; class M4A1_RCO_GL { weight = 4.5; }; class M8_carbine { weight = 3.4; }; class M8_compact { weight = 3; }; class M8_carbineGL { weight = 4.8; }; class M8_SAW { weight = 4.5; }; class M8_sharpshooter { weight = 4.5; }; class Mosin_DZ { weight = 4; }; class Mosin_FL_DZ { weight = 4.2; }; class Mosin_Belt_DZ { weight = 4.2; }; class Mosin_Belt_FL_DZ { weight = 4.4; }; class Mosin_PU_DZ { weight = 4.2; }; class Mosin_PU_FL_DZ { weight = 4.4; }; class Mosin_PU_Belt_DZ { weight = 4.4; }; class Mosin_PU_Belt_FL_DZ { weight = 4.6; }; class Sa58V_RCO_EP1 { weight = 3.3; }; class SA58_ACOG_DZ { weight = 3.3; }; class Sa58V_EP1 { weight = 3.1; }; class Sa58V_CCO_EP1 { weight = 3.5; }; class SA58_CCO_DZ { weight = 3.3; }; class Sa58P_EP1 { weight = 3.1; }; class SA58_DZ { weight = 3.1; }; class SA58_RIS_DZ { weight = 3.1; }; class SA58_RIS_FL_DZ { weight = 3.3; }; class SA58_CCO_FL_DZ { weight = 3.5; }; class SA58_Holo_DZ { weight = 3.3; }; class SA58_Holo_FL_DZ { weight = 3.5; }; class SA58_ACOG_FL_DZ { weight = 3.5; }; class SCAR_L_STD_Mk4CQT { weight = 3.6; }; class SCAR_L_STD_HOLO { weight = 3.5; }; class SCAR_L_STD_EGLM_TWS { weight = 5.3; }; class SCAR_L_STD_EGLM_RCO { weight = 4.5; }; class SCAR_L_CQC_Holo { weight = 3.7; }; class SCAR_L_CQC_EGLM_Holo { weight = 5; }; class SCAR_L_CQC_CCO_SD { weight = 3.7; }; class SCAR_L_CQC { weight = 3.5; }; class SCAR_H_STD_EGLM_Spect { weight = 5.5; }; class SCAR_H_CQC_CCO_SD { weight = 4; }; class SCAR_H_CQC_CCO { weight = 4; }; class SCAR_H_STD_TWS_SD { weight = 5.2; }; class SCAR_H_LNG_Sniper_SD { weight = 5; }; class SCAR_H_LNG_Sniper { weight = 5; }; class M4A3_RCO_GL_EP1 { weight = 4.5; }; class M4A3_CCO_EP1 { weight = 3; }; class M4A3_Camo_DZ { weight = 2.8; }; class M4A3_Camo_ACOG_DZ { weight = 3.0; }; class M14_EP1 { weight = 5.5; }; class M14_DZ { weight = 5.5; }; class M14_Gh_DZ { weight = 5.6; }; class M14_CCO_DZ { weight = 5.7; }; class M14_CCO_Gh_DZ { weight = 5.8; }; class M14_Holo_DZ { weight = 5.7; }; class M14_Holo_Gh_DZ { weight = 5.8; }; class M1A_SC16_BL_DZ { weight = 5.8; }; class M1A_SC16_BL_CCO_DZ { weight = 6.2; }; class M1A_SC16_BL_HOLO_DZ { weight = 6.2; }; class M1A_SC16_BL_ACOG_DZ { weight = 6.6; }; class M1A_SC16_BL_PU_DZ { weight = 6.8; }; class M1A_SC16_TAN_DZ { weight = 5.8; }; class M1A_SC16_TAN_CCO_DZ { weight = 6.2; }; class M1A_SC16_TAN_HOLO_DZ { weight = 6.2; }; class M1A_SC16_TAN_ACOG_DZ { weight = 6.6; }; class M1A_SC16_TAN_PU_DZ { weight = 6.8; }; class M1A_SC2_BL_DZ { weight = 5.8; }; class M1A_SC2_BL_CCO_DZ { weight = 6.2; }; class M1A_SC2_BL_HOLO_DZ { weight = 6.2; }; class M1A_SC2_BL_ACOG_DZ { weight = 6.6; }; class M1A_SC2_BL_PU_DZ { weight = 6.8; }; class G36C_Camo_Holo_SD_DZ { weight = 5.8; }; class HK53A3_DZ { weight = 7.8; }; class PDR_DZ { weight = 5.1; }; class HK416_DZ { weight = 5.0; }; class HK416_CCO_DZ { weight = 5.2; }; class HK416_SD_DZ { weight = 5.2; }; class HK416_CCO_SD_DZ { weight = 5.4; }; class HK416_Holo_SD_DZ { weight = 5.4; }; class HK416_GL_DZ { weight = 5.2; }; class HK416_GL_SD_DZ { weight = 5.4; }; class HK416_GL_CCO_DZ { weight = 5.4; }; class HK416_GL_CCO_SD_DZ { weight = 5.6; }; class HK416_GL_Holo_DZ { weight = 5.4; }; class HK416_GL_Holo_SD_DZ { weight = 5.6; }; class HK416C_DZ { weight = 5.0; }; class HK416C_CCO_DZ { weight = 5.2; }; class HK416C_Holo_DZ { weight = 5.2; }; class HK416C_GL_DZ { weight = 5.2; }; class HK416C_GL_CCO_DZ { weight = 5.4; }; class HK416C_GL_Holo_DZ { weight = 5.4; }; class HK416C_ACOG_DZ { weight = 5.4; }; class HK416C_GL_ACOG_DZ { weight = 5.6; }; class HK417_DZ { weight = 5.0; }; class HK417_CCO_DZ { weight = 5.2; }; class HK417_Holo_DZ { weight = 5.2; }; class HK417_SD_DZ { weight = 5.2; }; class HK417_CCO_SD_DZ { weight = 5.4; }; class HK417_Holo_SD_DZ { weight = 5.4; }; class HK417_ACOG_DZ { weight = 5.2; }; class HK417_ACOG_SD_DZ { weight = 5.4; }; class HK417C_DZ { weight = 5.4; }; class HK417C_CCO_DZ { weight = 5.6; }; class HK417C_Holo_DZ { weight = 5.4; }; class HK417C_GL_DZ { weight = 5.6; }; class HK417C_GL_CCO_DZ { weight = 5.0; }; class HK417C_GL_Holo_DZ { weight = 5.2; }; class HK417C_ACOG_DZ { weight = 5.4; }; class HK417C_GL_ACOG_DZ { weight = 5.6; }; class CTAR21_DZ { weight = 5.4; }; class CTAR21_CCO_DZ { weight = 5.4; }; class CTAR21_ACOG_DZ { weight = 5.4; }; class Groza1_DZ { weight = 5.6; }; class Groza1_SD_DZ { weight = 5.6; }; class Groza9_DZ { weight = 5.6; }; class Groza9_SD_DZ { weight = 5.6; }; class Groza9_GL_DZ { weight = 5.6; }; class MK14_DZ { weight = 5.6; }; class MK16_DZ { weight = 5.6; }; class MK16_CCO_DZ { weight = 5.6; }; class MK16_BL_CCO_DZ { weight = 5.6; }; class MK16_Holo_DZ { weight = 5.6; }; class MK16_CCO_SD_DZ { weight = 5.6; }; class MK16_Holo_SD_DZ { weight = 5.6; }; class MK16_GL_DZ { weight = 5.6; }; class MK16_GL_CCO_DZ { weight = 5.6; }; class MK16_GL_CCO_SD_DZ { weight = 5.6; }; class MK16_BL_GL_CCO_SD_DZ { weight = 5.6; }; class MK16_GL_Holo_DZ { weight = 5.6; }; class MK16_GL_Holo_SD_DZ { weight = 5.6; }; class MK16_BL_Holo_SD_DZ { weight = 5.4; }; class MK16_ACOG_DZ { weight = 5.6; }; class MK16_GL_ACOG_DZ { weight = 5.6; }; class MK16_BL_GL_ACOG_DZ { weight = 5.6; }; class MK16_ACOG_SD_DZ { weight = 5.6; }; class MK16_GL_ACOG_SD_DZ { weight = 5.6; }; class MK17_DZ { weight = 5.6; }; class MK17_CCO_DZ { weight = 5.6; }; class MK17_Holo_DZ { weight = 5.6; }; class MK17_CCO_SD_DZ { weight = 5.6; }; class MK17_Holo_SD_DZ { weight = 5.6; }; class MK17_GL_DZ { weight = 5.6; }; class MK17_GL_CCO_DZ { weight = 5.6; }; class MK17_GL_CCO_SD_DZ { weight = 5.6; }; class MK17_GL_Holo_DZ { weight = 5.6; }; class MK17_GL_Holo_SD_DZ { weight = 5.6; }; class MK17_ACOG_DZ { weight = 5.6; }; class MK17_GL_ACOG_DZ { weight = 5.6; }; class MK17_ACOG_SD_DZ { weight = 5.6; }; class XM8_Compact_DZ { weight = 5.6; }; class XM8_DES_Compact_DZ { weight = 5.6; }; class XM8_GREY_Compact_DZ { weight = 5.6; }; class XM8_GREY_2_Compact_DZ { weight = 5.6; }; class XM8_DZ { weight = 5.6; }; class XM8_DES_DZ { weight = 5.6; }; class XM8_GREY_DZ { weight = 5.6; }; class XM8_GREY_2_DZ { weight = 5.6; }; class XM8_GL_DZ { weight = 5.8; }; class XM8_DES_GL_DZ { weight = 5.8; }; class XM8_GREY_GL_DZ { weight = 5.6; }; class XM8_Sharpsh_DZ { weight = 5.6; }; class XM8_DES_Sharpsh_DZ { weight = 5.6; }; class XM8_GREY_Sharpsh_DZ { weight = 5.6; }; class XM8_SD_DZ { weight = 5.8; }; class BAF_L86A2_ACOG { weight = 5.8; }; class BAF_L7A2_GPMG { weight = 5.6; }; class GSh23L_L39 { weight = 6.0; }; class M4A3_EP1 { weight = 3.2; }; class BAF_L7A2_GPMG_Small { weight = 6.0; }; class AK_107_CP { weight = 3.4; }; class AK_107_GL_CP { weight = 3.6; }; class AKS_74_UN_CP { weight = 3.4; }; class M4A3_RCO_EP1 { weight = 3.4; }; class AN94_DZ { weight = 3.4; }; class AN94_GL_DZ { weight = 3.6; }; class AKS_Gold_DZ { weight = 6.0; }; class AKS_Silver_DZ { weight = 5.0; }; class G36A_Camo_SD_DZ { weight = 4.0; }; class M4A1_MFL_DZ { weight = 3.0; }; class M4A1_SD_MFL_DZ { weight = 3.2; }; class M4A1_GL_MFL_DZ { weight = 3.2; }; class M4A1_GL_SD_MFL_DZ { weight = 3.4; }; class M4A1_CCO_MFL_DZ { weight = 3.2; }; class M4A1_CCO_SD_MFL_DZ { weight = 3.4; }; class M4A1_GL_CCO_MFL_DZ { weight = 3.4; }; class M4A1_GL_CCO_SD_MFL_DZ { weight = 3.6; }; class M4A1_Holo_MFL_DZ { weight = 3.2; }; class M4A1_Holo_SD_MFL_DZ { weight = 3.4; }; class M4A1_GL_Holo_SD_MFL_DZ { weight = 3.6; }; class M4A1_ACOG_MFL_DZ { weight = 3.2; }; class M4A1_ACOG_SD_MFL_DZ { weight = 3.4; }; class M4A1_GL_ACOG_MFL_DZ { weight = 3.4; }; class M4A1_GL_ACOG_SD_MFL_DZ { weight = 3.6; }; class M4A1_Rusty_DZ { weight = 3.2; }; class M4A1_Camo_CCO_DZ { weight = 3.1; }; class M4A1_Camo_CCO_SD_DZ { weight = 3.3; }; class M4A1_Camo_Holo_GL_DZ { weight = 3.6; }; class M4A1_Camo_Holo_GL_SD_DZ { weight = 3.8; }; class HK416_Holo_DZ { weight = 3.1; }; class SteyrAug_A3_Green_DZ { weight = 5.0; }; class SteyrAug_A3_Black_DZ { weight = 5.0; }; class SteyrAug_A3_Blue_DZ { weight = 5.0; }; class SteyrAug_A3_ACOG_Green_DZ { weight = 5.2; }; class SteyrAug_A3_ACOG_Black_DZ { weight = 5.2; }; class SteyrAug_A3_ACOG_Blue_DZ { weight = 5.2; }; class SteyrAug_A3_Holo_Green_DZ { weight = 5.2; }; class SteyrAug_A3_Holo_Black_DZ { weight = 5.2; }; class SteyrAug_A3_Holo_Blue_DZ { weight = 5.2; }; class SteyrAug_A3_GL_Green_DZ { weight = 5.2; }; class SteyrAug_A3_GL_Black_DZ { weight = 5.2; }; class SteyrAug_A3_GL_Blue_DZ { weight = 5.2; }; class SteyrAug_A3_ACOG_GL_Green_DZ { weight = 5.4; }; class SteyrAug_A3_ACOG_GL_Black_DZ { weight = 5.4; }; class SteyrAug_A3_ACOG_GL_Blue_DZ { weight = 5.4; }; class SteyrAug_A3_Holo_GL_Green_DZ { weight = 5.4; }; class SteyrAug_A3_Holo_GL_Black_DZ { weight = 5.4; }; class HK53A3_CCO_DZ { weight = 4.2; }; class HK53A3_Holo_DZ { weight = 4.2; }; class PDR_CCO_DZ { weight = 3.6; }; class PDR_Holo_DZ { weight = 3.6; }; class Famas_DZ { weight = 5.0; }; class Famas_CCO_DZ { weight = 5.2; }; class Famas_Holo_DZ { weight = 5.2; }; class Famas_SD_DZ { weight = 5.2; }; class Famas_CCO_SD_DZ { weight = 5.4; }; class Famas_Holo_SD_DZ { weight = 5.4; }; class ACR_WDL_DZ { weight = 5.0; }; class ACR_WDL_SD_DZ { weight = 5.2; }; class ACR_WDL_GL_SD_DZ { weight = 5.4; }; class ACR_WDL_CCO_DZ { weight = 5.2; }; class ACR_WDL_CCO_SD_DZ { weight = 5.4; }; class ACR_WDL_CCO_GL_DZ { weight = 5.4; }; class ACR_WDL_CCO_GL_SD_DZ { weight = 5.6; }; class ACR_WDL_Holo_DZ { weight = 5.2; }; class ACR_WDL_Holo_SD_DZ { weight = 5.4; }; class ACR_WDL_Holo_GL_DZ { weight = 5.4; }; class ACR_WDL_Holo_GL_SD_DZ { weight = 5.6; }; class ACR_WDL_ACOG_DZ { weight = 5.2; }; class ACR_WDL_ACOG_SD_DZ { weight = 5.4; }; class ACR_WDL_ACOG_GL_DZ { weight = 5.4; }; class ACR_WDL_ACOG_GL_SD_DZ { weight = 5.6; }; class ACR_WDL_TWS_DZ { weight = 5.4; }; class ACR_WDL_TWS_GL_DZ { weight = 5.6; }; class ACR_WDL_TWS_SD_DZ { weight = 5.6; }; class ACR_WDL_TWS_GL_SD_DZ { weight = 5.8; }; class ACR_WDL_NV_DZ { weight = 5.4; }; class ACR_WDL_NV_SD_DZ { weight = 5.6; }; class ACR_WDL_NV_GL_DZ { weight = 5.6; }; class ACR_WDL_NV_GL_SD_DZ { weight = 5.8; }; class ACR_BL_DZ { weight = 5.0; }; class ACR_BL_SD_DZ { weight = 5.2; }; class ACR_BL_GL_SD_DZ { weight = 5.4; }; class ACR_BL_CCO_DZ { weight = 5.2; }; class ACR_BL_CCO_SD_DZ { weight = 5.4; }; class ACR_BL_CCO_GL_DZ { weight = 5.4; }; class ACR_BL_CCO_GL_SD_DZ { weight = 5.6; }; class ACR_BL_Holo_DZ { weight = 5.2; }; class ACR_BL_Holo_SD_DZ { weight = 5.4; }; class ACR_BL_Holo_GL_DZ { weight = 5.4; }; class ACR_BL_Holo_GL_SD_DZ { weight = 5.6; }; class ACR_BL_ACOG_DZ { weight = 5.2; }; class ACR_BL_ACOG_SD_DZ { weight = 5.4; }; class ACR_BL_ACOG_GL_DZ { weight = 5.4; }; class ACR_BL_ACOG_GL_SD_DZ { weight = 5.6; }; class ACR_BL_TWS_DZ { weight = 5.4; }; class ACR_BL_TWS_GL_DZ { weight = 5.6; }; class ACR_BL_TWS_SD_DZ { weight = 5.6; }; class ACR_BL_TWS_GL_SD_DZ { weight = 5.8; }; class ACR_BL_NV_DZ { weight = 5.4; }; class ACR_BL_NV_SD_DZ { weight = 5.6; }; class ACR_BL_NV_GL_DZ { weight = 5.6; }; class ACR_BL_NV_GL_SD_DZ { weight = 5.8; }; class ACR_DES_DZ { weight = 5.0; }; class ACR_DES_SD_DZ { weight = 5.2; }; class ACR_DES_GL_SD_DZ { weight = 5.4; }; class ACR_DES_CCO_DZ { weight = 5.2; }; class ACR_DES_CCO_SD_DZ { weight = 5.4; }; class ACR_DES_CCO_GL_DZ { weight = 5.4; }; class ACR_DES_CCO_GL_SD_DZ { weight = 5.6; }; class ACR_DES_Holo_DZ { weight = 5.2; }; class ACR_DES_Holo_SD_DZ { weight = 5.4; }; class ACR_DES_Holo_GL_DZ { weight = 5.4; }; class ACR_DES_Holo_GL_SD_DZ { weight = 5.6; }; class ACR_DES_ACOG_DZ { weight = 5.2; }; class ACR_DES_ACOG_SD_DZ { weight = 5.4; }; class ACR_DES_ACOG_GL_DZ { weight = 5.4; }; class ACR_DES_ACOG_GL_SD_DZ { weight = 5.6; }; class ACR_DES_TWS_DZ { weight = 5.4; }; class ACR_DES_TWS_GL_DZ { weight = 5.6; }; class ACR_DES_TWS_SD_DZ { weight = 5.6; }; class ACR_DES_TWS_GL_SD_DZ { weight = 5.8; }; class ACR_DES_NV_DZ { weight = 5.4; }; class ACR_DES_NV_SD_DZ { weight = 5.6; }; class ACR_DES_NV_GL_DZ { weight = 5.6; }; class ACR_DES_NV_GL_SD_DZ { weight = 5.8; }; class ACR_SNOW_DZ { weight = 5.0; }; class ACR_SNOW_SD_DZ { weight = 5.2; }; class ACR_SNOW_GL_SD_DZ { weight = 5.4; }; class ACR_SNOW_CCO_DZ { weight = 5.2; }; class ACR_SNOW_CCO_SD_DZ { weight = 5.4; }; class ACR_SNOW_CCO_GL_DZ { weight = 5.4; }; class ACR_SNOW_CCO_GL_SD_DZ { weight = 5.6; }; class ACR_SNOW_Holo_DZ { weight = 5.2; }; class ACR_SNOW_Holo_SD_DZ { weight = 5.4; }; class ACR_SNOW_Holo_GL_DZ { weight = 5.4; }; class ACR_SNOW_Holo_GL_SD_DZ { weight = 5.6; }; class ACR_SNOW_ACOG_DZ { weight = 5.2; }; class ACR_SNOW_ACOG_SD_DZ { weight = 5.4; }; class ACR_SNOW_ACOG_GL_DZ { weight = 5.4; }; class ACR_SNOW_ACOG_GL_SD_DZ { weight = 5.6; }; class ACR_SNOW_TWS_DZ { weight = 5.4; }; class ACR_SNOW_TWS_GL_DZ { weight = 5.6; }; class ACR_SNOW_TWS_SD_DZ { weight = 5.6; }; class ACR_SNOW_TWS_GL_SD_DZ { weight = 5.8; }; class ACR_SNOW_NV_DZ { weight = 5.4; }; class ACR_SNOW_NV_SD_DZ { weight = 5.6; }; class ACR_SNOW_NV_GL_DZ { weight = 5.6; }; class ACR_SNOW_NV_GL_SD_DZ { weight = 5.8; }; class KAC_PDW_DZ { weight = 5.0; }; class KAC_PDW_CCO_DZ { weight = 5.2; }; class KAC_PDW_HOLO_DZ { weight = 5.2; }; class KAC_PDW_ACOG_DZ { weight = 5.2; }; class Masada_DZ { weight = 5.0; }; class Masada_SD_DZ { weight = 5.2; }; class Masada_CCO_DZ { weight = 5.2; }; class Masada_CCO_SD_DZ { weight = 5.4; }; class Masada_Holo_DZ { weight = 5.2; }; class Masada_Holo_SD_DZ { weight = 5.4; }; class Masada_ACOG_DZ { weight = 5.2; }; class Masada_ACOG_SD_DZ { weight = 5.4; }; class Masada_BL_DZ { weight = 5.0; }; class Masada_BL_SD_DZ { weight = 5.2; }; class Masada_BL_CCO_DZ { weight = 5.2; }; class Masada_BL_CCO_SD_DZ { weight = 5.4; }; class Masada_BL_Holo_DZ { weight = 5.2; }; class Masada_BL_Holo_SD_DZ { weight = 5.4; }; class Masada_BL_ACOG_DZ { weight = 5.2; }; class Masada_BL_ACOG_SD_DZ { weight = 5.4; }; class MK14_CCO_DZ { weight = 5.2; }; class MK14_Holo_DZ { weight = 5.2; }; class MK14_ACOG_DZ { weight = 5.2; }; class MK14_SD_DZ { weight = 5.2; }; class MK14_CCO_SD_DZ { weight = 5.4; }; class MK14_Holo_SD_DZ { weight = 5.4; }; class MK14_ACOG_SD_DZ { weight = 5.4; }; class MK17_BL_Holo_DZ { weight = 5.6; }; class MK17_BL_GL_ACOG_DZ { weight = 5.8; }; class MK17_BL_CCO_SD_DZ { weight = 5.8; }; class MK17_BL_GL_Holo_SD_DZ { weight = 6.0; }; class CZ805_A1_DZ { weight = 6.0; }; class CZ805_A1_GL_DZ { weight = 6.2; }; class CZ805_A2_DZ { weight = 6.0; }; class CZ805_A2_SD_DZ { weight = 6.2; }; class CZ805_B_GL_DZ { weight = 6.2; }; class VAL_DZ { weight = 6.0; }; class VAL_Kobra_DZ { weight = 6.2; }; class VAL_PSO1_DZ { weight = 6.3; }; class M16A2_Rusty_DZ { weight = 4.2; }; class M16A4_MFL_DZ { weight = 4.4; }; class M16A4_GL_MFL_DZ { weight = 4.6; }; class M16A4_CCO_MFL_DZ { weight = 4.6; }; class M16A4_Holo_MFL_DZ { weight = 4.6; }; class M16A4_GL_Holo_MFL_DZ { weight = 4.8; }; class M16A4_ACOG_MFL_DZ { weight = 4.6; }; class M16A4_GL_ACOG_MFL_DZ { weight = 4.8; }; class SA58_RIS_MFL_DZ { weight = 4.4; }; class SA58_CCO_MFL_DZ { weight = 4.8; }; class SA58_Holo_MFL_DZ { weight = 4.8; }; class SA58_ACOG_MFL_DZ { weight = 4.8; }; class Sa58V_DZ { weight = 4.4; }; class Sa58V_Camo_CCO_DZ { weight = 4.8; }; class Sa58V_Camo_ACOG_DZ { weight = 4.8; }; class m8_carbine_pmc { weight = 3.2; }; class m8_compact_pmc { weight = 3.2; }; class m8_holo_sd { weight = 3.4; }; class m8_tws_sd { weight = 3.8; }; class m8_tws { weight = 3.7; }; class CZ805_A1_ACR { weight = 6.0; }; class CZ805_A1_GL_ACR { weight = 6.2; }; class CZ805_A2_ACR { weight = 6.0; }; class CZ805_A2_SD_ACR { weight = 6.2; }; class CZ805_B_GL_ACR { weight = 6.2; }; class M4A1_GL_Holo_MFL_DZ { weight = 3.6; }; class M4A3_DES_CCO_DZ { weight = 3.2; }; class M4A3_ACOG_GL_DZ { weight = 3.4; }; class SteyrAug_A3_Holo_GL_Blue_DZ { weight = 5.4; }; class ACR_WDL_GL_DZ { weight = 5.2; }; class ACR_BL_GL_DZ { weight = 5.2; }; class ACR_DES_GL_DZ { weight = 5.2; }; class ACR_SNOW_GL_DZ { weight = 5.2; }; class M16A4_GL_CCO_MFL_DZ { weight = 4.6; }; class RK95_DZ { weight = 6.1; }; class RK95_SD_DZ { weight = 6.2; }; class RK95_CCO_SD_DZ { weight = 6.3; }; class RK95_ACOG_SD_DZ { weight = 6.3; }; class RK95_CCO_DZ { weight = 6.2; }; class RK95_ACOG_DZ { weight = 6.2; }; class G3_DZ { weight = 6.1; }; class SCAR_H_AK_DZ { weight = 4.5; }; class SCAR_H_AK_CCO_DZ { weight = 4.6; }; class SCAR_H_B_AK_CCO_DZ { weight = 4.6; }; class SCAR_H_AK_HOLO_DZ { weight = 4.6; }; class SCAR_H_AK_ACOG_DZ { weight = 4.7; };
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2007 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef _WINDOWSOPAUINSTALLER_H_ #define _WINDOWSOPAUINSTALLER_H_ #ifdef AUTO_UPDATE_SUPPORT #ifdef AUTOUPDATE_PACKAGE_INSTALLATION #include "adjunct/autoupdate/updater/pi/auinstaller.h" class WindowsAUInstaller : public AUInstaller { private: LPWORD lpwAlign (LPWORD lpIn); static const uni_char* UPGRADER_MUTEX_NAME; HANDLE m_upgrader_mutex; public: WindowsAUInstaller(); ~WindowsAUInstaller(); virtual AUI_Status Install(uni_char *install_path, uni_char *package_file); virtual BOOL HasInstallPrivileges(uni_char *install_path); virtual BOOL ShowStartDialog(uni_char *caption, uni_char *message, uni_char *yes_text, uni_char *no_text); virtual bool IsUpgraderMutexPresent(); virtual void CreateUpgraderMutex(); virtual void Sleep(UINT32 ms); static INT_PTR CALLBACK StartDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); }; #endif // AUTOUPDATE_USE_UPDATER #endif // AUTO_UPDATE_SUPPORT #endif // _WINDOWSOPAUINSTALLER_H_
//Chuong trinh an nut sang LED void setup() { // put your setup code here, to run once: //Cau hinh uart Serial.begin(9600); pinMode(31, INPUT_PULLUP); //Cau hinh chan 31 noi voi nut nhan,tro keo len pinMode(40,OUTPUT); //Cau hinh LED xanh (tren kit) la output } void loop() { // put your main code here, to run repeatedly: //Chuong trinh chinh int buttonVal = digitalRead(31); //In gia tri cua nut nhan Serial.println(buttonVal); //Kiem tra neu nut chua duoc nhan thi tat LED if (buttonVal == HIGH) { digitalWrite(40, LOW); }else{ digitalWrite(40,HIGH); //Nguoc lai thi bat LED } }
#ifndef __DUSERDITOR_H #define __DUSERDITOR_H #include "BaseOkCancelDialog.h" #include "MUser2.h" #include "TPresenter.h" #include "DUserGroupEditor.h" #include "VUserPanel.h" namespace wh{ namespace view{ //----------------------------------------------------------------------------- /// Редактор для действия class DUserEditor : public wxDialog , public ctrlWithResMgr , public T_View { public: typedef MUser2 T_Model; DUserEditor(wxWindow* parent = nullptr, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(400, 300),//wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER, const wxString& name = wxDialogNameStr); virtual ~DUserEditor(); virtual void SetModel(std::shared_ptr<IModel>& model)override; virtual void UpdateModel()const override; virtual int ShowModal() override; private: //std::shared_ptr<T_Model> mModel; typedef TViewCtrlPanel <CtrlTool::AddDel | CtrlTool::Load, DUserGroupEditor, false> VGroupsCtrlPanel; VUserPanel* mUserPanel; VGroupsCtrlPanel* mGroupsPanel; wxAuiManager mAuiMgr; wxButton* mBtnOK; wxButton* mBtnCancel; wxStdDialogButtonSizer* mBtnSizer; }; //--------------------------------------------------------------------------- }//namespace view }//namespace wh #endif //__BASETABLE_H
// // Application0.cpp // Odin.MacOSX // // Created by Daniel on 21/09/15. // Copyright (c) 2015 DG. All rights reserved. // #include "Application0.h" #include "Engine.h" #include "Camera.h" #include "Text.h" #include "BoxShape.h" #include "Math.h" #include "Material.h" #include "ResourceManager.h" #include "Renderer.h" #include "EventManager.h" namespace odin { namespace app { Application0::Application0(F32 updateTime) : core::System(core::System::Type::APP, updateTime), m_camera(nullptr), m_moveFront(false), m_moveBack(false), m_moveLeft(false), m_moveRight(false), m_movementSpeed(2.0f), m_mouseSensitivity(1.0f) { } bool Application0::startUp() { // load assets //ResourceManager::loadShader("depth", "Assets/Shaders/depth.vert", "Assets/Shaders/depth.frag"); ResourceManager::loadShader("lighting", "Assets/Shaders/lighting_fw.vert", "Assets/Shaders/lighting_fw.frag"); //ResourceManager::loadShader("reflect", "Assets/Shaders/envmap_reflection.vert", "Assets/Shaders/envmap_reflection.frag"); //ResourceManager::loadShader("refract", "Assets/Shaders/envmap_refraction.vert", "Assets/Shaders/envmap_refraction.frag"); ResourceManager::loadTexture2D("container_diff", "Assets/Textures/container_diffuse.png"); ResourceManager::loadTexture2D("container_spec", "Assets/Textures/container_specular.png"); ResourceManager::loadTexture2D("grass", "Assets/Textures/grass.png", ODIN_LINEAR, ODIN_CLAMP_TO_EDGE); ResourceManager::loadTexture2D("wood", "Assets/Textures/wood.png"); ResourceManager::loadTexture2D("window", "Assets/Textures/transparent_window.png"); ResourceManager::loadFont("sansation", "Assets/Fonts/sansation.ttf"); ResourceManager::loadModel("nanosuit", "Assets/Models/nanosuit/nanosuit.obj", true); // load skybox (and shaders) render::Skybox* skybox = m_world.addSkybox(); skybox->load("skybox", "Assets/Textures/skybox_lowres"); resource::Shader* skyboxShader = ResourceManager::getShader("skybox"); resource::Shader* lighting = ResourceManager::getShader("lighting"); //resource::Shader* reflect = ResourceManager::getShader("reflect"); //resource::Shader* refract = ResourceManager::getShader("refract"); resource::Model* model = ResourceManager::getModel("nanosuit"); math::mat4 projection = render::perspective(45.0f, 800.0/600.0, 0.1f, 100.0f); lighting->setUniform("projection", projection); skyboxShader->setUniform("projection", projection); //reflect->setUniform("projection", projection); //refract->setUniform("projection", projection); // create camera m_camera = m_world.addCamera(); // create box instances { math::vec3 cubePositions[] = { math::vec3( 0.0f, 0.0f, 0.0f), math::vec3( 2.0f, 5.0f, -15.0f), math::vec3(-1.5f, -2.2f, -2.5f), math::vec3(-3.8f, -2.0f, -12.3f), math::vec3( 2.4f, -0.4f, -3.5f), math::vec3(-1.7f, 3.0f, -7.5f), math::vec3( 1.3f, -2.0f, -2.5f), math::vec3( 1.5f, 2.0f, -2.5f), math::vec3( 1.5f, 0.2f, -1.5f), math::vec3(-1.3f, 1.0f, -1.5f) }; ResourceManager::loadMaterial(render::MaterialCommon::Type::COMMON, "box"); render::MaterialCommon* boxMaterial = static_cast<render::MaterialCommon*>(ResourceManager::getMaterial("box")); boxMaterial->specular = math::vec4(1); boxMaterial->shininess = 32.0f; resource::Texture2D* diffTexture = ResourceManager::getTexture2D("container_diff"); resource::Texture2D* specTexture = ResourceManager::getTexture2D("container_spec"); boxMaterial->addTexture(render::MaterialCommon::TextureType::DIFFUSE, diffTexture); boxMaterial->addTexture(render::MaterialCommon::TextureType::SPECULAR, specTexture); //resource::Cubemap* cubemap = ResourceManager::getCubemap("skybox"); //boxMaterial->addTexture(render::MaterialCommon::TextureType::CUBEMAP, cubemap); m_box.setMaterial(boxMaterial); Entity* boxEntity = m_world.addEntity(); boxEntity->setDrawable(m_box); render::RenderStates states; for (I32 i = 0; i < 10; ++i) { render::Transform transform; transform.translate(cubePositions[i]); F32 angle = 20.0f * i; transform.rotate(angle, math::vec3(1.0f, 0.3f, 0.5f)); states.transforms.push_back(transform); } states.cullFace = false; states.shader = lighting; boxEntity->setRenderStates(states); } // Create lights { ResourceManager::loadMaterial(render::MaterialCommon::Type::COMMON, "light"); render::MaterialCommon* lightMaterial = static_cast<render::MaterialCommon*>(ResourceManager::getMaterial("light")); lightMaterial->diffuse = math::vec4(0); lightMaterial->emissive = math::vec4(1); lightMaterial->shininess = 1.0f; m_light.setMaterial(lightMaterial); // Directional Light render::DirectionalLight* directionalLight = m_world.addDirectionalLight(); directionalLight->direction = math::vec3(-0.2, -1.0, -0.3); directionalLight->color = math::vec4(0.2, 0.2, 0.2, 1.0); // Draw lights Entity* lightEntity = m_world.addEntity(); lightEntity->setDrawable(m_light); render::RenderStates lightStates; lightStates.shader = lighting; // draw directional light render::Transform dirLightTransform; dirLightTransform.translate(-math::vec3(-0.2, -1.0, -0.3) * 5); dirLightTransform.scale(math::vec3(0.1, 0.1, 0.1)); lightStates.transforms.push_back(dirLightTransform); // Point Lights math::vec3 pointLightPositions[] = { math::vec3( 0.7f, 0.2f, 2.0f), math::vec3( 2.3f, -3.3f, -4.0f), math::vec3(-4.0f, 2.0f, -12.0f), math::vec3( 0.0f, 0.0f, -3.0f) }; for (UI32 i = 0; i < 4; ++i) { render::PointLight* pointLight = m_world.addPointLight(); pointLight->position = pointLightPositions[i]; pointLight->color = math::vec4(1.0, 1.0, 1.0, 1.0); pointLight->constant = 1.0; pointLight->quadratic = 0.09; pointLight->linear = 0.032; // draw directional light render::Transform pointLightTransform; pointLightTransform.translate(pointLightPositions[i]); pointLightTransform.scale(math::vec3(0.1, 0.1, 0.1)); lightStates.transforms.push_back(pointLightTransform); } // Spot Light render::SpotLight* spotLight = m_world.addSpotLight(); spotLight->position = math::vec3(0.0, -2.5, -2.0); spotLight->direction = math::vec3(-0.7, -0.7, -0.8); spotLight->color = math::vec4(1.0, 1.0, 1.0, 1.0); spotLight->cutOff = math::cos(math::radians(12.5)); spotLight->outerCutOff = math::cos(math::radians(17.5)); // render spot light render::Transform spotLightTransform; spotLightTransform.translate(math::vec3(0.0, -3.0, -2.0)); spotLightTransform.scale(math::vec3(0.1, 0.1, 0.1)); lightStates.transforms.push_back(spotLightTransform); lightEntity->setRenderStates(lightStates); } // create floor { ResourceManager::loadMaterial(render::MaterialCommon::Type::COMMON, "floor"); render::MaterialCommon* floorMaterial = static_cast<render::MaterialCommon*>(ResourceManager::getMaterial("floor")); floorMaterial->specular = math::vec4(1); floorMaterial->shininess = 32.0f; resource::Texture2D* floorTexture = ResourceManager::getTexture2D("wood"); floorMaterial->addTexture(render::MaterialCommon::TextureType::DIFFUSE, floorTexture); floorMaterial->addTexture(render::MaterialCommon::TextureType::SPECULAR,floorTexture); m_floor.setMaterial(floorMaterial); Entity* floorInstance = m_world.addEntity(); floorInstance->setDrawable(m_floor); render::RenderStates floorStates; render::Transform floorTransform; floorTransform.translate(math::vec3(0.0, -5.0, -7.5)); floorTransform.scale(math::vec3(10.0)); floorTransform.rotate(-90.0, math::vec3(1,0,0)); floorStates.transforms.push_back(floorTransform); floorStates.cullFace = false; floorStates.shader = lighting; floorInstance->setRenderStates(floorStates); } // create model { Entity* nanosuit = m_world.addEntity(); nanosuit->setDrawable(*model); render::Transform nanosuitTransform; nanosuitTransform.translate(math::vec3(-2.0, -4.0, -4.0)); nanosuitTransform.scale(math::vec3(2.0)); render::RenderStates nanosuitStates; nanosuitStates.transforms.push_back(nanosuitTransform); nanosuitStates.shader = lighting; nanosuit->setRenderStates(nanosuitStates); } // create grass or windows { // TODO: windows need to be sorted or else produce wrong results ResourceManager::loadMaterial(render::MaterialCommon::Type::COMMON, "grass"); render::MaterialCommon* grassMaterial = static_cast<render::MaterialCommon*>(ResourceManager::getMaterial("grass")); grassMaterial->specular = math::vec4(1); grassMaterial->shininess = 32.0f; resource::Texture2D* grassTexture = ResourceManager::getTexture2D("grass"); //resource::Texture2D* windowTexture = ResourceManager::getTexture2D("window"); grassMaterial->addTexture(render::MaterialCommon::TextureType::DIFFUSE, grassTexture); grassMaterial->addTexture(render::MaterialCommon::TextureType::SPECULAR, grassTexture); m_grass.setMaterial(grassMaterial); Entity* grassInstance = m_world.addEntity(); grassInstance->setDrawable(m_grass); render::RenderStates grassStates; grassStates.cullFace = false; //grassStates.blendMode = render::BlendMode::BlendAlpha; grassStates.shader = lighting; math::vec3 grassPositions[] = { math::vec3(-1.5f, -4.5f, -4.5f), math::vec3( 1.5f, -4.5f, -3.5f), math::vec3( 0.0f, -4.5f, -3.7f), math::vec3(-0.3f, -4.5f, -6.3f), math::vec3( 0.5f, -4.5f, -4.6f) }; for (UI32 i = 0; i < 5; ++i) { render::Transform grassTransform; grassTransform.translate(grassPositions[i]); grassStates.transforms.push_back(grassTransform); } grassInstance->setRenderStates(grassStates); } // reflection model /*{ Entity nanosuitReflect; nanosuitReflect.setDrawable(*model); render::Transform nanosuitReflectTransform; nanosuitReflectTransform.translate(math::vec3(0.0, -4.0, -4.0)); nanosuitReflectTransform.scale(math::vec3(2.0)); render::RenderStates nanosuitReflectStates; nanosuitReflectStates.transforms.push_back(nanosuitReflectTransform); nanosuitReflectStates.shader = reflect; nanosuitReflect.setRenderStates(nanosuitReflectStates); m_drawableInstances.push_back(nanosuitReflect); } // refraction model { Entity nanosuitRefract; nanosuitRefract.setDrawable(*model); render::Transform nanosuitRefractTransform; nanosuitRefractTransform.translate(math::vec3(2.0, -4.0, -4.0)); nanosuitRefractTransform.scale(math::vec3(2.0)); render::RenderStates nanosuitRefractStates; nanosuitRefractStates.transforms.push_back(nanosuitRefractTransform); nanosuitRefractStates.shader = refract; nanosuitRefract.setRenderStates(nanosuitRefractStates); m_drawableInstances.push_back(nanosuitRefract); }*/ core::EventManager::broadcast(render::Renderer::SetScene { &m_world } ); return true; } void Application0::update(F32 deltaTime) { // Update camera if (m_moveFront) m_camera->move(m_movementSpeed * deltaTime * m_camera->forward()); if (m_moveBack) m_camera->move(m_movementSpeed * deltaTime * -m_camera->forward()); if (m_moveLeft) m_camera->move(m_movementSpeed * deltaTime * -m_camera->right()); if (m_moveRight) m_camera->move(m_movementSpeed * deltaTime * m_camera->right()); /// FIXME: all of this should be removed from here (the renderer should be responsible for this -> use UBOs) resource::Shader* skybox = ResourceManager::getShader("skybox"); //resource::Shader* reflect = ResourceManager::getShader("reflect"); //resource::Shader* refract = ResourceManager::getShader("refract"); math::mat4 view = m_camera->view(); /* reflect->setUniform("view", view); reflect->setUniform("viewPos", m_camera->position()); refract->setUniform("view", view); refract->setUniform("viewPos", m_camera->position()); */ // Set view for skybox math::mat3 viewNoTranslate(view); math::mat4 skyboxView(viewNoTranslate); skybox->setUniform("view", skyboxView); /// FIXME: this should go into the renderer and draw after all geometry /// ???: another pass or other kind of geometry resource::Font* font = ResourceManager::getFont("sansation"); render::Text text("The Quick Brown Fox Jumps Over The Lazy Dog", *font); text.setColor(math::vec4(1,0,0,1)); text.draw(); } void Application0::shutDown() { } void Application0::operator()(const io::IOManager::KeyboardKeyPress& kp) { switch (kp.key) { case io::ODIN_KEY_ESCAPE: core::EventManager::broadcast(Engine::OnStop()); break; case io::ODIN_KEY_W: m_moveFront = true; break; case io::ODIN_KEY_A: m_moveLeft = true; break; case io::ODIN_KEY_S: m_moveBack = true; break; case io::ODIN_KEY_D: m_moveRight = true; break; default: break; } } void Application0::operator()(const io::IOManager::KeyboardKeyRelease& kr) { switch (kr.key) { case io::ODIN_KEY_W: m_moveFront = false; break; case io::ODIN_KEY_A: m_moveLeft = false; break; case io::ODIN_KEY_S: m_moveBack = false; break; case io::ODIN_KEY_D: m_moveRight = false; break; default: break; } } void Application0::operator()(const io::IOManager::MouseMove& mm) { m_camera->rotate(math::vec2(m_mouseSensitivity * mm.deltaX, m_mouseSensitivity * mm.deltaY)); } void Application0::operator()(const io::IOManager::WindowClose& state) { core::EventManager::broadcast(Engine::OnStop()); } void Application0::operator()(const io::IOManager::WindowFocus& state) { core::EventManager::broadcast(Engine::OnResume()); } void Application0::operator()(const io::IOManager::WindowDeFocus& state) { core::EventManager::broadcast(Engine::OnPause()); } void Application0::operator()(const io::IOManager::WindowIconify& state) { core::EventManager::broadcast(Engine::OnPause()); } void Application0::operator()(const io::IOManager::WindowRestore& state) { core::EventManager::broadcast(Engine::OnResume()); } } }
#include <vector> #ifndef IMG_H_ #define IMG_H_ class img { private: std::size_t width; std::size_t height; std::vector<unsigned int> massiv; unsigned int *GPU_img; void copy_to_GPU(); public: void filter(); img(const char *filename, std::size_t width, std::size_t height); img(std::size_t width, std::size_t height,unsigned int *img_mass); void save(const char *filename); int operator() (int x, int y); unsigned int* to_massiv(); std::size_t get_width(){return width;} std::size_t get_height(){return height;} std::size_t get_size(){return massiv.size()*sizeof(unsigned int);} unsigned int* get_copy_in_GPU(); ~img(); }; #endif /* IMG_H_ */
// Created on: 1993-06-23 // Created by: Jean Yves LEBEY // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TopOpeBRepDS_CurvePointInterference_HeaderFile #define _TopOpeBRepDS_CurvePointInterference_HeaderFile #include <Standard.hxx> #include <Standard_Real.hxx> #include <TopOpeBRepDS_Interference.hxx> #include <TopOpeBRepDS_Kind.hxx> #include <Standard_Integer.hxx> #include <Standard_OStream.hxx> class TopOpeBRepDS_Transition; class TopOpeBRepDS_CurvePointInterference; DEFINE_STANDARD_HANDLE(TopOpeBRepDS_CurvePointInterference, TopOpeBRepDS_Interference) //! An interference with a parameter. class TopOpeBRepDS_CurvePointInterference : public TopOpeBRepDS_Interference { public: Standard_EXPORT TopOpeBRepDS_CurvePointInterference(const TopOpeBRepDS_Transition& T, const TopOpeBRepDS_Kind ST, const Standard_Integer S, const TopOpeBRepDS_Kind GT, const Standard_Integer G, const Standard_Real P); Standard_EXPORT Standard_Real Parameter() const; Standard_EXPORT void Parameter (const Standard_Real P); DEFINE_STANDARD_RTTIEXT(TopOpeBRepDS_CurvePointInterference,TopOpeBRepDS_Interference) protected: private: Standard_Real myParam; }; #endif // _TopOpeBRepDS_CurvePointInterference_HeaderFile
// Given 2 arrays of +ve integers, add their elements into new array using recursion // Eg: A = [23,5,2,7,87] B = [4,67,2,8] --> [27,72,4,15,87] #include<iostream> using namespace std; int c[10],k=0; void sum(int a[],int b[],int n1,int n2,int i,int j) { if(i == n1 && j == n2) return; if(i == n1) { c[k++] = b[j++]; sum(a,b,n1,n2,i,j); } if(j == n2) { c[k++] = a[i++]; sum(a,b,n1,n2,i,j); } else { c[k++] = a[i++] + b[j++]; sum(a,b,n1,n2,i,j); } } int main() { int i,n1,n2; int a[10],b[10]; cout<<"Enter no of elements 1st array "; cin>>n1; cout<<"Enter 1st array "; for(i=0;i<n1;i++) { cin>>a[i]; } cout<<"\nEnter no of elements 2nd array "; cin>>n2; cout<<"Enter 2nd array "; for(i=0;i<n2;i++) { cin>>b[i]; } sum(a,b,n1,n2,0,0); cout<<"\n\nSum of arrays "; for(i=0;i<k;i++) { cout<<c[i]<<' '; } return 0; }
#include <iostream> #include <vector> using namespace std; typedef long long ll; ll t, n, q, x, y, s[100001], diff[100001], ans; vector<int> pos[100001]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> t; for (int i = 1; i <= t; i++) { cout << "Case " << i << ":" << endl; cin >> n >> q; for (int j = 1; j <= n; j++) { cin >> s[j]; pos[s[j]].push_back(j); } ans = 0; //update the diff for (int j = 1; j < n; j++) { diff[j] = abs(s[j] - s[j + 1]); ans += diff[j]; } for (int j = 1; j <= q; j++) { cin >> x >> y; //append all x pos to y pos[y].insert(pos[y].end(), pos[x].begin(), pos[x].end()); //update the diff for (auto idx = pos[x].begin(); idx != pos[x].end(); idx++) { s[*idx] = y; if (*idx == 1) { ans -= diff[1]; diff[1] = abs(s[2] - y); ans += diff[1]; continue; } if (*idx == n) { ans -= diff[n - 1]; diff[n - 1] = abs(s[n - 1] - y); ans += diff[n - 1]; continue; } ans -= diff[*idx - 1]; ans -= diff[*idx]; diff[*idx - 1] = abs(s[*idx - 1] - y); diff[*idx] = abs(s[*idx + 1] - y); ans += diff[*idx - 1]; ans += diff[*idx]; } pos[x].clear(); cout << ans << endl; } for (int j = 1; j <= 100001; j++) pos[j].clear(); } }
#include "Game.h" #include <iostream> #include "Skills.h" #include "ColorStrings.h" #include <conio.h> #include "Window.h" #include "Texture.h" #include "MapDisplay.h" std::vector<Game::Object*> Game::objects; BioMap::map_t Game::map; void Game::main() { Window::init(); TextureManager::loadparts("bob,jeff,stevie,bills", "bob.png", { 64, 64 }, { 2,2 }); Camera c; c.set({ 10, 10 }); uint8_t in; while (true) { in = _getch(); TextureManager::render("bob", { 100, 100 }); Window::update(); switch (in) { case 'e': { Window::destroy(); TextureManager::destroy(); return; } case 'w': { break; } case 's': { break; } case 'a': { break; } case 'd': { break; } } } //unsigned int selectx = 0, selecty = 0; //BioMap::map_t map = BioMap::Generator::generate(); //while (true) //{ // system("cls"); // BioMap::printMap(map, selectx, selecty); // char c = _getch(); // _getch(); // if (c) // { // switch (c) // { // case ('w'): // { // if (selecty > 0) selecty--; // break; // } // case ('a'): // { // if (selectx > 0) selectx--; // break; // } // case ('s'): // { // if (selecty < mapw - 1) selecty++; // break; // } // case ('d'): // { // if (selectx < maph - 1) selectx++; // break; // } // } // } //} //std::cin.get(); }
#include<bits/stdc++.h> #define fast ios_base::sync_with_stdio(false); cin.tie(0); #define rep(i,a,n) for(int i=a;i<n;i++) #define all(x) x.begin(),x.end() #define watch(x) cout<<#x<<" = "<<x<<endl; #define V(x) vector<x> #define P(x,y) pair<x,y> #define UMP(x,y) unordered_map<x,y> #define MP(x,y) map<x,y> #define pb push_back #define mp make_pair #define fi first #define se second #define endl "\n" #define coutd(n) cout << fixed << setprecision(n) typedef long long ll; typedef double db; typedef long double ld; const ll mod = 1000000007; using namespace std; int main(){ fast int t; cin>>t; rep(_,0,t){ int n; cin>>n; int arr[n]; rep(i,0,n) cin>>arr[i]; int best = 0, sum = 0; rep(k,0,n){ sum = max(arr[k],sum+arr[k]); best = max(best,sum); } cout << best << endl; } return 0; }
/* * PowerControllerMCB.cpp * File implementing the MCB power controller * Author: Alex St. Clair * February 2018 */ #include "PowerControllerMCB.h" PowerControllerMCB::PowerControllerMCB() { // pin setup and disable level wind at startup pinMode(MC2_ENABLE_PIN, OUTPUT); pinMode(MTR2_ENABLE_PIN, OUTPUT); LevelWindOff(); // pin setup and disable reel at startup pinMode(MC1_ENABLE_PIN, OUTPUT); pinMode(MTR1_ENABLE_PIN, OUTPUT); ReelOff(); // setup and disable shared logic enable pinMode(MC_ENABLE_PIN, OUTPUT); digitalWrite(MC_ENABLE_PIN, LOW); // setup and disable the brake enable pin pinMode(BRAKE_ENABLE_PIN, OUTPUT); digitalWrite(BRAKE_ENABLE_PIN, LOW); } void PowerControllerMCB::ReelOn() { digitalWrite(MC_ENABLE_PIN, HIGH); delay(100); digitalWrite(MC1_ENABLE_PIN, HIGH); delay(100); digitalWrite(MTR1_ENABLE_PIN, HIGH); delay(100); digitalWrite(BRAKE_ENABLE_PIN, HIGH); } void PowerControllerMCB::ReelOff() { digitalWrite(MC1_ENABLE_PIN, LOW); digitalWrite(MTR1_ENABLE_PIN, LOW); digitalWrite(BRAKE_ENABLE_PIN, LOW); // if the level wind controller is on, turn it off too if (!digitalRead(MC2_ENABLE_PIN)) { LevelWindOff(); } digitalWrite(MC_ENABLE_PIN, LOW); } void PowerControllerMCB::LevelWindOn() { // need the reel on for the level wind if (!digitalRead(MC1_ENABLE_PIN)) { ReelOn(); } digitalWrite(MC2_ENABLE_PIN, LOW); delay(100); digitalWrite(MTR2_ENABLE_PIN, HIGH); } void PowerControllerMCB::LevelWindOff() { digitalWrite(MC2_ENABLE_PIN, HIGH); digitalWrite(MTR2_ENABLE_PIN, LOW); }
using namespace std; string to_hex(unsigned char s); string sha256(string line);
#include "AIntervalService.hpp" AIntervalService::AIntervalService(boost::asio::io_service &ioService, std::size_t seconds) : _started(false), _timer(ioService), _interval(seconds) {} void AIntervalService::start() { if (this->_started) { return ; } this->_started = true; this->run(); } void AIntervalService::run() { this->_timer.expires_from_now(this->_interval); this->_timer.async_wait([this](boost::system::error_code const &ec) { this->service(ec); this->run(); }); } void AIntervalService::stop() { this->_started = false; if (this->_started) { this->_timer.cancel(); } }