text
stringlengths
8
6.88M
#include "stdafx.h" //________________________________________ CalculadoraIMC.cpp #include "CalculadoraIMC.h" int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR cmdLine, int cmdShow) { CalculadoraIMC app; return app.BeginDialog(IDI_CalculadoraIMC, hInstance); } void CalculadoraIMC::Window_Open(Win::Event& e) { //________________________________________________________ lsIMC lsIMC.StateCount = 4; lsIMC.SetState(0, 0.0, 20.5, RGB(255,0,0), L"Bajo de peso"); lsIMC.SetState(1, 20.5, 25.5, RGB(255,255,0), L"Normal"); lsIMC.SetState(2, 25.5, 30.5, RGB(0,128,0), L"Sobrepeso"); lsIMC.SetState(3, 30.5, 45.0, RGB(0,0, 255), L"Normal"); lsIMC.Level = 20.0; this->radioHombre.Checked = true; this->radioMujer.Checked = false; } void CalculadoraIMC::btCalcular_Click(Win::Event& e) { const double peso = tbxPeso.DoubleValue; const double altura = tbxAltura.DoubleValue; double IMC = peso / (altura*altura); if (radioHombre.Checked == true) { lsIMC.SetState(0, 0.0, 20.5, RGB(255, 0, 0), L"Bajo de pedo"); lsIMC.SetState(1, 20.5, 25.5, RGB(255, 255, 0), L"Normal"); lsIMC.SetState(2, 25.5, 30.5, RGB(0, 128, 0), L"Sobrepeso"); lsIMC.SetState(3, 30.5, 45.0, RGB(0, 0, 255), L"Obesidad"); lsIMC.Level = IMC; } else { lsIMC.SetState(0, 0.0, 20.5, RGB(255, 0, 0), L"Bajo de paso"); lsIMC.SetState(1, 20.5, 24.5, RGB(255, 255, 0), L"Normal"); lsIMC.SetState(2, 24.5, 29.5, RGB(0, 128, 0), L"Sobrepeso"); lsIMC.SetState(3, 29.5, 45.0, RGB(0, 0, 255), L"Obesidad"); lsIMC.Level = IMC; } }
#include "RObjA.hpp" RObjA::RObjA() { } RObjA::~RObjA() { } // Relaxed include should moc the header instead #include "RObjA.moc"
#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 showmap(is, js, x) {rep(i, is){rep(j, js){cout << x[i][j] << " ";}cout << endl;}} #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; typedef pair<ll, ll> llP; 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);} int main() { int n; cin >> n; ll p = 1; ll m = -1; vector<ll> th; ll bai = 1; vector<ll> m2; const int max_bit = 35; rep(i, max_bit){ m2.push_back(bai); if (i%2 == 0){ th.push_back(p); p += bai; } else { th.push_back(m); m += bai; } bai *= -2; } // show(th); ll nn = n; vector<int> bit(max_bit, 0); for (int i = max_bit - 1; i >= 0; i--) { if (i%2 == 0){ if (th[i] <= nn) {nn -= m2[i]; bit[i] = 1;} } else { if (th[i] >= nn) {nn -= m2[i]; bit[i] = 1;} } } //show(bit); bool iswrite = false; for (int i = max_bit - 1; i >= 0; i--) { if (bit[i] == 1){ iswrite = true; } if (iswrite) cout << bit[i]; } if (!iswrite) {cout << 0 << endl; return 0;} cout << endl; }
/* * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/types.hpp> namespace cudf { namespace experimental { /** * @brief Base class for specifying the desired aggregation in an * `aggregation_request`. * * Other kinds of aggregations may derive from this class to encapsulate * additional information needed to compute the aggregation. */ class aggregation { public: /** * @brief Possible aggregation operations */ enum Kind { SUM, MIN, MAX, COUNT, MEAN, MEDIAN, QUANTILE }; aggregation(aggregation::Kind a) : kind{a} {} Kind kind; ///< The aggregation to perform }; namespace detail { /** * @brief Derived class for specifying a quantile aggregation */ struct quantile_aggregation : aggregation { quantile_aggregation(std::vector<double> const& q, experimental::interpolation i) : aggregation{QUANTILE}, _quantiles{q}, _interpolation{i} {} std::vector<double> _quantiles; ///< Desired quantile(s) experimental::interpolation _interpolation; ///< Desired interpolation }; } // namespace detail } // namespace experimental } // namespace cudf
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * 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 Petter Nilsen (pettern@opera.com) */ #include "core/pch.h" #include "adjunct/quick/widgets/OpToolbarMenuButton.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/quick-widget-names.h" #include "adjunct/desktop_util/resources/pi/opdesktopproduct.h" #include "modules/locale/locale-enum.h" #include "modules/locale/oplanguagemanager.h" /*********************************************************************************** ** Construct. ** ************************************************************************************/ OP_STATUS OpToolbarMenuButton::Construct(OpToolbarMenuButton** obj, OpButton::ButtonStyle button_style) { *obj = OP_NEW(OpToolbarMenuButton, (button_style)); if (*obj == NULL) return OpStatus::ERR_NO_MEMORY; if (OpStatus::IsError((*obj)->init_status)) { OP_DELETE(*obj); return OpStatus::ERR_NO_MEMORY; } return OpStatus::OK; } /*********************************************************************************** ** Constructor. ** ************************************************************************************/ OpToolbarMenuButton::OpToolbarMenuButton(OpButton::ButtonStyle button_style) : OpButton(TYPE_CUSTOM) { Init(); } OpToolbarMenuButton::OpToolbarMenuButton(const OpToolbarMenuButton & menu_button) : OpButton(TYPE_CUSTOM) { Init(); } void OpToolbarMenuButton::Init() { SetSkinned(TRUE); SetFixedTypeAndStyle(TRUE); OpInputAction* action = #ifdef QUICK_NEW_OPERA_MENU OP_NEW(OpInputAction, (OpInputAction::ACTION_SHOW_MENU)); #else OP_NEW(OpInputAction, (OpInputAction::ACTION_SHOW_HIDDEN_POPUP_MENU)); #endif // QUICK_NEW_OPERA_MENU if (action) { #ifndef QUICK_NEW_OPERA_MENU action->SetActionDataString(UNI_L("Browser Button Menu Bar")); #endif // QUICK_NEW_OPERA_MENU OpString title; g_languageManager->GetString(Str::SI_MENU_BUTTON_TEXT, title); // Specify that action comes from keyboard. The menu action will then be executed in the keyboard // context (DSK-287242). See IsInputContextAvailable() below. Both are needed for this to work action->SetActionMethod(OpInputAction::METHOD_KEYBOARD); action->GetActionInfo().SetStatusText(title.CStr()); SetAction(action); } const uni_char* title = NULL; switch (g_desktop_product->GetProductType()) { case PRODUCT_TYPE_OPERA_LABS: title = UNI_L("Opera Labs"); break; case PRODUCT_TYPE_OPERA_NEXT: title = UNI_L("Opera Next"); break; default: title = UNI_L("Opera"); break; } SetSkin(); SetText(title); SetName(WIDGET_NAME_MENU_BUTTON); } void OpToolbarMenuButton::SetSkin() { switch (g_desktop_product->GetProductType()) { case PRODUCT_TYPE_OPERA_LABS: GetBorderSkin()->SetImage("Main Menu Labs Toolbar Button Skin", "Toolbar Button Skin"); GetForegroundSkin()->SetImage("Main Menu Labs"); break; case PRODUCT_TYPE_OPERA_NEXT: GetBorderSkin()->SetImage("Main Menu Next Toolbar Button Skin", "Toolbar Button Skin"); GetForegroundSkin()->SetImage("Main Menu Next"); break; default: GetBorderSkin()->SetImage("Main Menu Toolbar Button Skin", "Toolbar Button Skin"); GetForegroundSkin()->SetImage("Main Menu"); break; } } void OpToolbarMenuButton::UpdateButton(OpButton::ButtonStyle button_style) { SetButtonTypeAndStyle(OpButton::TYPE_CUSTOM, button_style); // changing the style changes the skin, so make sure we reset it here again SetSkin(); } void OpToolbarMenuButton::GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows) { GetInfo()->GetPreferedSize(this, OpTypedObject::WIDGET_TYPE_BUTTON, w, h, cols, rows); } BOOL OpToolbarMenuButton::OnContextMenu(const OpPoint &point, BOOL keyboard_invoked) { return OpButton::OnContextMenu(point, NULL, keyboard_invoked); } BOOL OpToolbarMenuButton::IsInputContextAvailable(FOCUS_REASON reason) { // Keep focus and context activation away from this button. It will interfere // with the context where we want an action to take place (DSK-287242). See also // SetAction() above return FALSE; } BOOL OpToolbarMenuButton::OnInputAction(OpInputAction* action) { switch (action->GetAction()) { case OpInputAction::ACTION_GET_ACTION_STATE: { OpInputAction* child_action = action->GetChildAction(); switch (child_action->GetAction()) { case OpInputAction::ACTION_REMOVE: { child_action->SetEnabled(FALSE); return TRUE; } } } } return FALSE; }
#pragma once #include "stdafx.h" #include <memory> #define SISÄINENHINTA 3.0 // vaihtoehto 2: const float HELSINKIHINTA = 3.0; // C++:n nimetty vakio #define SEUTUHINTA 4.8 using namespace std; enum Matkatyyppi {SISÄINEN, SEUTU}; class Matkakortti { private: /* string *omistajanNimi; // T4 float *saldo; // T4 */ std::unique_ptr<string> omistajanNimi; std::unique_ptr<float> saldo; public: Matkakortti(); void lataaSaldo(float raha); void alusta(string rivi, float raha); bool matkusta(enum Matkatyyppi tyyppi); //void tulostaTiedot(); // ongelma: matkakortti ei suoraan saisi tulostaa kl:ään string palautaNimi(); float palautaSaldo(); ~Matkakortti(); };
#include "basicLocator.h" #include "basicLocatorManip.h" #include <maya/MFnPlugin.h> MStatus initializePlugin(MObject obj) { MStatus stat; MString errStr; MFnPlugin plugin(obj, "jason.li", "1.0", "Any"); stat = plugin.registerNode(BasicLocator::typeName, BasicLocator::typeId, &BasicLocator::creator, &BasicLocator::initialize, MPxNode::kLocatorNode); if (!stat) { errStr = "registerNode failed"; goto error; } stat = plugin.registerNode(BasicLocatorManip::typeName, BasicLocatorManip::typeId, &BasicLocatorManip::creator, &BasicLocatorManip::initialize, MPxNode::kManipContainer); if (!stat) { errStr = "registerNode failed"; goto error; } return stat; error: stat.perror(errStr); return stat; } MStatus uninitializePlugin(MObject obj) { MStatus stat; MString errStr; MFnPlugin plugin(obj, "jason.li", "1.0", "Any"); stat = plugin.deregisterNode(BasicLocator::typeId); if (!stat) { errStr = "deregisterNode failed"; goto error; } stat = plugin.deregisterNode(BasicLocatorManip::typeId); if (!stat) { errStr = "deregisterNode failed"; goto error; } return stat; error: stat.perror(errStr); return stat; }
#define _CRT_SECURE_NO_WARNINGS #include <GL/glew.h> #include <GLFW/glfw3.h> #include "mat.h" #include "vec.h" #include "InitShader.h" #include <iostream> #include "glm/glm/glm.hpp" #include "glm/glm/gtc/matrix_transform.hpp" #define BUFFER_OFFSET( offset ) ((GLvoid*) (offset)) void gasketSetKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); void gasketSetMouseButtonCallback(GLFWwindow* window, int button, int action, int mods); void idle(); int left_click = 0; float anglex = 0.0; float angley = 0.0; float anglez = 0.0; int flag = 1; //0:회전 1:멈춤 mat4 rotation; int main() { char check[100]; int vertexNum = 0; int faceNum = 0; FILE* file; int flag; int vertIndex = 0; int faceIndex = 0; printf("bunny(1) cube(2) dragon(3) buddha(4): "); scanf("%d", &flag); if (flag == 1) { file = fopen("bunny.obj", "r"); } else if (flag == 2) { file = fopen("cube.obj", "r"); } else if (flag == 3) { file = fopen("dragon.obj", "r"); } else { file = fopen("buddha.obj", "r"); } while (!feof(file)) { fscanf(file, "%s", check); if (check[0] == 'v' && check[1] == '\0') vertexNum += 1; else if (check[0] == 'f' && check[1] == '\0') faceNum += 1; memset(check, '\0', sizeof(check)); } vec4 *vertex; vec4 *face; vertex = (vec4 *)malloc(sizeof(vec4) * vertexNum); face = (vec4 *)malloc(sizeof(vec4) * faceNum); if (flag == 1) { file = fopen("bunny.obj", "r"); } else if (flag == 2) { file = fopen("cube.obj", "r"); } else if (flag == 3) { file = fopen("dragon.obj", "r"); } else { file = fopen("buddha.obj", "r"); } while (!feof(file)) { fscanf(file, "%s", check); if (check[0] == 'v' && check[1] == '\0') { fscanf(file, "%f %f %f", &vertex[vertIndex].x, &vertex[vertIndex].y, &vertex[vertIndex].z); vertIndex++; } else if (check[0] == 'f' && check[1] == '\0') { fscanf(file, "%f %f %f", &face[faceIndex].x, &face[faceIndex].y, &face[faceIndex].z); faceIndex++; } } GLFWwindow* window; //window 포인터 선언 if (!glfwInit()) //glfw 라이브러리 초기화 return -1; window = glfwCreateWindow(512, 512, "Hello World", NULL, NULL); //window 생성 if (!window) //window 생성 실패 시 프로그램 종료 { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); //매개변수 window 를 도화지를 삼아 그림을 그림 if (glewInit() != GLEW_OK) std::cout << "Error\n"; // glew 라이브러리 초기화 및 초기화 실패 시 에러 메세지 // glew 라이브러리는 반드시 window context 생성 후 초기화 아니면 에러 /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// float* positions = (float *)malloc(sizeof(float) * 3 * vertIndex); int position_index = 0; for (int i = 0; i < vertIndex; i++) { positions[position_index] = vertex[i].x; position_index++; positions[position_index] = vertex[i].y; position_index++; positions[position_index] = vertex[i].z; position_index++; } int* indices = (int *)malloc(sizeof(int) * 3 * faceIndex); int indices_index = 0; for (int i = 0; i < faceIndex; i++) { indices[indices_index] = face[i].x - 1; indices_index++; indices[indices_index] = face[i].y - 1; indices_index++; indices[indices_index] = face[i].z - 1; indices_index++; } GLuint va; // vertex array 선언, 메모리 할당, 바인드 glGenVertexArrays(1, &va); glBindVertexArray(va); GLuint vb; // vertex buffer 선언, 메모리 할당, 바인드, data가 구성된 형식에 맞게 buffer data 준비 glGenBuffers(1, &vb); glBindBuffer(GL_ARRAY_BUFFER, vb); glBufferData(GL_ARRAY_BUFFER, vertIndex * 3 * sizeof(float), positions, GL_STATIC_DRAW); // (vertex 갯수)*(각 vertex의 요소 갯수)*(각 요소 데이터 타입의 크기) GLuint ib; // index buffer, 선언, 메모리 할당, 바인드, data가 구성된 형식에 맞게 buffer data 준비 glGenBuffers(1, &ib); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib); glBufferData(GL_ELEMENT_ARRAY_BUFFER, faceIndex * 3 * sizeof(unsigned int), indices, GL_STATIC_DRAW); // (삼각형 갯수)*(각 삼각형에 필요한 vertex 갯수)*(각 요소 데이터 타입의 크기) GLuint program = InitShader("vshader.glsl", "fshader.glsl"); // shader program 가져오기 glUseProgram(program); // 어떤 shader program을 사용할 것인지 GLuint location = glGetAttribLocation(program, "vPosition"); // position vertex에 대한 정보를 shader program 안의 어떤 변수와 연결시킬 것인가 glEnableVertexAttribArray(location); glVertexAttribPointer(location, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glfwSetKeyCallback(window, gasketSetKeyCallback); glfwSetMouseButtonCallback(window, gasketSetMouseButtonCallback); /////////////////////////////////////////////////////////////////////////// // window 창이 종료될 때까지 무한루프 while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); rotation = RotateX(anglex)*RotateY(angley)*RotateZ(anglez); GLuint uMat = glGetUniformLocation(program, "uMat"); glUniformMatrix4fv(uMat, 1, GL_FALSE, rotation); idle(); ////////////////////////////////////////////////////////////////////// glDrawElements(GL_TRIANGLES, 3 * faceIndex, GL_UNSIGNED_INT, NULL); // 삼각형 정보가 들어있는 indices 배열을 차례로 읽어 3개씩 하나의 삼각형을 위한 index으로 묶고, // index에 해당하는 vertex 정보를 positions 배열에서 찾아오는 방식. ////////////////////////////////////////////////////////////////////// glfwSwapBuffers(window); // front buffer와 back buffer 교체 glfwPollEvents(); } glfwTerminate(); return 0; } void idle() { if (flag % 2 == 0) { if (left_click % 3 == 0) //z { anglez = anglez + 0.1f; } else if (left_click % 3 == 1) //x { anglex = anglex + 0.1f; } else if (left_click % 3 == 2) //y { angley = angley + 0.1f; } } } void gasketSetKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) { std::cout << "Key space is pressed\n"; flag++; } } void gasketSetMouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) { std::cout << "Left button is pressed\n"; left_click++; } }
#ifndef QROSCALLBACKQUEUE_H #define QROSCALLBACKQUEUE_H #include <QObject> #include <ros/callback_queue.h> #include <QSocketNotifier> class QRosCallBackQueue : public QObject, public ros::CallbackQueue{ Q_OBJECT public: QRosCallBackQueue(); virtual ~QRosCallBackQueue(); virtual void addCallback(const ros::CallbackInterfacePtr &callback, uint64_t owner_id); static void termSignalHandler(int signal); static void replaceGlobalQueue(); protected slots: void handleSigTerm(); void processCallbacks(void); signals: void onCallback(); private : static int m_sigtermFd[2]; QSocketNotifier* m_snTerm; }; #endif // QROSCALLBACKQUEUE_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ /** @file blockbox.h * * Inline box class prototypes for document layout. * * @author Geir Ivars°y * @author Karl Anders ěygard * */ #ifndef _BLOCKBOX_H_ #define _BLOCKBOX_H_ #include "modules/layout/content/content.h" #include "modules/style/css_all_values.h" /** Block box. */ class BlockBox : public VerticalBox, public VerticalLayout { private: /** Set the left and top CSS properties of positioned boxes, since these values need to be cached. */ virtual void SetRelativePosition(LayoutCoord new_left, LayoutCoord new_top) {} protected: union { struct { /** Can/must we break page before this block? See type BREAK_POLICY. */ unsigned int page_break_before:3; /** Can/must we break page after this block? See type BREAK_POLICY. */ unsigned int page_break_after:3; /** Can/must we break column before this block? See type BREAK_POLICY. */ unsigned int column_break_before:2; /** Can/must we break column after this block? See type BREAK_POLICY. */ unsigned int column_break_after:2; /** Has this block specified an absolute width? */ unsigned int has_absolute_width:1; /** Has this block a fixed left position? (not percent values for left margin and parent left border and padding) */ unsigned int has_fixed_left:1; /** Block box has clearance. This member is only used during reflow and can be moved to reflow_state if you need the space. */ unsigned int has_clearance:1; /** TRUE if this block spans all columns in a multi-column-container. */ unsigned int column_spanned:1; /** TRUE if this block lives in a paged or multicol container. */ unsigned int in_multipane:1; /** TRUE if this block is laid out on a line, logically. */ unsigned int on_line:1; } packed; unsigned long packed_init; }; /** X position of box. */ LayoutCoord x; /** Y position of box. */ LayoutCoord y; /** Y position if maximum width is satisfied. */ LayoutCoord min_y; /** Position on the virtual line the box was laid out on. Only useful if TraverseInLine() returns TRUE. Used to optimize logical line traversal. */ LayoutCoord virtual_position; /** Invalidate the bounding box during reflow. Assumes that the translation/transformation is at the parent. */ void InvalidateBoundingBox(LayoutInfo &info, LayoutCoord offset_x, LayoutCoord offset_y) const; public: BlockBox(HTML_Element* element, Content* content); virtual ~BlockBox() { Link::Out(); } /** Recalculate the top margin after a new block box has been added to a container's layout stack. Collapse the margin with preceding adjacent margins if appropriate. If the top margin of this block is adjacent to an ancestor's top margin, it may cause the ancestor's Y position to change. If the top margin of this block is adjacent to a preceding sibling's bottom margin, this block may change its Y position. @return TRUE if the Y position of any element was changed. */ virtual BOOL RecalculateTopMargins(LayoutInfo& info, const VerticalMargin* top_margin, BOOL has_bottom_margin = FALSE); /** Layout of this box is finished (or skipped). Propagate changes (bottom margins, bounding-box) to parents. This may grow the box, which in turn may cause its parents to be grown. Bottom margins may participate in margin collapsing with successive content, but only if this box is part of the normal flow. In that case, propagate the bottom margin to the reflow state of the container of this box. Since this member function is used to propagate bounding boxes as well, we may need to call it even when box is empty and is not part of the normal flow. To protect against margins being propagated and parent container reflow position updated in such case, 'has_inflow_content' flag has been introduced in order to notify container that this box is not a part of normal flow but has bounding box that still needs to be propagated. Separation of bounding box propagation and margin/reflow state update should be considered. */ virtual void PropagateBottomMargins(LayoutInfo& info, const VerticalMargin* bottom_margin = 0, BOOL has_inflow_content = TRUE); /** Expand relevant parent containers and their bounding-boxes to contain floating and absolutely positioned boxes. A call to this method is only to be initiated by floating or absolutely positioned boxes. @param info Layout information structure @param bottom Only relevant for floats: The bottom margin edge of the float, relative to top border-edge of this box. @param min_bottom Only relevant for floats: The bottom margin edge of the float if maximum width of its container is satisfied @param child_bounding_box Bounding-box of the propagating descendant, joined with the bounding-boxes of the elements up the parent chain towards this element. Relative to the top border-edge of this box. @param opts Bounding box propagation options */ virtual void PropagateBottom(const LayoutInfo& info, LayoutCoord bottom, LayoutCoord min_bottom, const AbsoluteBoundingBox& child_bounding_box, PropagationOptions opts); /** Propagate the right edge of absolute positioned boxes. Used for FlexRoot. */ virtual void PropagateRightEdge(const LayoutInfo& info, LayoutCoord right, LayoutCoord noncontent, LayoutFixed percentage); /** Propagate a break point caused by break properties or a spanned element. These are discovered during layout, and propagated to the nearest multicol container when appropriate. They are needed by the columnizer to do column balancing. @param virtual_y Virtual Y position of the break (relative to the top border edge of this box) @param break_type Type of break point @param breakpoint If non-NULL, it will be set to the MultiColBreakpoint created, if any. @return FALSE on OOM, TRUE otherwise. */ virtual BOOL PropagateBreakpoint(LayoutCoord virtual_y, BREAK_TYPE break_type, MultiColBreakpoint** breakpoint); /** Get width available for the margin box. */ virtual LayoutCoord GetAvailableWidth(LayoutProperties* cascade); /** Set X position of block box. */ void SetX(LayoutCoord new_x) { x = new_x; } /** Set Y position of block box. */ virtual void SetY(LayoutCoord new_y) { y = new_y; } /** Get box X position, relative to parent. */ LayoutCoord GetX() const { return x; } /** Get box Y position, relative to parent. */ virtual LayoutCoord GetStackPosition() const { return y; } /** Get box Y position, relative to parent. */ LayoutCoord GetY() const { return y; } /** Get and add the normal flow position of this box to the supplied coordinate variables. */ virtual void AddNormalFlowPosition(LayoutCoord &x, LayoutCoord &y) const { x += this->x; y += this->y; } /** Get height of content. */ virtual LayoutCoord GetLayoutHeight() const; /** Get height if maximum width is satisfied. */ virtual LayoutCoord GetLayoutMinHeight() const; /** Finish reflowing box. */ virtual LAYST FinishLayout(LayoutInfo& info); /** Update screen. */ virtual void UpdateScreen(LayoutInfo& info); /** Invalidate the screen area that the box uses. */ virtual void Invalidate(LayoutProperties* parent_cascade, LayoutInfo& info) const; /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Is this box a block box? */ virtual BOOL IsBlockBox() const { return TRUE; } /** Is this box (and potentially also its children) columnizable? A box may only be columnizable if it lives in a paged or multicol container. A descendant of a box that isn't columnizable can never be columnizable (unless there's a new paged or multicol container between that box and its descendant). Table-rows, table-captions, table-row-groups and block-level descendant boxes of a paged or multicol container are typically columnizable. Being columnizable means that they need to be taken into account by the ancestor paged or multicol container somehow. They may become a start or stop element of a column or page. It may also be possible to split them over multiple columns or pages, but that depends on details about the box type, and that is where the "require_children_columnizable" parameter comes into play. @param require_children_columnizable If TRUE, only return TRUE if this box is of such a type that not only the box itself is columnizable, but also that it doesn't prevent its children from becoming columnizable. A table-row, block with scrollbars, absolutely-positioned box or float prevents children from being columnizable (FALSE will be returned it this parameter is TRUE), but the box itself may be very well be columnizable. Example: an absolutely positioned box may live inside of a paged or multicol container (so that its Y position is stored as a virtual Y position within the paged or multicol container), but its descendants do not have to worry about the multi-columnness or multi-pagedness. @return TRUE if this box (and possibly its children too) is columnizable. Return FALSE if this box isn't columnizable, or if require_children_columnizable is set and the children aren't columnizable. */ virtual BOOL IsColumnizable(BOOL require_children_columnizable = FALSE) const; /** Specify whether this block logically sits on a line or not. Even if it is considered to sit "on a line", it still gets an entry in the vertical layout stack, as long as it's not absolutely positioned. If this is a float, it is placed before the line. Otherwise (if it's in-flow), it's placed after the line (as usual). */ void SetOnLine(BOOL on_line) { packed.on_line = !!on_line; } /** Traverse box with children. This method will traverse the contents of this box and its children, recursively. */ virtual void Traverse(TraversalObject* traversal_object, LayoutProperties* parent_lprops, HTML_Element* containing_element); /** Traverse z children. */ virtual void TraverseZChildren(TraversalObject* traversal_object, LayoutProperties* layout_props, BOOL after, BOOL handle_overflow_clip) {} /** Has z children with negative z-index */ virtual BOOL HasNegativeZChildren() { return FALSE; } /** Traverse box with children. This method will traverse this inline element and its children. It will only traverse the part of the virtual line that the elements have been laid out on indicated by position and length. */ virtual BOOL LineTraverseBox(TraversalObject* traversal_object, LayoutProperties* parent_lprops, LineSegment& segment, LayoutCoord baseline); /** Get position on the virtual line the box was laid out on. */ virtual LayoutCoord GetVirtualPosition() const { return virtual_position; } /** Set position on the virtual line the box was laid out on. */ void SetVirtualPosition(LayoutCoord x) { virtual_position = x; } /** Is this box traversed within a line? */ virtual BOOL TraverseInLine() const { return !!packed.on_line; } #ifdef PAGED_MEDIA_SUPPORT /** Insert a page break. */ virtual BREAKST InsertPageBreak(LayoutInfo& info, int strength); /** Attempt to break page. */ virtual BREAKST AttemptPageBreak(LayoutInfo& info, int strength); #endif // PAGED_MEDIA_SUPPORT /** Get baseline of vertical layout. @param last_line TRUE if last line baseline search (inline-block case). */ virtual LayoutCoord GetBaseline(BOOL last_line = FALSE) const; /** Propagate widths to container / table. */ virtual void PropagateWidths(const LayoutInfo& info, LayoutCoord min_width, LayoutCoord normal_min_width, LayoutCoord max_width); /** Is this a block? */ virtual BOOL IsBlock() const { return TRUE; } /** Is this an element that logically belongs in the stack? */ virtual BOOL IsInStack(BOOL include_floats = FALSE) const { return TRUE; } /** Calculate bottom margins of layout element, by collapsing with adjoining child margins. * This is only done when skipping layout of a box. * @param parent_cascade parent properties * @param info Layout information structure * @param bottom_margin Margin state * @return OpBoolean::IS_FALSE if top and bottom margins of this element are adjoining, * OpBoolean::IS_TRUE otherwise, unless an error occurred. */ virtual OP_BOOLEAN CalculateBottomMargins(LayoutProperties* parent_cascade, LayoutInfo& info, VerticalMargin* bottom_margin) const; /** Calculate top margins of layout element, by collapsing with adjoining child margins. * This is only done when skipping layout of a box. * @param parent_cascade parent properties * @param info Layout information structure * @param top_margin Margin state * @return OpBoolean::IS_FALSE if top and bottom margins of this element are adjoining, * OpBoolean::IS_TRUE otherwise, unless an error occurred. */ virtual OP_BOOLEAN CalculateTopMargins(LayoutProperties* parent_cascade, LayoutInfo& info, VerticalMargin* top_margin) const; /** Set page and column breaking policies on this block box. */ void SetBreakPolicies(BREAK_POLICY page_break_before, BREAK_POLICY column_break_before, BREAK_POLICY page_break_after, BREAK_POLICY column_break_after); #ifdef PAGED_MEDIA_SUPPORT /** Get page break policy before this layout element. */ virtual BREAK_POLICY GetPageBreakPolicyBefore() const { return (BREAK_POLICY) packed.page_break_before; } /** Get page break policy after this layout element. */ virtual BREAK_POLICY GetPageBreakPolicyAfter() const { return (BREAK_POLICY) packed.page_break_after; } #endif // PAGED_MEDIA_SUPPORT /** Get column break policy before this layout element. */ virtual BREAK_POLICY GetColumnBreakPolicyBefore() const { return (BREAK_POLICY) packed.column_break_before; } /** Get column break policy after this layout element. */ virtual BREAK_POLICY GetColumnBreakPolicyAfter() const { return (BREAK_POLICY) packed.column_break_after; } /** Is this a True Table candidate? */ virtual TRUE_TABLE_CANDIDATE IsTrueTableCandidate() const { return content->IsTrueTableCandidate(); } /** Has this box specified an absolute width? */ virtual BOOL HasAbsoluteWidth() const { return packed.has_absolute_width; } /** Has this block a fixed left position? (not percent values for left margin and parent left border and padding) */ BOOL HasFixedLeft() const { return packed.has_fixed_left; } /** Set that this block has a fixed left position. (not percent values for left margin and parent left border and padding) */ void SetHasFixedLeft() { packed.has_fixed_left = 1; } /** Set that this block has clearance (clear had effect on position). */ void SetHasClearance() { packed.has_clearance = TRUE; } /** * Move this VerticalLayout and all its content down by an offset. * * @param offset_y Offset to move down * @param containing_element. Element of the container for this vertical layout. Not used in this implementation. */ virtual void MoveDown(LayoutCoord offset_y, HTML_Element* containing_element) { y += offset_y; } /** Distribute content into columns. @return FALSE on OOM, TRUE otherwise. */ virtual BOOL Columnize(Columnizer& columnizer, Container* container); /** Figure out to which column(s) or spanned element a box belongs. */ virtual void FindColumn(ColumnFinder& cf, Container* container); /** Set minimum Y position. This is the position this block would get if maximum width of its shrink-to-fit block formatting context is satisfied). */ void SetMinY(LayoutCoord y) { min_y = y; } /** Get minimum Y position. This is the position this block would get if maximum width of its shrink-to-fit block formatting context is satisfied). */ LayoutCoord GetMinY() const { return min_y; } /** Has this box clearance applied */ BOOL HasClearance() const { return packed.has_clearance; } /** Return TRUE if this block spans all columns in a multi-column-container. */ BOOL IsColumnSpanned() const { return packed.column_spanned == 1; } /** Return TRUE if this block is inside of a paged or multicol container. */ BOOL IsInMultiPaneContainer() const { return packed.in_multipane == 1; } /** Signal that content may have changed. */ virtual void SignalChange(FramesDocument* doc, BoxSignalReason reason = BOX_SIGNAL_REASON_UNKNOWN); /** Is this an empty list item that has a marker? */ BOOL IsEmptyListItemWithMarker() const { return HasListMarkerBox() && content->IsEmpty(); } }; /** Vertical box reflow state. */ class AbsolutePositionedBoxReflowState : public VerticalBoxReflowState { public: /** Previous x translation. */ LayoutCoord previous_x_translation; /** Previous y translation. */ LayoutCoord previous_y_translation; /** The box that establishes the containing block of this box. */ Box* containing_box; /** Width of containing block. */ LayoutCoord containing_block_width; /** Width available for this box. This is set if width is non-fixed. */ LayoutCoord available_width; /** Static position within the container. This is set when position is auto. It represents the distance from the container's border edge to the margin edge of this box (for LTR, the edges will be the left edge, and for RTL, the edges will be the right edge). */ LayoutCoord static_position; /** Left border of containing block. */ short containing_border_left; /** horizontal position was static before reflow. */ BOOL x_was_static; /** vertical position was static before reflow. */ BOOL y_was_static; AbsolutePositionedBoxReflowState() : previous_x_translation(0), previous_y_translation(0), containing_box(NULL), static_position(0), containing_border_left(0), x_was_static(FALSE), y_was_static(FALSE) {} void* operator new(size_t nbytes) OP_NOTHROW { return g_absolutebox_reflow_state_pool->New(sizeof(AbsolutePositionedBoxReflowState)); } void operator delete(void* p, size_t nbytes) { g_absolutebox_reflow_state_pool->Delete(p); } }; class FLink; class FloatingBox; /** List of floats. Either belongs to a SpaceManager or to a temporary list used during reflow. */ class FloatList : public Head { public: FLink* First() const { return (FLink*) Head::First(); } FLink* Last() const { return (FLink*) Head::Last(); } /** Force full reflow of this block formatting context. */ virtual void ForceFullBfcReflow() = 0; }; /** Reflow state for a SpaceManager. Holds a list of floats that existed in this block formatting context prior to reflow. They will be moved back into the SpaceManager as they are encountered (or skipped) during reflow (unless they are deleted). */ class SpaceManagerReflowState : public FloatList { public: /** TRUE if all blocks in this block formatting context need to be reflowed (because of floats). */ BOOL full_bfc_reflow; /** TRUE if all blocks in this block formatting context have to recalculate their min/max widths (because of floats). */ BOOL full_bfc_min_max_calculation; SpaceManagerReflowState() : full_bfc_reflow(FALSE), full_bfc_min_max_calculation(FALSE) {} ~SpaceManagerReflowState(); /** Force full reflow of this block formatting context. */ virtual void ForceFullBfcReflow() { full_bfc_reflow = full_bfc_min_max_calculation = TRUE; } void* operator new(size_t nbytes) OP_NOTHROW { return g_spacemanager_reflow_state_pool->New(sizeof(SpaceManagerReflowState)); } void operator delete(void* p, size_t nbytes) { g_spacemanager_reflow_state_pool->Delete(p); } }; /** Space manager. The space manager keeps track of floats, etc. and gives out space for the block boxes to lay out lines and boxes into. Each block formatting context root has its own space manager. */ class SpaceManager : public FloatList { private: /** Reflow state. Present while the box to which this SpaceManager belongs is reflowed. */ SpaceManagerReflowState* reflow_state; union { struct { /** Needs full reflow of this block formatting context. */ unsigned int full_bfc_reflow:1; } spaceman_packed; unsigned long spaceman_packed_init; }; public: SpaceManager() : reflow_state(NULL) { spaceman_packed_init = 0; } ~SpaceManager(); /** Restart space manager - prepare it for reflow. @return FALSE on memory allocation failure. */ BOOL Restart(); /** Reflow of the box associated with this space manager is finished. */ void FinishLayout(); /** Force full reflow of this block formatting context. */ virtual void ForceFullBfcReflow() { spaceman_packed.full_bfc_reflow = 1; } /** Propagate bottom margins of child floats of element. */ void PropagateBottomMargins(LayoutInfo& info, HTML_Element* element, LayoutCoord y_offset, LayoutCoord min_y_offset); /** Skip over an element. */ void SkipElement(LayoutInfo& info, HTML_Element* element); /** Add floating block box to space manager. After a float has been added to the space manager, it won't give out space that would intersect with that float. */ void AddFloat(FloatingBox* floating_box); /** Get new space from space manager. The space manager will find a suitable position for content defined by the rectangle (bfc_x, bfc_y, min_width, min_height) that does not overlap with any of the floats' (in this block formatting context) margin boxes. It may not always be possible to satisfy the space requirements (if the containing block is too narrow). However, no matter what, the position returned (bfc_x, bfc_y) will never overlap with the margin edge of any floats in this block formatting context. @param bfc_y (in/out) Relative to the top border edge of the block formatting context. In: highest possible Y position for the element. Out: The in-value will be increased if that is needed to satisfy the space requirements. If it is below all the floats, it will not be increased any further (even if the space requirement cannot be satisfied at this position). @param bfc_x (in/out) Relative to the left border edge of the block formatting context. In: leftmost possible X position for the element. Out: Will be changed if putting an element at that position would overlap with any floats. @param width (in/out) In: containing block width (ensures that space handed out is confined to the containing block). Out: width available at the final position. @param min_width Minimum width requirement @param min_height Minimum height requirement @param lock_vertical If TRUE, the vertical position (@see y) will remain untouched, even if that would mean that the layout element will overlap with floats. The horizontal position may be affected by floats, though. @return How much vertical space is available at the final position. */ LayoutCoord GetSpace(LayoutCoord& bfc_y, LayoutCoord& bfc_x, LayoutCoord& width, LayoutCoord min_width, LayoutCoord min_height, VerticalLock vertical_lock) const; /** Get maximum width of all floats at the specified minimum Y position, and change minimum Y if necessary. This method is similar to GetSpace(), just that it is only used when calculating min/max widths. It will pretend that maximum widths are satisfied and try to find space among the floats for content at the Y position bfc_min_y with height min_height. The caller suggests a Y position for some content and wants to know the maximum widths of floats that are beside the content. This method may change the Y position if it finds that there is no way the content would fit there, and then provide the maximum width of floats to the left and to the right of the content at its potentially new position. @param bfc_min_y (in/out) Minimum Y position (the position that content would get if the maximum width of its container is satisfied), relative to the top border edge of the block formatting context. In: Highest (suggested) minimum Y position for the content. Out: Same or lower minimum Y position where there might actually be room for the content. @param min_height Minimum height - height that the content would get if the maximum width of its container is satisfied. @param max_width Maximum width of content (the width that the content would need in order to avoid implicit line breaks and floats being shifted downwards) @param bfc_left_edge_min_distance Minimum distance from left content edge of the content to the left content edge of the block formatting context. Does not include percentual padding and margin. May be negative (due to negative margins). @param bfc_right_edge_min_distance Minimum distance from right content edge of the content to the right content edge of the block formatting context. Does not include percentual padding and margin. May be negative (due to negative margins). @param container_width Width of the container of the content. If this is unknown (because of auto/percentual widths), it will be LONG_MAX. @param left_floats_max_width (out) The maximum width by which floats to the left of the content may possibly overlap the content's container. @param right_floats_max_width (out) The maximum width by which floats to the right of the content may possibly overlap the content's container. */ void GetFloatsMaxWidth(LayoutCoord& bfc_min_y, LayoutCoord min_height, LayoutCoord max_width, LayoutCoord bfc_left_edge_min_distance, LayoutCoord bfc_right_edge_min_distance, LayoutCoord container_width, LayoutCoord& left_floats_max_width, LayoutCoord& right_floats_max_width); /** Find bottom of floats. Returns the first possible Y position below all floats of the given type (left, right or both), relative to the top content edge of the block formatting context. If no relevant floats were found, LONG_MIN is returned. @param clear Which floats to consider; left, right or both. */ LayoutCoord FindBfcBottom(CSSValue clear) const; /** Find minimum bottom of floats. Returns the first possible minimum Y position (the hypothetic Y position if the maximum width of a shrink-to-fit block formatting context is satisfied) below all floats of the given type (left, right or both), relative to the top content edge of the block formatting context. If no relevant floats were found, LAYOUT_COORD_MIN is returned. @param clear Which floats to consider; left, right or both. */ LayoutCoord FindBfcMinBottom(CSSValue clear) const; /** Get the last float in this block formatting context. */ FloatingBox* GetLastFloat() const; /** Any pending floats? */ BOOL HasPendingFloats() const { return reflow_state && !reflow_state->Empty(); } /** Enable full reflow. Specify that all blocks in this block formatting context need to be reflowed. */ void EnableFullBfcReflow() { reflow_state->full_bfc_reflow = TRUE; } /** Is full reflow enabled? */ BOOL IsFullBfcReflowEnabled() const { return reflow_state->full_bfc_reflow; } /** Enable full min/max width calculation. Specify that all blocks in this block formatting context need to recalculate min/max widths. */ void EnableFullBfcMinMaxCalculation() { reflow_state->full_bfc_min_max_calculation = TRUE; } /** Is full min/max width calculation enabled? */ BOOL IsFullBfcMinMaxCalculationEnabled() const { return reflow_state->full_bfc_min_max_calculation; } }; /** Block box with space manager. Used by any statically-positioned block box type that establishes a new block formatting context (e.g. if it has overflow: auto/scroll). */ class SpaceManagerBlockBox : public BlockBox { private: /** Space manager for allocating space. */ SpaceManager space_manager; public: SpaceManagerBlockBox(HTML_Element* element, Content* content) : BlockBox(element, content) {} /** Return the space manager of the object, if it has any. */ virtual SpaceManager* GetLocalSpaceManager() { return &space_manager; } }; #define NO_HOFFSET LAYOUT_COORD_MIN #define NO_VOFFSET LAYOUT_COORD_MIN /** Absolute positioned box. */ class AbsolutePositionedBox : public BlockBox { private: /** Z element for stacking context. */ ZElement z_element; /** Space manager for allocating space. */ SpaceManager space_manager; /** Initialise reflow state. */ AbsolutePositionedBoxReflowState* InitialiseReflowState(); union { struct { /** Right aligned. */ unsigned int right_aligned:1; /** Cached right border of containing box. */ unsigned int cached_right_border:14; /** Bottom aligned. */ unsigned int bottom_aligned:1; /** Cached bottom border of containing box. */ unsigned int cached_bottom_border:15; /** Is fixed. */ unsigned int fixed:1; } abs_packed; unsigned long abs_packed_init; }; union { struct { /** Fixed left position and margin. */ unsigned int fixed_left:1; /** Does the width of the containing block affect the layout of this box? */ unsigned int containing_block_width_affects_layout:1; /** Does the height of the containing block affect the layout of this box? */ unsigned int containing_block_height_affects_layout:1; /** Does the containing block affect the position of this box? */ unsigned int containing_block_affects_position:1; /** Is the containing block established by a positioned inline box? */ unsigned int containing_block_is_inline:1; /** Does this box have a pending reflow because its containing block has changed in a way that affects it? */ unsigned int pending_reflow_check:1; /** This would have been an inline, hadn't the position property forced the display property to change to block. Its horizontal position is hypothetical-static (left:auto, right:auto). */ unsigned int horizontal_static_inline:1; /** Is inside transformed element. Note: If the element itself is transformed, this is not necessarily true, only if it has an transformed ancestor. */ unsigned int inside_transformed:1; } abs_packed2; unsigned int abs_packed2_init; }; /** Horizontal offset. */ LayoutCoord offset_horizontal; /** Vertical offset. */ LayoutCoord offset_vertical; /** Minimum width of containing block required to prevent this box from overflowing. Used for FlexRoot. If the value is negative, it signifies the percentage width of this box. */ LayoutCoord flexroot_width_required; /** Width of horizontal border and padding if box-sizing is content-box. */ LayoutCoord horizontal_border_padding; /** Clipping rectangle - this caches value of CSS 'clip' property. Caching is necessary as we may need to clip an abspos bbox during SkipBranch() call in which cascade and thus CSS properties will not be available */ RECT clip_rect; /** Get the height of the initial containing block. In normal cases this is the height of the layout viewport. Content sized iframes is an exception since the height of the view can depend on the size of the frame, causing a dual dependency. Thus, the height of the containing block is set to zero for content sized iframes. */ LayoutCoord InitialContainingBlockHeight(LayoutInfo& info) const; /** Calculate width available for this box. */ void CalculateAvailableWidth(const LayoutInfo& info); /** Calculate X position of box. The width may be needed to calculate this. */ void CalculateHorizontalPosition(); /** Set clipping rectangle */ void SetClipRect(LayoutCoord left, LayoutCoord top, LayoutCoord right, LayoutCoord bottom) { clip_rect.left = left; clip_rect.top = top; clip_rect.right = right; clip_rect.bottom = bottom; } public: AbsolutePositionedBox(HTML_Element* element, Content* content) : BlockBox(element, content), z_element(element), offset_horizontal(0), offset_vertical(0), flexroot_width_required(0), horizontal_border_padding(0) { abs_packed_init = 0; abs_packed2_init = 0; SetClipRect(CLIP_NOT_SET, CLIP_NOT_SET, CLIP_NOT_SET, CLIP_NOT_SET); } /** Get reflow state. */ AbsolutePositionedBoxReflowState* GetReflowState() const { return (AbsolutePositionedBoxReflowState*) BlockBox::GetReflowState(); } /** Get width available for the margin box. */ virtual LayoutCoord GetAvailableWidth(LayoutProperties* cascade); /** Is this box a positioned box? */ virtual BOOL IsPositionedBox() const { return TRUE; } /** Is this box an absolute positioned box? */ virtual BOOL IsAbsolutePositionedBox() const { return TRUE; } /** Is this an element that logically belongs in the stack? */ virtual BOOL IsInStack(BOOL include_floats = FALSE) const { return FALSE; } /** Is this box a fixed positioned box? Normally fixed positioned boxes inside transforms isn't included here, because they are not fixed to the viewport. Instead they are more similar to position:absolute with the exception that they have the nearest transformed element as containing block, instead of the nearest positioned element. If 'include_transformed' is TRUE, fixed positioned boxes inside transformed elements are also included. */ virtual BOOL IsFixedPositionedBox(BOOL include_transformed = FALSE) const { return abs_packed.fixed #ifdef CSS_TRANSFORMS && (include_transformed || !abs_packed2.inside_transformed) #endif ; } /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Update screen. */ virtual void UpdateScreen(LayoutInfo& info); /** Invalidate the screen area that the box uses. */ virtual void Invalidate(LayoutProperties* parent_cascade, LayoutInfo& info) const; /** Signal that content may have changed. */ virtual void SignalChange(FramesDocument* doc, BoxSignalReason reason = BOX_SIGNAL_REASON_UNKNOWN); /** Recalculate the top margin after a new block box has been added to a container's layout stack. Collapse the margin with preceding adjacent margins if appropriate. If the top margin of this block is adjacent to an ancestor's top margin, it may cause the ancestor's Y position to change. If the top margin of this block is adjacent to a preceding sibling's bottom margin, this block may change its Y position. @return TRUE if the Y position of any element was changed. */ virtual BOOL RecalculateTopMargins(LayoutInfo& info, const VerticalMargin* top_margin, BOOL has_bottom_margin = FALSE) { return FALSE; } /** Layout of this box is finished (or skipped). Propagate changes (bottom margins, bounding-box) to parents. This may grow the box, which in turn may cause its parents to be grown. Bottom margins may participate in margin collapsing with successive content, but only if this box is part of the normal flow. In that case, propagate the bottom margin to the reflow state of the container of this box. Since this member function is used to propagate bounding boxes as well, we may need to call it even when box is empty and is not part of the normal flow. To protect against margins being propagated and parent container reflow position updated in such case, 'has_inflow_content' flag has been introduced in order to notify container that this box is not a part of normal flow but has bounding box that still needs to be propagated. Separation of bounding box propagation and margin/reflow state update should be considered. */ virtual void PropagateBottomMargins(LayoutInfo& info, const VerticalMargin* bottom_margin = 0, BOOL has_inflow_content = TRUE); /** Get bounding box relative to top/left border edge of this box. Overflow may include overflowing content as well as absolutely positioned descendants. Returned box may be clipped to a rect defined by CSS 'clip' property. */ virtual void GetBoundingBox(AbsoluteBoundingBox& box, BOOL include_overflow = TRUE, BOOL adjust_for_multicol = FALSE, BOOL apply_clip = TRUE) const; /** Propagate a break point caused by break properties or a spanned element. These are discovered during layout, and propagated to the nearest multicol container when appropriate. They are needed by the columnizer to do column balancing. @param virtual_y Virtual Y position of the break (relative to the top border edge of this box) @param break_type Type of break point @param breakpoint If non-NULL, it will be set to the MultiColBreakpoint created, if any. @return FALSE on OOM, TRUE otherwise. */ virtual BOOL PropagateBreakpoint(LayoutCoord virtual_y, BREAK_TYPE break_type, MultiColBreakpoint** breakpoint); /** Traverse box with children. This method will traverse the contents of this box and its children, recursively. */ virtual void Traverse(TraversalObject* traversal_object, LayoutProperties* parent_lprops, HTML_Element* containing_element); /** Traverse box with children. This method will traverse this inline element and its children. It will only traverse the part of the virtual line that the elements have been laid out on indicated by position and length. */ virtual BOOL LineTraverseBox(TraversalObject* traversal_object, LayoutProperties* parent_lprops, LineSegment& segment, LayoutCoord baseline); #ifdef PAGED_MEDIA_SUPPORT /** Insert a page break. */ virtual BREAKST InsertPageBreak(LayoutInfo& info, int strength) { return BREAK_NOT_FOUND; } #endif // PAGED_MEDIA_SUPPORT /** Return the space manager of the object, if it has any. */ virtual SpaceManager* GetLocalSpaceManager() { return &space_manager; } /** Do we need to calculate min/max widths of this box's content? */ virtual BOOL NeedMinMaxWidthCalculation(LayoutProperties* cascade) const; /** Propagate widths to container / table. */ virtual void PropagateWidths(const LayoutInfo& info, LayoutCoord min_width, LayoutCoord normal_min_width, LayoutCoord max_width) {} /** Get height and top/bottom border of the containing box. * * @param info the info * @param container The container for the element whose containing box's height we are requesting * @param containing_border_top (out) the top border width of the containing box * @param containing_border_bottom (out) the bottom border width of the containing box * @param current_page_is_containing_block (out) returns TRUE if this box should be positioned * relative to the current page. Used in opera show * if the containing element is the document root. * * @return the height of the containing box */ LayoutCoord GetContainingBoxHeightAndBorders(LayoutInfo& info, Container* container, short& containing_border_top, short& containing_border_bottom, BOOL& current_page_is_containing_block) const; /** Set the initial Y position of this absolute positioned box. * This may be updated later through AbsolutePositionedBox::UpdatePosition * It will also set the root translation to incorporate the new y value. */ void CalculateVerticalPosition(LayoutProperties* cascade, LayoutInfo& info); /** Calculate used vertical CSS properties (height and margins). Resolve the actual content height of this absolute positioned box, based on constraints from variables such as min/max height, height, top & bottom. Also calculate vertical margins. Note! This function should avoid setting state, since it is currently called from different places. @return always TRUE, meaning that height and vertical margins have been resolved by this method, so that we shouldn't calculate them in the default manner. */ virtual BOOL ResolveHeightAndVerticalMargins(LayoutProperties* cascade, LayoutCoord& content_height, LayoutCoord& margin_top, LayoutCoord& margin_bottom, LayoutInfo& info) const; /** Return the z element of the object, if it has any. */ virtual ZElement* GetLocalZElement() { return &z_element; } /** Element was skipped, reposition. */ virtual BOOL SkipZElement(LayoutInfo& info); /** Update bottom aligned absolutepositioned boxes. */ virtual void UpdateBottomAligned(LayoutInfo& info); /** Update the position. The Y position depends on the box height if it is bottom-aligned. When this function is called the root translation must be at current position of the absolute positioned box. @param info Layout information structure @param translate When TRUE, the normal translation and the root translation is updated to the new box position. Note: the normal translation must also be at the absolute positioned box for this to be meaningful. */ void UpdatePosition(LayoutInfo &info, BOOL translate = FALSE); /** Get horizontal offset. */ LayoutCoord GetHorizontalOffset() const { return offset_horizontal; } /** Get vertical offset. */ long GetVerticalOffset() const { return offset_vertical; } /** Find the normal right edge of the rightmost absolute positioned box. */ virtual LayoutCoord FindNormalRightAbsEdge(HLDocProfile* hld_profile, LayoutProperties* parent_cascade); /** Is this box right aligned? */ BOOL IsRightAligned() const { return abs_packed.right_aligned == 1; } /** Has this box fixed left position and margin? */ BOOL HasFixedPosition() const { return abs_packed2.fixed_left == 1; } /** The size or position of the containing block has changed, and this * absolutely positioned box needs to know (and probably reflow). * @param info Layout information structure * @param width_changed Was the containing block width changed? * @param height_changed Was the containing block height changed? */ void ContainingBlockChanged(LayoutInfo &info, BOOL width_changed, BOOL height_changed); /** Check if this box is affected by the size or position of its containing block. */ BOOL CheckAffectedByContainingBlock(LayoutInfo &info, Box* containing_block, BOOL skipped); /** If the position property hadn't forced the display property to block, would this have been an inline, and is the horizontal position hypothetical-static (left:auto, right:auto)? */ BOOL IsHypotheticalHorizontalStaticInline() { return abs_packed2.horizontal_static_inline == 1; } /** * Move this VerticalLayout and all its content down by an offset. * * @param offset_y Offset to move down * @param containing_element. Element of the container for this vertical layout. Not used in this implementation. */ virtual void MoveDown(LayoutCoord offset_y, HTML_Element* containing_element) { if (GetVerticalOffset() == NO_VOFFSET) { y += offset_y; } } /** Distribute content into columns. @return FALSE on OOM, TRUE otherwise. */ virtual BOOL Columnize(Columnizer& columnizer, Container* container); /** Figure out to which column(s) or spanned element a box belongs. */ virtual void FindColumn(ColumnFinder& cf, Container* container); /** Calculate the translations for normal translation and root translation that AbsolutePositionedBox::Traverse must translate before traversing its children. @param traversal_object The TraversalObject used for the partial traverse. @param container_props The computed styles for the closest container of this absolute positioned element. This is needed to adjust the hypothetical static inline position of this box with text-align offsets. @param cancel_x_scroll The amount of horizontal scroll translation between this absolute positioned box and its containing block that needs to be cancelled out because it shouldn't affect the offset for this absolute positioned box. @param cancel_y_scroll The amount of vertical scroll translation between this absolute positioned box and its containing block that needs to be cancelled out because it shouldn't affect the offset for this absolute positioned box. @param translate_x The returned horizontal translation. @param translate_y The returned vertical translation. @param translate_root_x The returned horizontal root translation. @param translate_root_y The returned vertical root translation. */ void GetOffsetTranslations(TraversalObject* traversal_object, const HTMLayoutProperties& container_props, LayoutCoord cancel_x_scroll, LayoutCoord cancel_y_scroll, LayoutCoord& translate_x, LayoutCoord& translate_y, LayoutCoord& translate_root_x, LayoutCoord& translate_root_y); /** Return TRUE if this absolutely positioned box is affected by its containing block in any way. */ BOOL IsAffectedByContainingBlock() const { return abs_packed2.containing_block_width_affects_layout || abs_packed2.containing_block_height_affects_layout || abs_packed2.containing_block_affects_position; } }; /** Absolute positioned z indexed box. */ class AbsoluteZRootBox : public AbsolutePositionedBox { private: /** Ordered list of elements with z-index different from 0 and 'auto' */ StackingContext stacking_context; protected: /** Restart z element list. */ virtual void RestartStackingContext() { stacking_context.Restart(); } public: AbsoluteZRootBox(HTML_Element* element, Content* content) : AbsolutePositionedBox(element, content) {} /** Traverse z children. */ virtual void TraverseZChildren(TraversalObject* traversal_object, LayoutProperties* layout_props, BOOL after, BOOL handle_overflow_clip); /** Has z children with negative z-index */ virtual BOOL HasNegativeZChildren() { return stacking_context.HasNegativeZChildren(); } /** Return the z element list of the object, if it has any. */ virtual StackingContext* GetLocalStackingContext() { return &stacking_context; } /** Find the normal right edge of the rightmost absolute positioned box. */ virtual LayoutCoord FindNormalRightAbsEdge(HLDocProfile* hld_profile, LayoutProperties* parent_cascade); /** Should TraversalObject let Box handle clipping/overflow on its own? Some boxes, depending on traversed content, may need to differentiate between clipping and overflow. Clipping rectangle should include overflow (even if overflow is hidden) for some descendants (ie. objects on StackingContext) therefore clipping must be applied on-demand during traverse rather than in Enter*Box. */ virtual BOOL HasComplexOverflowClipping() const { return TRUE; } }; /** Information needed while the space manager in which a floating box lives is reflowed. A reflow cache is created for a floating box when it is created and laid out, or when reflow of its space manager is started, whichever comes first. It is deleted when reflow of its space manager is done. */ struct FloatReflowCache { /** Cached lowest bottom margin edge of all left-floats so far in the block formatting context (including this float), relative the top border edge of the block formatting context. Offset caused by position:relative is not included. */ LayoutCoord left_floats_bottom; /** Cached lowest bottom margin edge of all right-floats so far in the block formatting context (including this float), relative the top border edge of the block formatting context. Offset caused by position:relative is not included. */ LayoutCoord right_floats_bottom; /** Cached lowest minimum bottom margin edge of all left-floats so far in the block formatting context (including this float), relative to the top border edge of the block formatting context. Offset caused by position:relative is not included. */ LayoutCoord left_floats_min_bottom; /** Cached lowest minimum bottom margin edge of all right-floats so far in the block formatting context (including this float), relative to the top border edge of the block formatting context. Offset caused by position:relative is not included. */ LayoutCoord right_floats_min_bottom; /** Distance from the top border edge of the block formatting context (to which this float belongs) to the top margin edge of this float. Offset caused by position:relative is not included. */ LayoutCoord bfc_y; /** Distance from the minimum top border edge of the block formatting context (to which this float belongs) to the minimum top margin edge of this float. Offset caused by position:relative is not included. */ LayoutCoord bfc_min_y; /** Distance from the left border edge to the block formatting context (to which this float belongs) to the left margin edge of this float. Offset caused by position:relative is not included. */ LayoutCoord bfc_x; /** margin-left property. */ LayoutCoord margin_left; /** margin-right property. */ LayoutCoord margin_right; /** Highest accumulated maximum width of all left floats so far in the block formatting context (including this float). */ LayoutCoord highest_left_acc_max_width; /** Highest accumulated maximum width of all right floats so far in the block formatting context (including this float). */ LayoutCoord highest_right_acc_max_width; /** Next float to traverse. Traversal while the space manager is being reflowed may happen during incremental rendering. */ FloatingBox* next_float; /** If TRUE, the cache is invalid / dirty and needs an update before being accessed. */ BOOL invalid; void* operator new(size_t nbytes) OP_NOTHROW { return g_float_reflow_cache_pool->New(sizeof(FloatReflowCache)); } void operator delete(void* p, size_t nbytes) { g_float_reflow_cache_pool->Delete(p); } }; class FLink : public Link { public: FLink* Suc() { return (FLink*) Link::Suc(); } FLink* Pred() { return (FLink*) Link::Pred(); } /** Force full reflow of the block formatting context to which this float belongs. */ void ForceFullBfcReflow() { if (FloatList* float_list = (FloatList*) GetList()) float_list->ForceFullBfcReflow(); } FloatingBox* float_box; }; /** Floating box. */ class FloatingBox : public BlockBox { private: /** float_packed.has_float_reflow_cache determines which object is active in this union. */ union { /** Will be set while reflowing the space manager of this box. float_packed.has_float_reflow_cache is set when this object is active. */ FloatReflowCache* float_reflow_cache; /** Next float to traverse. float_packed.has_float_reflow_cache is not set when this object is active. */ FloatingBox* next_float; }; /** Space manager for allocating space. */ SpaceManager space_manager; /** Top margin of floating box. */ LayoutCoord margin_top; /** Bottom margin of floating box. */ LayoutCoord margin_bottom; /** Horizontal margin not resolved from percentual values. */ LayoutCoord nonpercent_horizontal_margin; /** Total maximum width of all floats to the left (if this is a left-float) or to the right (if this is a right-float) of this float, if the block formatting context's maximum width is satisfied. */ LayoutCoord prev_accumulated_max_width; /** Left or right edge of float. */ LayoutCoord float_edge; union { struct { /** Float is left aligned float? */ unsigned int left:1; /** Do we have a FloatReflowCache? */ unsigned int has_float_reflow_cache:1; /** Is margin-top resolved from a percentual value? */ unsigned int margin_top_is_percent:1; /** Is margin-bottom resolved from a percentual value? */ unsigned int margin_bottom_is_percent:1; } float_packed; unsigned long float_packed_init; }; FloatReflowCache* GetFloatReflowCache() const { OP_ASSERT(float_packed.has_float_reflow_cache); return float_reflow_cache; } public: FLink link; FloatingBox(HTML_Element* element, Content* content) : BlockBox(element, content), margin_top(0), margin_bottom(0), nonpercent_horizontal_margin(0), prev_accumulated_max_width(0) { float_packed_init = 0; link.float_box = this; } virtual ~FloatingBox(); /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Get the left and top relative offsets caused by position:relative. */ virtual void GetRelativeOffsets(LayoutCoord& left, LayoutCoord& top) const { left = LayoutCoord(0); top = LayoutCoord(0); } /** Finish reflowing box. */ virtual LAYST FinishLayout(LayoutInfo& info); /** Recalculate the top margin after a new block box has been added to a container's layout stack. Collapse the margin with preceding adjacent margins if appropriate. If the top margin of this block is adjacent to an ancestor's top margin, it may cause the ancestor's Y position to change. If the top margin of this block is adjacent to a preceding sibling's bottom margin, this block may change its Y position. @return TRUE if the Y position of any element was changed. */ virtual BOOL RecalculateTopMargins(LayoutInfo& info, const VerticalMargin* top_margin, BOOL has_bottom_margin = FALSE) { return FALSE; } /** Layout of this box is finished (or skipped). Propagate changes (bottom margins, bounding-box) to parents. This may grow the box, which in turn may cause its parents to be grown. Bottom margins may participate in margin collapsing with successive content, but only if this box is part of the normal flow. In that case, propagate the bottom margin to the reflow state of the container of this box. Since this member function is used to propagate bounding boxes as well, we may need to call it even when box is empty and is not part of the normal flow. To protect against margins being propagated and parent container reflow position updated in such case, 'has_inflow_content' flag has been introduced in order to notify container that this box is not a part of normal flow but has bounding box that still needs to be propagated. Separation of bounding box propagation and margin/reflow state update should be considered. */ virtual void PropagateBottomMargins(LayoutInfo& info, const VerticalMargin* bottom_margin = 0, BOOL has_inflow_content = TRUE); /** Propagate a break point caused by break properties or a spanned element. These are discovered during layout, and propagated to the nearest multicol container when appropriate. They are needed by the columnizer to do column balancing. @param virtual_y Virtual Y position of the break (relative to the top border edge of this box) @param break_type Type of break point @param breakpoint If non-NULL, it will be set to the MultiColBreakpoint created, if any. @return FALSE on OOM, TRUE otherwise. */ virtual BOOL PropagateBreakpoint(LayoutCoord virtual_y, BREAK_TYPE break_type, MultiColBreakpoint** breakpoint); /** Get height of float, including margins. */ LayoutCoord GetHeightAndMargins() const { return margin_top + margin_bottom + GetHeight(); } /** Get minimum height of float, including non-percentual margins. */ LayoutCoord GetMinHeightAndMargins() const { return (float_packed.margin_top_is_percent ? LayoutCoord(0) : margin_top) + (float_packed.margin_bottom_is_percent ? LayoutCoord(0) : margin_bottom) + content->GetMinHeight(); } /** Get offset from top margin edge to top border edge. */ LayoutCoord GetMarginTop(BOOL ignore_percent = FALSE) const { return ignore_percent && float_packed.margin_top_is_percent ? LayoutCoord(0) : margin_top; } /** Get distance between left border edge and left (right-floats) / right (left-floats) margin edge. For left-floats, return offset from left border edge to right margin edge. For right-floats, return offset from left margin edge to left border edge. */ LayoutCoord GetMarginToEdge() const { return float_edge; } /** Is this box a floating box? */ virtual BOOL IsFloatingBox() const { return TRUE; } /** Is this an element that logically belongs in the stack? */ virtual BOOL IsInStack(BOOL include_floats = FALSE) const { return include_floats; } /** Is this float a left aligned float? */ BOOL IsLeftFloat() const { return float_packed.left; } /** Get next float to traverse. */ FloatingBox* GetNextFloat() const { return float_packed.has_float_reflow_cache ? float_reflow_cache->next_float : next_float; } /** Set next float to traverse. */ void SetNextFloat(FloatingBox* next) { (float_packed.has_float_reflow_cache ? float_reflow_cache->next_float : next_float) = next; } /** Traverse box with children. This method will traverse the contents of this box and its children, recursively. */ virtual void Traverse(TraversalObject* traversal_object, LayoutProperties* parent_lprops, HTML_Element* containing_element); /** Traverse box with children. This method will traverse this inline element and its children. It will only traverse the part of the virtual line that the elements have been laid out on indicated by position and length. */ virtual BOOL LineTraverseBox(TraversalObject* traversal_object, LayoutProperties* parent_lprops, LineSegment& segment, LayoutCoord baseline); #ifdef PAGED_MEDIA_SUPPORT /** Insert a page break. */ virtual BREAKST InsertPageBreak(LayoutInfo& info, int strength); #endif // PAGED_MEDIA_SUPPORT /** Return the space manager of the object, if it has any. */ virtual SpaceManager* GetLocalSpaceManager() { return &space_manager; } /** Get the lowest bottom outer edge of this float and preceding floats. @param float_types Which float types to look at. Allowed values are: CSS_VALUE_left, CSS_VALUE_right and CSS_VALUE_both @return One pixel below the bottom outer edge of the lowest float, relative to the top border edge of the block formatting context. LAYOUT_COORD_MIN is returned if no relevant floats were found. */ LayoutCoord GetLowestFloatBfcBottom(CSSValue float_types); /** Get the lowest minimum bottom outer edge of this float and preceding floats. @param float_types Which float types to look at. Allowed values are: CSS_VALUE_left, CSS_VALUE_right and CSS_VALUE_both @return One pixel below the bottom outer edge of the lowest float, relative to the top content edge of this block formatting context. LAYOUT_COORD_MIN is returned if no relevant floats were found. */ LayoutCoord GetLowestFloatBfcMinBottom(CSSValue float_types); /** Get the highest maximum width among this float and preceding floats. @param float_type CSS_VALUE_left or CSS_VALUE_right */ LayoutCoord GetHighestAccumulatedMaxWidth(CSSValue float_type); /** Update the reflow cache of this float (and preceding floats with invalid cache, if any) if invalid. */ void UpdateFloatReflowCache(); /** Initialise the reflow cache for this floating box. See FloatReflowCache. @return FALSE on memory allocation error, TRUE otherwise */ BOOL InitialiseFloatReflowCache(); /** Delete the reflow state for this floating box. See FloatReflowCache. */ void DeleteFloatReflowCache(); /** Mark the reflow cache of this float, and all succeeding floats, invalid/dirty, so that it is updated before next time it needs to be accessed. */ void InvalidateFloatReflowCache(); /** Is the reflow cache of this float invalid/dirty? */ BOOL IsFloatReflowCacheInvalid() { return GetFloatReflowCache()->invalid; } /** Remove the float from the space manager. */ void RemoveFromSpaceManager() { OP_ASSERT(!link.Suc()); link.Out(); } /** Set Y position relative to the block formatting context. This is only valid during reflow of the block formatting context in which this float lives. */ void SetBfcY(LayoutCoord y) { GetFloatReflowCache()->bfc_y = y; } /** Set minimum Y position relative to the block formatting context. This is only valid during reflow of the block formatting context in which this float lives. The value represents the Y position that this float would get if maximum width of its shrink-to-fit block formatting context is satisfied). */ void SetBfcMinY(LayoutCoord min_y) { GetFloatReflowCache()->bfc_min_y = min_y; } /** Set X position relative to the block formatting context. This is only valid during reflow of the block formatting context in which this float lives. */ void SetBfcX(LayoutCoord x) { GetFloatReflowCache()->bfc_x = x; } /** Get Y position relative to the block formatting context. This is only valid during reflow of the block formatting context in which this float lives. */ LayoutCoord GetBfcY() const { return GetFloatReflowCache()->bfc_y; } /** Get minimum Y position relative to the block formatting context. This is only valid during reflow of the block formatting context in which this float lives. The value represents the Y position that this float would get if maximum width of its shrink-to-fit block formatting context is satisfied). */ LayoutCoord GetBfcMinY() const { return GetFloatReflowCache()->bfc_min_y; } /** Get X position relative to the block formatting context. This is only valid during reflow of the block formatting context in which this float lives. */ LayoutCoord GetBfcX() const { return GetFloatReflowCache()->bfc_x; } /** Get left margin property used value. */ LayoutCoord GetMarginLeft() const { return GetFloatReflowCache()->margin_left; } /** Get left margin property used value. */ LayoutCoord GetMarginRight() const { return GetFloatReflowCache()->margin_right; } /** Get total maximum width of this float, plus all floats to the left (if this is a left-float) or to the right (if this is a right-float) of this float, if the maximum width of the block formatting context in which this float lives is satisfied. */ LayoutCoord GetAccumulatedMaxWidth() const; /** Set total maximum width of all floats to the left (if this float is a left float) or right (if this float is a right float) of this float, if the maximum width of the block formatting context in which this float lives is satisfied. */ void SetPrevAccumulatedMaxWidth(LayoutCoord max_width) { prev_accumulated_max_width = max_width; } /** Skip layout of this float. */ void SkipLayout(LayoutInfo& info); }; /** Positioned floating box. */ class PositionedFloatingBox : public FloatingBox { protected: /** Z element for stacking context. */ ZElement z_element; /** Top relative offset. */ LayoutCoord top_offset; /** Left relative offset. */ LayoutCoord left_offset; public: PositionedFloatingBox(HTML_Element* element, Content* content) : FloatingBox(element, content), z_element(element), top_offset(0), left_offset(0) {} /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Get the left and top relative offsets caused by position:relative. */ virtual void GetRelativeOffsets(LayoutCoord& left, LayoutCoord& top) const { left = left_offset; top = top_offset; } /** Is this box a positioned box? */ virtual BOOL IsPositionedBox() const { return TRUE; } /** Return the z element of the object, if it has any. */ virtual ZElement* GetLocalZElement() { return &z_element; } }; /** Positioned floating box with z-index. */ class PositionedZRootFloatingBox : public PositionedFloatingBox { private: /** Ordered list of elements with z-index different from 0 and 'auto' */ StackingContext stacking_context; protected: /** Restart z element list. */ virtual void RestartStackingContext() { stacking_context.Restart(); } public: PositionedZRootFloatingBox(HTML_Element* element, Content* content) : PositionedFloatingBox(element, content) {} /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Traverse z children. */ virtual void TraverseZChildren(TraversalObject* traversal_object, LayoutProperties* layout_props, BOOL after, BOOL handle_overflow_clip); /** Has z children with negative z-index */ virtual BOOL HasNegativeZChildren() { return stacking_context.HasNegativeZChildren(); } /** Return the z element list of the object, if it has any. */ virtual StackingContext* GetLocalStackingContext() { return &stacking_context; } }; /** Block compact box. */ class BlockCompactBox : public BlockBox { public: BlockCompactBox(HTML_Element* element, Content* content) : BlockBox(element, content) {} /** Is this box a compact box? */ virtual BOOL IsBlockCompactBox() const { return TRUE; } }; /** Relative positioned or transformed block box. Transformed block boxes behave simliar to relative positioned block boxes. */ class PositionedBlockBox : public BlockBox { private: /** Cached top CSS property. */ LayoutCoord top; /** Cached left CSS property. */ LayoutCoord left; /** Set the left and top CSS properties of positioned boxes, since these values need to be cached. */ virtual void SetRelativePosition(LayoutCoord new_left, LayoutCoord new_top) { left = new_left; top = new_top; } /** Set Y position. */ virtual void SetY(LayoutCoord new_y) { y = new_y + LayoutCoord(top); } protected: /** Z element for stacking context. */ ZElement z_element; public: PositionedBlockBox(HTML_Element* element, Content* content) : BlockBox(element, content), top(0), left(0), z_element(element) {} /** Traverse box with children. */ virtual void Traverse(TraversalObject* traversal_object, LayoutProperties* parent_lprops, HTML_Element* containing_element); /** Get box Y position, relative to parent. */ virtual LayoutCoord GetStackPosition() const { return y - LayoutCoord(top); } /** Get and add the normal flow position of this box to the supplied coordinate variables. */ virtual void AddNormalFlowPosition(LayoutCoord &x, LayoutCoord &y) const { x += this->x - LayoutCoord(left); y += LayoutCoord(this->y) - LayoutCoord(top); } /** Is this box a positioned box? */ virtual BOOL IsPositionedBox() const { return TRUE; } /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Propagate a break point caused by break properties or a spanned element. These are discovered during layout, and propagated to the nearest multicol container when appropriate. They are needed by the columnizer to do column balancing. @param virtual_y Virtual Y position of the break (relative to the top border edge of this box) @param break_type Type of break point @param breakpoint If non-NULL, it will be set to the MultiColBreakpoint created, if any. @return FALSE on OOM, TRUE otherwise. */ virtual BOOL PropagateBreakpoint(LayoutCoord virtual_y, BREAK_TYPE break_type, MultiColBreakpoint** breakpoint); /** Return the z element of the object, if it has any. */ virtual ZElement* GetLocalZElement() { return &z_element; } }; /** Positioned block box with space manager. Used by any relatively-positioned block box type that establishes a new block formatting context (e.g. if it has overflow: auto/scroll). */ class PositionedSpaceManagerBlockBox : public PositionedBlockBox { private: /** Space manager for allocating space. */ SpaceManager space_manager; public: PositionedSpaceManagerBlockBox(HTML_Element* element, Content* content) : PositionedBlockBox(element, content) {} /** Return the space manager of the object, if it has any. */ virtual SpaceManager* GetLocalSpaceManager() { return &space_manager; } }; /** Relative positioned block box. */ class PositionedZRootBox : public PositionedBlockBox { private: /** Ordered list of elements with z-index different from 0 and 'auto' */ StackingContext stacking_context; protected: /** Restart z element list. */ virtual void RestartStackingContext() { stacking_context.Restart(); } public: PositionedZRootBox(HTML_Element* element, Content* content) : PositionedBlockBox(element, content) {} /** Traverse z children. */ virtual void TraverseZChildren(TraversalObject* traversal_object, LayoutProperties* layout_props, BOOL after, BOOL handle_overflow_clip); /** Has z children with negative z-index */ virtual BOOL HasNegativeZChildren() { return stacking_context.HasNegativeZChildren(); } /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Return the z element list of the object, if it has any. */ virtual StackingContext* GetLocalStackingContext() { return &stacking_context; } }; /** Positioned block box with ZList and space manager. Used by any relatively-positioned block box type that establishes a new block formatting context (e.g. if it has overflow: auto/scroll) and a new stacking context (e.g. non-auto z-index). */ class PositionedSpaceManagerZRootBox : public PositionedZRootBox { private: /** Space manager for allocating space. */ SpaceManager space_manager; public: PositionedSpaceManagerZRootBox(HTML_Element* element, Content* content) : PositionedZRootBox(element, content) {} /** Return the space manager of the object, if it has any. */ virtual SpaceManager* GetLocalSpaceManager() { return &space_manager; } }; /** Block box which establishes new stacking context. Used for opacity < 1. */ class ZRootBlockBox : public BlockBox { private: /** Z element for stacking context. */ ZElement z_element; /** Ordered list of elements with z-index different from 0 and 'auto' */ StackingContext stacking_context; protected: /** Restart z element list. */ virtual void RestartStackingContext() { stacking_context.Restart(); } public: ZRootBlockBox(HTML_Element* element, Content* content) : BlockBox(element, content), z_element(element) {} /** Return the z element of the object, if it has any. */ virtual ZElement* GetLocalZElement() { return &z_element; } /** Return the z element list of the object, if it has any. */ virtual StackingContext* GetLocalStackingContext() { return &stacking_context; } /** Traverse z children. */ virtual void TraverseZChildren(TraversalObject* traversal_object, LayoutProperties* layout_props, BOOL after, BOOL handle_overflow_clip) { stacking_context.Traverse(traversal_object, layout_props, this, after, handle_overflow_clip); } /** Has z children with negative z-index */ virtual BOOL HasNegativeZChildren() { return stacking_context.HasNegativeZChildren(); } /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Traverse box with children. This method will traverse the contents of this box and its children, recursively. */ virtual void Traverse(TraversalObject* traversal_object, LayoutProperties* parent_lprops, HTML_Element* containing_element); /** Find the normal right edge of the rightmost absolute positioned box. */ virtual LayoutCoord FindNormalRightAbsEdge(HLDocProfile* hld_profile, LayoutProperties* parent_cascade) { return stacking_context.FindNormalRightAbsEdge(hld_profile, parent_cascade); } }; /** Floating box which establishes new stacking context. Used for opacity < 1. */ class ZRootFloatingBox : public FloatingBox { private: /** Z element for stacking context. */ ZElement z_element; /** Ordered list of elements with z-index different from 0 and 'auto' */ StackingContext stacking_context; protected: /** Restart z element list. */ virtual void RestartStackingContext() { stacking_context.Restart(); } public: ZRootFloatingBox(HTML_Element* element, Content* content) : FloatingBox(element, content), z_element(element) {} /** Return the z element of the object, if it has any. */ virtual ZElement* GetLocalZElement() { return &z_element; } /** Return the z element list of the object, if it has any. */ virtual StackingContext* GetLocalStackingContext() { return &stacking_context; } /** Traverse z children. */ virtual void TraverseZChildren(TraversalObject* traversal_object, LayoutProperties* layout_props, BOOL after, BOOL handle_overflow_clip) { stacking_context.Traverse(traversal_object, layout_props, this, after, handle_overflow_clip); } /** Has z children with negative z-index */ virtual BOOL HasNegativeZChildren() { return stacking_context.HasNegativeZChildren(); } /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Find the normal right edge of the rightmost absolute positioned box. */ virtual LayoutCoord FindNormalRightAbsEdge(HLDocProfile* hld_profile, LayoutProperties* parent_cascade) { return stacking_context.FindNormalRightAbsEdge(hld_profile, parent_cascade); } /** Should TraversalObject let Box handle clipping/overflow on its own? Some boxes, depending on traversed content, may need to differentiate between clipping and overflow. Clipping rectangle should include overflow (even if overflow is hidden) for some descendants (ie. objects on StackingContext) therefore clipping must be applied on-demand during traverse rather than in Enter*Box. */ virtual BOOL HasComplexOverflowClipping() const { return TRUE; } }; /** Block box with space manager which establishes new stacking context. Used for opacity < 1. */ class ZRootSpaceManagerBlockBox : public SpaceManagerBlockBox { private: /** Z element for stacking context. */ ZElement z_element; /** Ordered list of elements with z-index different from 0 and 'auto' */ StackingContext stacking_context; protected: /** Restart z element list. */ virtual void RestartStackingContext() { stacking_context.Restart(); } public: ZRootSpaceManagerBlockBox(HTML_Element* element, Content* content) : SpaceManagerBlockBox(element, content), z_element(element) {} /** Return the z element of the object, if it has any. */ virtual ZElement* GetLocalZElement() { return &z_element; } /** Return the z element list of the object, if it has any. */ virtual StackingContext* GetLocalStackingContext() { return &stacking_context; } /** Traverse z children. */ virtual void TraverseZChildren(TraversalObject* traversal_object, LayoutProperties* layout_props, BOOL after, BOOL handle_overflow_clip) { stacking_context.Traverse(traversal_object, layout_props, this, after, handle_overflow_clip); } /** Has z children with negative z-index */ virtual BOOL HasNegativeZChildren() { return stacking_context.HasNegativeZChildren(); } /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Traverse box with children. This method will traverse the contents of this box and its children, recursively. */ virtual void Traverse(TraversalObject* traversal_object, LayoutProperties* parent_lprops, HTML_Element* containing_element); /** Find the normal right edge of the rightmost absolute positioned box. */ virtual LayoutCoord FindNormalRightAbsEdge(HLDocProfile* hld_profile, LayoutProperties* parent_cascade) { return stacking_context.FindNormalRightAbsEdge(hld_profile, parent_cascade); } /** Should TraversalObject let Box handle clipping/overflow on its own? Some boxes, depending on traversed content, may need to differentiate between clipping and overflow. Clipping rectangle should include overflow (even if overflow is hidden) for some descendants (ie. objects on StackingContext) therefore clipping must be applied on-demand during traverse rather than in Enter*Box. */ virtual BOOL HasComplexOverflowClipping() const { return TRUE; } }; /** Column/pane-attached float. These have a column, multi-column container or page as their flow root, and works quite differently from regular CSS 2.1 floats (which have a block formatting context as their flow root.) The 'x' and 'y' positions stored here are relative to the top/left edge of the first pane in which the float lives. */ class FloatedPaneBox : public SpaceManagerBlockBox { private: /** Entry in PaneFloatList. */ PaneFloatEntry list_entry; /** Entry in a list sorted by document tree order. */ PaneFloatEntry logical_entry; /** Entry in list of traversal targets. */ PaneFloatEntry traversal_entry; union { struct { /** TRUE if top-aligned, FALSE if bottom-aligned. */ unsigned int is_top_float:1; /** TRUE if aligned with the far (right in LTR mode) corner. */ unsigned int is_far_corner_float:1; /** TRUE if this float should be put in the row following the one it's defined in. */ unsigned int put_in_next_row:1; #ifdef PAGED_MEDIA_SUPPORT /** TRUE if this float should be put on the page following the one it's defined in. */ unsigned int put_on_next_page:1; /** TRUE if a page break is required after this floated pane box. */ unsigned int force_page_break_after:1; #endif // PAGED_MEDIA_SUPPORT /** TRUE if a column break is required after this floated pane box. */ unsigned int force_column_break_after:1; /** Actual value of column-span. */ unsigned int column_span:14; } panebox_packed; UINT32 panebox_packed_init; }; protected: /** Actual value of margin-top. */ LayoutCoord margin_top; /** Actual value of margin-bottom. */ LayoutCoord margin_bottom; /** The pane in which this float starts. -1 means auto or N/A. */ int start_pane; /** Set the left and top CSS properties of positioned boxes, since these values need to be cached. */ virtual void SetRelativePosition(LayoutCoord new_left, LayoutCoord new_top) {} public: FloatedPaneBox(HTML_Element* element, Content* content) : SpaceManagerBlockBox(element, content), list_entry(this), logical_entry(this), traversal_entry(this), panebox_packed_init(0), margin_top(0), margin_bottom(0) {} virtual ~FloatedPaneBox() { list_entry.Out(); logical_entry.Out(); traversal_entry.Out(); } /** Return TRUE if this is a FloatedPaneBox. */ virtual BOOL IsFloatedPaneBox() const { return TRUE; } /** Propagate bottom margins and bounding box to parents, and walk the dog. */ virtual void PropagateBottomMargins(LayoutInfo& info, const VerticalMargin* bottom_margin = 0, BOOL has_inflow_content = TRUE); /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Get width available for the margin box. */ virtual LayoutCoord GetAvailableWidth(LayoutProperties* cascade); /** Finish reflowing box. */ virtual LAYST FinishLayout(LayoutInfo& info); /** Traverse box with children. */ virtual void Traverse(TraversalObject* traversal_object, LayoutProperties* parent_lprops, HTML_Element* containing_element); /** Traverse box with children. This method will traverse this inline element and its children. It will only traverse the part of the virtual line that the elements have been laid out on indicated by position and length. */ virtual BOOL LineTraverseBox(TraversalObject* traversal_object, LayoutProperties* parent_lprops, LineSegment& segment, LayoutCoord baseline); /** Is this an element that logically belongs in the stack? */ virtual BOOL IsInStack(BOOL include_floats = FALSE) const { return include_floats; } /** Figure out to which column(s) or spanned element a box belongs. */ virtual void FindColumn(ColumnFinder& cf, Container* container); /** Insert this float into a float list. */ void IntoPaneFloatList(PaneFloatList& float_list, PaneFloatEntry* insert_before = NULL); /** Insert this float into a float list. */ void IntoPaneFloatList(PaneFloatList& float_list, int start_pane, BOOL in_next_row); /** Insert this float into the logically sorted list of floats. */ void IntoLogicalList(PaneFloatList& float_list) { logical_entry.Out(); logical_entry.Into(&float_list); } /** Queue box for traversal (floats are traversed in a separate pass between background and content). */ void QueueForTraversal(PaneFloatList& float_list) { /* Protect against duplicate queueing, as this method may be called on the same box more than once in some cases (happens for containers that are both paged and multicol). */ if (!traversal_entry.InList()) { traversal_entry.Out(); traversal_entry.Into(&float_list); } } /** Advance to next traversal target. Takes this box out of the traversal list. */ FloatedPaneBox* AdvanceToNextTraversalTarget() { PaneFloatEntry* next_entry = traversal_entry.Suc(); traversal_entry.Out(); return next_entry ? next_entry->GetBox() : NULL; } /** Return TRUE if this box is top-floated, or FALSE if it is bottom-floated. */ BOOL IsTopFloat() const { return panebox_packed.is_top_float; } /** Return TRUE if aligned with the far (right in LTR mode) corner. */ BOOL IsFarCornerFloat() const { return panebox_packed.is_far_corner_float; } #ifdef PAGED_MEDIA_SUPPORT /** Return TRUE if this float should be put in the page following the one it's defined in. */ BOOL IsForNextPage() const { return panebox_packed.put_on_next_page == 1; } #endif // PAGED_MEDIA_SUPPORT /** Get actual value of column-span. */ int GetColumnSpan() const { return panebox_packed.column_span; } /** Get actual value of margin-top. */ LayoutCoord GetMarginTop() const { return margin_top; } /** Get actual value of margin-bottom. */ LayoutCoord GetMarginBottom() const { return margin_bottom; } /** Get the start pane for this float. -1 means auto or N/A. */ int GetStartPane() const { return start_pane; } /** Return TRUE if this float should be put in the row following the one it's defined in. */ BOOL IsForNextRow() const { return panebox_packed.put_in_next_row; } /** Reset "for next row" flag. Happens when advancing to next row. */ void ResetIsForNextRow() { panebox_packed.put_in_next_row = 0; } /** Move float to next row. There were not enough columns left for it in the current row. */ void MoveToNextRow(); #ifdef PAGED_MEDIA_SUPPORT /** Return TRUE if a page break is required after this floated pane box. */ BOOL IsPageBreakAfterForced() const { return panebox_packed.force_page_break_after == 1; } #endif // PAGED_MEDIA_SUPPORT /** Return TRUE if a column break is required after this floated pane box. */ BOOL IsColumnBreakAfterForced() const { return panebox_packed.force_column_break_after == 1; } }; /** Column/pane-attached positioned float. */ class PositionedFloatedPaneBox : public FloatedPaneBox { protected: /** Z element for stacking context. */ ZElement z_element; /** Cached top CSS property. */ LayoutCoord top; /** Cached left CSS property. */ LayoutCoord left; public: PositionedFloatedPaneBox(HTML_Element* element, Content* content) : FloatedPaneBox(element, content), z_element(element) {} /** Return the z element of the object, if it has any. */ virtual ZElement* GetLocalZElement() { return &z_element; } /** Is this box a positioned box? */ virtual BOOL IsPositionedBox() const { return TRUE; } /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Set the left and top CSS properties of positioned boxes, since these values need to be cached. */ virtual void SetRelativePosition(LayoutCoord new_left, LayoutCoord new_top) { left = new_left; top = new_top; } /** Set Y position. */ virtual void SetY(LayoutCoord new_y) { y = new_y + top; } }; /** Column/pane-attached positioned float that establishes a new stacking context. */ class PositionedZRootFloatedPaneBox : public PositionedFloatedPaneBox { private: /** Ordered list of elements with z-index different from 0 and 'auto' */ StackingContext stacking_context; public: PositionedZRootFloatedPaneBox(HTML_Element* element, Content* content) : PositionedFloatedPaneBox(element, content) {} /** Return the z element list of the object, if it has any. */ virtual StackingContext* GetLocalStackingContext() { return &stacking_context; } /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Traverse z children. */ virtual void TraverseZChildren(TraversalObject* traversal_object, LayoutProperties* layout_props, BOOL after, BOOL handle_overflow_clip); /** Has z children with negative z-index */ virtual BOOL HasNegativeZChildren() { return stacking_context.HasNegativeZChildren(); } }; /** Column/pane-attached float that establishes a new stacking context. */ class ZRootFloatedPaneBox : public FloatedPaneBox { private: /** Z element for stacking context. */ ZElement z_element; /** Ordered list of elements with z-index different from 0 and 'auto' */ StackingContext stacking_context; public: ZRootFloatedPaneBox(HTML_Element* element, Content* content) : FloatedPaneBox(element, content), z_element(element) {} /** Return the z element of the object, if it has any. */ virtual ZElement* GetLocalZElement() { return &z_element; } /** Return the z element list of the object, if it has any. */ virtual StackingContext* GetLocalStackingContext() { return &stacking_context; } /** Lay out box. */ virtual LAYST Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child = NULL, LayoutCoord start_position = LAYOUT_COORD_MIN); /** Traverse z children. */ virtual void TraverseZChildren(TraversalObject* traversal_object, LayoutProperties* layout_props, BOOL after, BOOL handle_overflow_clip); /** Has z children with negative z-index */ virtual BOOL HasNegativeZChildren() { return stacking_context.HasNegativeZChildren(); } }; #ifdef CSS_TRANSFORMS TRANSFORMED_BOX(AbsoluteZRootBox); TRANSFORMED_BOX(PositionedSpaceManagerZRootBox); TRANSFORMED_BOX(PositionedZRootBox); TRANSFORMED_BOX(PositionedZRootFloatingBox); TRANSFORMED_BOX(PositionedZRootFloatedPaneBox); #endif // CSS_TRANSFORMS #endif // _BLOCKBOX_H_
#pragma once #include <comn.h> #include <read_aws_from_mysql.h> // MeteorSearchB 对话框 class MeteorSearchB : public CDialog { DECLARE_DYNAMIC(MeteorSearchB) public: MeteorSearchB(CWnd* pParent = NULL); // 标准构造函数 virtual ~MeteorSearchB(); // 对话框数据 enum { IDD = IDD_METEOR_SEARCH_B }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: enum HOURSPAN{HS0808,HS2020,HSANY}; enum ELEMENT{HIGH_TEMPH,LOW_TEMPH,MAX_WIND,MAX_10WIND,HIGH_STN_PRESS,LOW_STN_PRESS,ACCU_RAIN}; enum STATISWAY{MAXVALUE,MINVALUE,ACCUMULATE}; // 查询开始日期 CTime begin_day; // 查询开始时间 int begin_hour; // 查询结束日期 CTime end_day; // 查询结束时间 int end_hour; BOOL is_anytime_set,is_anyhour_set; //从控件计算出的开始结束时间 CTime begin_time,end_time; //所选择的站点 std::vector<int> select_stations; //选择的时间段 HOURSPAN hour_span; //选择的统计量 STATISWAY statis_way; //需要统计的元素 std::vector<ELEMENT> select_element; std::vector<std::string> head_titles; bool is_wind_query; awssql::QUERY_ELEMENT query_element; std::vector<std::vector<std::string> > view_contents; public: // 后退or前进一天 CButton back_button, forward_button; afx_msg void OnBnClickedButtonBack(); afx_msg void OnBnClickedButtonForward(); afx_msg void OnBnClickedRadioAnyHour(); // 根据选项的变化隐藏或显示窗口 void ButtonShowHideWindow(void); // 将所有选项数值化,作为启动参数 void GetStartArgument(void); // afx_msg void OnBnClickedMaxwind(); afx_msg void OnBnClickedRadioToday(); afx_msg void OnBnClickedRadioYeasterday(); afx_msg void OnBnClickedRadioCurmonth(); afx_msg void OnBnClickedRadioLastmonth(); afx_msg void OnBnClickedCheckAllstation(); afx_msg void OnBnClickedCheckSelectAll(); virtual BOOL OnInitDialog(); afx_msg void OnBnClickedButtonBeginSearch(); // 获取需要显示的内容 void GetViewContent(void); template<typename T> std::string StatisticOnePeriod(T& map, STATISWAY statis_way); template<typename T> std::string StatisticAccumulate(T& map); };
// Created by: Eugeny MALTCHIKOV // Copyright (c) 2017 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 _Bnd_OBB_HeaderFile #define _Bnd_OBB_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Real.hxx> #include <Bnd_Box.hxx> #include <gp_Ax3.hxx> #include <gp_Dir.hxx> #include <gp_Pnt.hxx> #include <gp_XYZ.hxx> #include <TColgp_Array1OfPnt.hxx> #include <TColStd_Array1OfReal.hxx> //! The class describes the Oriented Bounding Box (OBB), //! much tighter enclosing volume for the shape than the //! Axis Aligned Bounding Box (AABB). //! The OBB is defined by a center of the box, the axes and the halves //! of its three dimensions. //! The OBB can be used more effectively than AABB as a rejection mechanism //! for non-interfering objects. class Bnd_OBB { public: DEFINE_STANDARD_ALLOC //! Empty constructor Bnd_OBB() :myIsAABox(Standard_False) { myHDims[0] = myHDims[1] = myHDims[2] = -1.0; } //! Constructor taking all defining parameters Bnd_OBB(const gp_Pnt& theCenter, const gp_Dir& theXDirection, const gp_Dir& theYDirection, const gp_Dir& theZDirection, const Standard_Real theHXSize, const Standard_Real theHYSize, const Standard_Real theHZSize) :myCenter (theCenter.XYZ()), myIsAABox(Standard_False) { myAxes[0] = theXDirection.XYZ(); myAxes[1] = theYDirection.XYZ(); myAxes[2] = theZDirection.XYZ(); Standard_ASSERT_VOID(theHXSize >= 0.0, "Negative value of X-size"); Standard_ASSERT_VOID(theHYSize >= 0.0, "Negative value of Y-size"); Standard_ASSERT_VOID(theHZSize >= 0.0, "Negative value of Z-size"); myHDims[0] = theHXSize; myHDims[1] = theHYSize; myHDims[2] = theHZSize; } //! Constructor to create OBB from AABB. Bnd_OBB(const Bnd_Box& theBox) : myIsAABox(Standard_True) { if (theBox.IsVoid()) { myHDims[0] = myHDims[1] = myHDims[2] = -1.0; myIsAABox = Standard_False; return; } Standard_Real aX1, aY1, aZ1, aX2, aY2, aZ2; theBox.Get(aX1, aY1, aZ1, aX2, aY2, aZ2); myAxes[0].SetCoord(1.0, 0.0, 0.0); myAxes[1].SetCoord(0.0, 1.0, 0.0); myAxes[2].SetCoord(0.0, 0.0, 1.0); myHDims[0] = 0.5*(aX2 - aX1); myHDims[1] = 0.5*(aY2 - aY1); myHDims[2] = 0.5*(aZ2 - aZ1); myCenter.SetCoord(0.5*(aX2 + aX1), 0.5*(aY2 + aY1), 0.5*(aZ2 + aZ1)); } //! Creates new OBB covering every point in theListOfPoints. //! Tolerance of every such point is set by *theListOfTolerances array. //! If this array is not void (not null-pointer) then the resulted Bnd_OBB //! will be enlarged using tolerances of points lying on the box surface. //! <theIsOptimal> flag defines the mode in which the OBB will be built. //! Constructing Optimal box takes more time, but the resulting box is usually //! more tight. In case of construction of Optimal OBB more possible //! axes are checked. Standard_EXPORT void ReBuild(const TColgp_Array1OfPnt& theListOfPoints, const TColStd_Array1OfReal *theListOfTolerances = 0, const Standard_Boolean theIsOptimal = Standard_False); //! Sets the center of OBB void SetCenter(const gp_Pnt& theCenter) { myCenter = theCenter.XYZ(); } //! Sets the X component of OBB - direction and size void SetXComponent(const gp_Dir& theXDirection, const Standard_Real theHXSize) { Standard_ASSERT_VOID(theHXSize >= 0.0, "Negative value of X-size"); myAxes[0] = theXDirection.XYZ(); myHDims[0] = theHXSize; } //! Sets the Y component of OBB - direction and size void SetYComponent(const gp_Dir& theYDirection, const Standard_Real theHYSize) { Standard_ASSERT_VOID(theHYSize >= 0.0, "Negative value of Y-size"); myAxes[1] = theYDirection.XYZ(); myHDims[1] = theHYSize; } //! Sets the Z component of OBB - direction and size void SetZComponent(const gp_Dir& theZDirection, const Standard_Real theHZSize) { Standard_ASSERT_VOID(theHZSize >= 0.0, "Negative value of Z-size"); myAxes[2] = theZDirection.XYZ(); myHDims[2] = theHZSize; } //! Returns the local coordinates system of this oriented box. //! So that applying it to axis-aligned box ((-XHSize, -YHSize, -ZHSize), (XHSize, YHSize, ZHSize)) will produce this oriented box. //! @code //! gp_Trsf aLoc; //! aLoc.SetTransformation (theOBB.Position(), gp::XOY()); //! @endcode gp_Ax3 Position() const { return gp_Ax3 (myCenter, ZDirection(), XDirection()); } //! Returns the center of OBB const gp_XYZ& Center() const { return myCenter; } //! Returns the X Direction of OBB const gp_XYZ& XDirection() const { return myAxes[0]; } //! Returns the Y Direction of OBB const gp_XYZ& YDirection() const { return myAxes[1]; } //! Returns the Z Direction of OBB const gp_XYZ& ZDirection() const { return myAxes[2]; } //! Returns the X Dimension of OBB Standard_Real XHSize() const { return myHDims[0]; } //! Returns the Y Dimension of OBB Standard_Real YHSize() const { return myHDims[1]; } //! Returns the Z Dimension of OBB Standard_Real ZHSize() const { return myHDims[2]; } //! Checks if the box is empty. Standard_Boolean IsVoid() const { return ((myHDims[0] < 0.0) || (myHDims[1] < 0.0) || (myHDims[2] < 0.0)); } //! Clears this box void SetVoid() { myHDims[0] = myHDims[1] = myHDims[2] = -1.0; myCenter = myAxes[0] = myAxes[1] = myAxes[2] = gp_XYZ(); myIsAABox = Standard_False; } //! Sets the flag for axes aligned box void SetAABox(const Standard_Boolean& theFlag) { myIsAABox = theFlag; } //! Returns TRUE if the box is axes aligned Standard_Boolean IsAABox() const { return myIsAABox; } //! Enlarges the box with the given value void Enlarge(const Standard_Real theGapAdd) { const Standard_Real aGap = Abs(theGapAdd); myHDims[0] += aGap; myHDims[1] += aGap; myHDims[2] += aGap; } //! Returns the array of vertices in <this>. //! The local coordinate of the vertex depending on the //! index of the array are follow: //! Index == 0: (-XHSize(), -YHSize(), -ZHSize()) //! Index == 1: ( XHSize(), -YHSize(), -ZHSize()) //! Index == 2: (-XHSize(), YHSize(), -ZHSize()) //! Index == 3: ( XHSize(), YHSize(), -ZHSize()) //! Index == 4: (-XHSize(), -YHSize(), ZHSize()) //! Index == 5: ( XHSize(), -YHSize(), ZHSize()) //! Index == 6: (-XHSize(), YHSize(), ZHSize()) //! Index == 7: ( XHSize(), YHSize(), ZHSize()). Standard_Boolean GetVertex(gp_Pnt theP[8]) const { if(IsVoid()) return Standard_False; theP[0].SetXYZ(myCenter - myHDims[0]*myAxes[0] - myHDims[1]*myAxes[1] - myHDims[2]*myAxes[2]); theP[1].SetXYZ(myCenter + myHDims[0]*myAxes[0] - myHDims[1]*myAxes[1] - myHDims[2]*myAxes[2]); theP[2].SetXYZ(myCenter - myHDims[0]*myAxes[0] + myHDims[1]*myAxes[1] - myHDims[2]*myAxes[2]); theP[3].SetXYZ(myCenter + myHDims[0]*myAxes[0] + myHDims[1]*myAxes[1] - myHDims[2]*myAxes[2]); theP[4].SetXYZ(myCenter - myHDims[0]*myAxes[0] - myHDims[1]*myAxes[1] + myHDims[2]*myAxes[2]); theP[5].SetXYZ(myCenter + myHDims[0]*myAxes[0] - myHDims[1]*myAxes[1] + myHDims[2]*myAxes[2]); theP[6].SetXYZ(myCenter - myHDims[0]*myAxes[0] + myHDims[1]*myAxes[1] + myHDims[2]*myAxes[2]); theP[7].SetXYZ(myCenter + myHDims[0]*myAxes[0] + myHDims[1]*myAxes[1] + myHDims[2]*myAxes[2]); return Standard_True; } //! Returns square diagonal of this box Standard_Real SquareExtent() const { return 4.0 * (myHDims[0] * myHDims[0] + myHDims[1] * myHDims[1] + myHDims[2] * myHDims[2]); } //! Check if the box do not interfere the other box. Standard_EXPORT Standard_Boolean IsOut(const Bnd_OBB& theOther) const; //! Check if the point is inside of <this>. Standard_EXPORT Standard_Boolean IsOut(const gp_Pnt& theP) const; //! Check if the theOther is completely inside *this. Standard_EXPORT Standard_Boolean IsCompletelyInside(const Bnd_OBB& theOther) const; //! Rebuilds this in order to include all previous objects //! (which it was created from) and theOther. Standard_EXPORT void Add(const Bnd_OBB& theOther); //! Rebuilds this in order to include all previous objects //! (which it was created from) and theP. Standard_EXPORT void Add(const gp_Pnt& theP); //! Dumps the content of me into the stream Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const; protected: void ProcessOnePoint(const gp_Pnt& theP) { myIsAABox = Standard_True; myHDims[0] = myHDims[1] = myHDims[2] = 0.0; myAxes[0].SetCoord(1.0, 0.0, 0.0); myAxes[1].SetCoord(0.0, 1.0, 0.0); myAxes[2].SetCoord(0.0, 0.0, 1.0); myCenter = theP.XYZ(); } private: //! Center of the OBB gp_XYZ myCenter; //! Directions of the box's axes //! (all vectors are already normalized) gp_XYZ myAxes[3]; //! Half-size dimensions of the OBB Standard_Real myHDims[3]; //! To be set if the OBB is axis aligned box; Standard_Boolean myIsAABox; }; #endif
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #pragma once #include "Core/Log.hpp" #include <new> #include <string> #include <utility> #include <cassert> #include <type_traits> namespace Push { class Variant { public: Variant(); template<typename T> Variant(T&& rhs); Variant(const Variant& rhs); ~Variant(); template<typename T> Variant& operator=(T&& rhs); Variant& operator=(const Variant& rhs); template<typename T> bool Is() const; template<typename T> T& Get(); template<typename T> const T& Get() const; template<typename T> bool Get(T& value) const; private: template<typename T> static void Delete(void** ptr); template<typename T> static void Copy(void** dst, void* const* src); template<typename T> void Assign(T&& rhs); template<typename T> static bool ConstructInPlace(); private: union { void* m_pointer; char m_padding[sizeof(std::string)]; }; void (*m_copy)(void**, void* const*); void (*m_delete)(void**); }; template<typename T> bool Variant::ConstructInPlace() { return sizeof(T) <= sizeof(m_padding) && alignof(Variant) % alignof(T) == 0; } template<typename T> void Variant::Delete(void** ptr) { if (ConstructInPlace<T>()) { reinterpret_cast<T*>(ptr)->~T(); } else { delete static_cast<T*>(*ptr); } } template<> void Variant::Delete<void>(void**ptr); template<typename T> void Variant::Copy(void** dst, void* const* src) { if (ConstructInPlace<T>()) { new(dst) T(*reinterpret_cast<const T*>(src)); } else { *dst = new T(*static_cast<T*>(*src)); } } template<> void Variant::Copy<void>(void** dst, void* const* src); template<typename T> void Variant::Assign(T&& rhs) { m_delete(&m_pointer); using Type = typename std::decay<T>::type; static_assert(!std::is_pointer<Type>::value, "Variant doesn't support pointers"); if (ConstructInPlace<Type>()) { new(&m_pointer) Type(std::forward<T>(rhs)); } else { m_pointer = new Type(std::forward<T>(rhs)); } m_copy = Copy<Type>; m_delete = Delete<Type>; } template<> void Variant::Assign<Variant>(Variant&& rhs); template<> void Variant::Assign<Variant&>(Variant& rhs); template<> void Variant::Assign<const Variant&>(const Variant& rhs); template<typename T> Variant::Variant(T&& rhs) : m_pointer(nullptr) , m_copy(Copy<void>) , m_delete(Delete<void>) { Assign<T>(std::forward<T>(rhs)); } template<typename T> Variant& Variant::operator=(T&& rhs) { Assign<T>(std::forward<T>(rhs)); return *this; } template<typename T> bool Variant::Is() const { using Type = typename std::decay<T>::type; return Variant::Delete<Type> == m_delete; } template<typename T> T& Variant::Get() { using Type = typename std::decay<T>::type; assert(Variant::Delete<Type> == m_delete && "Invalid type for get!"); if (Variant::ConstructInPlace<Type>()) { return *reinterpret_cast<Type*>(&m_pointer); } return *reinterpret_cast<Type*>(m_pointer); } template<typename T> const T& Variant::Get() const { using Type = typename std::decay<T>::type; assert(Variant::Delete<Type> == m_delete && "Invalid type for get!"); if (Variant::ConstructInPlace<Type>()) { return *reinterpret_cast<const Type*>(&m_pointer); } return *reinterpret_cast<const Type*>(m_pointer); } template<typename T> bool Variant::Get(T& value) const { using Type = typename std::decay<T>::type; if (Variant::Delete<Type> == m_delete) { if (Variant::ConstructInPlace<Type>()) { value = *reinterpret_cast<const Type*>(&m_pointer); } else { value = *reinterpret_cast<const Type*>(m_pointer); } return true; } Log(LogType::Warning, "Variant", "Invalid type!"); return false; } }
/* Programación Orientada a Objetos PROYECTO 3 Ana Elisa Estrada Lugo A01251091 05/06/2020 */ //Material.h #include <iostream> #include <string> #ifndef MATERIAL_H #define MATERIAL_H using namespace std; class Material{ public: Material(); Material(int idM, string t); void setIdMaterial(int idM); void setTitulo(string t); int getIdMaterial(); string getTitulo(); virtual void muestraDatos()=0; virtual int cantidadDiasPrestamo()=0; protected: int idMaterial; string titulo; }; Material::Material(){ idMaterial = 0; titulo = "S/T"; } Material::Material(int idM,string t){ idMaterial = idM; titulo = t; } void Material::setIdMaterial(int idM){ idMaterial = idM; } void Material::setTitulo(string t){ titulo = t; } int Material::getIdMaterial(){ return idMaterial; } string Material::getTitulo(){ return titulo; } void Material::muestraDatos(){ cout<<"Id Material: "<<idMaterial<<endl; cout<<"Título: "<<titulo<<endl; } #endif
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "1234" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 10000 struct edge{ int one,two,weight; bool operator < (const edge &r ) const{ return weight > r.weight; } }; int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int times; scanf("%d",&times); int point,num; int set[MAXN+5],i; vector <edge> graph; edge tmp; int point_A,point_B; while( times-- ){ scanf("%d %d",&point,&num); for( i = 0 ; i <= point ; i++ ) set[i] = i; for( i = 0 ; i < num ; i++ ){ scanf("%d %d %d", &tmp.one, &tmp.two, &tmp.weight ); graph.push_back(tmp); } sort(&graph[0],&graph[num]); int ans = 0; for( i = 0 ; i < num ; i++ ){ point_A = graph[i].one; point_B = graph[i].two; while( set[point_A] != point_A ) point_A = set[point_A]; while( set[point_B] != point_B ) point_B = set[point_B]; if( point_A == point_B ) ans = ans + graph[i].weight; else set[point_B] = point_A; } printf("%d\n",ans ); graph.clear(); } return 0; }
#include "CocosPillar.h" #include "Definitions.h" USING_NS_CC; // Initialize instance (physics) bool CocosPillar::init() { // Super init first if (!Pillar::init()) return false; auto topPillarBody = PhysicsBody::createBox(topPillar_->getContentSize()); auto botPillarBody = PhysicsBody::createBox(botPillar_->getContentSize()); topPillarBody->setDynamic(false); botPillarBody->setDynamic(false); topPillarBody->setCollisionBitmask(COLLISION_BITMASK_OBSTACLE); botPillarBody->setCollisionBitmask(COLLISION_BITMASK_OBSTACLE); topPillarBody->setContactTestBitmask(COLLISION_BITMASK_SPACESHIP); botPillarBody->setContactTestBitmask(COLLISION_BITMASK_SPACESHIP); topPillar_->setPhysicsBody(topPillarBody); botPillar_->setPhysicsBody(botPillarBody); return true; }
//------------------------------------------------------------------------------ /* This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef BEAST_ATOMICFLAG_H_INCLUDED #define BEAST_ATOMICFLAG_H_INCLUDED /*============================================================================*/ /** A thread safe flag. This provides a simplified interface to an atomic integer suitable for representing a flag. The flag is signaled when on, else it is considered reset. @ingroup beast_core */ class BEAST_API AtomicFlag { public: /** Create an AtomicFlag in the reset state. */ AtomicFlag () noexcept : m_value (0) { } /** Signal the flag. If two or more threads simultaneously attempt to signal the flag, only one will receive a true return value. @return true if the flag was previously reset. */ inline bool trySignal () noexcept { return m_value.compareAndSetBool (1, 0); } /** Signal the flag. The flag must be in the reset state. Only one thread may call this at a time. */ inline void signal () noexcept { #if BEAST_DEBUG const bool success = m_value.compareAndSetBool (1, 0); bassert (success); #else m_value.set (1); #endif } /** Reset the flag. The flag must be in the signaled state. Only one thread may call this at a time. Usually it is the thread that was successful in a previous call to trySignal(). */ inline void reset () noexcept { #if BEAST_DEBUG const bool success = m_value.compareAndSetBool (0, 1); bassert (success); #else m_value.set (0); #endif } /** Check if the AtomicFlag is signaled The signaled status may change immediately after this call returns. The caller must synchronize. @return true if the flag was signaled. */ inline bool isSignaled () const noexcept { return m_value.get () == 1; } private: Atomic <int> m_value; }; #endif
#include <fstream> int main() { std::fstream i("input.txt"), o("output.txt", 2); int a, b, c, d, x = -100; i >> a >> b >> c >> d; for (; x < 101; ++x) if ( x*(a*x*x + b*x + c) == -d) o << x << " "; }
/** * Definition for a binary tree node. */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; inorder(res, root); return res; } void inorder(vector<int>& res, TreeNode* root){ if(root==nullptr) return; inorder(res, root->left); res.push_back(root->val); inorder(res, root->right); } };
#include "../device.hpp" void BufferMul() { Device clDevice; clDevice.Init(); //! Init data //create input data on CPU int num = 1024; float *h_idata = (float*)malloc(sizeof(float)* num); for (int i = 0; i < num; i++){ h_idata[i] = i; } //allocate memory for the results on CPU float *h_odata = (float*)malloc(sizeof(float)* num); //allocate memory and data on GPU cl_mem d_idata = clCreateBuffer(clDevice.Context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float)*num, h_idata, NULL); cl_mem d_odata = clCreateBuffer(clDevice.Context, CL_MEM_READ_WRITE, sizeof(float)*num, NULL, NULL); //! Get kernel std::string kernel_name = "mul2"; cl_kernel Kernel = clDevice.GetKernel(kernel_name); //! Set argments cl_int ret; ret = clSetKernelArg(Kernel, 0, sizeof(cl_mem), (void*)&d_idata); ret |= clSetKernelArg(Kernel, 1, sizeof(cl_mem), (void*)&d_odata); OCL_CHECK(ret, "mul2: clSetKernelArg"); //! Set global and local work size size_t global_work_size[] = { (size_t)num }; size_t local_work_size[] = { 256 }; //! Excute kernel OCL_CHECK( clEnqueueNDRangeKernel(clDevice.CommandQueue, Kernel, 1, NULL,global_work_size, local_work_size, 0, NULL, NULL), "mul2: kernel"); //! Get outputs // copy result from device to host clEnqueueReadBuffer(clDevice.CommandQueue, d_odata, CL_TRUE, 0, num * sizeof(float), h_odata, 0, NULL, NULL); for(int i=0; i<10; i++) std::cout << h_idata[i] << " " << h_odata[i] << std::endl; }
#include<bits/stdc++.h> using namespace std; int main() { //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); int x,y; int sum = 0; cin>>x>>y; if(x>y) { for(int i=(y+1); i<x; i++) { if(i%2 != 0) { sum = sum+i; } } } else if(x<y) { for(int i=(x+1); i<y; i++) { if(i%2 != 0) { sum = sum+i; } } } cout<<sum<<"\n"; return 0; }
// // Created by xiang on 18-11-19. // #include <iostream> #include <opencv2/core/core.hpp> #include <ceres/ceres.h> #include <chrono> using namespace std; // 代价函数的计算模型 struct CURVE_FITTING_COST { CURVE_FITTING_COST(double x, double y) : _x(x), _y(y) {} // 残差的计算 template<typename T> bool operator()( const T *const abc, // 模型参数,有3维 T *residual) const { residual[0] = T(_y) - ceres::exp(abc[0] * T(_x) * T(_x) + abc[1] * T(_x) ); // y-exp(ax^2+bx+c) return true; } const double _x, _y; // x,y数据 }; int main(int argc, char **argv) { double ar = 1.0, br = 0.5; // 真实参数值 double ae = 2.0, be = -2.0; // 估计参数值 int N = 100; // 数据点 double w_sigma = 0.5; // 噪声Sigma值 double inv_sigma = 1.0 / w_sigma; cv::RNG rng; // OpenCV随机数产生器 vector<double> x_data, y_data; // 数据 for (int i = 0; i < N; i++) { double x = i / 100.0; x_data.push_back(x); y_data.push_back(exp(ar * x * x + br * x ) + rng.gaussian(w_sigma * w_sigma)); } double abc[3] = {ae, be}; // 构建最小二乘问题 ceres::Problem problem; for (int i = 0; i < N; i++) { problem.AddResidualBlock( // 向问题中添加误差项 // 使用自动求导,模板参数:误差类型,输出维度,输入维度,维数要与前面struct中一致 new ceres::AutoDiffCostFunction<CURVE_FITTING_COST, 1, 2>( new CURVE_FITTING_COST(x_data[i], y_data[i]) ), nullptr, // 核函数,这里不使用,为空 abc // 待估计参数 ); } // 配置求解器 ceres::Solver::Options options; // 这里有很多配置项可以填 options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY; // 增量方程如何求解 options.minimizer_progress_to_stdout = true; // 输出到cout ceres::Solver::Summary summary; // 优化信息 chrono::steady_clock::time_point t1 = chrono::steady_clock::now(); ceres::Solve(options, &problem, &summary); // 开始优化 chrono::steady_clock::time_point t2 = chrono::steady_clock::now(); chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1); cout << "solve time cost = " << time_used.count() << " seconds. " << endl; // 输出结果 cout << summary.BriefReport() << endl; cout << "estimated a,b = "; for (auto a:abc) cout << a << " "; cout << endl; return 0; }
#include <iostream> #include <unistd.h> #include <cmath> #include <cstdio> #include <cstdlib> #include <string.h> #include <assert.h> #include <stdint.h> #include "globalTypes.h" #include "linkBlocks.h" #include <vector> using namespace std; vector<uint32_t> schedule[MAX_NUM_CMDS]; vector<uint32_t> cmdInd; uint32_t numScheds; void print_schedule(){ for ( uint32_t i = 0; i < numScheds; i++){ printf("\nPrinting Schedule %d: -------------\n", i); for ( uint32_t j = 0; j < schedule[i].size(); j++ ){ if ( j != 0){ printf("======>\t"); } else printf("\t"); printf("CmdEntry %d: ",schedule[i][j]); uint32_t input_addr_0 = globalCmdEntryBuff[schedule[i][j]].table0Addr; uint32_t input_addr_1 = globalCmdEntryBuff[schedule[i][j]].table1Addr; uint32_t output_addr = globalCmdEntryBuff[schedule[i][j]].outputAddr; switch (globalCmdEntryBuff[schedule[i][j]].op){ case SELECT: printf("SELECT{inputAddr: %d, outputAddr: %d}", input_addr_0, output_addr); break; case PROJECT: printf("PROJECT:{inputAddr: %d, outputAddr: %d}", input_addr_0, output_addr); break; case DEDUP: printf("DEDUP:{inputAddr: %d, outputAddr: %d}", input_addr_0, output_addr); break; case XPROD: printf("XPROD:{inputAddrs: %d and %d , outputAddr: %d}", input_addr_0, input_addr_1, output_addr); break; case UNION: printf("UNION:{inputAddrs: %d and %d , outputAddr: %d}", input_addr_0, input_addr_1, output_addr); break; case DIFFERENCE: printf("DIFFERENCE:{inputAddrs: %d and %d , outputAddr: %d}", input_addr_0, input_addr_1, output_addr); break; default: break; } printf("\n"); } } } void scheduleCmds(){ printf("Linking Blocks: enable data streaming between blocks????\n"); //printf("here here"); for (uint32_t i = 0; i < globalNCmds; i++) cmdInd.push_back(i); uint32_t ptr = 0; bool select_taken = false; bool project_taken = false; uint32_t tail_ind; uint32_t numChild; uint32_t new_tail_ind; bool dependence_found; while ( !cmdInd.empty() ){ if ( schedule[ptr].empty() ){ // a new schedule starts schedule[ptr].push_back(cmdInd.front()); cmdInd.erase(cmdInd.begin()); select_taken = false; project_taken = false; } else { // dependence_found = false; tail_ind = schedule[ptr][schedule[ptr].size()-1]; numChild = 0; for ( uint32_t i = 0; i < cmdInd.size(); i++){ uint32_t ind = cmdInd[i]; if ( globalCmdEntryBuff[tail_ind].outputAddr == globalCmdEntryBuff[ind].table1Addr) numChild++; if ( globalCmdEntryBuff[tail_ind].outputAddr == globalCmdEntryBuff[ind].table0Addr){ numChild++; if (globalCmdEntryBuff[ind].op == SELECT && !select_taken){ new_tail_ind = i; select_taken = true; dependence_found = true; } if (globalCmdEntryBuff[ind].op == PROJECT && !project_taken){ new_tail_ind = i; project_taken = true; dependence_found = true; } } } if ( numChild == 1 && dependence_found){ schedule[ptr].push_back(cmdInd[new_tail_ind]); cmdInd.erase(cmdInd.begin()+new_tail_ind); } else{ ptr++; } } } numScheds = ptr + 1; print_schedule(); }
#include "forme.h" int main() { Circle c; return 0; }
#pragma once #ifndef _CALCULATOR_LEXICAL_ANALYSIS_H_ #define _CALCULATOR_LEXICAL_ANALYSIS_H_ #include <iostream> #include <vector> #include <string> #include <cmath> #include "KyleBase.h" #include "Symbol.h" using namespace std; class LexicalAnalysis { public: //进行词法解析,简单实现 static vector<Symbol>& analysis(string str, vector<Symbol>& sequences); }; #endif // !_CALCULATOR_LEXICAL_ANALYSIS_H_
#ifdef TASK_INFO void Info_task(void * parameter) { for (;;) { delay(100); #else void update_Info() { { #endif if ((millis() - msPrint) > SHOW_PERIOD) { check_ZeroCross(); Pset = selectPower(); print_Serial(); update_DS(); #ifndef TASK_INFO display_Oled(); #endif //!TASK_SHOW update_Modbus(); check_WiFi(); check_Serial(); D(INFOcore = xPortGetCoreID()); print_Debug1(); print_Debug2(); reset_Counters(); msPrint = millis(); DPRINTF("PrevPrint: ", msPrint); DPRINTF("PrevDisplay: ", msDisplay); } } } void setPower(uint16_t Ptmp) { #ifdef USE_MODBUS mb.Hreg(hrPSET, Ptmp); #endif Premote = Ptmp; } uint16_t selectPower() // Check here for LocalControl flag, Modbus heartbeat and priority of sources. { uint16_t Plocal; #ifdef USE_MODBUS if (mbMasterOK) Premote = mb.Hreg(hrPSET); #endif if (RemoteON) Plocal = Premote; else Plocal = Pencoder; return Plocal; } void check_Encoder() { #ifdef USE_ENCODER key.readkey(); if (showSetMenu) key.readencoder(); // можно не так часто if ((millis() - msKeys) > 200) { msKeys = millis(); check_Keys(); if (showSetMenu) display_Oled(); } #endif } void check_Keys() { #ifdef USE_ENCODER if (key.shot_press()) // Короткое нажатие кнопки { LD_init(); if (!RemoteON) { showSetMenu = !showSetMenu; if (showSetMenu) Pencoder = Pset; DPRINTLN(". ENCODER Short while Local"); } else { showPower = !showPower; LD_clearDisplay(); LD_printString_12x16("switch ...", 2, 6); // индикатор короткого нажатия на энкодер DPRINTLN(". ENCODER Short while Remote"); } } // Долгое нажатие кнопки - переход с МБ на локальное управление !! if (key.long_press()) { showSetMenu = false; showPower = true; setPower(0); Pencoder = 0; RemoteON = !RemoteON; PRINTLN(". ENCODER Long Press"); } if (key.encoder) // вращение { if (showSetMenu) { Pencoder += int(ENCODER_STEP * key.encoder * abs(key.encoder)); Pencoder = (Pencoder < 0) ? 0 : (Pencoder > POWER_MAX) ? POWER_MAX : Pencoder; Pset = Pencoder; setPower(Pset); // мощность будет меняться во время кручения энкодера } key.encoder = 0; } if (key.previous_millis_down + 10000 < millis()) showSetMenu = false; #endif } void check_Serial() { #ifdef USE_SETSERIAL String T1, Var; while (Serial.available()) //Serial port, пока не конец сообщения, читаем данные и формируем строку { char ch = Serial.read(); Var += ch; if (ch == '\n') { Var.toUpperCase(); // ?? if (Var.substring(0, 2) == "SP") { T1 = Var.substring(Var.indexOf("SP", 2) + 3); //команда Pserial = T1.toFloat(); //Выставленная мощность с Serial setPower(Pserial); } Var = ""; } } #endif } void reset_Counters() { _cntrZC = 0; #ifdef DEV_DEBUG cntrRMS = 0; _cntrTR = 0; _cntrTRopen = 0; _cntrTRclose = 0; _tmrTriacNow = 0; tmrOpen = 0; tmrClose = 0; adcUmax = 0; adcImax = 0; #endif }
// Created on: 1991-04-11 // Created by: Laurent PAINNOT // Copyright (c) 1991-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 _AppParCurves_HeaderFile #define _AppParCurves_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <math_Vector.hxx> #include <math_IntegerVector.hxx> class math_Matrix; //! Parallel Approximation in n curves. //! This package gives all the algorithms used to approximate a MultiLine //! described by the tool MLineTool. //! The result of the approximation will be a MultiCurve. class AppParCurves { public: DEFINE_STANDARD_ALLOC Standard_EXPORT static void BernsteinMatrix (const Standard_Integer NbPoles, const math_Vector& U, math_Matrix& A); Standard_EXPORT static void Bernstein (const Standard_Integer NbPoles, const math_Vector& U, math_Matrix& A, math_Matrix& DA); Standard_EXPORT static void SecondDerivativeBernstein (const Standard_Real U, math_Vector& DDA); Standard_EXPORT static void SplineFunction (const Standard_Integer NbPoles, const Standard_Integer Degree, const math_Vector& Parameters, const math_Vector& FlatKnots, math_Matrix& A, math_Matrix& DA, math_IntegerVector& Index); }; #endif // _AppParCurves_HeaderFile
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "11854" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 100 int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int tri[5]; while( ~scanf("%d %d %d",&tri[0],&tri[1],&tri[2]) && tri[0] ){ sort(&tri[0],&tri[3]); if( tri[0]*tri[0]+tri[1]*tri[1] == tri[2]*tri[2] ) printf("right\n"); else printf("wrong\n"); } return 0; }
#ifndef __SHADE_H__ #define __SHADE_H__ #include "cocos2d.h" USING_NS_CC; class Shade : public Node { public: virtual bool init(); void initWithLevel(int level, int index); // implement the "static create()" method manually CREATE_FUNC(Shade); public: Sprite* sp; int level; //color int index; //pos }; #endif // __SHADE_H__
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; 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. */ #ifndef OP_SPEED_DIAL_LISTENER_H #define OP_SPEED_DIAL_LISTENER_H class OpSpeedDialView; class OpSpeedDialListener { public: virtual ~OpSpeedDialListener() {} /** Called when speed dial contents change */ virtual void OnContentChanged(OpSpeedDialView* speeddial) = 0; }; #endif // OP_SPEED_DIAL_LISTENER_H
#include "MQ135.h" #include <ESP8266WiFi.h> #define ANALOGPIN A0 WiFiClient client; String apiKey = "Z1T563WF17IV62TW"; // Enter your Write API key from ThingSpeak const char *ssid = "Moto G3 TE"; // replace with your wifi ssid and wpa2 key const char *pass = "physics@science"; const char* server = "api.thingspeak.com"; MQ135 gasSensor = MQ135(ANALOGPIN); //int sum =0; //int den=1; void setup() { // put your setup code here, to run once: Serial.begin(115200); WiFi.disconnect(); delay(10); WiFi.begin(ssid, pass); Serial.println(); Serial.println("Connecting to "); Serial.println(ssid); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); pinMode(5, OUTPUT); // pinmode for led } void loop() { digitalWrite(5, LOW); // put your main code here, to run repeatedly: float ppm = gasSensor.getPPM(); //float rzero = gasSensor.getRZero(); Serial.println(ppm); /**Serial.println(rzero); sum=sum+rzero; float avg=(sum)/den; den=den+1; Serial.println("avg="); Serial.print(avg);**/ if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com { String postStr = apiKey; postStr +="&field1="; postStr += String(ppm); postStr += String("\r\n\r\n"); client.print("POST /update HTTP/1.1\n"); client.print("Host: api.thingspeak.com\n"); client.print("Connection: close\n"); client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n"); client.print("Content-Type: application/x-www-form-urlencoded\n"); client.print("Content-Length: "); client.print(postStr.length()); client.print("\n\n"); client.print(postStr); Serial.println("%. Send to Thingspeak."); } client.stop(); Serial.println("Waiting..."); if(ppm>400) { digitalWrite(5, HIGH); // turn the LED on (HIGH is the voltage level) } else { digitalWrite(5, LOW); // turn the LED off (LOW the voltage level) } delay(1600); }
#include <iostream> using namespace std; const int max_arr = 16; int search_num = 421; int recursion_binary_search(int * p, int left_n, int right_n, int num); int main() { int arr[max_arr] = {1,31,61,91,121,151,181,211,241,271,301,331,361,391,421,999}; int num = recursion_binary_search(arr, 0 , max_arr,search_num); cout << search_num <<"位置为:" << num << endl; for (int i = 0; i < max_arr; ++i) { cout << arr[i] <<"位置为:" << recursion_binary_search(arr,0, max_arr,arr[i]) << endl; } return 0; } int recursion_binary_search(int * p, int left_n, int right_n, int num) { int min = left_n; int max = right_n; int mid = (max + min)/2; if (p[mid] == num) return mid; else if (p[mid] > num) recursion_binary_search(p, min, mid-1, num); else recursion_binary_search(p, mid+1, max, num); }
#include "Timer.h" #include "AudioListener.h" #include "KeyboardListener.h" #include <QDebug> #include <QThread> #include <QTime> #include <StatsUtility.h> #include <mainui.h> #include <TaskerPerf/perftimer.h> #include <iostream> using namespace Engine; using namespace util; using namespace udata; Timer *Timer::thisInstance; /** * @brief Timer::Timer */ Timer::Timer(int newNiceness) { currentProductiveTime = 0; currentUnproductiveTime = 0; timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &Timer::tickUpdate); connect(this, &Timer::stopTimer, this, &Timer::stopTimerSlot); } /** * @brief Timer::Timer * @param newListenerType This tells timer what type of listener to instantiate. * It's not the prettiest way of doing this, but at least we're not doing * weird/prone-to-bugs type probing at runtime, like dynamic_cast nonsense. * */ Timer::Timer(Listener::ListenerType newListenerType, Session newSession) { qDebug() << "Timer() constructor: " << currentThreadId(); currentSession = newSession; listenerType = newListenerType; currentProductiveTime = 0; currentUnproductiveTime = 0; connect(timer, &QTimer::timeout, this, &Timer::tickUpdate); timer = new QTimer(this); connect(this, &Timer::stopTimer, this, &Timer::stopTimerSlot); qDebug() << "Timer() constructor after start(): " << currentThreadId(); } /** * @brief Timer::~Timer */ Timer::~Timer() { if (timer != nullptr) delete timer; delete listener; } /** * @brief Timer::run * This function is called when the thread starts. *Any and all QObjects(such as Listener) MUST be instantiated inside this method. * Otherwise, QT's thread management will NOT consider that QObject as part of the Timer * thread. *The code in &Listener::start, which is the ACTUAL code that listents to hardware, * does not run until the startListner() signal is sent. */ void Timer::run() { qDebug() << "run method on Timer:" << QThread::currentThreadId(); startTimer(); exec(); } void Timer::startTimer() { qDebug() << "From work thread: " << currentThreadId(); if (listenerType == Listener::ListenerType::keyboard) { listener = new KeyboardListener(); } else if (listenerType == Listener::ListenerType::audio) { listener = new AudioListener(); } /** This block of code WORKS! DO NOT DELETE THIS BLOCK OF CODE. IT IS PERFECT! Specifically the statements regarding the listener and listenerThread. I'm talking about the next 3 lines of code. */ connect(&listenerThread, &QThread::started, listener, &Listener::start); listener->moveToThread(&listenerThread); listenerThread.start(); } /** * @brief Timer::tickUpdate * This is a time-sensitive function. Whatever it executes, it MUST return * within 1 second. * Current latency(average)= 14000 nanoseconds */ void Timer::tickUpdate() { newPerfTimer.restart(); int tickDelta; if (listener->getState() == Listener::ListenerState::productive) { tickDelta = tickCount - producitveTickCount; currentProductiveTime += 1; producitveTickCount += 1; lastProductiveTick = tickCount; } else { currentUnproductiveTime += unproductiveTimeSurplus; unProducitveTickCount += 1; lastUnproductiveTick = tickCount; } totalTimeElapsed = currentProductiveTime + currentUnproductiveTime; if (currentProductiveTime == productiveTimeGoal) { timer->stop(); emit stopTimer(); } updateProductiveStatus(); updateUnproductiveStatus(); updateTimeElapsedStatus(); tickCount++; newPerfTimer.stop(); qDebug()<<"tick update on Timer took this long(nanoseconds):"<<newPerfTimer.duration; emit tick(); } int Timer::getTotalTimeElapsed() { return currentUnproductiveTime + currentProductiveTime; } Timer *Timer::getInstance() { if (thisInstance == nullptr) { thisInstance = new Timer(); } return thisInstance; } void Timer::setCurrentSession(Session newSession) { currentSession = newSession; productiveTimeGoal = currentSession.getGoal(); } void Timer::setListener(Listener::ListenerType newListenerType) { listenerType = newListenerType; } void Timer::initTimer(Listener::ListenerType newListener, udata::Session newSession) { thisInstance->setCurrentSession(newSession); thisInstance->setListener(newListener); timer->start(TIMER_TICK); this->start(); } /** * @brief Timer::productiveSlot * * Called every time the listener emits the prductive signal. * This function can be used to crunch more stats on hardware interaction. * For example; we could keep internal productive counters on timer * and give the user data such as "you were most productive * on the first 10 minutes of the session" because there was a constant increment * on your productive signal count. I think the possibilities are endless, in terms of data, * depending on the context, whether they're writing or practicing music. * */ void Timer::productiveSlot() { productiveSignalCount++; } /** * @brief Timer::unProductiveSlot *Called every time the listener emits the unProductive signal. * This function can be used to crunch more stats on hardware interaction. * For example; we could keep internal unProductive counters on Timer * and give the user data such as "you were least productive * on the first 10 minutes of the session" because there was a constant decrement * on your productive signal count. That's just a silly example, but I think the possibilities are endless, * in terms of data, * depending on the context, whether they're writing or practicing music. * */ void Timer::unProductiveSlot() { unProductiveSignalCount++; } void Timer::stopTimerSlot() { emit congrats(); timer->stop(); } void Timer::updateProductiveStatus() { long long int productiveMinutes = StatsUtility::toMinutes(currentProductiveTime); int resultProductive = currentProductiveTime; if (resultProductive > MINUTE) { resultProductive = currentProductiveTime - (productiveMinutes * MINUTE); } else if (resultProductive % MINUTE == 0) { resultProductive = 0; } productiveStatus = QString::number(productiveMinutes) + ":" + QString::number(resultProductive); if (productiveMinutes == ZERO) { } else { } } /** * @brief Timer::getProductiveStatus * @return the productime time status(the string representation) * of the current productive time count. */ QString& Timer::getProductiveStatus() { return productiveStatus; } void Timer::updateUnproductiveStatus() { long long int productiveMinutes = StatsUtility::toMinutes(currentUnproductiveTime); int resultProductive = currentUnproductiveTime; if (currentUnproductiveTime > MINUTE) { resultProductive = currentUnproductiveTime - (productiveMinutes * MINUTE); } else if (resultProductive % MINUTE == 0) { resultProductive = 0; } UnproductiveStatus = QString::number(productiveMinutes) + ":" + QString::number(resultProductive); } QString& Timer::getUnproductiveStatus() { return UnproductiveStatus; } void Timer::updateTimeElapsedStatus() { long long int productiveMinutes = StatsUtility::toMinutes(totalTimeElapsed); int resultProductive = totalTimeElapsed; if (resultProductive > MINUTE) { resultProductive = totalTimeElapsed - (productiveMinutes * MINUTE); } else if (resultProductive % MINUTE == 0) { resultProductive = 0; } TimeElapsedStatus = QString::number(productiveMinutes) + ":" + QString::number(resultProductive); } QString& Timer::getTimeElapsedStatus() { return TimeElapsedStatus; }
/* * @lc app=leetcode.cn id=698 lang=cpp * * [698] 划分为k个相等的子集 */ // @lc code=start #include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: bool canPartitionKSubsets(vector<int>& nums, int k) { int sum = 0; for(int i : nums)sum+=i; if(sum % k > 0) return false; int target = sum / k; } bool canPartitionKSubsets2(vector<int>& nums, int k) { int sum = 0; for(int i : nums)sum+=i; if(sum % k > 0) return false; int target = sum / k; sort(nums.begin(), nums.end()); int row = nums.size() - 1; if(nums[row] > target) return false; while(row>=0 && nums[row] == target){ row--; k--; } return search(vector<int>(k, 0), row, nums, target); } bool search(vector<int> groups, int row, vector<int> nums, int target) { if(row < 0) return true; int v = nums[row--]; for(int i=0;i<groups.size();i++) { if(groups[i]+v <= target) { groups[i] += v; if(search(groups, row, nums, target))return true; groups[i] -= v; } } return false; } }; // @lc code=end
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/Chrono.h> #include <folly/Optional.h> #include <quic/QuicConstants.h> #include <quic/codec/Types.h> #include <quic/common/TimeUtil.h> #include <quic/congestion_control/CongestionController.h> #include <quic/flowcontrol/QuicFlowController.h> #include <quic/logging/QLoggerConstants.h> #include <quic/observer/SocketObserverTypes.h> #include <quic/state/QuicStateFunctions.h> #include <quic/state/SimpleFrameFunctions.h> #include <quic/state/StateData.h> namespace quic { // Forward-declaration bool hasAckDataToWrite(const QuicConnectionStateBase& conn); WriteDataReason hasNonAckDataToWrite(const QuicConnectionStateBase& conn); std::chrono::microseconds calculatePTO(const QuicConnectionStateBase& conn); /** * Whether conn is having persistent congestion. * * Persistent congestion requires a time period much longer than crypto timer. * This means no handshake packet should be in a persistent congestion range. * Thus persistent congestion is per pnSpace, and it's AppData space only. * */ bool isPersistentCongestion( folly::Optional<std::chrono::microseconds> pto, TimePoint lostPeriodStart, TimePoint lostPeriodEnd, const CongestionController::AckEvent& ack) noexcept; inline std::ostream& operator<<( std::ostream& os, const LossState::AlarmMethod& alarmMethod) { switch (alarmMethod) { case LossState::AlarmMethod::EarlyRetransmitOrReordering: os << "EarlyRetransmitOrReordering"; break; case LossState::AlarmMethod::PTO: os << "PTO"; break; } return os; } template <class ClockType = Clock> std::pair<std::chrono::milliseconds, LossState::AlarmMethod> calculateAlarmDuration(const QuicConnectionStateBase& conn) { std::chrono::microseconds alarmDuration; folly::Optional<LossState::AlarmMethod> alarmMethod; TimePoint lastSentPacketTime = conn.lossState.lastRetransmittablePacketSentTime; auto lossTimeAndSpace = earliestLossTimer(conn); if (lossTimeAndSpace.first) { if (*lossTimeAndSpace.first > lastSentPacketTime) { // We do this so that lastSentPacketTime + alarmDuration = lossTime alarmDuration = std::chrono::duration_cast<std::chrono::microseconds>( *lossTimeAndSpace.first - lastSentPacketTime); } else { // This should trigger an immediate alarm. alarmDuration = 0us; } alarmMethod = LossState::AlarmMethod::EarlyRetransmitOrReordering; } else { auto ptoTimeout = calculatePTO(conn); ptoTimeout *= 1ULL << std::min(conn.lossState.ptoCount, (uint32_t)31); alarmDuration = ptoTimeout; alarmMethod = LossState::AlarmMethod::PTO; } TimePoint now = ClockType::now(); std::chrono::milliseconds adjustedAlarmDuration{0}; // The alarm duration is calculated based on the last packet that was sent // rather than the current time. if (lastSentPacketTime + alarmDuration > now) { adjustedAlarmDuration = folly::chrono::ceil<std::chrono::milliseconds>( lastSentPacketTime + alarmDuration - now); } else { VLOG(10) << __func__ << " alarm already due method=" << *alarmMethod << " lastSentPacketTime=" << lastSentPacketTime.time_since_epoch().count() << " now=" << now.time_since_epoch().count() << " alarm=" << alarmDuration.count() << "us" << " deadline=" << (lastSentPacketTime + alarmDuration).time_since_epoch().count() << " " << conn; } DCHECK(alarmMethod.hasValue()) << "Alarm method must have a value"; return std::make_pair(adjustedAlarmDuration, *alarmMethod); } /* * This function should be invoked after some event that is possible to change * the loss detection timer, for example, write happened, timeout happened or * packets are acked. */ template <class Timeout, class ClockType = Clock> void setLossDetectionAlarm(QuicConnectionStateBase& conn, Timeout& timeout) { /* * We might have new data or lost data to send even if we don't have any * outstanding packets. When we get a PTO event, it is possible that only * cloned packets might be outstanding. Since cwnd might be set to min cwnd, * we might not be able to send data. However we might still have data sitting * in the buffers which is unsent or known to be lost. We should set a timer * in this case to be able to send this data on the next PTO. */ bool hasDataToWrite = hasAckDataToWrite(conn) || (hasNonAckDataToWrite(conn) != WriteDataReason::NO_WRITE); auto totalPacketsOutstanding = conn.outstandings.numOutstanding(); /* * We have this condition to disambiguate the case where we have. * (1) All outstanding packets that are clones that are processed and there is * no data to write. (2) All outstanding are clones that are processed and * there is data to write. If there are only clones with no data, then we * don't need to set the timer. This will free up the evb. However after a PTO * verified event, clones take up space in cwnd. If we have data left to * write, we would not be able to write them since we could be blocked by * cwnd. So we must set the loss timer so that we can write this data with the * slack packet space for the clones. */ if (!hasDataToWrite && conn.outstandings.packetEvents.empty() && totalPacketsOutstanding == conn.outstandings.numClonedPackets()) { VLOG(10) << __func__ << " unset alarm pure ack or processed packets only" << " outstanding=" << totalPacketsOutstanding << " handshakePackets=" << conn.outstandings.packetCount[PacketNumberSpace::Handshake] << " " << conn; conn.pendingEvents.setLossDetectionAlarm = false; timeout.cancelLossTimeout(); return; } /** * Either previous timer or an Ack can clear the lossTime without setting a * new one, for example, if such timer or ack marks everything as loss, or * every as acked. In that case, if an early retransmit timer is already set, * we should clear it. */ if (conn.lossState.currentAlarmMethod == LossState::AlarmMethod::EarlyRetransmitOrReordering && !earliestLossTimer(conn).first) { VLOG(10) << __func__ << " unset alarm due to invalidated early retran timer"; timeout.cancelLossTimeout(); } if (!conn.pendingEvents.setLossDetectionAlarm) { VLOG_IF(10, !timeout.isLossTimeoutScheduled()) << __func__ << " alarm not scheduled" << " outstanding=" << totalPacketsOutstanding << " initialPackets=" << conn.outstandings.packetCount[PacketNumberSpace::Initial] << " handshakePackets=" << conn.outstandings.packetCount[PacketNumberSpace::Handshake] << " " << nodeToString(conn.nodeType) << " " << conn; return; } timeout.cancelLossTimeout(); auto alarmDuration = calculateAlarmDuration<ClockType>(conn); conn.lossState.currentAlarmMethod = alarmDuration.second; VLOG(10) << __func__ << " setting transmission" << " alarm=" << alarmDuration.first.count() << "ms" << " method=" << conn.lossState.currentAlarmMethod << " haDataToWrite=" << hasDataToWrite << " outstanding=" << totalPacketsOutstanding << " outstanding clone=" << conn.outstandings.numClonedPackets() << " packetEvents=" << conn.outstandings.packetEvents.size() << " initialPackets=" << conn.outstandings.packetCount[PacketNumberSpace::Initial] << " handshakePackets=" << conn.outstandings.packetCount[PacketNumberSpace::Handshake] << " " << nodeToString(conn.nodeType) << " " << conn; timeout.scheduleLossTimeout(alarmDuration.first); conn.pendingEvents.setLossDetectionAlarm = false; } /** * Processes outstandings for loss and returns true if the loss timer should be * set. False otherwise. */ bool processOutstandingsForLoss( QuicConnectionStateBase& conn, PacketNum largestAcked, const PacketNumberSpace& pnSpace, const InlineMap<StreamId, PacketNum, 20>& largestDsrAcked, const folly::Optional<PacketNum>& largestNonDsrAcked, const TimePoint& lossTime, const std::chrono::microseconds& rttSample, const LossVisitor& lossVisitor, std::chrono::microseconds& delayUntilLost, CongestionController::LossEvent& lossEvent, folly::Optional<SocketObserverInterface::LossEvent>& observerLossEvent); /* * This function should be invoked after some event that is possible to * trigger loss detection, for example: packets are acked */ folly::Optional<CongestionController::LossEvent> detectLossPackets( QuicConnectionStateBase& conn, const folly::Optional<PacketNum> largestAcked, const LossVisitor& lossVisitor, const TimePoint lossTime, const PacketNumberSpace pnSpace, const CongestionController::AckEvent* ackEvent = nullptr); void onPTOAlarm(QuicConnectionStateBase& conn); /* * Function invoked when loss detection timer fires */ template <class ClockType = Clock> void onLossDetectionAlarm( QuicConnectionStateBase& conn, const LossVisitor& lossVisitor) { auto now = ClockType::now(); if (conn.outstandings.packets.empty()) { VLOG(10) << "Transmission alarm fired with no outstanding packets " << conn; return; } if (conn.lossState.currentAlarmMethod == LossState::AlarmMethod::EarlyRetransmitOrReordering) { auto lossTimeAndSpace = earliestLossTimer(conn); CHECK(lossTimeAndSpace.first); auto lossEvent = detectLossPackets( conn, getAckState(conn, lossTimeAndSpace.second).largestAckedByPeer, lossVisitor, now, lossTimeAndSpace.second); if (conn.congestionController && lossEvent) { DCHECK(lossEvent->largestLostSentTime && lossEvent->smallestLostSentTime); conn.congestionController->onPacketAckOrLoss( nullptr, lossEvent.get_pointer()); } } else { onPTOAlarm(conn); } conn.pendingEvents.setLossDetectionAlarm = conn.outstandings.numOutstanding() > 0; VLOG(10) << __func__ << " setLossDetectionAlarm=" << conn.pendingEvents.setLossDetectionAlarm << " outstanding=" << conn.outstandings.numOutstanding() << " initialPackets=" << conn.outstandings.packetCount[PacketNumberSpace::Initial] << " handshakePackets=" << conn.outstandings.packetCount[PacketNumberSpace::Handshake] << " " << conn; } /* * Process streams in a RegularQuicWritePacket for loss * * processed: whether this packet is a already processed clone */ void markPacketLoss( QuicConnectionStateBase& conn, RegularQuicWritePacket& packet, bool processed); folly::Optional<CongestionController::LossEvent> handleAckForLoss( QuicConnectionStateBase& conn, const LossVisitor& lossVisitor, CongestionController::AckEvent& ack, PacketNumberSpace pnSpace); /** * We force mark zero rtt packets as lost during zero rtt rejection. */ template <class ClockType = Clock> void markZeroRttPacketsLost( QuicConnectionStateBase& conn, const LossVisitor& lossVisitor) { CongestionController::LossEvent lossEvent(ClockType::now()); auto iter = getFirstOutstandingPacket(conn, PacketNumberSpace::AppData); while (iter != conn.outstandings.packets.end()) { DCHECK_EQ( iter->packet.header.getPacketNumberSpace(), PacketNumberSpace::AppData); auto isZeroRttPacket = iter->packet.header.getProtectionType() == ProtectionType::ZeroRtt; if (isZeroRttPacket) { auto& pkt = *iter; DCHECK(!pkt.metadata.isHandshake); bool processed = pkt.associatedEvent && !conn.outstandings.packetEvents.count(*pkt.associatedEvent); lossVisitor(conn, pkt.packet, processed); // Remove the PacketEvent from the outstandings.packetEvents set if (pkt.associatedEvent) { conn.outstandings.packetEvents.erase(*pkt.associatedEvent); CHECK(conn.outstandings.clonedPacketCount[PacketNumberSpace::AppData]); --conn.outstandings.clonedPacketCount[PacketNumberSpace::AppData]; } lossEvent.addLostPacket(pkt); if (!processed) { CHECK(conn.outstandings.packetCount[PacketNumberSpace::AppData]); --conn.outstandings.packetCount[PacketNumberSpace::AppData]; } iter = conn.outstandings.packets.erase(iter); iter = getNextOutstandingPacket(conn, PacketNumberSpace::AppData, iter); } else { iter = getNextOutstandingPacket(conn, PacketNumberSpace::AppData, iter + 1); } } conn.lossState.rtxCount += lossEvent.lostPackets; if (conn.congestionController && lossEvent.largestLostPacketNum.hasValue()) { conn.congestionController->onRemoveBytesFromInflight(lossEvent.lostBytes); } VLOG(10) << __func__ << " marked=" << lossEvent.lostPackets; } } // namespace quic
#include<bits/stdc++.h> using namespace std; class Polynomial { public : int *degCoeff; // Name of your array (Don't change this) int capacity; // total size public : Polynomial() { degCoeff = new int[10]; for(int i=0;i<10;i++)degCoeff[i]=0; capacity = 10; } Polynomial(const Polynomial &d) { this -> degCoeff = new int[d.capacity]; for(int i = 0; i < d.capacity; i++) { this -> degCoeff[i] = d.degCoeff[i]; } this -> capacity = d.capacity; } void setCoefficient(int deg,int coeff) { if(deg>=capacity) { //int size = this->capacity; int size=deg+1; int *newarr = new int[size]; for(int i=0;i<capacity;i++)newarr[i]=this->degCoeff[i]; for(int i=capacity;i<size;i++)newarr[i]=0; delete[] this->degCoeff; this->degCoeff=newarr; this->capacity = size; } this->degCoeff[deg]=coeff; } // Complete the class void print() { for(int i = 0;i<capacity;i++) { if(degCoeff[i]) cout << degCoeff[i] << "x" <<i << " "; } cout << endl; } Polynomial operator+(Polynomial &p) { Polynomial newP; newP.capacity = max(p.capacity,capacity); newP.degCoeff = new int[newP.capacity]; if (capacity<p.capacity) { int k; for (k=0;k<capacity;k++) { newP.degCoeff[k]=degCoeff[k]+p.degCoeff[k]; } for (;k<p.capacity;k++) { newP.degCoeff[k]=p.degCoeff[k]; } } else { int k; for ( k=0;k<p.capacity;k++) { newP.degCoeff[k]=degCoeff[k]+p.degCoeff[k]; } for (;k<capacity;k++) { newP.degCoeff[k]=degCoeff[k] ; } } return newP; } Polynomial operator-(Polynomial &p) { Polynomial newP; newP.capacity = max(capacity,p.capacity); newP.degCoeff = new int[newP.capacity]; if (capacity<p.capacity) { int k; for (k=0;k<capacity;k++) { newP.degCoeff[k]=degCoeff[k]-p.degCoeff[k]; } for (;k<p.capacity;k++) { newP.degCoeff[k]=-p.degCoeff[k]; } } else { int k; for ( k=0;k<p.capacity;k++) { newP.degCoeff[k]=degCoeff[k]-p.degCoeff[k]; } for (;k<capacity;k++) { newP.degCoeff[k]=degCoeff[k] ; } } return newP; } Polynomial operator*(Polynomial const &p) { Polynomial newP; newP.capacity = p.capacity+capacity; newP.degCoeff = new int[newP.capacity]; for(int i=0;i<newP.capacity;i++) newP.degCoeff[i]=0; for (int i=0;i<capacity;i++) { for (int j=0;j<p.capacity;j++) { newP.degCoeff[i+j] += degCoeff[i]*p.degCoeff[j]; } } return newP; } Polynomial operator=(Polynomial const &d) { this -> degCoeff = new int[d.capacity]; for(int i = 0; i < d.capacity; i++) { this -> degCoeff[i] = d.degCoeff[i]; } this -> capacity = d.capacity; return *this; } }; int main(){ int count1,count2,choice; cin >> count1; int *degree1 = new int[count1]; int *coeff1 = new int[count1]; for(int i=0;i < count1; i++) { cin >> degree1[i]; } for(int i=0;i < count1; i++) { cin >> coeff1[i]; } Polynomial first; for(int i = 0; i < count1; i++){ first.setCoefficient(degree1[i],coeff1[i]); } cin >> count2; int *degree2 = new int[count2]; int *coeff2 = new int[count2]; for(int i=0;i < count2; i++) { cin >> degree2[i]; } for(int i=0;i < count2; i++) { cin >> coeff2[i]; } Polynomial second; for(int i = 0; i < count2; i++){ second.setCoefficient(degree2[i],coeff2[i]); } cin >> choice; switch(choice){ // Add case 1: { Polynomial result1 = first + second; result1.print(); break; } // Subtract case 2 : { Polynomial result2 = first - second; result2.print(); break; } // Multiply case 3 : { Polynomial result3 = first * second; result3.print(); break; } case 4 : // Copy constructor { Polynomial third(first); if(third.degCoeff == first.degCoeff) { cout << "false" << endl; } else { cout << "true" << endl; } break; } case 5 : // Copy assignment operator { Polynomial fourth(first); if(fourth.degCoeff == first.degCoeff) { cout << "false" << endl; } else { cout << "true" << endl; } break; } } return 0; }
// Created on: 1993-04-29 // Created by: Yves FRICAUD // 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 _MAT_Graph_HeaderFile #define _MAT_Graph_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <MAT_DataMapOfIntegerArc.hxx> #include <MAT_DataMapOfIntegerBasicElt.hxx> #include <MAT_DataMapOfIntegerNode.hxx> #include <Standard_Integer.hxx> #include <Standard_Transient.hxx> class MAT_ListOfBisector; class MAT_Arc; class MAT_BasicElt; class MAT_Node; class MAT_Graph; DEFINE_STANDARD_HANDLE(MAT_Graph, Standard_Transient) //! The Class Graph permits the exploration of the //! Bisector Locus. class MAT_Graph : public Standard_Transient { public: //! Empty constructor. Standard_EXPORT MAT_Graph(); //! Construct <me> from the result of the method //! <CreateMat> of the class <MAT> from <MAT>. //! //! <SemiInfinite> : if some bisector are infinites. //! <TheRoots> : Set of the bisectors. //! <NbBasicElts> : Number of Basic Elements. //! <NbArcs> : Number of Arcs = Number of Bisectors. Standard_EXPORT void Perform (const Standard_Boolean SemiInfinite, const Handle(MAT_ListOfBisector)& TheRoots, const Standard_Integer NbBasicElts, const Standard_Integer NbArcs); //! Return the Arc of index <Index> in <theArcs>. Standard_EXPORT Handle(MAT_Arc) Arc (const Standard_Integer Index) const; //! Return the BasicElt of index <Index> in <theBasicElts>. Standard_EXPORT Handle(MAT_BasicElt) BasicElt (const Standard_Integer Index) const; //! Return the Node of index <Index> in <theNodes>. Standard_EXPORT Handle(MAT_Node) Node (const Standard_Integer Index) const; //! Return the number of arcs of <me>. Standard_EXPORT Standard_Integer NumberOfArcs() const; //! Return the number of nodes of <me>. Standard_EXPORT Standard_Integer NumberOfNodes() const; //! Return the number of basic elements of <me>. Standard_EXPORT Standard_Integer NumberOfBasicElts() const; //! Return the number of infinites nodes of <me>. Standard_EXPORT Standard_Integer NumberOfInfiniteNodes() const; //! Merge two BasicElts. The End of the BasicElt Elt1 //! of IndexElt1 becomes The End of the BasicElt Elt2 //! of IndexElt2. Elt2 is replaced in the arcs by //! Elt1, Elt2 is eliminated. //! //! <MergeArc1> is True if the fusion of the BasicElts => //! a fusion of two Arcs which separated the same elements. //! In this case <GeomIndexArc1> and <GeomIndexArc2> are the //! Geometric Index of this arcs. //! //! If the BasicElt corresponds to a close line , //! the StartArc and the EndArc of Elt1 can separate the same //! elements . //! In this case there is a fusion of this arcs, <MergeArc2> //! is true and <GeomIndexArc3> and <GeomIndexArc4> are the //! Geometric Index of this arcs. Standard_EXPORT void FusionOfBasicElts (const Standard_Integer IndexElt1, const Standard_Integer IndexElt2, Standard_Boolean& MergeArc1, Standard_Integer& GeomIndexArc1, Standard_Integer& GeomIndexArc2, Standard_Boolean& MergeArc2, Standard_Integer& GeomIndexArc3, Standard_Integer& GeomIndexArc4); Standard_EXPORT void CompactArcs(); Standard_EXPORT void CompactNodes(); Standard_EXPORT void ChangeBasicElts (const MAT_DataMapOfIntegerBasicElt& NewMap); Standard_EXPORT Handle(MAT_BasicElt) ChangeBasicElt (const Standard_Integer Index); DEFINE_STANDARD_RTTIEXT(MAT_Graph,Standard_Transient) protected: private: //! Merge two Arcs. the second node of <Arc2> becomes //! the first node of <Arc1>. Update of the first //! node and the neighbours of <Arc1>. //! <Arc2> is eliminated. Standard_EXPORT void FusionOfArcs (const Handle(MAT_Arc)& Arc1, const Handle(MAT_Arc)& Arc2); Standard_EXPORT void UpDateNodes (Standard_Integer& Index); MAT_DataMapOfIntegerArc theArcs; MAT_DataMapOfIntegerBasicElt theBasicElts; MAT_DataMapOfIntegerNode theNodes; Standard_Integer numberOfArcs; Standard_Integer numberOfNodes; Standard_Integer numberOfBasicElts; Standard_Integer numberOfInfiniteNodes; }; #endif // _MAT_Graph_HeaderFile
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2008-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Jan Borsodi */ #ifndef OP_PROTOBUF_UTILS_H #define OP_PROTOBUF_UTILS_H #ifdef PROTOBUF_SUPPORT #include "modules/protobuf/src/opvaluevector.h" #include "modules/protobuf/src/protobuf_data.h" #include "modules/util/adt/opvector.h" #include "modules/util/adt/bytebuffer.h" #include "modules/util/opstring.h" class ByteBuffer; class TempBuffer; class OpString8; class UniString; template<typename T> class OpValueVector; template<typename T> class OpProtobufValueVector; /** * ADS 1.2 workaround to avoid problems with using * a function pointer argument to a templated function. * In particular it seem to be the uni_char** that * cause trouble and leads to: * Serious error: C2408E: type deduction fails: function type 0-way resolvable */ template<typename T> class ConvFunction { public: ConvFunction( T (*f)(const uni_char *, uni_char**, int, BOOL *) ) : strtol_f(f) {} T (*strtol_f)(const uni_char *, uni_char**, int, BOOL *); }; struct OpProtobufUtils { // This is a helper class which binds a uni_char pointer and a length into one object, // this allows it to be used as parameter for the Copy() function. class UniStringPtr { public: UniStringPtr(const uni_char *str_, unsigned int len_) : str(str_) , len(len_) {} const uni_char *CStr() const { return str; } unsigned int Length() const { return len; } private: const uni_char *str; unsigned int len; }; // This is a helper class which binds a char pointer and a length into one object, // this allows it to be seen as binary data and not a C string. class Bytes { public: Bytes(const char *data, unsigned int len) : data(data) , len(len) {} const char *Data() const { return data; } unsigned int Length() const { return len; } private: const char *data; unsigned int len; }; // TODO: Add max_len to all Copy() funcs static inline OP_STATUS Copy(const TempBuffer *from, ByteBuffer *to); static OP_STATUS Copy(const TempBuffer &from, ByteBuffer &to); template<typename T> static OP_STATUS Copy(const UniStringPtr &from, T &to, unsigned int max_len = ~0u); static OP_STATUS Copy(OpProtobufStringChunkRange from, TempBuffer &to); static OP_STATUS Convert(ByteBuffer &out, const uni_char *in_str, int char_count = -1); static OP_STATUS Convert(OpString &out, const char *in_str, int char_count = -1); static OP_STATUS ConvertUTF8toUTF16(TempBuffer &out, const ByteBuffer &in, int char_count = -1); static OP_STATUS ConvertUTF8toUTF16(ByteBuffer &out, const ByteBuffer &in, int char_count = -1); static OP_STATUS ExtractUTF16BE(OpString &out, const ByteBuffer &in, int char_count = -1); /** * Append a new string to container @a container containing OpString * objects. @a string is copied to a new OpString object and added to * the container. * * @param container A container with OpString objects. Must have an Add(OpString *) method. * @param string The string to place in container. * @return OK for success, ERR_NO_MEMORY on OOM. */ template<typename C> static OP_STATUS AppendString(C &container, const OpString &string); /** * Similar to AppendString(C &, const OpString &) but takes a Unicode string pointer and length. * * @param container A container with OpString objects. Must have an Add(OpString *) method. * @param string The string data to place in container. * @param len The amount of characters to copy from @a string or @c KAll to use the whole string. * @return OK for success, ERR_NO_MEMORY on OOM. */ template<typename C> static OP_STATUS AppendString(C &container, const uni_char *string, int len = KAll); /** * Similar to AppendString(C &, const OpString &) but takes a C-string pointer and length. * See OpString::Set() for details on how the C-string is converted. * * @param container A container with OpString objects. Must have an Add(OpString *) method. * @param string The string data to place in container. * @param len The amount of characters to copy from @a string or @c KAll to use the whole string. * @return OK for success, ERR_NO_MEMORY on OOM. */ template<typename C> static OP_STATUS AppendString(C &container, const char *string, int len = KAll); /** * Append a new string to container @a container containing TempBuffer * objects. @a string is copied to a new TempBuffer object and added to * the container. * * @param container A container with TempBuffer objects. Must have an Add(TempBuffer *) method. * @param string The string to place in container. * @return OK for success, ERR_NO_MEMORY on OOM. */ template<typename C> static OP_STATUS AppendTempBuffer(C &container, const TempBuffer &string); /** * Similar to AppendTempBuffer(C &, const OpString &) but takes a Unicode string pointer and length. * * @param container A container with TempBuffer objects. Must have an Add(TempBuffer *) method. * @param string The string data to place in container. * @param len The amount of characters to copy from @a string or @c KAll to use the whole string. * @return OK for success, ERR_NO_MEMORY on OOM. */ template<typename C> static OP_STATUS AppendTempBuffer(C &container, const uni_char *string, int len = KAll); /** * Similar to AppendString(C &, const TempBuffer &) but takes a C-string pointer and length. * See TempBuffer::Append() for details on how the C-string is converted. * * @param container A container with TempBuffer objects. Must have an Add(TempBuffer *) method. * @param string The string data to place in container. * @param len The amount of characters to copy from @a string or @c KAll to use the whole string. * @return OK for success, ERR_NO_MEMORY on OOM. */ template<typename C> static OP_STATUS AppendTempBuffer(C &container, const char *string, int len = KAll); /** * Append a new string to UniString container @a container. * * @param container A value vector with UniString objects. * @param string The string to place in container. * @return OK for success, ERR_NO_MEMORY on OOM. */ static OP_STATUS AppendUniString(OpProtobufValueVector<UniString> &container, const UniString &string); /** * Similar to AppendUniString(OpProtobufValueVector<UniString> &, const UniString &) but takes a Unicode string pointer and length. * * @param container A container with UniString objects. Must have an Add(UniString) method. * @param string The string data to place in container. * @param len The amount of characters to copy from @a string or @c KAll to use the whole string. * @return OK for success, ERR_NO_MEMORY on OOM. */ static OP_STATUS AppendUniString(OpProtobufValueVector<UniString> &container, const uni_char *string, int len = KAll); /** * Similar to AppendUniString(OpProtobufValueVector<UniString> &, const UniString &) but takes a C-string pointer and length. * See TempBuffer::Append() for details on how the C-string is converted. * * @param container A container with UniString objects. Must have an Add(UniString) method. * @param string The string data to place in container. * @param len The amount of characters to copy from @a string or @c KAll to use the whole string. * @return OK for success, ERR_NO_MEMORY on OOM. */ static OP_STATUS AppendUniString(OpProtobufValueVector<UniString> &container, const char *string, int len = KAll); /** * Append a new bytebuffer to container @a container containing ByteBuffer * objects. @a bytes is copied to a new ByteBuffer object and added to * the container. * * @param container A container with ByteBuffer objects. Must have an Add(ByteBuffer *) method. * @param bytes The byte data to place in container. * @return OK for success, ERR_NO_MEMORY on OOM. */ template<typename C> static OP_STATUS AppendBytes(C &container, const ByteBuffer &bytes); /** * Similar to AppendBytes(C &, const ByteBuffer &) but takes a pointer to * byte data instead. * * @param container A container with ByteBuffer objects. Must have an Add(ByteBuffer *) method. * @param bytes The byte data to place in container. * @param len The amount of bytes to copy from @a bytes. * @return OK for success, ERR_NO_MEMORY on OOM. */ template<typename C> static OP_STATUS AppendBytes(C &container, const char *bytes, int len); /** * Append a new OpData to container @a container containing OpData * objects. @a bytes is copied to a new OpData object and added to * the container. * * @param container A container with OpData objects. Must have an Add(OpData *) method. * @param bytes The byte data to place in container. * @return OK for success, ERR_NO_MEMORY on OOM. */ template<typename C> static OP_STATUS AppendOpData(C &container, const OpData &bytes); /** * Similar to AppendOpData(C &, const OpData &) but takes a pointer to * byte data instead. * * @param container A container with OpData objects. Must have an Add(OpData *) method. * @param bytes The byte data to place in container. * @param len The amount of bytes to copy from @a bytes. * @return OK for success, ERR_NO_MEMORY on OOM. */ template<typename C> static OP_STATUS AppendOpData(C &container, const char *bytes, int len); template<typename T> static OP_STATUS Append(T &col, int num); template<typename T> static inline OP_STATUS Append(T &col, unsigned int num); static inline OP_STATUS Append(TempBuffer &col, int num); static inline OP_STATUS Append(TempBuffer &col, unsigned int num); static inline OP_STATUS Append(TempBuffer &col, const uni_char *in_str, unsigned int max_len = ~0u); static inline OP_STATUS Append(OpString8 &col, const char *in_str, unsigned int max_len = ~0u); static inline OP_STATUS Append(OpString &col, const char *in_str, unsigned int max_len = ~0u); static inline OP_STATUS Append(OpString &col, const Bytes &in_str, unsigned int max_len = ~0u); static inline OP_STATUS Append(ByteBuffer &col, const char *in_str, unsigned int max_len = ~0u); static inline OP_STATUS Append(ByteBuffer &col, const Bytes &in_bytes, unsigned int max_len = ~0u); template<typename T> static inline int Length(const OpValueVector<T> &v); template<typename T> static inline int Length(const OpVector<T> &v); static inline int Length(const OpINT32Vector &v); static int ParseDelimitedInteger(const uni_char *buffer, unsigned int buffer_len, uni_char delimiter, int &chars_read); // missing functions from stdlib static char *uitoa( unsigned int value, char *str, int radix); /** * Parse a long integer using the specified function (e.g. uni_strtol/uni_strtoul). * * @param text The text to parse. * @param strtol_f The function used to parse the number (uni_strtol/uni_strtoul). * @param min If the parsed value is less than 'min', this function fails. * @param min If the parsed value is greater than 'max', this function fails. * @param number The resulting number will be stored in this variable on success. * @param invalid_first If the first character of the text is equal to this value, parsing fails. */ template<typename T> static OP_STATUS ParseLong(const uni_char *text, ConvFunction<T> f, T min, T max, T &number, char invalid_first = '\0'); #ifndef OPERA_BIG_ENDIAN static void ByteSwap(uni_char* buf, size_t buf_len); #endif // OPERA_BIG_ENDIAN }; /*static*/ inline OP_STATUS OpProtobufUtils::Copy(const TempBuffer *from, ByteBuffer *to) { OP_ASSERT(from != NULL || to != NULL); if (from == NULL || to == NULL) return OpStatus::ERR; return Copy(*from, *to); } // Note: This method cannot be put as static member of a class, VS6 does not support that. template<typename T> OP_STATUS OpScopeCopy(const ByteBuffer &from, T &to, unsigned int max_len = ~0u) { unsigned int remaining = MIN(max_len, from.Length()); unsigned int count = from.GetChunkCount(); for (unsigned int i = 0; i < count; ++i) { unsigned int nbytes; char *chunk = from.GetChunk(i, &nbytes); OP_ASSERT(chunk != NULL); if (nbytes == 0) continue; unsigned int copy_size = MIN(nbytes, remaining); RETURN_IF_ERROR(OpProtobufUtils::Append(to, OpProtobufUtils::Bytes(chunk, nbytes), copy_size)); remaining -= copy_size; if (remaining == 0) break; } return OpStatus::OK; } template<typename T> /*static*/ OP_STATUS OpProtobufUtils::Copy(const UniStringPtr &from, T &to, unsigned int max_len) { unsigned int remaining = MIN(max_len, from.Length())*2; return Append(to, reinterpret_cast<const char *>(from.CStr()), remaining); } template<typename C> /*static*/ OP_STATUS OpProtobufUtils::AppendString(C &container, const OpString &string) { OpAutoPtr<OpString> tmp(OP_NEW(OpString, ())); RETURN_OOM_IF_NULL(tmp.get()); RETURN_IF_ERROR(tmp->Set(string)); RETURN_IF_ERROR(container.Add(tmp.get())); tmp.release(); return OpStatus::OK; } template<typename C> /*static*/ OP_STATUS OpProtobufUtils::AppendString(C &container, const uni_char *string, int len) { OpAutoPtr<OpString> tmp(OP_NEW(OpString, ())); RETURN_OOM_IF_NULL(tmp.get()); RETURN_IF_ERROR(tmp->Set(string, len)); RETURN_IF_ERROR(container.Add(tmp.get())); tmp.release(); return OpStatus::OK; } template<typename C> /*static*/ OP_STATUS OpProtobufUtils::AppendString(C &container, const char *string, int len) { OpAutoPtr<OpString> tmp(OP_NEW(OpString, ())); RETURN_OOM_IF_NULL(tmp.get()); RETURN_IF_ERROR(tmp->Set(string, len)); RETURN_IF_ERROR(container.Add(tmp.get())); tmp.release(); return OpStatus::OK; } // TempBuffer template<typename C> /*static*/ OP_STATUS OpProtobufUtils::AppendTempBuffer(C &container, const TempBuffer &string) { OpAutoPtr<TempBuffer> tmp(OP_NEW(TempBuffer, ())); RETURN_OOM_IF_NULL(tmp.get()); RETURN_IF_ERROR(tmp->Append(string.GetStorage(), string.Length())); RETURN_IF_ERROR(container.Add(tmp.get())); tmp.release(); return OpStatus::OK; } template<typename C> /*static*/ OP_STATUS OpProtobufUtils::AppendTempBuffer(C &container, const uni_char *string, int len) { OpAutoPtr<TempBuffer> tmp(OP_NEW(TempBuffer, ())); RETURN_OOM_IF_NULL(tmp.get()); RETURN_IF_ERROR(tmp->Append(string, len)); RETURN_IF_ERROR(container.Add(tmp.get())); tmp.release(); return OpStatus::OK; } template<typename C> /*static*/ OP_STATUS OpProtobufUtils::AppendTempBuffer(C &container, const char *string, int len) { OpAutoPtr<TempBuffer> tmp(OP_NEW(TempBuffer, ())); RETURN_OOM_IF_NULL(tmp.get()); RETURN_IF_ERROR(tmp->Append(string, len)); RETURN_IF_ERROR(container.Add(tmp.get())); tmp.release(); return OpStatus::OK; } // ByteBuffer template<typename C> /*static*/ OP_STATUS OpProtobufUtils::AppendBytes(C &container, const ByteBuffer &bytes) { OpAutoPtr<ByteBuffer> tmp(OP_NEW(ByteBuffer, ())); RETURN_OOM_IF_NULL(tmp.get()); RETURN_IF_ERROR(OpScopeCopy(bytes, *tmp)); RETURN_IF_ERROR(container.Add(tmp.get())); tmp.release(); return OpStatus::OK; } template<typename C> /*static*/ OP_STATUS OpProtobufUtils::AppendBytes(C &container, const char *bytes, int len) { OpAutoPtr<ByteBuffer> tmp(OP_NEW(ByteBuffer, ())); RETURN_OOM_IF_NULL(tmp.get()); RETURN_IF_ERROR(tmp->AppendBytes(bytes, len)); RETURN_IF_ERROR(container.Add(tmp.get())); tmp.release(); return OpStatus::OK; } template<typename C> /*static*/ OP_STATUS OpProtobufUtils::AppendOpData(C &container, const OpData &bytes) { OpAutoPtr<OpData> tmp(OP_NEW(OpData, ())); RETURN_OOM_IF_NULL(tmp.get()); RETURN_IF_ERROR(tmp->Append(bytes)); RETURN_IF_ERROR(container.Add(tmp.get())); tmp.release(); return OpStatus::OK; } template<typename C> /*static*/ OP_STATUS OpProtobufUtils::AppendOpData(C &container, const char *bytes, int len) { OpAutoPtr<OpData> tmp(OP_NEW(OpData, ())); RETURN_OOM_IF_NULL(tmp.get()); RETURN_IF_ERROR(tmp->AppendCopyData(bytes, len)); RETURN_IF_ERROR(container.Add(tmp.get())); tmp.release(); return OpStatus::OK; } template<typename T> /*static*/ OP_STATUS OpProtobufUtils::Append(T &col, int num) { char buf[ DECIMALS_FOR_128_BITS + 1 ]; // ARRAY OK 2008-11-14 jborsodi op_itoa(num, buf, 10); return Append(col, buf); } template<typename T> /*static*/ inline OP_STATUS OpProtobufUtils::Append(T &col, unsigned int num) { return Append(col, static_cast<int>(num)); } /*static*/ inline OP_STATUS OpProtobufUtils::Append(TempBuffer &col, int num) { uni_char buf[ DECIMALS_FOR_128_BITS + 1 ]; // ARRAY OK 2008-11-14 jborsodi uni_itoa(num, buf, 10); return col.Append(buf); } /*static*/ inline OP_STATUS OpProtobufUtils::Append(TempBuffer &col, unsigned int num) { return col.AppendUnsignedLong(num); } /*static*/ inline OP_STATUS OpProtobufUtils::Append(TempBuffer &col, const uni_char *in_str, unsigned int max_len) { unsigned int len = MIN(max_len, uni_strlen(in_str)); return col.Append(in_str, len); } /*static*/ inline OP_STATUS OpProtobufUtils::Append(ByteBuffer &col, const char *in_str, unsigned int max_len) { unsigned int len = MIN(max_len, op_strlen(in_str)); return col.AppendBytes(in_str, len); } /*static*/ inline OP_STATUS OpProtobufUtils::Append(ByteBuffer &col, const Bytes &in_bytes, unsigned int max_len) { unsigned int len = MIN(max_len, in_bytes.Length()); return col.AppendBytes(in_bytes.Data(), len); } /*static*/ inline OP_STATUS OpProtobufUtils::Append(OpString8 &col, const char *in_str, unsigned int max_len) { unsigned int len = MIN(max_len, op_strlen(in_str)); return col.Append(in_str, len); } /*static*/ inline OP_STATUS OpProtobufUtils::Append(OpString &col, const char *in_str, unsigned int max_len) { unsigned int len = MIN(max_len, op_strlen(in_str)); return col.Append(in_str, len); } /*static*/ inline OP_STATUS OpProtobufUtils::Append(OpString &col, const Bytes &in_str, unsigned int max_len) { unsigned int len = MIN(max_len, in_str.Length()); return col.Append(in_str.Data(), len); } template<typename T> /*static*/ inline int OpProtobufUtils::Length(const OpValueVector<T> &v) { return v.GetCount(); } template<typename T> /*static*/ inline int OpProtobufUtils::Length(const OpVector<T> &v) { return v.GetCount(); } /*static*/ inline int OpProtobufUtils::Length(const OpINT32Vector &v) { return v.GetCount(); } template<typename T> /*static*/ OP_STATUS OpProtobufUtils::ParseLong(const uni_char *text, ConvFunction<T> f, T min, T max, T &number, char invalid_first) { if(text == NULL) return OpStatus::ERR_PARSING_FAILED; if(text[0] == invalid_first) return OpStatus::ERR_PARSING_FAILED; BOOL overflow; uni_char *end = NULL; number = f.strtol_f(text, &end, 10, &overflow); if(*end != '\0') return OpStatus::ERR_PARSING_FAILED; if(overflow) return OpStatus::ERR_PARSING_FAILED; // Out of range. if(number < min || number > max) return OpStatus::ERR_PARSING_FAILED; return OpStatus::OK; } #endif // PROTOBUF_SUPPORT #endif // OP_PROTOBUF_UTILS_H
// Created on: 1995-08-04 // Created by: Modelistation // Copyright (c) 1995-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 _StdPrs_WFSurface_HeaderFile #define _StdPrs_WFSurface_HeaderFile #include <Adaptor3d_Surface.hxx> #include <Prs3d_Root.hxx> #include <Prs3d_Drawer.hxx> //! Computes the wireframe presentation of surfaces //! by displaying a given number of U and/or V isoparametric //! curves. The isoparametric curves are drawn with respect //! to a given number of points. class StdPrs_WFSurface : public Prs3d_Root { public: DEFINE_STANDARD_ALLOC //! Draws a surface by drawing the isoparametric curves with respect to //! a fixed number of points given by the Drawer. //! The number of isoparametric curves to be drawn and their color are //! controlled by the furnished Drawer. Standard_EXPORT static void Add (const Handle(Prs3d_Presentation)& aPresentation, const Handle(Adaptor3d_Surface)& aSurface, const Handle(Prs3d_Drawer)& aDrawer); protected: private: }; #endif // _StdPrs_WFSurface_HeaderFile
#pragma once #include "Image.h" class GameNode { private: static Image* m_backBuffer; HDC _hdc; public: GameNode(); ~GameNode(); virtual HRESULT Init(); virtual void Release(); virtual void Update(); virtual void Render(); virtual void Render(HDC hdc); HDC GetMemDC() { return m_backBuffer->GetMemDC(); } HDC GetHDC() { return _hdc; } static Image* SetBackBuffer(); LRESULT MainProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); };
#include <iostream> #include <string> #include <vector> using namespace std; class Building; class GoodGay { public: GoodGay(string hall, string bedroom); // 类内声明,类外实现 void visit(); Building *b; }; class Building { // friend void print_Building(Building &b); // friend class GoodGay;//一个类成为另一个类的友元 friend void GoodGay::visit();//类的成员函数成为另一个类的友元 public: Building(string hall, string bedroom) { this->hall = hall; this->bedroom = bedroom; } string hall; private: string bedroom; }; GoodGay::GoodGay(string hall, string bedroom) { b = new Building(hall, bedroom); } void GoodGay::visit() { cout << b->hall << " " << b->bedroom << endl; } void test01() { GoodGay gd("气象楼", "办公室"); gd.visit(); } int main(int argc, char **argv) { test01(); return 0; }
#ifndef PID_H #define PID_H #include<math.h> #include <iostream> class PID { private: unsigned int step = 0; double const twiddle_upd_param = 1.1; double const twiddle_dwn_param = 0.9; double dp[3] = {1.0, 1.0, 1.0}; //TODO : double max would be better then a high number double best_err = 1000000; unsigned int num_of_steps = 1000; bool tried_adding = false; bool tried_subtracting = false; public: /* * Errors */ double p_error; double i_error; double d_error; /* * Coefficients */ double Kp; double Ki; double Kd; /* * Constructor */ PID(); /* * Destructor. */ virtual ~PID(); /* * Initialize PID. */ void Init(double Kp, double Ki, double Kd, int twiddle_steps); /* * Update the PID error variables given cross track error. */ void UpdateError(double cte); /* * Calculate the total PID error. */ double TotalError(); }; #endif /* PID_H */
//: C07:UnionClass.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Unie z konstruktorami i funkcjami skladowymi #include<iostream> using namespace std; union U { private: // Kontrola dostepu! int i; float f; public: U(int a); U(float b); ~U(); int read_int(); float read_float(); }; U::U(int a) { i = a; } U::U(float b) { f = b;} U::~U() { cout << "U::~U()\n"; } int U::read_int() { return i; } float U::read_float() { return f; } int main() { U X(12), Y(1.9F); cout << X.read_int() << endl; cout << Y.read_float() << endl; } ///:~
//interrupt vector TIMER0_COMPA //timer/counter0 compare match ISR (TIMER0_COMPA); TCCR0A = 0; TCCR0A |= (1<<WGM01);// CTC mode OCR0A = 0xff;
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2004 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 "WindowsOpLocale.h" char *StrToLocaleEncoding(const uni_char *str) { int len; len = WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, str, -1, NULL, 0, NULL, NULL); char *result = new char[len]; if (result) WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, str, -1, result, len, NULL, NULL); return result; } uni_char *StrFromLocaleEncoding(const char *str) { int len = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0); uni_char *result = NULL; if (len) { result = new uni_char[len]; if (result) { result[0] = '\0'; // If the next call fails MultiByteToWideChar(CP_ACP, 0, str, -1, result, len); } } return result; } static int LocaleGroupingToNumber() { // This is ugly. Read for instance the article // at http://blogs.msdn.com/shawnste/archive/2006/07/17/668741.aspx for background. uni_char buf[10]; int ret = 0; if (GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SGROUPING, buf, 10) != 0) { int last_digit = 0; uni_char* p = buf; while (*p) { if (*p < '0' || *p > '9') { break; } last_digit = *p-'0'; ret = 10*ret + last_digit; p++; if (*p == ';') { p++; } } if (last_digit == 0) { ret /= 10; } else { ret *= 10; } } return ret; } static int GetLocaleInfoInt(int locale_value) { int i; if (!GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_RETURN_NUMBER | locale_value, (LPWSTR)&i, sizeof(i) / sizeof(TCHAR))) { return -1; } return i; } /** * Get a locale seperator from the windows locale. */ static void GetLocaleSeparator(int separator, uni_char buf[4]) { if (!GetLocaleInfo(LOCALE_USER_DEFAULT, separator, buf, 4)) { buf[0] = separator == LOCALE_SDECIMAL ? '.' : '\0'; buf[1] = '\0'; } } OP_STATUS OpLocale::Create(OpLocale** new_locale) { OP_ASSERT(new_locale); *new_locale = new WindowsOpLocale(); if (*new_locale == NULL) return OpStatus::ERR_NO_MEMORY; OP_STATUS err; if (OpStatus::IsError(err =((WindowsOpLocale*)*new_locale)->InitLocale())) { delete *new_locale; return err; } return OpStatus::OK; } OP_STATUS WindowsOpLocale::InitLocale() { OpString tmpbuf; if (!tmpbuf.Reserve(2)) return OpStatus::ERR_NO_MEMORY; GetLocaleInfo( LOCALE_USER_DEFAULT, LOCALE_ITIME, tmpbuf, tmpbuf.Capacity()); if (tmpbuf.Compare(UNI_L("0"))) m_use_24_hours = TRUE; else m_use_24_hours = FALSE; m_leading_zero = GetLocaleInfoInt(LOCALE_ILZERO); m_grouping = LocaleGroupingToNumber(); m_negative_order = GetLocaleInfoInt(LOCALE_INEGNUMBER); GetLocaleSeparator(LOCALE_STHOUSAND, m_thousands_sep); GetLocaleSeparator(LOCALE_SDECIMAL, m_decimal_sep); return OpStatus::OK; } int WindowsOpLocale::CompareStringsL(const uni_char *str1, const uni_char *str2, long len, BOOL ignore_case) { int retval; errno = 0; if (len > 0) // Compare a specific number of characters. retval = ignore_case ? _wcsnicoll(str1, str2, len) : _wcsncoll(str1, str2, len); else if (len < 0) // Compare everything. retval = ignore_case ? wcsicoll(str1, str2) : wcscoll(str1, str2); else retval = 0; if (errno == EINVAL) LEAVE(OpStatus::ERR); // If the length is 0 we should compare the first zero characters. return retval; } const uni_char *WindowsOpLocale::op_ctime( const time_t *t ) { return _wctime(t); } size_t WindowsOpLocale::op_strftime( uni_char *dest, size_t max, const uni_char *fmt, const struct tm *tm ) { // do some validation if(max == 0 || tm->tm_mday > 31 || tm->tm_mday < 1 || /* mday in decimal (01-31) */ tm->tm_year > 8000 || tm->tm_hour < 0 || tm->tm_hour > 23 || /* 24-hour decimal (00-23) */ tm->tm_yday < 0 || tm->tm_yday > 365 || /* yday in decimal (001-366) */ tm->tm_mon < 0 || tm->tm_mon > 12 || /* month in decimal (01-12) */ tm->tm_sec < 0 || tm->tm_sec > 59 ) /* secs in decimal (00-59) */ { return 0; } return wcsftime(dest, max, fmt, tm); } BOOL WindowsOpLocale::Use24HourClock() { return m_use_24_hours; } OP_STATUS WindowsOpLocale::GetFirstDayOfWeek(int& day) { int val = 0; int retval = GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_IFIRSTDAYOFWEEK|LOCALE_RETURN_NUMBER, (LPWSTR)&val, sizeof(int)); if (retval == 0) return OpStatus::ERR; day = (val + 1) % 7; return OpStatus::OK; } int WindowsOpLocale::NumberFormat(uni_char * buffer, size_t max, int number, BOOL with_thousands_sep) { OpString number_string; OpStatus::Ignore(number_string.AppendFormat(UNI_L("%i"), number)); return InternalNumberFormat(buffer, max, number_string.CStr(), 0, with_thousands_sep); } int WindowsOpLocale::NumberFormat(uni_char * buffer, size_t max, double number, int precision, BOOL with_thousands_sep) { int decimal_pos = 0; int sign = 0; const char* fcvt_buf = _fcvt(number, precision, &decimal_pos, &sign); if (fcvt_buf == 0) return 0; OpString8 number_string; if (sign != 0) OpStatus::Ignore(number_string.Append("-")); if (decimal_pos >= 0) { OpStatus::Ignore(number_string.Append(fcvt_buf, decimal_pos)); OpStatus::Ignore(number_string.AppendFormat(".%s", fcvt_buf + decimal_pos)); } else { OpString8 format; OpStatus::Ignore(format.AppendFormat(".%%0%uu%%s", -decimal_pos)); OpStatus::Ignore(number_string.AppendFormat(format.CStr(), 0, fcvt_buf)); } OpString number_string16; number_string16.Set(number_string); return InternalNumberFormat(buffer, max, number_string16.CStr(), precision, with_thousands_sep); } int WindowsOpLocale::NumberFormat(uni_char * buffer, size_t max, OpFileLength number, BOOL with_thousands_sep) { OpString number_string; if (number_string.Reserve(max) == 0) return 0; // Use the MS version here, since it supports 64 bit numbers. swprintf(number_string.CStr(), UNI_L("%I64u"), number); return InternalNumberFormat(buffer, max, number_string.CStr(), 0, with_thousands_sep); } int WindowsOpLocale::InternalNumberFormat(uni_char* buffer, size_t max, const uni_char* number, int precision, BOOL with_thousands_sep) { if (buffer == 0 || max == 0) return 0; int characters_written = 0; NUMBERFMT format; format.NumDigits = precision; // GetLocaleInfoInt(LOCALE_IDIGITS); format.LeadingZero = m_leading_zero; if (with_thousands_sep) { format.Grouping = m_grouping; format.lpThousandSep = m_thousands_sep; } else { format.Grouping = 0; format.lpThousandSep = UNI_L(""); } format.lpDecimalSep = m_decimal_sep; format.NegativeOrder = m_negative_order; characters_written = GetNumberFormat(LOCALE_USER_DEFAULT, 0, number, &format, buffer, max); if (characters_written > 0) --characters_written; // GetNumberFormat() seems to include the null terminator in its count. return characters_written; } OP_STATUS WindowsOpLocale::ConvertToLocaleEncoding(OpString8* locale_str, const uni_char* utf16_str) { char* locale_buf = StrToLocaleEncoding(utf16_str); if (!locale_buf) return OpStatus::ERR_NO_MEMORY; locale_str->TakeOver(locale_buf); return OpStatus::OK; } OP_STATUS WindowsOpLocale::ConvertFromLocaleEncoding(OpString* utf16_str, const char* locale_str) { uni_char* utf16_buf = StrFromLocaleEncoding(locale_str); if (!utf16_buf) return OpStatus::ERR_NO_MEMORY; utf16_str->TakeOver(utf16_buf); return OpStatus::OK; }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // Copyright (C) 2005-2011 Opera Software ASA. 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 WEBFEEDS_BACKEND_SUPPORT #include "modules/webfeeds/src/webfeed.h" #include "modules/webfeeds/src/webfeedparser.h" #include "modules/webfeeds/src/webfeedstorage.h" #include "modules/webfeeds/src/webfeeds_api_impl.h" #include "modules/webfeeds/src/webfeedutil.h" #include "modules/about/operafeeds.h" #include "modules/locale/oplanguagemanager.h" #include "modules/prefs/prefsmanager/collections/pc_files.h" #include "modules/stdlib/util/opdate.h" #include "modules/url/url_man.h" #include "modules/xmlutils/xmlparser.h" #ifdef DOC_PREFETCH_API # include "modules/doc/prefetch.h" #endif // DOC_PREFETCH_API #define MsPerMinute 60000 // *************************************************************************** // // WebFeed // // *************************************************************************** WebFeed::WebFeed() : m_stub(NULL), m_reference_count(1), m_marked_for_removal(FALSE), m_title(NULL), m_link(WebFeedLinkElement::Alternate), m_author(NULL), m_tagline(NULL), m_status(STATUS_OK), m_next_free_entry_id(1), m_max_age(0), m_max_entries(0), m_show_images(TRUE), m_show_permalink(FALSE), m_prefetch_entries(FALSE) { OP_ASSERT(g_webfeeds_api); } OP_STATUS WebFeed::Init() { WebFeedsAPI_impl::WebFeedStub* stub = OP_NEW(WebFeedsAPI_impl::WebFeedStub, ()); if (!stub) return OpStatus::ERR_NO_MEMORY; OP_STATUS status = stub->Init(); if (status == OpStatus::OK) status = Init(stub); if (OpStatus::IsError(status)) OP_DELETE(stub); return status; } OP_STATUS WebFeed::Init(WebFeedsAPI_impl::WebFeedStub* stub) { OP_ASSERT(m_title == NULL && m_author == NULL && m_tagline == NULL && m_stub == NULL); m_title = OP_NEW(WebFeedContentElement, ()); m_author = OP_NEW(WebFeedPersonElement, ()); m_tagline = OP_NEW(WebFeedContentElement, ()); m_stub = stub; if (!m_title || !m_author || !m_tagline) { if (m_title) m_title->DecRef(); OP_DELETE(m_author); if (m_tagline) m_tagline->DecRef(); return OpStatus::ERR_NO_MEMORY; } m_stub->SetFeed(this, TRUE); return OpStatus::OK; } WebFeed::~WebFeed() { OP_ASSERT(m_reference_count == 0 || m_reference_count == 1); /* WebFeed and its WebFeedEntries is one system which is deleted * at the same time. The reference count refers to all external * references to either feed or its entries. When no references * exists to either a feed or one of its entries delete all of them */ // delete all entries: m_entries.Clear(); if (m_title) m_title->DecRef(); OP_DELETE(m_author); if (m_tagline) m_tagline->DecRef(); } OpFeed* WebFeed::IncRef() { m_reference_count++; return this; } void WebFeed::DecRef() { OP_ASSERT(m_reference_count > 0); if (--m_reference_count == 0) { OP_DELETE(m_stub); OP_DELETE(this); } else if (m_reference_count == 1 && m_marked_for_removal) // Only reference left is from api, and it has marked it for removal m_stub->RemoveFeedFromMemory(); } ES_Object* WebFeed::GetDOMObject(DOM_Environment* environment) { ES_Object* dom_feed = NULL; if (m_dom_objects.GetData(environment, &dom_feed) == OpStatus::OK) return dom_feed; return NULL; } void WebFeed::SetDOMObject(ES_Object *dom_obj, DOM_Environment* environment) { ES_Object* dummy; // Have to remove entry first, because if it already exists adding it again will result in error, and there is no update method // Ignore error from removing something which doesn't exist m_dom_objects.Remove(environment, &dummy); m_dom_objects.Add(environment, dom_obj); } OpFeed::FeedStatus WebFeed::GetStatus() { return m_stub->GetStatus(); } void WebFeed::SetStatus(OpFeed::FeedStatus status) { m_stub->SetStatus(status); } double WebFeed::LastUpdated() { OP_ASSERT(m_stub); return m_stub->GetUpdateTime(); } void WebFeed::SetLastUpdated(double opdate) { OP_ASSERT(m_stub); m_stub->SetUpdateTime(opdate); } void WebFeed::Subscribe() { OP_ASSERT(m_stub); if (m_stub) m_stub->SetSubscribed(TRUE); } void WebFeed::UnSubscribe() { OP_ASSERT(m_stub); if (m_stub) m_stub->SetSubscribed(FALSE); } BOOL WebFeed::IsSubscribed() { OP_ASSERT(m_stub); if (!m_stub) return FALSE; return m_stub->IsSubscribed(); } OP_STATUS WebFeed::Update(OpFeedListener* listener) { return ((WebFeedsAPI_impl*)g_webfeeds_api)->LoadFeed(this, GetURL(), listener); } OpFeed* WebFeed::GetPrevious() { return (WebFeed*)Pred(); } OpFeed* WebFeed::GetNext() { return (WebFeed*)Suc(); } OpFeedEntry* WebFeed::GetFirstEntry() { WebFeedEntry* first = (WebFeedEntry*)m_entries.First(); if (first && first->MarkedForRemoval()) // ignore the real first if it's being removed first = (WebFeedEntry*)first->GetNext(); return first; } OpFeedEntry* WebFeed::GetLastEntry() { WebFeedEntry* last = (WebFeedEntry*)m_entries.Last(); if (last && last->MarkedForRemoval()) // ignore the real last if it's being removed last = (WebFeedEntry*)last->GetPrevious(); return last; } OpFeedEntry* WebFeed::GetEntryById(UINT id) { for (OpFeedEntry* entry = GetFirstEntry(); entry; entry = entry->GetNext()) if (entry->GetId() == id) return entry; return NULL; } OpFeed::FeedId WebFeed::GetId() { if(m_stub) return m_stub->GetId(); else return 0; } void WebFeed::SetId(FeedId id) { OP_ASSERT(m_stub); m_stub->SetId(id); } OpFeedEntry::EntryId WebFeed::GetNextFreeEntryId() { return m_next_free_entry_id; } void WebFeed::SetNextFreeEntryId(OpFeedEntry::EntryId id) { m_next_free_entry_id = id; } UINT WebFeed::GetMaxAge() { return m_max_age; } void WebFeed::SetMaxAge(UINT age) { m_max_age = age; } UINT WebFeed::GetMaxEntries() { return m_max_entries; } void WebFeed::SetMaxEntries(UINT entries) { m_max_entries = entries; } UINT WebFeed::GetUpdateInterval() { OP_ASSERT(m_stub); return m_stub ? m_stub->GetUpdateInterval() : 1000; } void WebFeed::SetUpdateInterval(UINT interval) { OP_ASSERT(m_stub && interval > 0); if (interval == 0) interval = 1; if (m_stub) m_stub->SetUpdateInterval(interval); } UINT WebFeed::GetMinUpdateInterval() { return m_stub ? m_stub->GetMinUpdateInterval() : 0; } void WebFeed::SetMinUpdateInterval(UINT interval) { if (m_stub) m_stub->SetMinUpdateInterval(interval); } BOOL WebFeed::GetShowImages() { return m_show_images; } void WebFeed::SetShowImages(BOOL show) { m_show_images = show; } BOOL WebFeed::GetShowPermalink() { return m_show_permalink; } void WebFeed::SetShowPermalink(BOOL show) { m_show_permalink = show; } void WebFeed::SetPrefetchPrimaryWhenNewEntries(BOOL prefetch, BOOL prefetch_now) { #ifdef DOC_PREFETCH_API if (!m_prefetch_entries && prefetch_now) for (OpFeedEntry* entry = GetFirstEntry(); entry; entry = entry->GetNext()) { RAISE_AND_RETURN_VOID_IF_ERROR(((WebFeedEntry*)entry)->PrefetchPrimaryLink()); } #endif // DOC_PREFETCH_API m_prefetch_entries = prefetch; } UINT WebFeed::GetTotalCount() { return m_stub->GetTotalCount(); } UINT WebFeed::GetUnreadCount() { return m_stub->GetUnreadCount(); } void WebFeed::MarkOneEntryUnread() { m_stub->IncrementUnreadCount(); #ifdef WEBFEEDS_DISPLAY_SUPPORT // g_webfeeds_api_impl->UpdateFeedWindow(this); #endif // WEBFEEDS_DISPLAY_SUPPORT } void WebFeed::MarkOneEntryNotUnread() { m_stub->IncrementUnreadCount(-1); #ifdef WEBFEEDS_DISPLAY_SUPPORT // g_webfeeds_api_impl->UpdateFeedWindow(this); #endif // WEBFEEDS_DISPLAY_SUPPORT } void WebFeed::MarkAllEntries(OpFeedEntry::ReadStatus status) { for (OpFeedEntry* entry = GetFirstEntry(); entry; entry = entry->GetNext()) entry->SetReadStatus(status); #ifdef WEBFEEDS_REFRESH_FEED_WINDOWS g_webfeeds_api_impl->UpdateFeedWindow(this); #endif // WEBFEEDS_REFRESH_FEED_WINDOWS } UINT WebFeed::GetSizeUsed() { #ifdef WEBFEEDS_SAVED_STORE_SUPPORT return m_stub->GetDiskSpaceUsed(); #else return 0; #endif // WEBFEEDS_SAVED_STORE_SUPPORT } URL& WebFeed::GetURL() { OP_ASSERT(m_stub); return m_stub->GetURL(); } void WebFeed::SetURL(URL& url) { OP_ASSERT(m_stub); m_stub->SetURL(url); } OP_STATUS WebFeed::GetFeedIdURL(OpString& res) { return GetStub()->GetFeedIdURL(res); } OpFeedContent* WebFeed::GetTitle() { return m_title; } void WebFeed::SetParsedTitle(WebFeedContentElement* title) { if (m_title == title) return; if (m_title) m_title->DecRef(); m_title = title; m_title->IncRef(); if (title && !title->IsBinary() && !m_stub->HasTitle()) m_stub->SetTitle(title->Data()); } OP_STATUS WebFeed::GetUserDefinedTitle(OpString& title) { if (GetStub()->HasTitle()) return GetStub()->GetTitle(title); else return title.Set(m_title->Data()); } OP_STATUS WebFeed::SetUserDefinedTitle(const uni_char* new_title) { return GetStub()->SetTitle(new_title); } WebFeedLinkElement* WebFeed::FeedLink() { return &m_link; } WebFeedPersonElement* WebFeed::AuthorElement() { return m_author; } const uni_char* WebFeed::GetAuthor() { return m_author->Name().CStr(); } WebFeedContentElement* WebFeed::Tagline() { return m_tagline; } const uni_char* WebFeed::GetProperty(const uni_char* property) { // TODO return NULL; } const uni_char* WebFeed::GetLogo() { // TODO return NULL; } const uni_char* WebFeed::GetIcon() { return m_icon.CStr(); } OP_STATUS WebFeed::SetIcon(const uni_char* icon_url) { return m_icon.Set(icon_url); } BOOL WebFeed::AddEntryL(WebFeedEntry* entry, OpFeedEntry::EntryId id/*=0*/, WebFeedEntry** actual_entry /* = NULL */) { if (actual_entry) *actual_entry = NULL; if (id == 0) entry->SetId(m_next_free_entry_id++); else entry->SetId(id); double current_time = OpDate::GetCurrentUTCTime(); double time_to_live = GetMaxAge() ? GetMaxAge() : g_webfeeds_api->GetDefMaxAge(); double expired_time = current_time - (time_to_live * MsPerMinute); if (entry->GetPublicationDate() == 0.0) // none set from the feed, give it current time entry->SetPublicationDate(current_time); // Don't add entry if it has already expired else if (time_to_live && entry->GetPublicationDate() < expired_time) return FALSE; // If entry list is full, only accept entry if it is newer than oldest entry if (GetTotalCount() == GetMaxEntries() || m_stub->HasReachedDiskSpaceLimit()) { OpFeedEntry* last = GetLastEntry(); if (last && entry->GetPublicationDate() <= last->GetPublicationDate()) return FALSE; } // Find if we already have this entry. // Have to search entire list since update time might have changed WebFeedEntry* e; OpString guid; ANCHOR(OpString, guid); guid.SetL(entry->GetGuid()); if (!guid.IsEmpty()) { for (e = (WebFeedEntry*)m_entries.First(); e; e = (WebFeedEntry*)e->Suc()) { const uni_char* eid = e->GetGuid(); if (eid && (guid == eid)) { if (entry->GetPublicationDate() <= e->GetPublicationDate()) { if (actual_entry) *actual_entry = e; return FALSE; } else // if last added is newer then replace old { m_stub->IncrementTotalCount(-1); entry->SetReadStatus(e->GetReadStatus()); // keep read status of old entry e->MarkForRemoval(); break; } } } } else if (entry->GetTitle())// If the entry doesn't have a guid, then assume entries with same title and timestamp are the same { OpString link; ANCHOR(OpString, link); entry->GetPrimaryLink().GetAttributeL(URL::KUniName_Username_Password_Hidden, link); const uni_char* title = entry->GetTitle()->Data(); // Only in RSS is guid optional, and title can only be text in RSS (and not binary as in Atom) double timestamp = entry->GetPublicationDate(); if (title || !link.IsEmpty()) { for (e = (WebFeedEntry*)m_entries.First(); e; e = (WebFeedEntry*)e->Suc()) { // Check if link is different, then it can't be same entry OpString elink; ANCHOR(OpString, elink); e->GetPrimaryLink().GetAttributeL(URL::KUniName_Username_Password_Hidden,elink); if (!(elink == link)) continue; if (!title || !e->GetTitle()) continue; const uni_char* etitle = e->GetTitle()->Data(); if (etitle && (uni_strcmp(title, etitle) == 0) && (link == elink) && (timestamp == e->GetPublicationDate())) { if (actual_entry) *actual_entry = e; return FALSE; } } } } CheckFeedForNumEntries(1); // make room for one more entry if full // Insert into correct position (chronological). As most feeds are already sorted // this usually shouldn't have to search very far. for (e = (WebFeedEntry*)m_entries.Last(); e && (e->GetPublicationDate() < entry->GetPublicationDate()); e = (WebFeedEntry*)e->Pred()) /* empty body */; if (e) entry->Follow(e); else // insert first if list is empty, or no one is newer entry->IntoStart(&m_entries); // Add reference to entry from feed entry->SetFeed(this); entry->IncRef(); m_stub->IncrementTotalCount(); if (entry->GetReadStatus() == OpFeedEntry::STATUS_UNREAD) m_stub->IncrementUnreadCount(); if (actual_entry) *actual_entry = entry; return TRUE; } void WebFeed::RemoveEntry(WebFeedEntry* entry) { entry->Out(); if (!entry->MarkedForRemoval()) // marked ones have already been acounted for RemoveEntryFromCount(entry); OP_DELETE(entry); } void WebFeed::RemoveEntryFromCount(WebFeedEntry* entry) { m_stub->IncrementTotalCount(-1); if (entry->GetReadStatus() == OpFeedEntry::STATUS_UNREAD) m_stub->IncrementUnreadCount(-1); } void WebFeed::CheckFeedForNumEntries(UINT free_entries_to_reserve) { UINT max_entries = GetMaxEntries() ? GetMaxEntries() : g_webfeeds_api->GetDefMaxEntries(); if (!max_entries) // no limit return; int need_to_free = GetTotalCount() + free_entries_to_reserve - max_entries; // Remove from the rear as many as necessary WebFeedEntry* entry = (WebFeedEntry*)GetLastEntry(); while (entry && need_to_free > 0) { WebFeedEntry* prev_entry = (WebFeedEntry*)entry->GetPrevious(); // have to get this now as entry might be deleted by next few calls if (!entry->GetKeep()) { entry->MarkForRemoval(); need_to_free--; } entry = prev_entry; } } void WebFeed::CheckFeedForExpiredEntries() { UINT time_to_live = GetMaxAge() ? GetMaxAge() : g_webfeeds_api->GetDefMaxAge(); if (!time_to_live) return; double expired_time = OpDate::GetCurrentUTCTime() - (time_to_live * MsPerMinute); WebFeedEntry* entry = (WebFeedEntry*)GetLastEntry(); while (entry && entry->GetPublicationDate() < expired_time) { WebFeedEntry* prev_entry = (WebFeedEntry*)entry->GetPrevious(); // have to get this now as entry might be deleted by next few calls if (!entry->GetKeep()) entry->MarkForRemoval(); entry = prev_entry; } } #ifdef WEBFEEDS_DISPLAY_SUPPORT # ifdef OLD_FEED_DISPLAY inline void AddHTMLL(URL& out_url, const uni_char* data) { LEAVE_IF_ERROR(out_url.WriteDocumentData(URL::KNormal, data)); } # endif // OLD_FEED_DISPLAY OP_STATUS WebFeed::WriteFeed(URL& out_url, BOOL complete_document, BOOL write_subscribe_header) { #ifndef OLD_FEED_DISPLAY if (out_url.IsEmpty()) { out_url = g_url_api->GetURL("opera:feeds"); out_url.Unload(); } OperaFeeds feed_preview(out_url, this); OP_STATUS status = feed_preview.GenerateData(); #else TRAPD(status, WriteFeedL(out_url, complete_document, write_subscribe_header)); #endif return status; } #ifdef OLD_FEED_DISPLAY void WebFeed::WriteFeedL(URL& out_url, BOOL complete_document, BOOL write_subscribe_header) { BOOL subscribe_header = write_subscribe_header && !IsSubscribed(); // Create a new URL to write generated data to: OpString id_url; ANCHOR(OpString, id_url); LEAVE_IF_ERROR(GetFeedIdURL(id_url)); if (out_url.IsEmpty()) out_url = urlManager->GetURL(id_url.CStr()); if (complete_document) { // Get address of style file: OpString styleurl; ANCHOR(OpString, styleurl); g_pcfiles->GetFileURLL(PrefsCollectionFiles::StyleWebFeedsDisplay, &styleurl); OpString direction; ANCHOR(OpString, direction); switch (g_languageManager->GetWritingDirection) { case OpLanguageManager::LTR: default: direction.SetL("ltr"); break; case OpLanguageManager::RTL: direction.SetL("rtl"); break; } // Write headers AddHTMLL(out_url, UNI_L("\xFEFF")); // Byte order mark AddHTMLL(out_url, UNI_L("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n")); out_url.WriteDocumentDataUniSprintf(UNI_L("<html dir=\"%s\" lang=\"%s\">\n<head>\n"), direction.CStr(), g_languageManager->GetLanguage().CStr()); out_url.WriteDocumentDataUniSprintf(UNI_L("<title>%s</title>\n"), m_stub->GetTitle()); out_url.WriteDocumentDataUniSprintf(UNI_L("<link rel=\"stylesheet\" href=\"%s\" type=\"text/css\" media=\"screen,projection,tv,handheld,speech\">\n"), styleurl.CStr()); AddHTMLL(out_url, UNI_L("<script type='text/javascript'>\n")); if (subscribe_header) out_url.WriteDocumentDataUniSprintf(UNI_L("function subscribe(elem) { var feed = opera.feeds.getFeedById(%d); if(feed) { feed.subscribe(); elem.style.visibility = 'hidden';}}\n"), GetId()); AddHTMLL(out_url, UNI_L("function markread(elem) { elem.className = 'readentry'; }\n")); AddHTMLL(out_url, UNI_L("</script>\n</head>\n<body>\n")); } // Translated strings OpString subscribed_title, unsubscribed_title, subscribe_text, subscribe_button, title_text, author_text, newest_text, every_x_minutes, every_x_hours, every_x_days, update_frequency, address_text; #if LANGUAGE_DATABASE_VERSION >= 864 g_languageManager->GetStringL(Str::S_WEBFEEDS_SUBSCRIBED_TITLE, subscribed_title); g_languageManager->GetStringL(Str::S_WEBFEEDS_UNSUBSCRIBED_TITLE, unsubscribed_title); g_languageManager->GetStringL(Str::S_WEBFEEDS_SUBSCRIBE, subscribe_text); g_languageManager->GetStringL(Str::S_MINI_FEED_SUBSCRIBE, subscribe_button); g_languageManager->GetStringL(Str::S_WEBFEEDS_FEED_TITLE, title_text); g_languageManager->GetStringL(Str::S_WEBFEEDS_FEED_AUTHOR, author_text); g_languageManager->GetStringL(Str::S_WEBFEEDS_FEED_NEWEST_ENTRY, newest_text); g_languageManager->GetStringL(Str::S_WEBFEEDS_UPDATE_FREQUENCY, update_frequency); g_languageManager->GetStringL(Str::SI_LOCATION_TEXT, address_text); g_languageManager->GetStringL(Str::S_EVERY_X_MINUTES, every_x_minutes); g_languageManager->GetStringL(Str::S_EVERY_X_HOURS, every_x_hours); g_languageManager->GetStringL(Str::S_WEBFEEDS_UPDATE_EVERY_X_DAYS, every_x_days); #else every_x_minutes.SetL("%d"); every_x_hours.SetL("%d"); every_x_days.SetL("%d"); #endif if (subscribe_header) { out_url.WriteDocumentDataUniSprintf(UNI_L("<h1>%s</h1>\n"), subscribed_title.CStr()); out_url.WriteDocumentDataUniSprintf(UNI_L("<h2>%s <button type=\"button\" onclick=\"subscribe(this)\">%s</button></h2>\n"), subscribe_text.CStr(), subscribe_button.CStr()); AddHTMLL(out_url, UNI_L("<dl>\n")); if (m_title->HasValue()) { out_url.WriteDocumentDataUniSprintf(UNI_L("<dt>%s:</dt><dd>"), title_text.CStr()); m_title->WriteAsStrippedHTMLL(out_url); AddHTMLL(out_url, UNI_L("</dd>\n")); } if (GetAuthor()) out_url.WriteDocumentDataUniSprintf(UNI_L("<dt>%s:</dt><dd>%s</dd>\n"), author_text.CStr(), GetAuthor()); if (GetFirstEntry()) { uni_char* time = WebFeedUtil::TimeToString(GetFirstEntry()->GetPublicationDate()); out_url.WriteDocumentDataUniSprintf(UNI_L("<dt>%s:</dt><dd>%s</dd>\n"), newest_text.CStr(), time); OP_DELETEA(time); } if (UINT update_interval = GetMinUpdateInterval()) { if (update_interval <= 180) { out_url.WriteDocumentDataUniSprintf(UNI_L("<dt>%s:</dt><dd>"), update_frequency.CStr()); out_url.WriteDocumentDataUniSprintf(every_x_minutes.CStr(), update_interval); AddHTMLL(out_url, UNI_L("</dd>\n")); } else { out_url.WriteDocumentDataUniSprintf(UNI_L("<dt>%s:</dt><dd>"), update_frequency.CStr()); update_interval /= 60; if (update_interval < 72) out_url.WriteDocumentDataUniSprintf(every_x_hours.CStr(), update_interval); else out_url.WriteDocumentDataUniSprintf(every_x_days.CStr(), update_interval / 24); AddHTMLL(out_url, UNI_L("</dd>\n")); } } const uni_char* feed_url = GetURL().GetUniName(FALSE, PASSWORD_HIDDEN); out_url.WriteDocumentDataUniSprintf(UNI_L("<dt>%s:</dt><dd><a href=\"%s\">%s</a></dd>\n"), address_text.CStr(), feed_url, feed_url); AddHTMLL(out_url, UNI_L("</dl>")); } else out_url.WriteDocumentDataUniSprintf(UNI_L("<h1>%s</h1>\n"), subscribed_title.CStr()); // Write title (if any): AddHTMLL(out_url, UNI_L("<h3>\n")); OpString icon; ANCHOR(OpString, icon); LEAVE_IF_ERROR(m_stub->GetInternalFeedIcon(icon)); if (!icon.IsEmpty()) { AddHTMLL(out_url, UNI_L("<img src=\"")); AddHTMLL(out_url, icon.CStr()); AddHTMLL(out_url, UNI_L("\" alt=\"\" height=\"16\" width=\"16\">")); } AddHTMLL(out_url, m_stub->GetTitle()); // Add last updated time in brackets after title: uni_char* short_time = WebFeedUtil::TimeToShortString(LastUpdated(), TRUE); if (short_time) out_url.WriteDocumentDataUniSprintf(UNI_L(" [%s]"), short_time); OP_DELETEA(short_time); short_time = NULL; AddHTMLL(out_url, UNI_L("\n</h3>\n")); // Write title of all entries: AddHTMLL(out_url, UNI_L("<ul>")); for (WebFeedEntry* entry = (WebFeedEntry*)GetFirstEntry(); entry; entry = (WebFeedEntry*)entry->GetNext()) { if (entry->GetReadStatus() == OpFeedEntry::STATUS_UNREAD) AddHTMLL(out_url, UNI_L("<li><a class=\"unread\" onclick=\"markread(this);\"")); else AddHTMLL(out_url, UNI_L("<li><a ")); if (m_show_permalink) { URL link = entry->GetPrimaryLink(); ANCHOR(URL, link); if (!link.IsEmpty()) out_url.WriteDocumentDataUniSprintf(UNI_L(" href=\"%s\">"), link.GetUniName(FALSE, PASSWORD_SHOW)); } else out_url.WriteDocumentDataUniSprintf(UNI_L(" href=\"opera:feed-id/%08x-%08x\">"), GetId(), entry->GetId()); ((WebFeedContentElement*)entry->GetTitle())->WriteAsStrippedHTMLL(out_url); AddHTMLL(out_url, UNI_L("</a></li>\n")); } AddHTMLL(out_url, UNI_L("</ul>\n")); if (complete_document) WebFeedUtil::WriteGeneratedPageFooterL(out_url); } #ifdef WEBFEEDS_SUBSCRIPTION_LIST_FORM_UI void WebFeed::WriteSettingsPageL(URL& out_url) { // Create a new URL to write generated data to: if (out_url.IsEmpty()) out_url = urlManager->GetNewOperaURL(); OpString title; ANCHOR(OpString, title); LEAVE_IF_ERROR(title.AppendFormat(UNI_L("%s - %s"), m_stub->GetTitle(), UNI_L("settings"))); WebFeedUtil::WriteGeneratedPageHeaderL(out_url, title.CStr()); out_url.WriteDocumentDataUniSprintf(UNI_L("<h1>%s</h1>\n"), title.CStr()); AddHTMLL(out_url, UNI_L("<form id=\"feed-settings\" action=\"\">\n")); AddHTMLL(out_url, UNI_L("<dl>\n")); AddHTMLL(out_url, UNI_L("<dt>Title</dt>")); // TODO locallize OpString escaped_title; ANCHOR(OpString, escaped_title); LEAVE_IF_ERROR(WebFeedUtil::EscapeHTML(m_stub->GetTitle(), escaped_title)); out_url.WriteDocumentDataUniSprintf(UNI_L("<dd><input name=\"title\" type=\"text\" size=\"50\" value=\"%s\"></dd>\n"), escaped_title.CStr()); g_webfeeds_api_impl->WriteUpdateAndExpireFormL(out_url, this); AddHTMLL(out_url, UNI_L("</dl></form>\n")); WebFeedUtil::WriteGeneratedPageFooterL(out_url); } #endif // WEBFEEDS_SUBSCRIPTION_LIST_FORM_UI #endif // OLD_FEED_DISPLAY #endif // WEBFEEDS_DISPLAY_SUPPORT #ifdef WEBFEEDS_SAVED_STORE_SUPPORT void WebFeed::SaveOverrideSettingsL(WriteBuffer &buf) { if (m_max_age == g_webfeeds_api->GetDefMaxAge() && m_max_entries == g_webfeeds_api->GetDefMaxEntries() && m_show_images == g_webfeeds_api->GetDefShowImages() && !m_show_permalink) return; buf.Append("<overrides>\n"); if (m_max_age != g_webfeeds_api->GetDefMaxAge()) WriteSettingNum(buf, "max-age", m_max_age); if (m_max_entries != g_webfeeds_api->GetDefMaxEntries()) WriteSettingNum(buf, "max-entries", m_max_entries); if (m_show_images != g_webfeeds_api->GetDefShowImages()) WriteSettingBool(buf, "show-images", m_show_images); if (m_show_permalink) WriteSettingBool(buf, "show-permalink", m_show_permalink); buf.Append("</overrides>\n"); } void WebFeed::SaveEntriesL(WriteBuffer &buf, int space_available) { UINT pre_space_used = buf.GetBytesWritten(); WebFeedEntry *entry = NULL; for (entry = (WebFeedEntry *)m_entries.First(); entry; entry = (WebFeedEntry *)entry->Suc()) if (entry->GetKeep()) entry->SaveL(buf); // TODO: notify someone if there is no space left at this point? m_stub->SetHasReachedDiskSpaceLimit(FALSE); // Next pass save as many other entries as we have room for, starting with newest one for (entry = (WebFeedEntry *)m_entries.First(); entry; entry = (WebFeedEntry *)entry->Suc()) { if (entry->GetKeep()) continue; // already saved if (entry->MarkedForRemoval()) continue; // removed, should not keep this one if (space_available) // limited disk space { UINT space_used = buf.GetBytesWritten() - pre_space_used; if (space_available < 0 || space_used + 10 + entry->GetApproximateSaveSize() > (UINT)space_available) { m_stub->SetHasReachedDiskSpaceLimit(TRUE); // remove the remaining entries: while (entry) { WebFeedEntry* next_entry = (WebFeedEntry *)entry->Suc(); entry->MarkForRemoval(); // might delete entry entry = next_entry; } break; } } entry->SaveL(buf); } } /* static */ void WebFeed::WriteSettingNum(WriteBuffer &buf, const char *name, UINT num) { buf.Append(" <setting name=\""); buf.Append(name); buf.Append("\" value=\""); buf.Append(num); buf.Append("\"/>\n"); } /* static */ void WebFeed::WriteSettingBool(WriteBuffer &buf, const char *name, BOOL value) { buf.Append(" <setting name=\""); buf.Append(name); buf.Append("\" value=\""); if (value) buf.Append("yes\"/>\n"); else buf.Append("no\"/>\n"); } #endif // WEBFEEDS_SAVED_STORE_SUPPORT #endif // WEBFEEDS_BACKEND_SUPPORT
#include "Types.hpp" #include "Log.hpp" //////////////////////////////////////////////////////////////////////////////////////////// StateStatistics::StateStatistics(){ nSegments=0; nTransitions=0; }; StateStatistics::StateStatistics(uint64_t label_){ nSegments=0; nTransitions=0; label=label_; }; void StateStatistics::update(uint64_t finalState){ nSegments++; if(finalState!=label) { counts[finalState]+=1; nTransitions+=1; } }; void StateStatistics::update(StateStatistics s){ nSegments+=s.nSegments; nTransitions+=s.nTransitions; for(auto it=s.counts.begin(); it!=s.counts.end(); it++) { counts[it->first]+=s.counts[it->first]; } }; void StateStatistics::sampleSegmentBKL(double unknownPrior, boost::random::mt11213b &rand, boost::random::uniform_01<> &uniform,Label &final, bool &absorbed){ unknownPrior=std::max(unknownPrior,1e-10); double r1=uniform(rand); final=label; double rN=r1*(nSegments+unknownPrior+1); double rAccum=unknownPrior; //this was absorbed into the unknown if(rAccum>=rN) { absorbed=true; } for(auto it=counts.begin(); it!=counts.end(); it++) { rAccum+=it->second; //this is a real transition if(rAccum>=rN) { final=it->first; break; } } absorbed=false; }; void StateStatistics::sampleEscapeBKL(double unknownPrior, boost::random::mt11213b &rand, boost::random::uniform_01<> &uniform, Label &final, bool &absorbed,int &nConsumed){ unknownPrior=std::max(unknownPrior,1e-10); double pstay=unknownPrior; for(auto it=counts.begin(); it!=counts.end(); it++) { pstay+=it->second; } pstay/=(nSegments+unknownPrior+1); pstay=1-pstay; //sample a number of self transition before an escape boost::random::negative_binomial_distribution<int,double> nbino(1,1-pstay); nConsumed=nbino(rand); //sample a transition double r1=uniform(rand); double rN=r1*(nTransitions+unknownPrior); double rAccum=unknownPrior; final=label; //this was absorbed into the unknown if(rAccum>=rN) { absorbed=true; } for(auto it=counts.begin(); it!=counts.end(); it++) { rAccum+=it->second; //this is a real transition if(rAccum>=rN) { final=it->first; break; } } absorbed=false; }; void StateStatistics::clear(){ nSegments=0; counts.clear(); }; //////////////////////////////////////////////////////////////////////////////////////////// TransitionStatistics::TransitionStatistics(){ boost::random::random_device rd; rng.seed(rd()); }; void TransitionStatistics::clear(){ statistics.clear(); }; void TransitionStatistics::update(uint64_t initialState, uint64_t finalState){ if(statistics.count(initialState)==0) { StateStatistics s(initialState); statistics.insert(std::make_pair(initialState,s)); } statistics.find(initialState)->second.update(finalState); }; void TransitionStatistics::assimilate(TransitionStatistics &s){ for(auto it=s.statistics.begin(); it!=s.statistics.end(); it++) { if(statistics.count(it->first)==0) { StateStatistics s(it->first); statistics.insert(std::make_pair(it->first,s)); } statistics.find(it->first)->second.update(it->second); } s.clear(); }; void TransitionStatistics::sampleSegmentBKL(Label &lb,double unknownPrior, Label &final, bool &absorbed){ //unknown state final=lb; absorbed=true; if( statistics.count(lb)==0 ) { StateStatistics s(lb); statistics.insert(std::make_pair(lb,s)); } statistics.find(lb)->second.sampleSegmentBKL(unknownPrior,rng,uniform,final,absorbed); }; void TransitionStatistics::sampleEscapeBKL(Label &lb,double unknownPrior, Label &final, bool &absorbed, int &nSegments){ //unknown state final=lb; absorbed=true; nSegments=0; if( statistics.count(lb)==0 ) { StateStatistics s(lb); statistics.insert(std::make_pair(lb,s)); } statistics.find(lb)->second.sampleEscapeBKL(unknownPrior,rng,uniform,final,absorbed,nSegments); }; int TransitionStatistics::size(){ return statistics.size(); }; //////////////////////////////////////////////////////////////////////////////////////////// Trajectory::Trajectory(){ (*this).length=0; (*this).overhead_=0; (*this).nSplice=1; }; void Trajectory::print(){ std::cout<<"============"<<std::endl; for(auto it=visits.begin(); it!=visits.end(); it++) { std::cout<<it->label<<" "<<it->duration<<std::endl; } }; void Trajectory::log(){ #ifdef USE_BOOST_LOG boost::log::sources::severity_logger< boost::log::trivial::severity_level > lg; BOOST_LOG_SEV(lg, boost::log::trivial::info) <<"============"; for(auto it=visits.begin(); it!=visits.end(); it++) { BOOST_LOG_SEV(lg, boost::log::trivial::info) <<it->label<<" "<<it->duration; } #else std::cout<<"============\n"; for(auto it=visits.begin(); it!=visits.end(); it++) { std::cout<<it->label<<" "<<it->duration<<std::endl; } #endif }; void Trajectory::clear(){ visits.clear(); length=0; index=0; nSplice=0; overhead_=0; }; //append a visit to a trajectory. Extends the last visit if possible void Trajectory::appendVisit(Visit &v, bool extend){ (*this).length+=v.duration; if( extend and !(*this).empty() and (*this).back().label==v.label) { //extend the last visit (*this).back().duration+=v.duration; return; } //new visit (*this).visits.push_back(v); }; //splice two trajectories bool Trajectory::splice(Trajectory &t){ //do not splice empty trajectories if( (*this).empty() or t.empty() ) { return false; } //splice only if the beginning and end match if( (*this).back().label == t.front().label ) { (*this).back().duration+=t.front().duration; t.visits.pop_front(); (*this).visits.splice((*this).visits.end(), t.visits); (*this).length+=t.length; (*this).overhead_+=t.overhead_; //consume t t.clear(); (*this).nSplice++; return true; } return false; }; void Trajectory::truncate(int maxDuration, Trajectory &leftover){ leftover.clear(); //we don't need to do anything if( (*this).duration()<=maxDuration) { return; } int dt=(*this).duration(); leftover=*this; (*this).clear(); int nUsed=0; while(nUsed<maxDuration) { Visit front=leftover.front(); if(nUsed+front.duration<=maxDuration) { //use the whole visit (*this).appendVisit(front); nUsed+=front.duration; leftover.pop_front(); } else{ //take only a fraction Visit v; v.label=front.label; v.duration=maxDuration-nUsed; (*this).appendVisit(v); leftover.front().duration-=(maxDuration-nUsed); leftover.length-=(maxDuration-nUsed); nUsed=maxDuration; } } if(dt!=(*this).duration()+leftover.duration() ) { std::cout<<"ERROR!!! LOST SOME BLOCKS"<<std::endl; } }; uint64_t Trajectory::duration(){ return length; }; uint64_t& Trajectory::overhead(){ return overhead_; }; bool Trajectory::empty(){ return visits.size()==0; }; Visit& Trajectory::back(){ return visits.back(); }; Visit& Trajectory::front(){ return visits.front(); }; void Trajectory::pop_back(){ if(visits.size()>0) { length-=visits.back().duration; visits.pop_back(); } }; void Trajectory::pop_front(){ if(visits.size()>0) { length-=visits.front().duration; visits.pop_front(); } }; //////////////////////////////////////////////////////////////////////////////////////////// void SegmentDatabase::clear(){ db.clear(); }; int SegmentDatabase::size(){ return db.size(); }; int SegmentDatabase::count(Label lb, int flavor){ auto key=std::make_pair(lb,flavor); if(db.count(key)) { return db[key].size(); } return 0; }; bool SegmentDatabase::front(Label lb, int flavor, Trajectory &t){ if(count(lb,flavor)==0) { return false; } auto key=std::make_pair(lb,flavor); t=db[key].front(); return true; }; void SegmentDatabase::pop_front(Label lb, int flavor){ if(count(lb,flavor)!=0) { auto key=std::make_pair(lb,flavor); db[key].pop_front(); if(db[key].empty()) { db.erase(key); } } }; void SegmentDatabase::add(int flavor, Trajectory &t){ if(not t.empty() and not (t.duration()==0)) { Label lb=t.front().label; auto key=std::make_pair(lb,flavor); //if trajectory exist in that bin, try to splice at back. Otherwise, add if(db.count(key)>0) { if(db[key].empty() or (not db[key].back().splice(t))) { db[key].push_back(t); } } else{ db[key]=std::deque<Trajectory>(); db[key].push_back(t); } } else{ std::cout<<"SegmentDatabase::add WARNING! Adding an empty trajectory"<<std::endl; } }; void SegmentDatabase::log(){ #ifdef USE_BOOST_LOG boost::log::sources::severity_logger< boost::log::trivial::severity_level > lg; BOOST_LOG_SEV(lg, boost::log::trivial::info) <<"SEGMENT DB "; for(auto it=db.begin(); it!=db.end(); it++) { BOOST_LOG_SEV(lg, boost::log::trivial::info) <<it->first.first<<" "<<it->first.second<<" "<<it->second.size(); for(auto itt=it->second.begin(); itt!=it->second.end(); itt++) { itt->log(); } BOOST_LOG_SEV(lg, boost::log::trivial::info) <<" - "; } #else std::cout<<"SEGMENT DB\n"; for(auto it=db.begin(); it!=db.end(); it++) { std::cout<<it->first.first<<" "<<it->first.second<<" "<<it->second.size()<<std::endl; for(auto itt=it->second.begin(); itt!=it->second.end(); itt++) itt->log(); std::cout<<"-\n"; } #endif }; void SegmentDatabase::print(){ for(auto it=db.begin(); it!=db.end(); it++) { std::cout<<it->first.first<<" "<<it->first.second<<std::endl; for(auto itt=it->second.begin(); itt!=it->second.end(); itt++) { itt->print(); } } }; int SegmentDatabase::duration(){ int dura=0; for(auto it=db.begin(); it!=db.end(); it++) { for(auto itt=it->second.begin(); itt!=it->second.end(); itt++) { dura+=itt->duration(); } } return dura; }; int SegmentDatabase::duration(Label lb, int flavor){ int dura=0; auto key=std::make_pair(lb,flavor); for(auto it=db[key].begin(); it!=db[key].end(); it++) { dura+=it->duration(); } return dura; }; void SegmentDatabase::merge(SegmentDatabase &supp){ //loop over initial states for(auto it=supp.db.begin(); it!=supp.db.end(); it++) { //loop over trajectories int flavor=it->first.second; for(auto itt=it->second.begin(); itt!=it->second.end(); itt++) { Trajectory &t=*itt; this->add(flavor,t); } } supp.clear(); };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author karie, adamm */ #ifndef DESKTOP_WIDGET_WINDOW_H #define DESKTOP_WIDGET_WINDOW_H #include "modules/widgets/WidgetWindow.h" /** @brief /*/ class DesktopWidgetWindow : public WidgetWindow { public: DesktopWidgetWindow() : m_id(GetUniqueID()) {} OP_STATUS Init(OpWindow::Style style, const OpStringC8& name, OpWindow* parent_window = NULL, OpView* parent_view = NULL, UINT32 effects = 0, void* native_handle = NULL); virtual const char* GetWindowName() { return m_window_name.CStr(); } virtual const uni_char* GetTitle() { if (GetWindow()) return GetWindow()->GetTitle(); else return UNI_L(""); } OpWidget* GetWidgetByName(const OpStringC8& name); OpWidget* GetWidgetByText(const OpStringC8& text); // Is an OpTypedObject cause WidgetWindow subclasses OpInputContext virtual Type GetType() { return WIDGET_TYPE_WIDGETWINDOW; } virtual INT32 GetID() { return m_id; } // == OpScopeDesktopWindowManager ======= virtual OP_STATUS ListWidgets(OpVector<OpWidget> &widgets); OP_STATUS ListWidgets(OpWidget* widget, OpVector<OpWidget> &widgets); private: INT32 m_id; OpString8 m_window_name; }; #endif // DESKTOP_WIDGET_WINDOW_H
#include "LiveStreamMediaSource.hh" #include "GroupsockHelper.hh" #include "RtspSvr.hh" LiveStreamMediaSource* LiveStreamMediaSource::instance = NULL; //default sps pps static char sps[15] = { 0x67,0x42,0x00 ,0x29, 0x8d,0x8d,0x40,0x3c , 0x03 ,0xcd ,0x00,0xf0, 0x88 ,0x45,0x38}; static char pps[4] = { 0x68,0xca,0x43,0xc8}; static unsigned const samplingFrequencyTable[16] = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350, 0, 0, 0 }; static u_int8_t get_frequency_index(unsigned frequency) { int index = 4; for(int i=0; i<sizeof(samplingFrequencyTable)/sizeof(samplingFrequencyTable[0]); i++) { if(samplingFrequencyTable[i] == frequency) { index = i; break; } } return index; } LiveStreamMediaSource* LiveStreamMediaSource::GetInstance(UsageEnvironment& env) { if(instance == NULL) { instance = new LiveStreamMediaSource(env); } return instance; } LiveStreamMediaSource* LiveStreamMediaSource::createNew(UsageEnvironment& env) { if(instance == NULL) { instance = new LiveStreamMediaSource(env); } return instance; } LiveStreamMediaSource::LiveStreamMediaSource(UsageEnvironment& env) : Medium(env),funDemandIDR(NULL),fOurVideoSource(NULL),fOurAudioSource(NULL) ,mSps(NULL),mSpsLen(0) ,mPps(NULL),mPpsLen(0) { m_FrameRate = DEFAULT_MAX_VEDIOFRAME_RATE; mSps = new u_int8_t[64]; mSpsLen = 63; mPps = new u_int8_t[64]; mPpsLen = 63; memcpy(mSps, sps, 15); mSpsLen = 15; memcpy(mPps, pps, 4); mPpsLen = 4; fbiteRate = 128000; fSamplingFrequency = 32000; fNumChannels = 1; fprofile = 1; fuSecsPerFrame = (1024/*samples-per-frame*/ * 1000000) / fSamplingFrequency/*samples-per-second*/; unsigned char audioSpecificConfig[2]; u_int8_t sampling_frequency_index = get_frequency_index(fSamplingFrequency); //44100 u_int8_t channel_configuration = fNumChannels; u_int8_t const audioObjectType = fprofile + 1; audioSpecificConfig[0] = (audioObjectType << 3) | (sampling_frequency_index >> 1); audioSpecificConfig[1] = (sampling_frequency_index << 7) | (channel_configuration << 3); memset(fConfigStr,0x0,5); sprintf(fConfigStr, "%02X%02x", audioSpecificConfig[0], audioSpecificConfig[1]); VbuffMgr = new CBufferManager_t(); VbuffMgr->Init(5 * 1024 * 1024); AbuffMgr = new CBufferManager_t(); AbuffMgr->Init(20 * 1024); } LiveStreamMediaSource::~LiveStreamMediaSource() { if (VbuffMgr != NULL) { delete[] VbuffMgr; VbuffMgr = NULL; } if (AbuffMgr != NULL) { delete[] AbuffMgr; AbuffMgr = NULL; } if (fOurVideoSource != NULL) { Medium::close(fOurVideoSource); fOurVideoSource = NULL; } if (fOurVideoSource != NULL) { Medium::close(fOurAudioSource); fOurAudioSource = NULL; } if(mSps != NULL) { delete[] mSps; mSps = NULL; } if(mPps != NULL) { delete[] mPps; mPps = NULL; } LOGD_print("LiveStreamMediaSource", "~LiveStreamMediaSource"); } void LiveStreamMediaSource::SrcPointerSync(int flag) { switch(flag) { case 1: VbuffMgr->Sync(); break; case 2: AbuffMgr->Sync(); break; default: VbuffMgr->Sync(); AbuffMgr->Sync(); break; } } void LiveStreamMediaSource::RegisterVideoDemandIDR(callback_func handler) { funDemandIDR = handler; } void LiveStreamMediaSource::UnRegisterVideoDemandIDR() { funDemandIDR = NULL; } void LiveStreamMediaSource::VideoDemandIDR() { if( funDemandIDR != NULL) { funDemandIDR(NULL, 0); } } VideoOpenSource* LiveStreamMediaSource::videoSource() { LOGD_print("LiveStreamMediaSource", "----->>>>LiveStreamMediaSource::videoSource()"); #if 1 return VideoOpenSource::createNew(envir(), NULL, *this); #else if (fOurVideoSource == NULL) { fOurVideoSource = VideoOpenSource::createNew(envir(), NULL, *this); } //VbuffMgr->Sync(); //VideoDemandIDR(); return fOurVideoSource; #endif } AudioOpenSource* LiveStreamMediaSource::audioSource() { //AbuffMgr->SyncRwPoint(); #if 1 return AudioOpenSource::createNew(envir(), NULL, *this); #else if (fOurAudioSource == NULL) { fOurAudioSource = AudioOpenSource::createNew(envir(), NULL, *this); } return fOurAudioSource; #endif } void LiveStreamMediaSource::SaveSpsAndPps(u_int8_t* sps, unsigned sps_len, u_int8_t* pps, unsigned pps_len) { if(sps != NULL) { memcpy(mSps, sps, sps_len); mSpsLen = sps_len; } if( pps != NULL) { memcpy(mPps, pps, pps_len); mPpsLen = pps_len; } } bool LiveStreamMediaSource::GetSpsAndPps(u_int8_t* &sps, unsigned& spsLen, u_int8_t* &pps,unsigned& ppsLen) { if(mSps == NULL || mPps == NULL) { return false; } else { sps = mSps; pps = mPps; spsLen = mSpsLen; ppsLen = mPpsLen; } return true; } char const* LiveStreamMediaSource::configStr() { unsigned char audioSpecificConfig[2]; u_int8_t sampling_frequency_index = get_frequency_index(fSamplingFrequency); //44100 u_int8_t channel_configuration = fNumChannels; u_int8_t const audioObjectType = fprofile + 1; audioSpecificConfig[0] = (audioObjectType << 3) | (sampling_frequency_index >> 1); audioSpecificConfig[1] = (sampling_frequency_index << 7) | (channel_configuration << 3); memset(fConfigStr,0x0,5); sprintf(fConfigStr, "%02X%02x", audioSpecificConfig[0], audioSpecificConfig[1]); return fConfigStr; } VideoOpenSource* VideoOpenSource::createNew(UsageEnvironment& env, char const* fileName, LiveStreamMediaSource& input, unsigned preferredFrameSize, unsigned playTimePerFrame) { VideoOpenSource* newSource = new VideoOpenSource(env, input, preferredFrameSize, playTimePerFrame); return newSource; } VideoOpenSource::VideoOpenSource(UsageEnvironment& env, LiveStreamMediaSource& input, unsigned preferredFrameSize, unsigned playTimePerFrame) : FramedSource(env), fInput(input), fPreferredFrameSize(preferredFrameSize), fPlayTimePerFrame(playTimePerFrame), fLastPlayTime(0), fHaveStartedReading(False), fLimitNumBytesToStream(False), fNumBytesToStream(0) ,m_NoDataCnt(0),m_ref(0) { fPresentationTime.tv_sec = 0; fPresentationTime.tv_usec = 0; uSecsToDelay = 1000; uSecsToDelayMax = 1666; memset(mName, 0x0, 128); sprintf(mName, "VideoOpenSource_%p",this); fInput.VbuffMgr->Register(mName,this); } VideoOpenSource::~VideoOpenSource() { fInput.VbuffMgr->UnRegister(mName); if (fInput.fOurVideoSource != NULL) { Medium::close(fInput.fOurVideoSource); fInput.fOurVideoSource = NULL; } LOGD_print("LiveStreamMediaSource", "----->>>>~VideoOpenSource"); } void VideoOpenSource::doGetNextFrame() { //do read from memory incomingDataHandler(this); } void VideoOpenSource::incomingDataHandler(VideoOpenSource* source) { if (!source->isCurrentlyAwaitingData()) { source->doStopGettingFrames(); // we're not ready for the data yet return; } source->incomingDataHandler1(); } void VideoOpenSource::incomingDataHandler1() { if (fLimitNumBytesToStream && fNumBytesToStream < (u_int64_t)fMaxSize) { fMaxSize = (unsigned)fNumBytesToStream; } if (fPreferredFrameSize > 0 && fPreferredFrameSize < fMaxSize) { fMaxSize = fPreferredFrameSize; } fFrameSize = 0; int unHandleCnt = 0; CBuffer_t buffer; if (usingQueue()->PopFront(buffer, unHandleCnt)) { m_NoDataCnt = 0; if (buffer.lenght <= 0) { handleClosure(this); return; } else { int type = buffer.data[0]&0x1f; fFrameSize = buffer.lenght; if (fFrameSize > fMaxSize) { LOGD_print("VideoOpenSource", "----->>>>fFrameSize > fMaxSize lost data!!!"); fFrameSize = fMaxSize; fNumTruncatedBytes = fFrameSize - fMaxSize; } else { fNumTruncatedBytes = 0; } memcpy(fTo , buffer.data, fFrameSize); // Set the 'presentation time': if(type != 7 && type != 8) { if (fPresentationTime.tv_sec == 0 && fPresentationTime.tv_usec == 0 && m_ref == 0) { m_ref = buffer.pts; } else { fPresentationTime.tv_sec = (buffer.pts-m_ref)/1000000; fPresentationTime.tv_usec = (buffer.pts-m_ref)%1000000; } } fDurationInMicroseconds = 100000000 / (fInput.m_FrameRate * 100 * unHandleCnt);; struct timeval tv; getTickCount(&tv, NULL); int64_t _time = (int64_t)tv.tv_sec*1000 + tv.tv_usec/1000; int64_t _presentationTime = (int64_t)fPresentationTime.tv_sec*1000000 + fPresentationTime.tv_usec; LOGD_print("VideoOpenSource", "Call incomingDataHandler1 Time:%lld type:%d fFrameSize:%u unHandleCnt:%d _presentationTime:%llu fMaxSize:%u buffer.pts:%llu" ,/*GetTickCount()*/_time, type, fFrameSize, unHandleCnt, _presentationTime, fMaxSize, buffer.pts); if(unHandleCnt >= 1 || type == 7 || type == 8) { //LOGI_print("VideoOpenSource","type:%d unHandleCnt:%d",type, unHandleCnt); } nextTask() = envir().taskScheduler().scheduleDelayedTask(0, (TaskFunc*)FramedSource::afterGetting, this); } } else { if (uSecsToDelay >= uSecsToDelayMax) { uSecsToDelay = uSecsToDelayMax; } else{ uSecsToDelay *= 2; } // if for long time no data //* //m_NoDataCnt++; if(m_NoDataCnt > 500) { handleClosure(this); return; } //*/ nextTask() = envir().taskScheduler().scheduleDelayedTask(uSecsToDelay, (TaskFunc*)incomingDataHandler, this); } } //=============================================================================================================== AudioOpenSource* AudioOpenSource::createNew(UsageEnvironment& env, char const* fileName, LiveStreamMediaSource& input, unsigned preferredFrameSize, unsigned playTimePerFrame) { AudioOpenSource* newSource = new AudioOpenSource(env, input, preferredFrameSize, playTimePerFrame); return newSource; } AudioOpenSource::AudioOpenSource(UsageEnvironment& env, LiveStreamMediaSource& input, unsigned preferredFrameSize, unsigned playTimePerFrame) : FramedSource(env), fInput(input) ,m_NoDataCnt(0),m_ref(0) { fPresentationTime.tv_sec = 0; fPresentationTime.tv_usec = 0; memset(mName, 0x0, 128); sprintf(mName, "AudioOpenSource%p",this); fInput.AbuffMgr->Register(mName,this); } AudioOpenSource::~AudioOpenSource() { fInput.AbuffMgr->UnRegister(mName); if (fInput.fOurAudioSource != NULL) { Medium::close(fInput.fOurAudioSource); fInput.fOurAudioSource = NULL; } LOGD_print("LiveStreamMediaSource", "----->>>>~AudioOpenSource"); } void AudioOpenSource::doGetNextFrame() { //do read from memory incomingDataHandler(this); } void AudioOpenSource::incomingDataHandler(AudioOpenSource* source) { if (!source->isCurrentlyAwaitingData()) { source->doStopGettingFrames(); // we're not ready for the data yet return; } source->incomingDataHandler1(); } void AudioOpenSource::incomingDataHandler1() { fFrameSize = 0; AudioElem elem; int unHandleCnt = 0; CBuffer_t buffer; if (!usingQueue()->PopFront(buffer, unHandleCnt)) { // if for long time no data //m_NoDataCnt++; if(m_NoDataCnt > 500) { handleClosure(this); return; } nextTask() = envir().taskScheduler().scheduleDelayedTask(1500, (TaskFunc*)incomingDataHandler,this); } else { m_NoDataCnt = 0; if (buffer.lenght <= 0) { handleClosure(this); return; } fFrameSize = buffer.lenght; if (fFrameSize > fMaxSize) { memcpy(fTo, buffer.data, fMaxSize); } else { memcpy(fTo, buffer.data, fFrameSize); } #if 0 // Set the 'presentation time': if (fPresentationTime.tv_sec == 0 && fPresentationTime.tv_usec == 0) { // This is the first frame, so use the current time: getTickCount(&fPresentationTime, NULL); } else { // Increment by the play time of the previous frame: unsigned uSeconds = fPresentationTime.tv_usec + fInput.fuSecsPerFrame; fPresentationTime.tv_sec += uSeconds / 1000000; fPresentationTime.tv_usec = uSeconds % 1000000; } #else if (fPresentationTime.tv_sec == 0 && fPresentationTime.tv_usec == 0 && m_ref == 0) { m_ref = buffer.pts; } else { fPresentationTime.tv_sec = (buffer.pts-m_ref)/1000000; fPresentationTime.tv_usec = (buffer.pts-m_ref)%1000000; } #endif fDurationInMicroseconds = fInput.fuSecsPerFrame; LOGD_print("AudioOpenSource", "===========>>>>>>>>>>>>> fInput.fuSecsPerFrame:%d pts:%llu\n",fInput.fuSecsPerFrame, buffer.pts); //LOGD_print("AudioOpenSource", "Call incomingDataHandler1 fFrameSize:%d unHandleCnt:%d",fFrameSize,unHandleCnt); // Switch to another task, and inform the reader that he has data: nextTask() = envir().taskScheduler().scheduleDelayedTask(0, (TaskFunc*)FramedSource::afterGetting, this); } //*/ }
// https://oj.leetcode.com/problems/palindrome-number/ class Solution { public: bool isPalindrome(int x) { if (x < 0) { return false; } // In case of overflow long long base = 1; while (x / (base * 10) > 0) { base = base * 10; } for (long long i = base, j = 1; i >= j; i /= 10, j *= 10) { if ((x / i) % 10 != (x / j) % 10) { return false; } } return true; } };
/** @author Umaralikhon Kayumov @since 3.1 @version 7.7 */ /* Название отеля, Город, Количество звезд, Информация о общем количестве номеров для каждого класса Реализовать возможность сортировки массива объектов класса с применением перегрузки оператора сравнения на основе: - количества звезд Реализовать возможность вывода: а) списка отелей для указанного пользователем города; б) списка отелей, у которых для заданного пользователем класса номеров, свобод- ных мест больше Х (значение Х также указывает пользователь); в) списка отелей, у которых общее количество свободных мест больше Х для ука- занного пользователем города (значение Х также указывает пользователь). */ #include "Hotel.h" string city; string name; int star; int choice; int freeVip, freeSimple; int busyVip, busySimple; int menu(); void printData(); void fromFile(); int main() { setlocale(0, ""); int choice; cout << "Выберите дайствие" << endl; cout << "(1) - Ввести данные вручную" << endl; cout << "(2) - Получить данные из файла" << endl; cout << "(0) - Выход из программы" << endl; cout << ">>>"; cin >> choice; if (choice == 0) return 0; while (choice != 0) { //Запись вручную if (choice == 1) { printData(); } else if (choice == 2) { fromFile(); } else cout << "Введите корректные данные!" << endl; cout << "Выберите дайствие" << endl; cout << "(1) - Ввести данные вручную" << endl; cout << "(2) - Получить данные из файла" << endl; cout << "(0) - Выход из программы" << endl; cout << ">>>"; cin >> choice; } } //Функция для вывода меню int menu() { int choice; cout << "\n(1) - Сортировка по количеству звезд" << endl << "(2) - Выбор по количеству мест" << endl << "(3) - Выбор по городам" << endl << "(4) - Город и количество номеров" << endl << "(5) - Сортировка по возростанию" << endl << "(6) - Изменение данных" << endl << "(0) - Главное меню" << endl; cout << ">>>"; cin >> choice; cout << "____________________________________________________" << endl; return choice; } //Вывод вручную void printData() { int size; cout << "Введите кол-во гостиниц: "; cin >> size; cout << "____________________________________________________" << endl; Hotel* add = new Hotel[size]; //Создание массива объектов ofstream fout("Hotel.txt"); if (fout.is_open()) { for (int i = 0; i < size; i++) { cout << "City: "; cin >> city; cout << "Name: "; cin >> name; cout << "Stars: "; cin >> star; cout << "Кол-во свободных номеров: " << endl; cout << "Vip: "; cin >> freeVip; cout << "Simple: "; cin >> freeSimple; cout << "Кол-во занятых номеров: " << endl; cout << "Vip: "; cin >> busyVip; cout << "Simple: "; cin >> busySimple; cout << endl; fout << city << "\t" << name << "\t" << star << freeVip << freeSimple << busyVip << busySimple << endl; //Ввод в файлы add[i].setInfo(city, name, star, freeVip, freeSimple, busyVip, busySimple); //Инициализация объектов } cout << "Данные сохранены в файл!" << endl << endl; cout << "____________________________________________________" << endl; //Вывод данных cout << "City \t" << "Name \t" << "Stars \t" << "FS \t" << "FV \t" << "BS\t" << "BV" << endl; for (int i = 0; i < size; i++) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << "\t" << add[i].setFreeVip() << "\t" << add[i].setBusySimple() << "\t" << add[i].setBusyVip() << endl; } cout << "____________________________________________________" << endl; choice = menu(); //Вызов меню //Сортировка по кол-во звезд if (choice == 1) { Hotel temp; for (int i = 0; i < size; i++) { // i - номер прохода for (int j = i + 1; j < size - 1; j++) { //Внутренний цикл if (add[j + 1].setStar() >= add[j].setStar()) { temp = add[j]; add[j] = add[j + 1]; add[j + 1] = temp; } } } cout << "Сортировка по количеству звезд" << endl; for (int i = 0; i < size; i++) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << "\t" << add[i].setFreeVip() << "\t" << add[i].setBusySimple() << "\t" << add[i].setBusyVip() << endl; } cout << endl; cout << "____________________________________________________" << endl; } //Выбор по количеству свободных мест else if (choice == 2) { int num; int type; cout << "(1) - Vip" << endl; cout << "(2) - Simple" << endl; cout << ">>>"; cin >> type; cout << "\nВведите количество необходимых мест: "; cin >> num; cout << "____________________________________________________" << endl; if (type == 1) { cout << "City \t" << "Name \t" << "Stars \t" << "FV"; for (int i = 0; i < size; i++) { if (num < add[i].setFreeVip()) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeVip() << endl; } } cout << "____________________________________________________" << endl; } else if (type == 2) { cout << "City \t" << "Name \t" << "Stars \t" << "FS \t"; for (int i = 0; i < size; i++) { if (num < add[i].setFreeSimple()) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << endl; } } cout << "____________________________________________________" << endl; } else cout << "По вашему запросу ничего не найдено :-(" << endl; } //Выбор по городам else if (choice == 3) { string chooseCity; cout << "\nВведите город: "; cin >> chooseCity; cout << "City \t" << "Name \t" << "Stars \t" << "FS \t" << "FV \t" << "BS\t" << "BV" << endl; for (int i = 0; i < size; i++) { if (chooseCity == add[i].setCity()) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << "\t" << add[i].setFreeVip() << "\t" << add[i].setBusySimple() << "\t" << add[i].setBusyVip() << endl; } } cout << "____________________________________________________" << endl; cout << endl; } //Выбор по городам else if (choice == 4) { string chooseCity; int numOfPlace; cout << "\nВведите город: "; cin >> chooseCity; cout << "Введите кол - во мест: "; cin >> numOfPlace; cout << "City \t" << "Name \t" << "Stars \t" << "FS \t" << "FV \t" << "BS\t" << "BV" << endl; for (int i = 0; i < size; i++) { if (chooseCity == add[i].setCity()) { if (numOfPlace < (add[i].setFreeVip() + add[i].setFreeSimple())) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << "\t" << add[i].setFreeVip() << "\t" << add[i].setBusySimple() << "\t" << add[i].setBusyVip() << endl; } } } cout << "____________________________________________________" << endl; cout << endl; } else cout << "По вашему запросу ничего не найдено :-(" << endl; delete[] add; //Освобождение памяти } } //Получает данные из файла void fromFile() { //Чтение данных из файла int size; int number; bool flag = true; string fileName; cout << "Введите название файла: "; cin >> fileName; ifstream fin(fileName + ".txt"); cout << "\nЧтение из файла..." << endl; while (flag) { fin >> number; flag = false; } size = number; Hotel* add = new Hotel[size]; //Инициализация данных в объекты for (int i = 0; i < size; i++) { fin >> city >> name >> star >> freeSimple >> freeVip >> busySimple >> busyVip; add[i].setInfo(city, name, star, freeVip, freeSimple, busyVip, busySimple); } fin.close(); //Вывод данных cout << "City \t" << "Name \t" << "Stars \t" << "FS \t" << "FV \t" << "BS\t" << "BV" << endl; for (int i = 0; i < size; i++) { cout << add[i].setCity() << "\t"<<add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << "\t" << add[i].setFreeVip() << "\t" << add[i].setBusySimple() << "\t" << add[i].setBusyVip() << endl; } cout << "____________________________________________________" << endl; choice = menu(); //Вызов меню //Сортировка по кол-во звезд if (choice == 1) { Hotel temp; for (int i = 0; i < size; i++) { // i - номер прохода for (int j = i + 1; j < size - 1; j++) { //Внутренний цикл if (add[j + 1].setStar() > add[j].setStar()) { temp = add[j]; add[j] = add[j + 1]; add[j + 1] = temp; } } } cout << "Сортировка по количеству звезд" << endl; for (int i = 0; i < size; i++) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << "\t" << add[i].setFreeVip() << "\t" << add[i].setBusySimple() << "\t" << add[i].setBusyVip() << endl; } cout << endl; cout << "____________________________________________________" << endl; } //Сортировка по возростанию else if (choice == 5) { Hotel temp; for (int i = 1; i < size; i++) { // i - номер прохода for (int j = 0; j < size - 1; j++) { //Внутренний цикл if (add[j].setStar() > add[j+1].setStar()) { temp = add[j]; add[j] = add[j + 1]; add[j + 1] = temp; } } } cout << "Сортировка по количеству звезд" << endl; for (int i = 0; i < size; i++) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << "\t" << add[i].setFreeVip() << "\t" << add[i].setBusySimple() << "\t" << add[i].setBusyVip() << endl; } cout << endl; cout << "____________________________________________________" << endl; } //ИЗМЕНЕНИЕ ДАННЫХ else if (choice == 6) { string remake; cout << "Выберите данные для изменения: "; cin >> remake; for (int i = 0; i < size; i++) { if (remake == add[i].setCity()) { cout << "Изменение данных: "; cout << "City: "; cin >> city; cout << "Name: "; cin >> name; cout << "Stars: "; cin >> star; cout << "Кол-во свободных номеров: " << endl; cout << "Vip: "; cin >> freeVip; cout << "Simple: "; cin >> freeSimple; cout << "Кол-во занятых номеров: " << endl; cout << "Vip: "; cin >> busyVip; cout << "Simple: "; cin >> busySimple; cout << endl; add[i].setInfo(city, name, star, freeVip, freeSimple, busyVip, busySimple); //Инициализация объектов } } cout << "City \t" << "Name \t" << "Stars \t" << "FS \t" << "FV \t" << "BS\t" << "BV" << endl; for (int i = 0; i < size; i++) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << "\t" << add[i].setFreeVip() << "\t" << add[i].setBusySimple() << "\t" << add[i].setBusyVip() << endl; } cout << "____________________________________________________" << endl; } //Выбор по количеству свободных мест else if (choice == 2) { int num; int type; cout << "(1) - Vip" << endl; cout << "(2) - Simple" << endl; cout << ">>>"; cin >> type; cout << "\nВведите количество необходимых мест: "; cin >> num; cout << "____________________________________________________" << endl; if (type == 1) { cout << "City \t" << "Name \t" << "Stars \t" << "FV" << endl; for (int i = 0; i < size; i++) { if (num < add[i].setFreeVip()) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeVip() << endl; } } cout << "____________________________________________________" << endl; } else if (type == 2) { cout << "City \t" << "Name \t" << "Stars \t" << "FS \t" << endl; for (int i = 0; i < size; i++) { if (num < add[i].setFreeSimple()) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << endl; } } cout << "____________________________________________________" << endl; } else cout << "По вашему запросу ничего не найдено :-(" << endl; } //Выбор по городам else if (choice == 3) { string chooseCity; cout << "\nВведите город: "; cin >> chooseCity; cout << "City \t" << "Name \t" << "Stars \t" << "FS \t" << "FV \t" << "BS\t" << "BV" << endl; for (int i = 0; i < size; i++) { if (chooseCity == add[i].setCity()) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << "\t" << add[i].setFreeVip() << "\t" << add[i].setBusySimple() << "\t" << add[i].setBusyVip() << endl; } } cout << "____________________________________________________" << endl; cout << endl; } //Выбор по городам else if (choice == 4) { string chooseCity; int numOfPlace; cout << "\nВведите город: "; cin >> chooseCity; cout << "Введите кол - во мест: "; cin >> numOfPlace; cout << "City \t" << "Name \t" << "Stars \t" << "FS \t" << "FV \t" << "BS\t" << "BV" << endl; for (int i = 0; i < size; i++) { if (chooseCity == add[i].setCity()) { if (numOfPlace < (add[i].setFreeVip() + add[i].setFreeSimple())) { cout << add[i].setCity() << "\t" << add[i].setName() << "\t" << add[i].setStar() << "\t" << add[i].setFreeSimple() << "\t" << add[i].setFreeVip() << "\t" << add[i].setBusySimple() << "\t" << add[i].setBusyVip() << endl; } } } cout << "____________________________________________________" << endl; cout << endl; } else cout << "По вашему запросу ничего не найдено :-(" << endl; delete[] add; //Освобождение памяти }
#include <iostream> using namespace std; int main() { int time; float litr =2; double pow ,div ; float bottle=1.5; cout << "Enter : How long you stay at shower(in minutes)?" << endl; cin >> time ; if ( time<=40 ){ pow = time * litr; cout << "You spent "<<pow<<" litrs"<<endl; div = pow/bottle ; cout << " You spent water "<< div <<" in bottles"; } else { cout<<"You stay at shower very long"; } return 0; }
// // Created by aleksey on 18.04.2019. // #include "MyVisCommandSceneAddElectricField.h" #include "G4UIcmdWithAnInteger.hh" #include "G4VisManager.hh" #include "G4TransportationManager.hh" #include "G4RunManager.hh" #include "G4Run.hh" #include "G4PhysicalVolumeModel.hh" #include "G4ApplicationState.hh" #include "G4UImanager.hh" #include "G4UIcommand.hh" G4VisManager * MyVisCommandSceneAddElectricField::G4VVisCommand::fpVisManager; MyVisCommandSceneAddElectricField::MyVisCommandSceneAddElectricField() { fpCommand = new G4UIcommand ("/vis/scene/add/electricField", this); G4UIparameter* parameter; parameter = new G4UIparameter ("nDataPointsPerHalfScene", 'i', true); parameter -> SetDefaultValue (5); fpCommand -> SetParameter (parameter); } MyVisCommandSceneAddElectricField::~MyVisCommandSceneAddElectricField() { delete fpCommand; } G4String MyVisCommandSceneAddElectricField::GetCurrentValue(G4UIcommand *command) { return ""; } void MyVisCommandSceneAddElectricField::SetNewValue(G4UIcommand *command, G4String newValue) { fpVisManager = G4VisManager::GetInstance(); G4VisManager::Verbosity verbosity = fpVisManager->GetVerbosity(); G4bool warn(verbosity >= G4VisManager::warnings); G4Scene* pScene = fpVisManager->GetCurrentScene(); if (!pScene) { if (verbosity >= G4VisManager::errors) { G4cout << "ERROR: No current scene. Please create one." << G4endl; } return; } G4int nDataPointsPerHalfScene; std::istringstream iss(newValue); iss >> nDataPointsPerHalfScene; G4VModel* model = new MyElectricFieldModel(nDataPointsPerHalfScene, MyElectricFieldModel::fullArrow, 3); const G4String& currentSceneName = pScene -> GetName (); G4bool successful = pScene -> AddRunDurationModel (model, warn); if (successful) { if (verbosity >= G4VisManager::confirmations) { G4cout << "Electric field, if any, will be drawn in scene \"" << currentSceneName << "\"\n with " << nDataPointsPerHalfScene << " data points per half scene." << G4endl; } } else { if (verbosity >= G4VisManager::warnings) { G4cout << "WARNING: For some reason, possibly mentioned above, it has not been\n possible to add to the scene." << G4endl; } } CheckSceneAndNotifyHandlers (pScene); }
// Здесь будет представленна реализация класса "Участник" и всех необходимых методов. #include "Member.h" Member::Member() { } Member::Member(const char *nick, const char *sts) { } Member::~Member() { }
// // Created by arnito on 4/06/17. // #include "Quote1Actor.h" Quote1Actor::Quote1Actor(int player,Quote &q, Scene &s) : Actor(player, s){ _quote = &q; } Quote1Actor::~Quote1Actor(){ } void Quote1Actor::update(const sf::Time& deltatime) { } void Quote1Actor::action(Inputs::Key key){ if(key == Inputs::Key::LEFT){ _quote->_speed.x = 70; _quote->_facingState = Quote::LEFT; } else if(key == Inputs::Key::RIGHT){ _quote->_speed.x = 70; _quote->_facingState = Quote::RIGHT; } else if(key == Inputs::Key::DOWN){ _quote->_facingState = Quote::DOWN; } else if(key == Inputs::Key::UP){ _quote->_facingState = Quote::UP; } else if(key == Inputs::Key::JUMP){ if(_quote->_state==Quote::STANDING){ _quote->_speed.y = -200; _quote->_state = Quote::JUMPING; } else { _quote->_timerBoost = 250; _quote->_state = Quote::BOOSTING; } } }
//this is a code to multiply two given numbers #include<bits/stdc++.h> using namespace std; int main() { int i,j,mul; cout>>"Enter numbers to multiply: ">>endl; cin<<i<<j; mul=i*j; cout<<"Result: "<<mul<<endl; return 0; }
#include <stdio.h> void shell_sort(int arr[], int len) { int gap, i, j, k, g, temp; for(gap = len / 2; gap > 0; gap = gap / 2) { for(g = 0; g < gap; g++) for(i = gap + g; i < len; i = i + gap) { for(j = i - gap; j >= g; j = j - gap) { if(arr[j] < arr[i]) break; } temp = arr[i]; for(k = i - gap; k >= j + gap; k = k - gap) { arr[k + gap] = arr[k]; } arr[j + gap] = temp; } } } main() { int arr[10] = {5, 4, 3, 2, 1, 6, 7, 8, 9, 10}; shell_sort(arr, 10); for(int i=0; i < 10; i++) { printf("%d ", arr[i]); } getchar(); }
#pragma once #include "ARPG.h" #include "Enum/SkillRangeDirection.h" #include "SkillRangeInfo.generated.h" USTRUCT(BlueprintType) struct ARPG_API FSkillRangeInfo { GENERATED_USTRUCT_BODY() public: // Sphere Trace 사용 여부를 나타냅니다. UPROPERTY(EditAnywhere, BlueprintReadWrite) bool bUseSphereTrace; // 캐릭터가 기준이 되는 트레이싱 시작 위치 오프셋 UPROPERTY(EditAnywhere, BlueprintReadWrite) FVector TraceStartOffset; // 트레이싱 방향 UPROPERTY(EditAnywhere, BlueprintReadWrite) ESkillRangeDirection TraceDirection; // Sphere Trace 거리 UPROPERTY(EditAnywhere, BlueprintReadWrite) float TraceDistance; // Sphere Trace 구 반지름 UPROPERTY(EditAnywhere, BlueprintReadWrite) float TraceRadius; // 스킬 대미지 계산식을 나타냅니다. UPROPERTY(EditAnywhere, BlueprintReadWrite) FString DamageCalcFormula; // 여러 영역 생성 시 영역 생성 딜레이를 나타냅니다. UPROPERTY(EditAnywhere, BlueprintReadWrite) float CreateDelay; public: FSkillRangeInfo(); /// basedActor 를 기준으로 하는 TraceDirection 방향을 나타냅니다. FVector GetTraceDirection(AActor* basedActor); // 이 범위의 타격 횟수와, 대미지를 반환합니다. TTuple<int32, float> GetSkillCalcFormulaResult(); };
#include "qinput.h" namespace qEngine { /************************************ qInput::qInput ************************************* description: Constructor access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:21:10 creator: qDot *****************************************************************************************/ qInput::qInput(void) { } /************************************* qInput::init ************************************** description: Initialization function. Initializes all specified devices and moves the console to the internal pointer for the object. @hWnd[in]: A handle that references the current window. @spConsole[in]: A smart pointer to the console already started by the engine. @dwDevices[in]: A bitfield to decide which devices the class will initialize value: Returns true if all specified devices are initialized properly. access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:23:08 creator: qDot *****************************************************************************************/ bool qInput::init(HWND hWnd, boost::shared_ptr<qConsole> spConsole, boost::shared_ptr<qConfigManager> spCM, DWORD dwDevices) { m_spConsole = spConsole; m_spCM = spCM; getValuesFromConfigManager(); if(dwDevices == 0) { m_spConsole->setMessage(MSG_ERROR, "qInput", "init : No devices to initialize!"); return false; } if(FAILED(DirectInput8Create((HINSTANCE)GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDI, NULL))) { m_spConsole->setMessage(MSG_ERROR, "qInput", "init : Cannot Create DI8 interface"); return false; } m_hWnd = hWnd; m_spConsole->setMessage(MSG_INIT, "qInput", "init : DI8 Interface created"); if(dwDevices && Q_KEYBOARD == Q_KEYBOARD) { m_spConsole->setMessage(MSG_INIT, "qInput", "init : Creating Keyboard Interface"); if(!initKeyboard()) { m_spConsole->setMessage(MSG_ERROR, "qInput", "init : Cannot create keyboard interface"); return false; } m_spConsole->setMessage(MSG_INIT, "qInput", "init : Keyboard Initialized"); } if(dwDevices && Q_MOUSE == Q_MOUSE) { m_lMouseX = 0; m_lMouseY = 0; m_spConsole->setMessage(MSG_INIT, "qInput", "init : Creating Mouse Interface"); if(!initMouse()) { m_spConsole->setMessage(MSG_ERROR, "qInput", "init : Cannot create mouse interface"); return false; } m_spConsole->setMessage(MSG_INIT, "qInput", "init : Mouse Initialized"); } return true; } /******************************** qInput::updateDevices ********************************** description: Checks to make sure which devices have initialized, and reads the information from them. access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:27:32 creator: qDot *****************************************************************************************/ void qInput::updateDevices() { if(m_pDIKeyboard) { readKeyboard(); } if(m_pDIMouse) { readMouse(); } } /********************************* qInput::initKeyboard ********************************** description: Initializes the keyboard object. value: Returns true if the keyboard has been initialized properly, otherwise returns false. access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:28:05 creator: qDot *****************************************************************************************/ bool qInput::initKeyboard() { if (FAILED(m_pDI->CreateDevice(GUID_SysKeyboard, &m_pDIKeyboard, NULL))) { m_spConsole->setMessage(MSG_ERROR, "qInput", "initKeyboard : Keyboard device cannot be created."); return false; } if (FAILED(m_pDIKeyboard->SetDataFormat(&c_dfDIKeyboard))) { m_spConsole->setMessage(MSG_ERROR, "qInput", "initKeyboard : Keyboard data format cannot be set."); return false; } if (FAILED(m_pDIKeyboard->SetCooperativeLevel(m_hWnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE))) { m_spConsole->setMessage(MSG_ERROR, "qInput", "initKeyboard : Keyboard device coop level cannot be set."); return false; } if (FAILED(m_pDIKeyboard->Acquire())) { m_spConsole->setMessage(MSG_ERROR, "qInput", "initKeyboard : Keyboard device cannot be acquired."); return false; } return true; } /********************************* qInput::readKeyboard ********************************** description: Reads the current keyboard state. value: Returns true if keyboard has been read successfully, otherwise returns false (in case of lost device). access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:24:08 creator: qDot *****************************************************************************************/ bool qInput::readKeyboard() { if (FAILED(m_pDIKeyboard->GetDeviceState(sizeof(UCHAR[256]), (LPVOID)m_pKeyState))) { return false; } return true; } /*********************************** qInput::keyDown ************************************* description: Returns true if the key requested is currently in a "down" state. @key[in]: DIK constant pertaining to the key needed. value: Returns true if the key requested is down. access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:25:24 creator: qDot *****************************************************************************************/ bool qInput::keyDown(DWORD key) { return ((m_pKeyState[key] & 0x80) ? true : false); } /********************************** qInput::initMouse ************************************ description: Initializes the Mouse Device value: Returns true if the mouse is successfully initialized. access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:26:23 creator: qDot *****************************************************************************************/ bool qInput::initMouse() { if (FAILED(m_pDI->CreateDevice(GUID_SysMouse, &m_pDIMouse, NULL))) { m_spConsole->setMessage(MSG_ERROR, "qInput", "initMouse : Mouse device cannot be created."); return false; } if (FAILED(m_pDIMouse->SetCooperativeLevel(m_hWnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE))) { m_spConsole->setMessage(MSG_ERROR, "qInput", "initMouse : Mouse device coop level cannot be set."); return false; } if (FAILED(m_pDIMouse->SetDataFormat(&c_dfDIMouse))) { m_spConsole->setMessage(MSG_ERROR, "qInput", "initMouse : Data format cannot be set."); return false; } if (FAILED(m_pDIMouse->Acquire())) { m_spConsole->setMessage(MSG_ERROR, "qInput", "initMouse : Mouse device cannot be aquired."); return false; } return true; } /********************************** qInput::readMouse ************************************ description: Reads the current state of the mouse, and updates the buffered input variables. value: Returns true if the device is read successfully, otherwise returns false (possibly from lost device). access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:28:58 creator: qDot *****************************************************************************************/ bool qInput::readMouse() { if(FAILED(m_pDIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &m_DIMouseState))) { m_spConsole->setMessage(MSG_ERROR, "qInput", "readMouse : Cannot read mouse device."); return false; } m_lMouseX += m_DIMouseState.lX; m_lMouseY += m_DIMouseState.lY; if(m_lMouseX < 0) m_lMouseX = 0; if (m_lMouseY < 0) m_lMouseY = 0; if (m_lMouseX > m_iWindowWidth) m_lMouseX = (long)m_iWindowWidth; if (m_lMouseY > m_iWindowHeight) m_lMouseY = (long)m_iWindowHeight; return true; } /******************************** qInput::mousePosition ********************************** description: Returns the mouse position into two pointers passed to it. @lX[in]: Pointer to a long variable to store the x coord to. @lY[in]: Pointer to a long variable to store the y coord to. access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:29:42 creator: qDot *****************************************************************************************/ void qInput::getMousePosition(long* lX, long* lY) { *lX = m_lMouseX; *lY = m_lMouseY; } /******************************* qInput::mouseButtonDown ********************************* description: Checks the state of mouse buttons. @iButton[in]: Number of the button to check. 0 - Left 1 - Right value: Returns true if the button requested is down, otherwise returns false. access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:30:52 creator: qDot *****************************************************************************************/ bool qInput::getMouseButtonDown(int iButton) { return (m_DIMouseState.rgbButtons[iButton] & 0x80) ? true : false; } /*********************************** qInput::shutdown ************************************ description: Releases all COM objects that have been initialized. access: public ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:31:10 creator: qDot *****************************************************************************************/ void qInput::shutdown() { if(m_pDIKeyboard) { m_pDIKeyboard->Unacquire(); m_pDIKeyboard->Release(); } if(m_pDIMouse) { m_pDIMouse->Unacquire(); m_pDIMouse->Release(); } if(m_pDI) { m_pDI->Release(); } m_spConsole->setMessage(MSG_SHUTDOWN, "qInput", "Shutdown() : DI8 Shutdown successful"); m_spConsole.reset(); } /*********************************** qInput::~qInput ************************************* description: Destructor. Calls the shutdown function. access: public, state: virtual ------------------------------------------------------------------------------------------ created: 30.10.02 - 17:32:51 creator: qDot *****************************************************************************************/ qInput::~qInput(void) { shutdown(); } void qInput::getValuesFromConfigManager() { //Values to get from Console: //WindowWidth - Window Width //WindowHeight - Window Height m_iWindowWidth = boost::lexical_cast<int>(m_spCM->getValue("WindowWidth")); m_iWindowHeight = boost::lexical_cast<int>(m_spCM->getValue("WindowHeight")); } }
#include <bits/stdc++.h> using namespace std; bool hassh[100]; int countt = 0; int main() { char str1[100],str2[100]; scanf("%s%s",str1,str2); for(int i =0;i < strlen(str1);i++) { hassh[str1[i]%26] = 1; } for(int i = 0; i < strlen(str2);i++) { if(hassh[str2[i]%26] == 0) countt += 1; } if(countt > 2) { printf("Cant"); } else printf("can"); cout<<endl; for(int i = 0; i < 26; i++) if(hassh[i] == 0) printf("%c",i+65); }
#include<iostream> using namespace std; int main() { // referance variable string food = "chapathi"; string &tiffen = food; cout << food << endl; cout << tiffen << endl; // get memory address cout << &food << endl ; cout << &tiffen << endl; return 0; }
#ifndef __REQUEST_HANDLER_ECHO_H_DEFINED__ #define __REQUEST_HANDLER_ECHO_H_DEFINED__ #include <communicating_tcp_socket.hpp> #include <generic_handler.hpp> namespace request_handler { class echo_handler : public generic_handler { public: virtual void handle(server::net::communicating_tcp_socket socket); }; } #endif
// // Iterator.hpp // Sorted_Doubly_Linked_List // // Created by 세광 on 2021/08/12. // #ifndef Iterator_hpp #define Iterator_hpp #include "DoublyLinkedList.hpp" class Iterator { public: Iterator(const DoublyLinkedList &dlist); ~Iterator(); DoublyLinkedList GetdList() const; NodeType* GetpCurPointer() const; void SetpCurPointer(NodeType* pCurPointer); bool NotNull(); bool NextNotNull(); bool PrevNotNull(); ItemType First(); ItemType Next(); ItemType Prev(); NodeType GetCurrentNode(); private: const DoublyLinkedList &dList; NodeType *pCurPointer; }; #endif /* Iterator_hpp */
#include<bits/stdc++.h> using namespace std; int main() { // only gravity will pull me down // Minimum Operations int t, n; cin >> t; while (t--) { cin >> n; int dp[n+1]; dp[1]=1; dp[2]=2; for(int i=3; i<=n; i++) { if(i%2) dp[i] = min(dp[(i-1)/2]+2, dp[i-1]+1); else dp[i] = min(dp[i/2]+1, dp[i-1]+1); } cout << dp[n] << endl; } return 0; }
#include <iostream> using namespace std; int main() { int p = 1; for (int x = 1; x <= 4; x++) { for (int y = 1; y <= x; y++) { cout << p << " "; p++; } cout << endl; } return 0; }
#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 edge { int to; int cost; }; vector<int> dijkstra(int start, vector<vector<edge>> G){ const int INF = 1e9; vector<int> dist((int)G.size(), INF); dist[start] = 0; using P = pair<int, int>; priority_queue<P, vector<P>, greater<P>> que; que.push(P(dist[start], start)); while(!que.empty()){ P p = que.top(); que.pop(); int v = p.second; if(dist[v] < p.first) continue; for(auto e : G[v]){ auto [to, cost] = e; if(chmin(dist[to], dist[v]+cost)) que.push(P(dist[to], to)); } } return dist; } int main(){ int n, m; cin >> n >> m; const int INF = 1e9; vector<int> selfLoop_d(n, INF); vector<vector<edge>> G(n), U(n); rep(i, m){ int a, b, c; cin >> a >> b >> c; a--; b--; if(a == b) chmin(selfLoop_d[a], c); else{ G[a].push_back(edge{b, c}); U[b].push_back(edge{a, c}); } } rep(start, n){ auto dist_g = dijkstra(start, G); auto dist_u = dijkstra(start, U); int ans = INF; rep(i, n){ if(i == start){ if(selfLoop_d[i] == INF) continue; else chmin(ans, selfLoop_d[i]); } else chmin(ans, dist_g[i]+dist_u[i]); } if(ans == INF) cout << -1 << endl; else cout << ans << endl; } }
#include<bits/stdc++.h> using namespace std; int n, a[1000][1000], b[1000][1000]; void input(){ cin >> n; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cin >> a[i][j]; } } } bool MTDX(){ for(int i = 0; i < n-1; i++){ for (int j = i+1; j < n; j++) { if(a[i][j] != a[j][i]) return false; } } return true; } void xoaDX(){ for(int i = 0; i < n; i++){ for(int j = 0; j <= i; j++){ cout << a[i][j] << " "; } cout << '\n'; } } void taoDX(){ for(int i = 0; i < n-1; i++){ for (int j = i+1; j < n; j++) { a[i][j] = a[j][i]; } } for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cout << a[i][j] << " "; } cout << '\n'; } } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); freopen("MTDX.inp", "r", stdin); freopen("MTDX.out", "w", stdout); input(); if(MTDX()){ cout << "YES \n"; xoaDX(); } else{ cout << "NO \n"; taoDX(); } return 0; }
#include <iostream> #include <string.h> #include <vector> #include <algorithm> using namespace std; // -1은 아직 답이 계산되지 않았음을 의미한다. // 1은 해당 입력들이 서로 대응됨을 의미한다. // 0은 해당 입력들이 서로 대응되지 않음을 의미한다. int cache[101][101]; // 패턴과 문자열 string W, S; // 와일드카드 패턴 W[w..]가 문자열 S[s..]에 대응되는지 여부를 반환한다. bool matchMemoized(int w, int s){ // 메모이제이션 int& ret = cache[w][s]; if(ret != -1) return ret; // W[w]와 S[s]를 맞춰나간다. if(w < W.size() && s < S.size() && (W[w] == '?' || W[w] == S[s])){ return ret = matchMemoized(w+1, s+1); } // 패턴 끝에 도달해서 끝난 경우: 문자열도 끝났어야 참 if(w == W.size()) return ret = (s == S.size()); // *를 만나서 끝난 경우: *에 몇글자를 대응해야 할 지 재귀호출하면서 확인 if(W[w] == '*'){ if(matchMemoized(w+1, s) || (s < S.size() && matchMemoized(w, s+1))){ return ret = 1; } } // 이외의 경우는 모두 대응되지 않음 return ret = 0; } int main(){ int numTest, numFiles; bool result; vector<string> resultNames; cin >> numTest; while(numTest--){ cin >> W; cin >> numFiles; while (numFiles--) { cin >> S; memset(cache, -1, sizeof(cache)); result = matchMemoized(0, 0); if (result) { resultNames.push_back(S); //cout << S << endl; } } sort(resultNames.begin(), resultNames.end()); for(int i = 0; i< resultNames.size(); i++){ cout << resultNames[i] << endl; } resultNames.clear(); } return 0; }
// Created on: 2016-07-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 _BRepMesh_MeshAlgoFactory_HeaderFile #define _BRepMesh_MeshAlgoFactory_HeaderFile #include <Standard_Transient.hxx> #include <IMeshTools_MeshAlgoFactory.hxx> //! Default implementation of IMeshTools_MeshAlgoFactory providing algorithms //! of different complexity depending on type of target surface. class BRepMesh_MeshAlgoFactory : public IMeshTools_MeshAlgoFactory { public: //! Constructor. Standard_EXPORT BRepMesh_MeshAlgoFactory(); //! Destructor. Standard_EXPORT virtual ~BRepMesh_MeshAlgoFactory(); //! Creates instance of meshing algorithm for the given type of surface. Standard_EXPORT virtual Handle(IMeshTools_MeshAlgo) GetAlgo( const GeomAbs_SurfaceType theSurfaceType, const IMeshTools_Parameters& theParameters) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(BRepMesh_MeshAlgoFactory, IMeshTools_MeshAlgoFactory) }; #endif
#include <iostream> #include <cstdio> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <vector> #include <set> #include <time.h> #include <sstream> #include <fstream> typedef unsigned int uint; using namespace std; struct Edge { uint v; unsigned long long w; Edge(uint _v = 0, unsigned long long _w = 0) : v(_v), w(_w){}; }; vector<vector<Edge>> e; vector<vector<Edge>> re; vector<uint> sstack; vector<vector<uint>> cycles; unordered_map<uint, uint> vtn; vector<uint> vs; vector<uint> vss; vector<bool> vis; vector<vector<uint>> ordered; // vector<unordered_map<uint, vector<uint>>> p2; vector<unordered_map<uint, vector<vector<uint>>>> p3; vector<vector<uint>> eempty; vector<unsigned long long> wstack; uint cnt = 0; uint cnt1 = 0; void addEdge(uint u, uint v, unsigned long long w, uint i) { if (i >= e.size()) { e.resize(i); re.resize(i); } e[u].push_back(Edge(v, w)); re[v].push_back(Edge(u, w)); return; } // void construct1() // { // p2.resize(e.size()); // for (int i = 0; i < e.size(); i++) // { // vector<Edge> t1 = e[i]; // for (int k = 0; k < t1.size(); k++) // { // vector<Edge> t2 = e[t1[k].v]; // for (int j = 0; j < t2.size(); j++) // { // if (t2[j].v != i) // { // // vector<uint> ttmp; // // if(p2[t2[j].v].count(i)) // // { // // p2[t2[j].v].at(i).emplace_back(t1[k].v); // // } // // else // // { // // ttmp.emplace_back(t1[k].v); // // p2[t2[j].v].insert(pair < uint, vector<uint>>(i, ttmp)); // // } // p2[t2[j].v][i].emplace_back(t1[k].v); // } // } // } // } // for (int i = 0; i < p2.size(); i++) // { // for (auto j : p2[i]) // { // if (j.second.size() > 1) // { // sort(j.second.begin(), j.second.end()); // } // } // } // } void construct2() { p3.resize(e.size()); for (int i = 0; i < e.size(); i++) { vector<Edge> t1 = e[i]; for (int k = 0; k < t1.size(); k++) { vector<Edge> t2 = e[t1[k].v]; for (int j = 0; j < t2.size(); j++) { if (t2[j].v != i) { int n = p3[t2[j].v][i].size(); p3[t2[j].v][i].resize(n+1); p3[t2[j].v][i][n].emplace_back(t1[k].v); } vector<Edge> t3=e[t2[j].v]; for(int q=0;q<t3.size();q++) { if(t3[q].v!=i&&t1[k].v!=t2[j].v) { int n = p3[t3[q].v][i].size(); p3[t3[q].v][i].resize(n+1); p3[t3[q].v][i][n].emplace_back(t1[k].v); p3[t3[q].v][i][n].emplace_back(t2[j].v); } vector<Edge> t4=e[t3[q].v]; for(int w=0;w<t4.size();w++) { if(t4[w].v!=i&&t1[k].v!=t2[j].v&&t2[j].v!=t3[q].v&&t3[q].v!=t1[k].v) { int n = p3[t4[w].v][i].size(); p3[t4[w].v][i].resize(n+1); p3[t4[w].v][i][n].emplace_back(t1[k].v); p3[t4[w].v][i][n].emplace_back(t2[j].v); p3[t4[w].v][i][n].emplace_back(t3[q].v); } } } } } } } void construct3() { p3.resize(e.size()); for (int i = 0; i < e.size(); i++) { vector<Edge> t1 = e[i]; for (int k = 0; k < t1.size(); k++) { vector<Edge> t2 = e[t1[k].v]; for (int j = 0; j < t2.size(); j++) { vector<Edge> t3=e[t2[j].v]; if(t2[j].w==0||t1[k].w==0) continue; if((float)t2[j].w/t1[k].w<0.2||(float)t2[j].w/t1[k].w>3) continue; for(int q=0;q<t3.size();q++) { if(t2[j].w==0||t3[q].w==0) continue; if((float)t3[q].w/t2[j].w<0.2||(float)t3[q].w/t2[j].w>3) continue; vector<Edge> t4=e[t3[q].v]; for(int w=0;w<t4.size();w++) { if(t4[w].w==0||t3[q].w==0) continue; if((float)t4[w].w/t3[q].w<0.2||(float)t4[w].w/t3[q].w>3) continue; if(t4[w].v!=i&&t1[k].v!=t2[j].v&&t2[j].v!=t3[q].v&&t3[q].v!=t1[k].v&&t1[k].v>t4[w].v&&t2[j].v>t4[w].v&&t3[q].v>t4[w].v) { if (!p3[t4[w].v].count(i)) { p3[t4[w].v].insert(pair<uint, vector<vector<uint>>>(i, eempty)); } int n = p3[t4[w].v][i].size(); p3[t4[w].v][i].resize(n+1); p3[t4[w].v][i][n].emplace_back(t1[k].v); p3[t4[w].v][i][n].emplace_back(t2[j].v); p3[t4[w].v][i][n].emplace_back(t3[q].v); p3[t4[w].v][i][n].emplace_back(e[i][k].w); p3[t4[w].v][i][n].emplace_back(t4[w].w); } } } } } } } void construct4(uint a,uint b) { vector<Edge> t1 = e[b]; for (int k = 0; k < t1.size(); k++) { vector<Edge> t2 = e[t1[k].v]; for (int j = 0; j < t2.size(); j++) { vector<Edge> t3=e[t2[j].v]; if(t2[j].w==0||t1[k].w==0) continue; if((float)t2[j].w/t1[k].w<0.2||(float)t2[j].w/t1[k].w>3) continue; for(int q=0;q<t3.size();q++) { if(t2[j].w==0||t3[q].w==0) continue; if((float)t3[q].w/t2[j].w<0.2||(float)t3[q].w/t2[j].w>3) continue; vector<Edge> t4=e[t3[q].v]; for(int w=0;w<t4.size();w++) { if(t4[w].w==0||t3[q].w==0) continue; if((float)t4[w].w/t3[q].w<0.2||(float)t4[w].w/t3[q].w>3) continue; if(t4[w].v!=b&&t4[w].v==a&&t1[k].v!=t2[j].v&&t2[j].v!=t3[q].v&&t3[q].v!=t1[k].v&&t1[k].v>t4[w].v&&t2[j].v>t4[w].v&&t3[q].v>t4[w].v) { if (!p3[t4[w].v].count(b)) { p3[t4[w].v].insert(pair<uint, vector<vector<uint>>>(b, eempty)); } int n = p3[t4[w].v][b].size(); p3[t4[w].v][b].resize(n+1); p3[t4[w].v][b][n].emplace_back(t1[k].v); p3[t4[w].v][b][n].emplace_back(t2[j].v); p3[t4[w].v][b][n].emplace_back(t3[q].v); p3[t4[w].v][b][n].emplace_back(e[b][k].w); p3[t4[w].v][b][n].emplace_back(t4[w].w); } } } } } } void construct5(uint v,unordered_map<uint,vector<uint>> &layer2,unordered_set<uint> &layer3) { uint t1,t2; for(int i=0;i<re[v].size();i++) { if(re[v][i].v>v) { t1=re[v][i].v; for(int j=0;j<re[t1].size();j++) { if(re[t1][j].v>v) { t2=re[t1][j].v; if(layer2.count(t2)) { layer2[t2].push_back(t1); } else { layer2[t2]=vector<uint>{t1}; } for(int k=0;k<re[t2].size();k++) { if(re[t2][k].v>v) { layer3.insert(re[t2][k].v); } } } } } } } bool check(int mode,int a=0,int b=0) { wstack.clear(); if(mode==0) { for(int i=0;i<sstack.size();i++) { for(int j=0;j<e[sstack[i]].size();j++) { if(e[sstack[i]][j].v==sstack[(i+1)%sstack.size()]) { if(e[sstack[i]][j].w==0) return false; wstack.emplace_back(e[sstack[i]][j].w); break; } } } for(int i=0;i<wstack.size();i++) { if((float)wstack[(i+1)%wstack.size()]/wstack[i]>=0.2&&(float)wstack[(i+1)%wstack.size()]/wstack[i]<=3) continue; else return false; } } else if(mode==1) { for(int i=0;i<sstack.size()-1;i++) { for(int j=0;j<e[sstack[i]].size();j++) { if(e[sstack[i]][j].v==sstack[i+1]) { if(e[sstack[i]][j].w==0) return false; wstack.emplace_back(e[sstack[i]][j].w); break; } } } wstack.emplace_back(a); int u=wstack.size(); wstack.emplace_back(b); int q=wstack.size(); for(int i=0;i<u-1;i++) { if((float)wstack[i+1]/wstack[i]>=0.2&&(float)wstack[i+1]/wstack[i]<=3) continue; else return false; } if((float)wstack[0]/wstack[q-1]<0.2||(float)wstack[0]/wstack[q-1]>3) return false; } return true; } void dfs3(uint v,uint s) { vis[v] = 1; sstack.emplace_back(v); for (int i = 0; i < e[v].size(); i++) { if(sstack.size()==3||sstack.size()==4) { if (e[v][i].v == s&&check(0)) { cycles.resize(cycles.size() + 1); for (int j = 0; j < sstack.size(); j++) { cycles[cnt].emplace_back(sstack[j]); } cnt++; } } if(sstack.size()<4&&e[v][i].v>s&&vis[e[v][i].v]==0) dfs3(e[v][i].v, s); } if(sstack.size()>=2) { vector<vector<uint>> kk; bool flag=0; int ww=0; // if(sstack.size()==2) ww=first_w; // else // { // int n=sstack.size(); // for(int p=0;p<e[sstack[n-2]].size();p++) // { // if(e[sstack[n - 2]][p].v==sstack[n-1]) {ww=e[sstack[n - 2]][p].w; break; } // } // } if(p3[s].count(v)) kk = p3[s][v]; else kk.resize(0); for(int j=0;j<kk.size();j++) { if(sstack.size()<=4&&vis[kk[j][1]]==0&&vis[kk[j][0]]==0&&vis[kk[j][2]]==0&&check(1,kk[j][3],kk[j][4]))//&&(float)kk[j][3]/ww>=0.2&&(float)kk[j][3]/ww<=3&&(float)first_w/kk[j][4]>=0.2&&(float)first_w/kk[j][4]<=3) { cycles.resize(cycles.size() + 1); for (int k = 0; k < sstack.size(); k++) { cycles[cnt].emplace_back(sstack[k]); } cycles[cnt].emplace_back(kk[j][0]); cycles[cnt].emplace_back(kk[j][1]); cycles[cnt].emplace_back(kk[j][2]); // cout<<cycles[cnt].size()<<endl; cnt++; cnt1++; flag=1; } } } // cout<<"herhe"<<endl; vis[v] = 0; sstack.pop_back(); return; } void dfs4(uint v,uint s) { vis[v] = 1; sstack.emplace_back(v); for (int i = 0; i < e[v].size(); i++) { if(sstack.size()==3||sstack.size()==4) { if (e[v][i].v == s&&check(0)) { cycles.resize(cycles.size() + 1); for (int j = 0; j < sstack.size(); j++) { cycles[cnt].emplace_back(sstack[j]); } cnt++; } } if(sstack.size()<4&&e[v][i].v>s&&vis[e[v][i].v]==0) dfs4(e[v][i].v, s); } if(sstack.size()>=2) { vector<vector<uint>> kk; bool flag=0; if(!p3[s].count(v)) construct4(s,v); if(p3[s].count(v)) kk = p3[s][v]; else kk.resize(0); for(int j=0;j<kk.size();j++) { if(sstack.size()<=4&&vis[kk[j][1]]==0&&vis[kk[j][0]]==0&&vis[kk[j][2]]==0&&check(1,kk[j][3],kk[j][4]))//&&(float)kk[j][3]/ww>=0.2&&(float)kk[j][3]/ww<=3&&(float)first_w/kk[j][4]>=0.2&&(float)first_w/kk[j][4]<=3) { cycles.resize(cycles.size() + 1); for (int k = 0; k < sstack.size(); k++) { cycles[cnt].emplace_back(sstack[k]); } cycles[cnt].emplace_back(kk[j][0]); cycles[cnt].emplace_back(kk[j][1]); cycles[cnt].emplace_back(kk[j][2]); // cout<<cycles[cnt].size()<<endl; cnt++; cnt1++; flag=1; } } } // cout<<"herhe"<<endl; vis[v] = 0; sstack.pop_back(); return; } void dfs5(uint v,uint s,unordered_map<uint,vector<uint>> &layer2,unordered_set<uint> &layer3) { vis[v] = 1; sstack.emplace_back(v); int vv; vector<uint> kk; for(int i=0;i<e[v].size();i++) { if(e[v][i].v>s) { vv=e[v][i].v; if(vis[vv]) continue; if(layer2.count(vv)) { sstack.emplace_back(vv); kk=layer2[vv]; for(int j=0;j<kk.size();j++) { vv=kk[j]; if(vis[vv]) continue; sstack.emplace_back(vv); if(check(0)) { cycles.resize(cycles.size() + 1); cycles[cnt] = sstack; cnt++; } sstack.pop_back(); } sstack.pop_back(); } vv=e[v][i].v; if(sstack.size()<5||(sstack.size()==5&&layer3.find(vv)!=layer3.end())) { dfs5(vv,s,layer2,layer3); } } } vis[v] = 0; sstack.pop_back(); return; } void findc(int start,int end) { unordered_map<uint,vector<uint>> layer2; unordered_set<uint> layer3; for(int i=start;i<end;i++) { layer2.clear(); layer3.clear(); construct5(i,layer2,layer3); dfs5(i,i,layer2,layer3); } } int main() { FILE *fp1=fopen("test_data.txt","r"); FILE *fp2=fopen("result.txt","wb"); char douhao=','; char huanhang='\n'; int id; char buf[1024]; string str1; //freopen("test_data.txt", "r", stdin); //freopen("result11.txt", "w", stdout); uint u, v; double w; unsigned long long www; clock_t t = clock(); uint num = 0; vector<unsigned long long> ws; while (fscanf(fp1,"%d,%d,%lf", &u, &v, &w) != EOF) { vs.emplace_back(u); vs.emplace_back(v); // ws.emplace_back((unsigned long long)w*100); www=w; w-=www; www=www*100+100*w; ws.emplace_back(www); // cout<<www<<endl; } vss = vs; sort(vs.begin(), vs.end()); set<uint> se(vs.begin(), vs.end()); vs.assign(se.begin(), se.end()); set<uint>().swap(se); for (int i = 0; i < vs.size(); i++) { vtn.insert(pair<uint, uint>(vs[i], i)); } int k=0; for (int i = 0; i < vss.size(); i = i + 2) { addEdge(vtn.at(vss[i]), vtn.at(vss[i + 1]), ws[k], max(vtn.at(vss[i]), vtn.at(vss[i + 1])) + 2); k++; } // cout<<k<<","<<ws.size()<<endl; vector<uint>().swap(vss); num = e.size() + 2; vis.resize(num); // vector<uint> tmpp; // int sub_num = submap.size(); // int cc = 0; // clock_t t2 = clock(); // construct3(); // // cout<<vtn.at(427)<< " " <<vtn.at(441)<<endl; // while (cc < sub_num) // { // int C = 0; // while (C < submap[cc].size()) // { // vector<uint>().swap(sstack); // dfs3(submap[cc][C], submap[cc][C]); // C++; // // cout << cnt << "," << cnt1 << "," << cnt2 << "," << (clock() - t2) * 1000 / CLOCKS_PER_SEC << "ms" << endl; // } // cc++; // } // p3.resize(e.size()); // cout<<vtn.at(6053); findc(0,e.size()-1); // id=sprintf(buf,"%d",cnt); // fwrite(buf,id,sizeof(char),fp2); // fwrite(&huanhang,sizeof(huanhang),1,fp2); fprintf(fp2,"%d\n",cnt); int ans = 0; int limites[] = {3, 4, 5, 6, 7,8}; ordered.resize(cycles.size()); for (int i = 0; i < cycles.size(); i++) { for (int j = 0; j < cycles[i].size(); j++) { ordered[i].push_back(vs[cycles[i][j]]); } } sort(ordered.begin(), ordered.end()); for (int k = 0; k < 6; k++) { for (int i = 0; i < ordered.size(); i++) { if (ordered[i].size() == limites[k]) { for (int j = 0; j < ordered[i].size(); j++) { if (j == ordered[i].size() - 1) { //fwrite(&ordered[i][j],sizeof(ordered[i][j]),1,fp2); // printf("%d,", ordered[i][j]); id=sprintf(buf,"%d",ordered[i][j]); fwrite(buf,id,sizeof(char),fp2); // fprintf(fp2,"%u",ordered[i][j]); } else { //fwrite(&ordered[i][j],sizeof(ordered[i][j]),1,fp2); //printf("%d", ordered[i][j]); id=sprintf(buf,"%d",ordered[i][j]); fwrite(buf,id,sizeof(char),fp2); fwrite(&douhao,sizeof(douhao),1,fp2); // fprintf(fp2,"%u,",ordered[i][j]); } } // fprintf(fp2,"\n"); //printf("\n"); fwrite(&huanhang,sizeof(huanhang),1,fp2); } } } clock_t t1 = clock(); int secondd= (t1 - t) * 1000 / CLOCKS_PER_SEC ; //id=sprintf(buf,"%d",secondd); // fwrite(buf,id,sizeof(char),fp2); // fprintf(fp2,"%dms",secondd); fclose(fp2); return 0; }
/* ** EPITECH PROJECT, 2019 ** tek3 ** File description: ** TcpServer */ #ifndef TCPSERVER_H #define TCPSERVER_H #include <QObject> #include <QTcpSocket> #include <QTcpServer> #include <QDebug> namespace babel { class Core; namespace network { class TcpServer : public QObject { Q_OBJECT public: explicit TcpServer(babel::Core *parent = 0); signals: public slots: QTcpSocket *getNewConnection(); public: void startListening(); void stopListening(); private: QTcpServer *_server; }; } } #endif // MYTCPSERVER_H
#include <Poco/Exception.h> #include <Poco/Logger.h> #include "di/Injectable.h" #include "util/CryptoConfig.h" #include "util/CryptoParams.h" BEEEON_OBJECT_BEGIN(BeeeOn, CryptoConfig) BEEEON_OBJECT_PROPERTY("algorithm", &CryptoConfig::setAlgorithm) BEEEON_OBJECT_PROPERTY("passphrase", &CryptoConfig::setPassphrase) BEEEON_OBJECT_PROPERTY("interationCount", &CryptoConfig::setIterationCount) BEEEON_OBJECT_END(BeeeOn, CryptoConfig) using namespace std; using namespace Poco; using namespace Poco::Crypto; using namespace BeeeOn; const std::string CryptoConfig::DEFAULT_ALGORITHM = "aes256"; CryptoConfig::CryptoConfig(): m_algorithm(DEFAULT_ALGORITHM), m_iterationCount(CipherKey::DEFAULT_ITERATION_COUNT) { } void CryptoConfig::setAlgorithm(const string &name) { m_algorithm = name; } void CryptoConfig::setPassphrase(const string &passphrase) { m_passphrase = passphrase; } void CryptoConfig::setIterationCount(const int count) { if (count < 0) throw InvalidArgumentException("iteration count must be non-negative"); if (count < CipherKey::DEFAULT_ITERATION_COUNT) { logger().critical( "iteration count " + to_string(count) + " is too low for enough security", __FILE__, __LINE__ ); } m_iterationCount = count; } /** * The number of iterations does not have to match because * it is a parameter of crypted data that we are (very probably) * going to decrypt after this call. */ CipherKey CryptoConfig::createKey(const CryptoParams &params) const { if (params.algorithm() != m_algorithm) { throw InvalidArgumentException( "inappropriate algorithm " + params.algorithm() + ", required " + m_algorithm ); } return params.createKey(m_passphrase); } CryptoParams CryptoConfig::deriveParams(const string &salt) const { CryptoParams params = CryptoParams::create(m_algorithm); params.setIterationCount(m_iterationCount); params.setSalt(salt.empty()? CryptoParams::randomString(32) : salt); return params; }
//------------------------------------------------------------------------------------------------- // // llreplace 9/16/2016 Dennis Lang // // Regular expression file text replacement tool // //------------------------------------------------------------------------------------------------- // // Author: Dennis Lang - 2016 // http://landenlabs.com/ // // This file is part of llreplace project. // // ----- License ---- // // Copyright (c) 2016 Dennis Lang // // 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. // 4291 - No matching operator delete found #pragma warning( disable : 4291 ) #include <stdio.h> #include <ctype.h> #include <fstream> #include <iostream> #include <iomanip> #include <stdlib.h> // stroul #include "ll_stdhdr.h" #include "directory.h" #include "split.h" #include "filters.h" #include "colors.h" #include <vector> #include <map> #include <algorithm> #include <regex> #include <exception> using namespace std; // Helper types typedef std::vector<lstring> StringList; typedef std::vector<std::regex> PatternList; typedef unsigned int uint; // Runtime options std::regex fromPat; lstring toPat; lstring backupDir; PatternList includeFilePatList; PatternList excludeFilePatList; StringList fileDirList; lstring outFile; lstring printPat; bool showPattern = false; bool inverseMatch = false; uint optionErrCnt = 0; uint patternErrCnt = 0; lstring printPosFmt = "%f(%o)\n"; lstring cwd; // current working directory // Working values bool doReplace = false; std::vector<char> buffer; #if 0 // Sample replace fragment. std::regex specialCharRe("[*?-]+"); std::regex_constants::match_flag_type flags = std::regex_constants::match_default; title = std::regex_replace(title, specialCharRe, "_", flags); std::replace(title.begin(), title.end(), SLASH_CHR, '_'); #endif Filter nopFilter; LineFilter lineFilter; Filter* pFilter = &nopFilter; // --------------------------------------------------------------------------- // Dump String, showing non-printable has hex value. static void DumpStr(const char* label, const std::string& str) { if (showPattern) { std::cerr << "Pattern " << label << " length=" << str.length() << std::endl; for (int idx = 0; idx < str.length(); idx++) { std::cerr << " [" << idx << "]"; if (isprint(str[idx])) std::cerr << str[idx] << std::endl; else std::cerr << "(hex) " << std::hex << (unsigned)str[idx] << std::dec << std::endl; } std::cerr << "[end-of-pattern]\n"; } } // --------------------------------------------------------------------------- // Convert special characters from text to binary. static std::string& ConvertSpecialChar(std::string& inOut) { uint len = 0; int x, n; const char *inPtr = inOut.c_str(); char* outPtr = (char*)inPtr; while (*inPtr) { if (*inPtr == '\\') { inPtr++; switch (*inPtr) { case 'n': *outPtr++ = '\n'; break; case 't': *outPtr++ = '\t'; break; case 'v': *outPtr++ = '\v'; break; case 'b': *outPtr++ = '\b'; break; case 'r': *outPtr++ = '\r'; break; case 'f': *outPtr++ = '\f'; break; case 'a': *outPtr++ = '\a'; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': sscanf(inPtr,"%3o%n",&x,&n); inPtr += n-1; *outPtr++ = (char)x; break; case 'x': // hexadecimal sscanf(inPtr+1,"%2x%n",&x,&n); if (n>0) { inPtr += n; *outPtr++ = (char)x; break; } // seep through default: throw( "Warning: unrecognized escape sequence" ); case '\\': case '\?': case '\'': case '\"': *outPtr++ = *inPtr; break; } inPtr++; } else *outPtr++ = *inPtr++; len++; } inOut.resize(len); return inOut;; } #ifdef WIN32 const char SLASH_CHAR('\\'); #else const char SLASH_CHAR('/'); #endif // --------------------------------------------------------------------------- // Extract name part from path. lstring& getName(lstring& outName, const lstring& inPath) { size_t nameStart = inPath.rfind(SLASH_CHAR) + 1; if (nameStart == 0) outName = inPath; else outName = inPath.substr(nameStart); return outName; } // --------------------------------------------------------------------------- // Return true if inPath (filename part) matches pattern in patternList bool FileMatches(const lstring& inName, const PatternList& patternList, bool emptyResult) { if (patternList.empty() || inName.empty()) return emptyResult; for (size_t idx = 0; idx != patternList.size(); idx++) if (std::regex_match(inName.begin(), inName.end(), patternList[idx])) return true; return false; } // --------------------------------------------------------------------------- void printParts( const char* customFmt, const char* filepath, size_t fileOffset, size_t matchLen, const lstring& matchStr) { // TODO - handle custom printf syntax to get to path parts: // %#.#s s=fullpath, p=path only, n=name only, e=extension only f=filename name+ext // %0#d o=offset, l=length // printf(filepath, fileOffset, len, filepath); const int NONE = 12345; lstring itemFmt; char* fmt = (char*)customFmt; while (*fmt) { char c = *fmt; if (c != '%') { putchar(c); fmt++; } else { const char* begFmt = fmt; int precision = NONE; int width = (int)strtol(fmt+1, &fmt, 10); if (*fmt == '.') { precision = (int)strtol(fmt+1, &fmt, 10); } c = *fmt; itemFmt = begFmt; itemFmt.resize(fmt - begFmt); switch (c) { case 's': itemFmt += "s"; printf(itemFmt, filepath); break; case 'p': itemFmt += "s"; printf(itemFmt, Directory_files::parts(filepath, true, false, false).c_str()); break; case 'r': // relative path itemFmt += "s"; printf(itemFmt, Directory_files::parts(filepath, true, false, false).replaceStr(cwd, "").c_str()); break; case 'n': itemFmt += "s"; printf(itemFmt, Directory_files::parts(filepath, false, true, false).c_str()); break; case 'e': itemFmt += "s"; printf(itemFmt, Directory_files::parts(filepath, false, false, true).c_str()); break; case 'f': itemFmt += "s"; printf(itemFmt, Directory_files::parts(filepath, false, true, true).c_str()); break; case 'o': itemFmt += "lu"; // unsigned long formatter printf(itemFmt, fileOffset); break; case 'l': itemFmt += "lu"; // unsigned long formatter printf(itemFmt, matchLen); break; case 'm': itemFmt += "s"; printf(itemFmt, matchStr.c_str()); break; case 't': // match convert using printPat itemFmt += "s"; if (printPat.length() == 0) { printf("Missing -printPat=pattern"); } else { std::regex_constants::match_flag_type flags = std::regex_constants::match_default; printf(itemFmt, std::regex_replace(matchStr, fromPat, printPat, flags).c_str()); } break; default: putchar(c); break; } fmt++; } } } // --------------------------------------------------------------------------- // Find 'fromPat' in file unsigned FindGrep(const char* filepath) { lstring filename; ifstream in; ofstream out; struct stat filestat; uint matchCnt = 0; #if 1 std::regex_constants::match_flag_type flags = std::regex_constants::match_default; #else std::regex_constants::match_flag_type flags = std::regex_constants::match_flag_type( std::regex_constants::match_default + std::regex_constants::match_not_eol + std::regex_constants::match_not_bol); #endif try { if (stat(filepath, &filestat) != 0) return 0; in.open(filepath); if (in.good()) { buffer.resize(filestat.st_size); streamsize inCnt = in.read(buffer.data(), buffer.size()).gcount(); in.close(); std::match_results <const char*> match; const char* begPtr = (const char*)buffer.data(); const char* endPtr = begPtr + inCnt; size_t off = 0; pFilter->init(buffer); while (std::regex_search(begPtr, endPtr, match, fromPat, flags)) { // for (auto group : match) // std::cout << group << endl; size_t pos = match.position(); size_t len = match.length(); // size_t numMatches = match.size(); // std::string matchedStr = match.str(); // std::string m0 = match[0]; off += pos; if (pFilter->valid(off, len)) { if (!inverseMatch) { printParts(printPosFmt, filepath, off, len, lstring(begPtr+pos, len)); } matchCnt++; } begPtr += pos + len; } return inverseMatch ? (matchCnt>0?0:1): matchCnt; } else { cerr << "Unable to open " << filepath << endl; } } catch (exception ex) { cerr << "Parsing error in file:" << filepath << endl; cerr << ex.what() << std::endl; } return 0; } // --------------------------------------------------------------------------- // Find fromPat and Replace with toPat in filepath. // inFilepath = full file name path // outfilePath = full file name paht, can be same as inFilepath // backupToName = name only part bool ReplaceFile(const lstring& inFilepath, const lstring& outFilepath, const lstring& backupToName) { ifstream in; ofstream out; struct stat filestat; std::regex_constants::match_flag_type flags = std::regex_constants::match_default; try { if (stat(inFilepath, &filestat) != 0) return false; in.open(inFilepath); if (in.good()) { buffer.resize(filestat.st_size); streamsize inCnt = in.read(buffer.data(), buffer.size()).gcount(); in.close(); std::match_results <const char*> match; const char* begPtr = (const char*)buffer.data(); const char* endPtr = begPtr + inCnt; pFilter->init(buffer); // WARNING - LineFilter only validates first match and not multiple replacements. if (std::regex_search(begPtr, endPtr, match, fromPat, flags) && pFilter->valid(match.position(), match.length())) { if (!backupDir.empty()) { lstring backupFull; rename(inFilepath, Directory_files::join(backupFull, backupDir, backupToName)); } ostream* outPtr = &cout; if (outFilepath != "-") { out.open(outFilepath); if (out.is_open()) { outPtr = &out; } else { cerr << strerror(errno) << ", Unable to write to " << outFilepath << endl; return false; } } // TODO - support LineFilter validation. std::regex_replace(std::ostreambuf_iterator<char>(*outPtr), begPtr, endPtr, fromPat, toPat, flags); if (out.is_open()) { out.close(); } return true; } } else { cerr << strerror(errno) << ", Unable to open " << inFilepath << endl; } } catch (exception ex) { cerr << ex.what() << ", Error in file:" << inFilepath << endl; } return false; } // --------------------------------------------------------------------------- static size_t ReplaceFile(const lstring& inFullname) { size_t fileCount = 0; lstring name; getName(name, inFullname); if (!name.empty() && !FileMatches(name, excludeFilePatList, false) && FileMatches(name, includeFilePatList, true)) { if (doReplace) { string outFullname = (outFile.length() != 0) ? outFile : inFullname; if (ReplaceFile(inFullname, outFullname, name)) { fileCount++; // printParts(printPosFmt, fullname, 0, 0, ""); } } else { unsigned matchCnt = FindGrep(inFullname); if (matchCnt != 0) { fileCount++; // printParts(printPosFmt, fullname, 0, 0, ""); } } } return fileCount; } // --------------------------------------------------------------------------- static size_t ReplaceFiles(const lstring& dirname) { Directory_files directory(dirname); lstring fullname; size_t fileCount = 0; struct stat filestat; try { if (stat(dirname, &filestat) == 0 && S_ISREG(filestat.st_mode)) { fileCount += ReplaceFile(dirname); } } catch (exception ex) { // Probably a pattern, let directory scan do its magic. } while (directory.more()) { directory.fullName(fullname); if (directory.is_directory()) { fileCount += ReplaceFiles(fullname); } else if (fullname.length() > 0) { fileCount += ReplaceFile(fullname); } } return fileCount; } // --------------------------------------------------------------------------- // Return compiled regular expression from text. std::regex getRegEx(const char* value) { try { std::string valueStr(value); ConvertSpecialChar(valueStr); DumpStr("From", valueStr); return std::regex(valueStr); // return std::regex(valueStr, regex_constants::icase); } catch (const std::regex_error& regEx) { std::cerr << regEx.what() << ", Pattern=" << value << std::endl; } patternErrCnt++; return std::regex(""); } // --------------------------------------------------------------------------- // Validate option matchs and optionally report problem to user. bool ValidOption(const char* validCmd, const char* possibleCmd, bool reportErr = true) { // Starts with validCmd else mark error size_t validLen = strlen(validCmd); size_t possibleLen = strlen(possibleCmd); if ( strncasecmp(validCmd, possibleCmd, std::min(validLen, possibleLen)) == 0) return true; if (reportErr) { std::cerr << "Unknown option:'" << possibleCmd << "', expect:'" << validCmd << "'\n"; optionErrCnt++; } return false; } // --------------------------------------------------------------------------- template<typename TT> std::string stringer(const TT& value) { return string(value); } template<typename TT, typename ... Args > std::string stringer(const TT& value, const Args& ... args) { return string(value) + stringer(args...); } // --------------------------------------------------------------------------- void help(const char* argv0) { const char* helpMsg = " Dennis Lang v1.4 (LandenLabs.com) " __DATE__ "\n" "\nDes: Replace text in files\n" "Use: llreplace [options] directories...\n" "\n" "_P_Main options:_X_\n" " -_y_from=<regExpression> ; Pattern to find\n" " -_y_to=<regExpression or string> ; Optional replacment \n" " -_y_backupDir=<directory> ; Optional Path to store backup copy before change\n" " -_y_out= - | outfilepath ; Optional alternate output, default is input file \n" "\n" " -_y_includeFiles=<filePattern> ; Optional files to include in file scan, default=*\n" " -_y_excludeFiles=<filePattern> ; Optional files to exclude in file scan, no default\n" " -_y_range=beg,end ; Optional line range filter \n" "\n" " directories... ; Directories to scan\n" "\n" "_P_Other options:_X_\n" " -_y_inverse ; Invert Search, show files not matching \n" " -_y_printFmt='%o,%l' ; Printf format to present match \n" " ; Def: %f(%o)\\n \n" " %s=fullpath, %p=path, %f=relative path %f=filename, %n=name only %e=extension \n" " %o=character offset, %l=match length %m=match string %t=match convert using toPattern \n" "\n" " ex: -_y_printPos='%20.20f %08o' \n" " Filename padded to 20 characters, max 20, and offset 8 digits leading zeros.\n" "\n" "_p_NOTES:\n" " . (dot) does not match \\r \\n, you need to use [\\r\\n] or (.|\\r|\\n)* \n" " Use single quotes to wrap from and/or to patterns if they use special characters\n" " like $ dollar signt to prevent shell from interception it.\n" "\n" "_p_Examples\n" " Search only, show patterns and defaults showing file and match:\n" " llreplace -_y_from='Copyright' '-_y_include=*.java' -_y_print='%r/%f\\n' src1 src2\n" " llreplace -_y_from='Copyright' '-_y_include=*.java' -_y_include='*.xml' -_y_print='%s' -_y_inverse src res\n" " llreplace '-_y_from=if [(]MapConfigInfo.DEBUG[)] [{][\\r\\n ]*Log[.](d|e)([(][^)]*[)];)[\\r\\n ]*[}]' '-_y_include=*.java' -_y_range=0,10 -_y_range=20,-1 -_y_printFmt='%f %03d: ' src1 src2\n" "\n" " _P_Search and replace in-place:_X_\n" " llreplace '-_y_from=if [(]MapConfigInfo.DEBUG[)] [{][\\r\\n ]*Log[.](d|e)([(][^)]*[)];)[\\r\\n ]*[}]' '-_y_to=MapConfigInfo.$1$2$3' '-_y_include=*.java' src\n" "\n"; std::cerr << Colors::colorize(stringer("\n_W_", argv0, "_X_").c_str()) << Colors::colorize(helpMsg); } // --------------------------------------------------------------------------- int main(int argc, char* argv[]) { if (argc == 1) { help(argv[0]); } else { bool doParseCmds = true; string endCmds = "--"; for (int argn = 1; argn < argc; argn++) { if (*argv[argn] == '-' && doParseCmds) { lstring argStr(argv[argn]); Split cmdValue(argStr, "=", 2); if (cmdValue.size() >= 1) { lstring cmd = cmdValue[0]; lstring value = cmdValue[1]; if (cmd.length() > 1 && cmd[0] == '-') cmd.erase(0); // allow -- prefix on commands switch (cmd[1]) { case 'b': // backup path if (ValidOption("backupdir", cmd+1)) backupDir = value; break; case 'f': // from=<pat> if (ValidOption("from", cmd+1)) ConvertSpecialChar(value); fromPat = getRegEx(value); break; case 't': // to=<pat> if (ValidOption("to", cmd+1)) { toPat = value; ConvertSpecialChar(toPat); DumpStr("To", toPat); doReplace = true; } break; case 'i': // includeFile=<pat> if (ValidOption("inverse", argStr+1, false)) { inverseMatch = true; } if (ValidOption("includefile", cmd+1, false)) { ReplaceAll(value, "*", ".*"); includeFilePatList.push_back(getRegEx(value)); } break; case 'e': // excludeFile=<pat> if (ValidOption("excludefile", cmd+1)) { ReplaceAll(value, "*", ".*"); excludeFilePatList.push_back(getRegEx(value)); } break; case 'r': // range=beg,end if (ValidOption("range", cmd+1)) { char* nPtr; size_t n1 = strtoul(value, &nPtr, 10); size_t n2 = strtoul(nPtr+1, &nPtr, 10); if (n1 <= n2) { pFilter = &lineFilter; lineFilter.zones.push_back(Zone(n1, n2)); } } break; case 'o': // alternate output if (ValidOption("out", cmd+1)) outFile = value; break; case 'p': if (ValidOption("printFmt", cmd+1, false)) { printPosFmt = value; ConvertSpecialChar(printPosFmt); } else if (ValidOption("printPat", cmd+1)) { printPat = value; ConvertSpecialChar(printPat); } break; default: std::cerr << "Unknown command " << cmd << std::endl; optionErrCnt++; break; } } else { if (endCmds == argv[argn]) { doParseCmds = false; } else { switch (argStr[1]) { case 'i': inverseMatch = ValidOption("inverse", argStr+1, false); break; default: std::cerr << "Unknown command " << argStr << std::endl; optionErrCnt++; break; } } } } else { // Store file directories fileDirList.push_back(argv[argn]); } } if (patternErrCnt == 0 && optionErrCnt == 0 && fileDirList.size() != 0) { char cwdTmp[256]; cwd = getcwd(cwdTmp, sizeof(cwdTmp)); cwd += Directory_files::SLASH; if (!toPat.empty() && pFilter == &lineFilter) { cerr << "\a\nRange filter does not work for replacement only searching\a\n" << std::endl; } if (fileDirList.size() == 1 && fileDirList[0] == "-") { string filePath; while (std::getline(std::cin, filePath)) { std::cerr << ReplaceFiles(filePath) << std::endl; } } else { for (auto const& filePath : fileDirList) { std::cerr << ReplaceFiles(filePath) << std::endl; } } } else { help(argv[0]); } std::cerr << std::endl; } return 0; }
//https://onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=353 #include <bits/stdc++.h> #define PI 3.1415926535897932384626433832795 #define loop(i,n) for(i = 0; i < n; i++) #define sz (int) 1e5 + 5 #define ll long long using namespace std; int arr[55]; int gcd(int x, int y) { if(y > x) swap(x,y); if(y == 0) return x; return gcd(x%y, y); } double cal_factorial(int s, int e) { double total = 1; for(int i = s; i >= e; i--) { total = total * i; } return total; } int main() { #ifndef ONLINE_JUDGE freopen("F:\\Programming\\Competitve Programming\\Answers\\input.txt", "r", stdin); freopen("F:\\Programming\\Competitve Programming\\Answers\\output.txt", "w", stdout); #endif int n; cin >> n; while(n != 0) { int i,j; loop(i, n) { cin >> arr[i]; } double nfac = cal_factorial(n,2); double possible_pairs = nfac / ((nfac / (n*(n-1))) * 2); // n! / ((n - m)! * m!) // m = 2 // (n - 2)! = n! / (n * (n - 1)) int cnt = 0; loop(i, n) { for(int j = i+1; j < n; j++) { if(gcd(arr[i], arr[j]) == 1) { cnt++; } } } if(cnt != 0) { double result = cnt / possible_pairs; cout << fixed << setprecision(6) << sqrt(6/result) << endl; } else { cout << "No estimate for this data set." << endl; } cin >> n; } return 0; }
// -*- C++ -*- // // Package: EgammaHLTAlgos // Class : EgammaHLTEcalIsolation // // Implementation: // <Notes on implementation> // // Original Author: Monica Vazquez Acosta // Created: Tue Jun 13 12:16:00 CEST 2006 // // system include files // user include files #include "RecoEgamma/EgammaHLTAlgos/interface/EgammaHLTEcalIsolation.h" #define PI 3.141592654 #define TWOPI 6.283185308 float EgammaHLTEcalIsolation::isolPtSum(const reco::RecoCandidate* recocandidate, const std::vector<const reco::SuperCluster*>& sclusters, const std::vector<const reco::BasicCluster*>& bclusters) const { float ecalIsol = 0.; float candSCphi = recocandidate->superCluster()->phi(); float candSCeta = recocandidate->superCluster()->eta(); // match the photon hybrid supercluster with those with Algo==0 (island) float delta1 = 1000.; float deltacur = 1000.; const reco::SuperCluster* matchedsupercluster = nullptr; bool MATCHEDSC = false; for (std::vector<const reco::SuperCluster*>::const_iterator scItr = sclusters.begin(); scItr != sclusters.end(); ++scItr) { const reco::SuperCluster* supercluster = *scItr; float SCphi = supercluster->phi(); float SCeta = supercluster->eta(); if (supercluster->seed()->algo() == algoType_) { float deltaphi; if (candSCphi < 0) candSCphi += TWOPI; if (SCphi < 0) SCphi += TWOPI; deltaphi = fabs(candSCphi - SCphi); if (deltaphi > TWOPI) deltaphi -= TWOPI; if (deltaphi > PI) deltaphi = TWOPI - deltaphi; float deltaeta = fabs(SCeta - candSCeta); deltacur = sqrt(deltaphi * deltaphi + deltaeta * deltaeta); if (deltacur < delta1) { delta1 = deltacur; matchedsupercluster = supercluster; MATCHEDSC = true; } } } const reco::BasicCluster* cluster = nullptr; //loop over basic clusters for (std::vector<const reco::BasicCluster*>::const_iterator cItr = bclusters.begin(); cItr != bclusters.end(); ++cItr) { cluster = *cItr; // float ebc_bcchi2 = cluster->chi2(); //chi2 for SC was useless and it is removed in 31x int ebc_bcalgo = cluster->algo(); float ebc_bce = cluster->energy(); float ebc_bceta = cluster->eta(); float ebc_bcphi = cluster->phi(); float ebc_bcet = ebc_bce * sin(2 * atan(exp(ebc_bceta))); float newDelta; if (ebc_bcet > etMin && ebc_bcalgo == algoType_) { // if (ebc_bcchi2 < 30.) { if (MATCHEDSC) { bool inSuperCluster = false; reco::CaloCluster_iterator theEclust = matchedsupercluster->clustersBegin(); // loop over the basic clusters of the matched supercluster for (; theEclust != matchedsupercluster->clustersEnd(); theEclust++) { if (&(**theEclust) == cluster) inSuperCluster = true; } if (!inSuperCluster) { float deltaphi; if (ebc_bcphi < 0) ebc_bcphi += TWOPI; if (candSCphi < 0) candSCphi += TWOPI; deltaphi = fabs(ebc_bcphi - candSCphi); if (deltaphi > TWOPI) deltaphi -= TWOPI; if (deltaphi > PI) deltaphi = TWOPI - deltaphi; float deltaeta = fabs(ebc_bceta - candSCeta); newDelta = sqrt(deltaphi * deltaphi + deltaeta * deltaeta); if (newDelta < conesize) { ecalIsol += ebc_bcet; } } } // } // matches ebc_bcchi2 } // matches ebc_bcet && ebc_bcalgo } return ecalIsol; }
#include "finance.h" facture::facture() { } facture::facture(QString Nom,QString Adresse,QString Num_Tel,QString courriel,int ID,QString Info,QString paiement,QString Tpaiement) { this->Nom=Nom; this->Adresse=Adresse; this->Num_Tel=Num_Tel; this->courriel=courriel; this->ID=ID; this->Info=Info; this->paiement=paiement; this->Tpaiement=Tpaiement; } bool facture::AjoutFacture(facture *FA) { QSqlQuery query; QString IDD= QString::number(FA->getID()); QString str= "insert into Facture values('"+FA->getNom()+"','"+FA->getAdresse()+"','"+FA->getNum_Tel()+"','"+FA->getcourriel()+"','"+IDD+"','"+FA->getInfo()+"','"+FA->getpaiement()+"','"+FA->getTpaiement()+"')"; qDebug()<<str; if (query.exec(str)) return true; else return false; } QSqlQueryModel * facture::AfficherFacture() { QSqlQueryModel * model= new QSqlQueryModel(); model->setQuery("select * from Facture"); model->setHeaderData(0, Qt::Horizontal, QObject::tr("NOM")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("PRENOM")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUM_TEL")); return model; } QSqlQueryModel * facture::RechercherFacture(int ID) { QSqlQueryModel * model= new QSqlQueryModel(); QString str="select * from Facture where ID ="+QString::number(ID); model->setQuery(str); return model; } bool facture::SupprimerFacture(int ID) { QSqlQuery query; QString str="delete from Facture where ID ="+QString::number(ID); qDebug()<<str; bool res = query.exec(str); return res; } bool facture::ModifierFacture(facture *FA) { QSqlQuery query; QString IDD= QString::number(FA->getID()); QString str=("update Facture set Nom='"+FA->getNom()+"'" ",Adresse='"+FA->getAdresse()+"'" ",Num_Tel='"+FA->getNum_Tel()+"'" ",Courriel='"+FA->getcourriel()+"'" ",ID='"+IDD+"'" ",Info='"+FA->getInfo()+"'" ",Paiement='"+FA->getpaiement()+"'" ",Tpaimement='"+FA->getTpaiement()+"'where ID='"+IDD+"'"); qDebug()<<str; bool res =query.exec(str); return res; }
#pragma once #include "ParallelPrimeFinder.h" class NaivePar : public ParallelPrimeFinder { // Inherited via ParallelPrimeFinder virtual std::string name() override; virtual int* find(int min, int max, int* size) override; };
#include <iostream> #include "CameraPositionShifter.h" namespace Game { CameraPositionShifter::CameraPositionShifter(Camera &camera) : mCamera(camera) { } void CameraPositionShifter::onKeyPress(sf::Event::KeyEvent event) { switch (event.code) { case sf::Keyboard::Down: mCamera.moveDown(true); break; case sf::Keyboard::Up: mCamera.moveUp(true); break; case sf::Keyboard::Left: mCamera.moveLeft(true); break; case sf::Keyboard::Right: mCamera.moveRight(true); break; case sf::Keyboard::J: mCamera.rotateLeft(true); break; case sf::Keyboard::L: mCamera.rotateRight(true); break; case sf::Keyboard::I: mCamera.rotateUp(true); break; case sf::Keyboard::K: mCamera.rotateDown(true); break; } } void CameraPositionShifter::onKeyUp(sf::Event::KeyEvent event) { switch (event.code) { case sf::Keyboard::Down: mCamera.moveDown(false); break; case sf::Keyboard::Up: mCamera.moveUp(false); break; case sf::Keyboard::Left: mCamera.moveLeft(false); break; case sf::Keyboard::Right: mCamera.moveRight(false); break; case sf::Keyboard::J: mCamera.rotateLeft(false); break; case sf::Keyboard::L: mCamera.rotateRight(false); break; case sf::Keyboard::I: mCamera.rotateUp(false); break; case sf::Keyboard::K: mCamera.rotateDown(false); break; } } }
#include "Character.hpp" namespace rlrpg { Character::Character( unsigned level, attrs_t const& base_attributes, Inventory && inventory): m_level(level), m_base_attributes(base_attributes), m_inventory(std::move(inventory)), m_health(base_attributes[size_t(Attr::Health)]) { } unsigned Character::health() const { return m_health; } unsigned Character::level() const { return m_level; } attrs_t & Character::base_attributes() { return m_base_attributes; } attrs_t const& Character::base_attributes() const { return m_base_attributes; } Inventory & Character::inventory() { return m_inventory; } Inventory const& Character::inventory() const { return m_inventory; } }
#pragma once #include "Proto/paxoskv.pb.h" class PaxosKVServiceImpl { public: static PaxosKVServiceImpl *GetInstance(); static void SetInstance(PaxosKVServiceImpl *); static int BeforeServerStart(const char * czConf) { return 0; } int BeforeWorkerStart() { return 0; } int Get(const ::paxoskv::GetReq & oReq, ::paxoskv::GetResp & oResp); int Set(const ::paxoskv::SetReq & oReq, ::paxoskv::SetResp & oResp); int Del(const ::paxoskv::DelReq & oReq, ::paxoskv::DelResp & oResp); };
/* * string.c * * Created on: 27 mai 2013 * Author: droper */ #include "string.h" #include <cstdlib> #include <cstring> #include <iostream> const char *str_find_exp(const char *begin, const char *end, const char *pat) { const char *i, *j; unsigned short k = 0; for (i = begin; i < end && *i != '\0'; ++i) { if (*i == '(') ++k; else if (*i == ')') --k; else for (j = pat; *j != '\0'; j++) { if (*i == *j && k == 0) { return i; } } } return end; }
#include <iostream> #include <algorithm> #include <cmath> using namespace std; int test(int h, int w, int n) { int x = ceil((float)n / h); int y = n % h; if(y == 0) y = h; return y * 100 + x; } int main() { int T; cin >> T; while(T--) { int h, w, n; cin >> h >> w >> n; cout << test(h, w, n) << endl; } return 0; }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "ClangPluginCheck.h" #include "ClangPluginRegistry.h" #include "clang/AST/Decl.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchers.h" #include <string> using namespace clang; namespace clang { namespace ast_matchers { AST_MATCHER(ParmVarDecl, hasDefaultArgument) { return Node.hasDefaultArg(); } } // namespace ast_matchers } // namespace clang namespace { using namespace clang::ast_matchers; class NoDefaultParametersStmtCallback : public MatchFinder::MatchCallback { public: void run(const MatchFinder::MatchResult &Result) override { DiagnosticsEngine &Diagnostics = Result.Context->getDiagnostics(); if (const CXXDefaultArgExpr *S = Result.Nodes.getNodeAs<CXXDefaultArgExpr>("stmt")) { unsigned ErrorID = Diagnostics.getDiagnosticIDs()->getCustomDiagID( DiagnosticIDs::Error, "[system-c++] Calling functions which use " "default arguments is disallowed"); unsigned NoteID = Diagnostics.getDiagnosticIDs()->getCustomDiagID( DiagnosticIDs::Note, "[system-c++] The default parameter was declared here:"); Diagnostics.Report(S->getUsedLocation(), ErrorID); Diagnostics.Report(S->getParam()->getLocStart(), NoteID); } } }; class NoDefaultParametersDeclCallback : public MatchFinder::MatchCallback { public: void run(const MatchFinder::MatchResult &Result) override { DiagnosticsEngine &Diagnostics = Result.Context->getDiagnostics(); if (const ParmVarDecl *D = Result.Nodes.getNodeAs<ParmVarDecl>("decl")) { unsigned ID = Diagnostics.getDiagnosticIDs()->getCustomDiagID( DiagnosticIDs::Error, "[system-c++] Declaring functions which use " "default arguments is disallowed"); Diagnostics.Report(D->getLocStart(), ID); } } }; NoDefaultParametersStmtCallback NoDefaultParametersStmt; NoDefaultParametersDeclCallback NoDefaultParametersDecl; class NoDefaultArgumentsCheck : public ClangPluginCheck { public: void add(ast_matchers::MatchFinder &Finder) override { // Calling a function which uses default arguments is disallowed. Finder.addMatcher(cxxDefaultArgExpr().bind("stmt"), &NoDefaultParametersStmt); // Declaring default parameters is disallowed. Finder.addMatcher(parmVarDecl(hasDefaultArgument()).bind("decl"), &NoDefaultParametersDecl); } }; } // namespace static ClangPluginRegistry::Add<NoDefaultArgumentsCheck> X("no-default-arguments", "Disallow C++ default arguments");
// // GnITabButton.h // Core // // Created by Max Yoon on 11. 7. 25.. // Copyright 2011년 __MyCompanyName__. All rights reserved. // #ifndef Core_GnITabButton_h #define Core_GnITabButton_h class GnITabPage; class GnITabButton : public GnIButton { private: GnITabPage* mpTabPage; public: GnITabButton(GnITabPage* pTabPage, const gchar* pcDefaultImage, const gchar* pcClickImage = NULL , const gchar* pcDisableImage = NULL, eButtonType eDefaultType = TYPE_NORMAL); virtual ~GnITabButton(); public: virtual bool PushUp(float fPointX, float fPointY); virtual bool PushMove(float fPointX, float fPointY); virtual void Push(); virtual void PushUp(); virtual void SetVisibleNormal(bool val){}; public: inline GnITabPage* GetTabPage() { return mpTabPage; } }; #endif
#pragma once #include <functional> #include <string> namespace Poco { class Thread; } namespace BeeeOn { /** * @brief The class implements working with POSIX signals. */ class PosixSignal { private: PosixSignal(); public: typedef std::function<void(unsigned int)> Handler; /** * Send signal to a process of the given pid. * @param pid Process ID * @param name Name of the signal to send (e.g. SIGUSR1) */ static void send(long pid, const std::string name); /** * Send signal to a thread owning by this process. We assume that the Poco::Thread * is using pthread internally. The implementation calls pthread_kill() to send * the signal to the proper thread. * * @param thread Thread to send the signal to * @param name Name of the signal to send */ static void send(const Poco::Thread &thread, const std::string &name); /** * Ignore the selected signal to not influence the current process (SIG_IGN). * @param name Name of the signal to be ignored */ static void ignore(const std::string &name); /** * Install a handler for the given signal name. * @param name Name of the signal to handle * @param handler Handler to be used */ static void handle(const std::string &name, Handler handler); /** * Install appropriate handlers for the most fatal signals like * SIGSEGV, SIGBUS, etc. The application would provide some more * information during the actual crash. The handlers terminates * the application by calling _exit(). */ static void trapFatal(); protected: /** * Translate name of a signal to its internal representation. */ static unsigned int byName(const std::string &name); static void send(long pid, unsigned int num); static void send(const Poco::Thread &thread, unsigned int num); static void ignore(unsigned int num); static void handle(unsigned int num, Handler handler); }; }
#include "Utils.h" namespace dyablo { /** Basic algebraic operations on vectors **/ Vec operator+(const Vec &v1, const Vec &v2) { return Vec{v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2]}; }; Vec operator-(const Vec &v1, const Vec &v2) { return Vec{v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2]}; } Vec& operator+=(Vec &v1, const Vec &v2) { v1[0] += v2[0]; v1[1] += v2[1]; v1[2] += v2[2]; return v1; } Vec& operator-=(Vec &v1, const Vec &v2) { v1[0] -= v2[0]; v1[1] -= v2[1]; v1[2] -= v2[2]; return v1; } Vec operator*(const Vec &v, float q) { return Vec{v[0]*q, v[1]*q, v[2]*q}; } Vec& operator*=(Vec &v, float q) { v[0] *= q; v[1] *= q; v[2] *= q; return v; } /** * Returns if the given position is inside the bounding box * @param bb the bounding box * @param pos a position to check * @param nDim number of dimensions to test **/ bool inBoundingBox(BoundingBox bb, Vec pos, int nDim) { for (int i=0; i < nDim; ++i) { if (pos[i] < bb.first[i] || pos[i] > bb.second[i]) return false; } return true; } }
#ifndef CRASHRESULT_H #define CRASHRESULT_H #include "CrashEvent.h" #include "Vector.h" class Field::CrashEvent::CrashResult { public: enum ResultCode {FAIL, POLYGON_AND_VERTEX, LINE_AND_LINE}; CrashResult(void); CrashResult(const CrashResult&); virtual ~CrashResult(void); const CrashResult& operator=(const CrashResult&); void setObjPlgnAndVrtx(Object*, Object*, short, short); void setObjLineAndLine(Object*, Object*, short, short); void setResult(ResultCode); void setDist(float); void setCrashSpot(const Vector&); // void setRelativeVelocity(const Vector&); void addTangency(void); void addHandVelocityToPlayerNeo(void); void restorePlayerNeo(void); void triggerHandVelocityOfPlayerNeo(bool); Object* getObjPlgn(void); Object* getObjVrtx(void); Object* getObjLine1(void); Object* getObjLine2(void); ResultCode getResult(void); short getPlgnIdx(void); short getVrtxIdx(void); short getLine1Idx(void); short getLine2Idx(void); float getDist(void); Vector getCrashSpot(void); // Vector getRelativeVelocity(void); short getTangencyNum(void); float getRelativeSpeed(void); private: Object* objPlgnOrLine1; Object* objVrtxOrLine2; ResultCode result; short plgnIdx; short vrtxIdx; short line1Idx; short line2Idx; float dist; Vector crashSpot; short tangencyNum; // Vector relativeVelocity; }; #endif
#include "btn.h" #include <QDebug> #include <QMessageBox> BTN::BTN(QString text, QWidget *parent) : QPushButton(parent), m_text(text) { setText(m_text); setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); } BTN::~BTN() { qDebug() << "Destruction !" ; } //void BTN::ActionButton(){ // QMessageBox::information(this, "Toto", "Ceci est un message"); //}
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int N; cin >> N; vector<int> v(N); for (int i = 0; i < N; ++i) { cin >> v[i]; } sort(v.rbegin(), v.rend()); int x = v.front(); int y = 0; for (int i = 0; i < N; ++i) { if (v[i] == v[i + 1] || x % v[i] > 0) { y = v[i]; break; } } cout << x << " " << y << endl; return 0; }
#pragma once #include "physics/physics.h" namespace jsphysics { JSObject* CreatePhysicsManagerObject(physics::PhysicsManager* manager); void DestroyPhysicsManagerObject(physics::PhysicsManager* manager); }
#include<iostream> #include<fstream> using namespace std; int main(int argc, char* argv[]) { ifstream dna_file (argv[1]); char x; int A=0; int T=0; int C=0; int G=0; while(dna_file.get(x)){ if (x=='A'){ A+=1; }else if(x=='T'){ T+=1; }else if (x=='C'){ C+=1; }else if (x=='G'){ G+=1; } } cout << A << " "<< C << " "<< G<< " " << T << endl; }
#include "Renderer.h" Renderer::Renderer() { // --- INIT --- if (SDL_Init(SDL_INIT_EVERYTHING) != 0) throw "No es pot inicialitzar SDL subsystems"; // --- WINDOW --- m_window = SDL_CreateWindow("SDL...", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (m_window == nullptr) throw "No es pot inicialitzar SDL_Window"; // --- RENDERER --- m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (m_renderer == nullptr) throw "No es pot inicialitzar SDL_Renderer"; //Initialize renderer color SDL_SetRenderDrawColor(m_renderer, 255, 255, 255, 255); //Initialize PNG loading const Uint8 imgFlags{ IMG_INIT_PNG | IMG_INIT_JPG }; if (!(IMG_Init(imgFlags) & imgFlags)) throw "Error: SDL_imageinit"; // ---- TTF ---- if (TTF_Init() != 0) throw"No es pot inicialitzar SDL_ttf"; LoadTexture(SPLASH_IMAGE_ID, SPLASH_BACKGROUND_PATH); Font menuFont{ MENU_FONT::ID, MENU_FONT::PATH, MENU_FONT::SIZE }; LoadFont(menuFont); Font playFont{ PLAY_FONT::ID, PLAY_FONT::PATH, PLAY_FONT::SIZE }; LoadFont(playFont); Text playButton{ PLAY_BUTTON::ID, PLAY_BUTTON::TEXT, PLAY_BUTTON::COLOR, PLAY_BUTTON::W, PLAY_BUTTON::H }; LoadTextureText(menuFont.id, playButton); Text playButtonHover{ PLAY_BUTTON::HOVER_ID, PLAY_BUTTON::HOVER_TEXT, PLAY_BUTTON::COLOR, PLAY_BUTTON::W, PLAY_BUTTON::H }; LoadTextureText(menuFont.id, playButtonHover); Text soundButton{ SOUND_BUTTON::ID, SOUND_BUTTON::TEXT, SOUND_BUTTON::COLOR, SOUND_BUTTON::W, SOUND_BUTTON::H }; LoadTextureText(menuFont.id, soundButton); Text soundButtonHover{ SOUND_BUTTON::HOVER_ID, SOUND_BUTTON::HOVER_TEXT, SOUND_BUTTON::COLOR, SOUND_BUTTON::W, SOUND_BUTTON::H }; LoadTextureText(menuFont.id, soundButtonHover); Text rankingButton{ RANKING_BUTTON::ID, RANKING_BUTTON::TEXT, RANKING_BUTTON::COLOR, RANKING_BUTTON::W, RANKING_BUTTON::H }; LoadTextureText(menuFont.id, rankingButton); Text rankingButtonHover{ RANKING_BUTTON::HOVER_ID, RANKING_BUTTON::HOVER_TEXT, RANKING_BUTTON::COLOR, RANKING_BUTTON::W, RANKING_BUTTON::H }; LoadTextureText(menuFont.id, rankingButtonHover); Text exitButton{ EXIT_BUTTON::ID, EXIT_BUTTON::TEXT, EXIT_BUTTON::COLOR, EXIT_BUTTON::W, EXIT_BUTTON::H }; LoadTextureText(menuFont.id, exitButton); Text exitButtonHover{ EXIT_BUTTON::HOVER_ID, EXIT_BUTTON::HOVER_TEXT, EXIT_BUTTON::COLOR, EXIT_BUTTON::W, EXIT_BUTTON::H }; LoadTextureText(menuFont.id, exitButtonHover); Text backButton{ BACK_BUTTON::ID, BACK_BUTTON::TEXT, BACK_BUTTON::COLOR, BACK_BUTTON::W, BACK_BUTTON::H }; LoadTextureText(menuFont.id, backButton); Text backButtonHover{ BACK_BUTTON::HOVER_ID, BACK_BUTTON::HOVER_TEXT, BACK_BUTTON::COLOR, BACK_BUTTON::W, BACK_BUTTON::H }; LoadTextureText(menuFont.id, backButtonHover); Text Score0{ SCORE_0::ID, SCORE_0::TEXT, SCORE_0::COLOR, HUD_INFO::SCORE_W, HUD_INFO::SCORE_H }; LoadTextureText(playFont.id, Score0); Text Score1{ SCORE_1::ID, SCORE_1::TEXT, SCORE_1::COLOR, HUD_INFO::SCORE_W, HUD_INFO::SCORE_H }; LoadTextureText(playFont.id, Score1); Text Score2{ SCORE_2::ID, SCORE_2::TEXT, SCORE_2::COLOR, HUD_INFO::SCORE_W, HUD_INFO::SCORE_H }; LoadTextureText(playFont.id, Score2); Text Score3{ SCORE_3::ID, SCORE_3::TEXT, SCORE_3::COLOR, HUD_INFO::SCORE_W, HUD_INFO::SCORE_H }; LoadTextureText(playFont.id, Score3); Text Score4{ SCORE_4::ID, SCORE_4::TEXT, SCORE_4::COLOR, HUD_INFO::SCORE_W, HUD_INFO::SCORE_H }; LoadTextureText(playFont.id, Score4); Text Score5{ SCORE_5::ID, SCORE_5::TEXT, SCORE_5::COLOR, HUD_INFO::SCORE_W, HUD_INFO::SCORE_H }; LoadTextureText(playFont.id, Score5); Text Score6{ SCORE_6::ID, SCORE_6::TEXT, SCORE_6::COLOR, HUD_INFO::SCORE_W, HUD_INFO::SCORE_H }; LoadTextureText(playFont.id, Score6); Text Score7{ SCORE_7::ID, SCORE_7::TEXT, SCORE_7::COLOR, HUD_INFO::SCORE_W, HUD_INFO::SCORE_H }; LoadTextureText(playFont.id, Score7); Text Score8{ SCORE_8::ID, SCORE_8::TEXT, SCORE_8::COLOR, HUD_INFO::SCORE_W, HUD_INFO::SCORE_H }; LoadTextureText(playFont.id, Score8); Text Score9{ SCORE_9::ID, SCORE_9::TEXT, SCORE_9::COLOR, HUD_INFO::SCORE_W, HUD_INFO::SCORE_H }; LoadTextureText(playFont.id, Score9); Text ScoreX{ SCORE_X::ID, SCORE_X::TEXT, SCORE_X::COLOR, HUD_INFO::SCORE_W, HUD_INFO::SCORE_H }; LoadTextureText(playFont.id, ScoreX); Text Spcae_Start1{ PRESS_SPACE1::ID, PRESS_SPACE1::TEXT, PRESS_SPACE1::COLOR, PRESS_SPACE1::W, PRESS_SPACE1::H }; LoadTextureText(menuFont.id, Spcae_Start1); Text Spcae_Start2{ PRESS_SPACE2::ID, PRESS_SPACE2::TEXT, PRESS_SPACE2::COLOR, PRESS_SPACE2::W, PRESS_SPACE2::H }; LoadTextureText(menuFont.id, Spcae_Start2); Text Spcae_Pause1{ STOP_PRESS_SPACE1::ID, STOP_PRESS_SPACE1::TEXT, STOP_PRESS_SPACE1::COLOR, STOP_PRESS_SPACE1::W, STOP_PRESS_SPACE1::H }; LoadTextureText(menuFont.id, Spcae_Pause1); Text Spcae_Pause2{ STOP_PRESS_SPACE2::ID, STOP_PRESS_SPACE2::TEXT, STOP_PRESS_SPACE2::COLOR, STOP_PRESS_SPACE2::W, STOP_PRESS_SPACE2::H }; LoadTextureText(menuFont.id, Spcae_Pause2); Text Spcae_Pause3{ STOP_PRESS_SPACE3::ID, STOP_PRESS_SPACE3::TEXT, STOP_PRESS_SPACE3::COLOR, STOP_PRESS_SPACE3::W, STOP_PRESS_SPACE3::H }; LoadTextureText(menuFont.id, Spcae_Pause3); Text Sound_Pause{ SOUND_PAUSE::ID, SOUND_PAUSE::TEXT, SOUND_PAUSE::COLOR, SOUND_PAUSE::W, SOUND_PAUSE::H }; LoadTextureText(menuFont.id, Sound_Pause); Text NullText{ NULL_TEXT::ID, NULL_TEXT::TEXT, NULL_TEXT::COLOR, NULL_TEXT::W, NULL_TEXT::H }; LoadTextureText(menuFont.id, NullText); Text spritesheet{ PACMAN_SPRITESHEET::ID, PACMAN_SPRITESHEET::TEXT, PACMAN_SPRITESHEET::COLOR, PACMAN_SPRITESHEET::W, PACMAN_SPRITESHEET::H }; LoadTexture(spritesheet.id, PACMAN_SPRITESHEET::PATH); }; Renderer::~Renderer() { for (auto &t : m_textureData) SDL_DestroyTexture(t.second), t.second = nullptr; for (auto &f : m_fontData) TTF_CloseFont(f.second), f.second = nullptr; SDL_DestroyRenderer(m_renderer); m_renderer = nullptr; SDL_DestroyWindow(m_window); m_window = nullptr; IMG_Quit(); TTF_Quit(); SDL_Quit(); }; void Renderer::Clear() { SDL_RenderClear(m_renderer); }; void Renderer::Render() { SDL_RenderPresent(m_renderer); }; void Renderer::LoadFont(Font font) { TTF_Font *ttfFont{ TTF_OpenFont(font.path.c_str(), font.size) }; if (ttfFont == nullptr) throw"No espot inicialitzar TTF_Font"; m_fontData[font.id] = ttfFont; }; void Renderer::LoadTexture(const std::string &id, const std::string &path) { SDL_Texture *texture{ IMG_LoadTexture(m_renderer, path.c_str()) }; if (texture == nullptr) throw "No s'han pogut crear les textures"; m_textureData[id] = texture; }; void Renderer::LoadTextureText(const std::string &fontId, Text text) { SDL_Surface *tmpSurf = TTF_RenderText_Blended(m_fontData[fontId], text.text.c_str(), SDL_Color{ text.color.r, text.color.g, text.color.b,text.color.a }); if (tmpSurf == nullptr) throw "Unable to create the SDL text surface"; SDL_Texture *texture{ SDL_CreateTextureFromSurface(m_renderer, tmpSurf) }; m_textureData[text.id] = texture; }; Vec2 Renderer::GetTextureSize(const std::string &id) { int w; int h; SDL_QueryTexture(m_textureData[id], NULL, NULL,&w, &h); return {w, h}; }; void Renderer::PushImage(const std::string &id, const Rect &rect) { SDL_Rect newRect; newRect.x = rect.x; newRect.y = rect.y; newRect.w = rect.w; newRect.h = rect.h; SDL_RenderCopy(m_renderer, m_textureData[id], nullptr, &newRect); }; void Renderer::PushSprite(const std::string &id, const Rect &rectSprite,const Rect &rectPos) { SDL_Rect newSprite; newSprite.x = rectSprite.x; newSprite.y = rectSprite.y; newSprite.w = rectSprite.w; newSprite.h = rectSprite.h; SDL_Rect newPos; newPos.x = rectPos.x; newPos.y = rectPos.y; newPos.w = rectPos.w; newPos.h = rectPos.h; SDL_RenderCopy(m_renderer, m_textureData[id], &newSprite, &newPos); } void Renderer::PushRotatedSprite(const std::string & id, const Rect & rectSprite, const Rect & rectPos, float angle){ SDL_Point center = { rectPos.w / 2, rectPos.h / 2 }; SDL_Rect newSprite; newSprite.x = rectSprite.x; newSprite.y = rectSprite.y; newSprite.w = rectSprite.w; newSprite.h = rectSprite.h; SDL_Rect newPos; newPos.x = rectPos.x; newPos.y = rectPos.y; newPos.w = rectPos.w; newPos.h = rectPos.h; SDL_RenderCopyEx(m_renderer, m_textureData[id], &newSprite, &newPos, angle, &center, SDL_FLIP_NONE); } void Renderer::SetRendreDrawColor(int r, int g, int b) { SDL_SetRenderDrawColor(m_renderer, r, g, b, 255); } Renderer* Renderer::renderer = nullptr;
class Solution { public: string decodeAtIndex(string S, int K) { int n = S.size(); long size = 0; for(int i = 0; i<n; i++) { if(isdigit(S[i])) { size *= S[i] - '0'; } else { size++; } } for(int i = n-1; i>=0; i--) { K = K % size; // cout << K << " " << size << endl; if(K == 0 && isalpha(S[i])) { return (string) "" + S[i]; } if(isdigit(S[i])) { // cout << typeid(S[i] - '0').name() << endl; size /= S[i] - '0'; } else { size--; } } return ""; } };
#ifndef GRID_H #define GRID_H #include <vector> #include <memory> #include <random> #include "Cell.h" extern std::mt19937 myRandomSeed; namespace Minesweeper { class Grid { private: int gridHeight; int gridWidth; int numOfMines; int numOfMarkedMines = 0; int numOfWronglyMarkedMines = 0; int numOfVisibleCells = 0; bool _checkedMine = false; std::vector< std::vector< std::unique_ptr<Cell> > > cells; int verifyNumOfMines(int numOfMines); std::vector< std::vector< std::unique_ptr<Cell> > > initCells(); void chooseRandomMineCells(std::vector<int>& mineSpots, const int initChosenX, const int initChosenY) const; void createMine(const int X, const int Y); void incrNumsAroundMine(const int X, const int Y); void checkAroundCoordinate(const int X, const int Y); bool allMinesMarked() const; bool allNonMinesVisible() const; bool checkedMine() const; public: Grid(int gridSize, int numOfMines); Grid(int gridHeight, int gridWidth, int numOfMines); void createMinesAndNums(const int initChosenX, const int initChosenY); // to check user given coordinates, and make it visible void checkInputCoordinates(const int X, const int Y); // to mark (or unmark) given coordinates, and keeping track of marked and wrongly marked mines void markInputCoordinates(const int X, const int Y); bool playerHasWon() const; bool playerHasLost() const; bool isCellVisible(const int X, const int Y) const; bool doesCellHaveMine(const int X, const int Y) const; bool isCellMarked(const int X, const int Y) const; int numOfMinesAroundCell(const int X, const int Y) const; // --------------- // static methods: // --------------- static int maxNumOfMines(int gridHeight, int gridWidth); static int minNumOfMines(); static int minNumOfMines(int gridHeight, int gridWidth); }; } #endif
////////////////////////////////////////////////////////////////////// ///Copyright (C) 2011-2012 Benjamin Quach // //This file is part of the "Lost Horizons" video game demo // //"Lost Horizons" 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. // //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. // //You should have received a copy of the GNU General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "planet.h" planet::planet(irr::IrrlichtDevice *graphics, planet_base *planet_type, core::vector3df& position, ship_faction faction, const wchar_t *name, core::stringc texture) : CObject(name) { this->graphics = graphics; this->faction = faction; this->planet_type = planet_type; this->model = graphics->getSceneManager()->addAnimatedMeshSceneNode(graphics->getSceneManager()->getMesh(planet_type->planet_model)); this->model->setPosition(position); this->model->setScale(planet_type->scale); this->model->setMaterialTexture(0,graphics->getVideoDriver()->getTexture(texture)); this->model->getMaterial(0).NormalizeNormals=true; this->model->setMaterialType(video::EMT_SOLID); //ensure only certain planets get clouds //having moons with clouds would be dumb if(planet_type->clouds==true) { this->cloud = graphics->getSceneManager()->addAnimatedMeshSceneNode(graphics->getSceneManager()->getMesh(planet_type->planet_model)); this->cloud->setPosition(position); this->cloud->setScale(planet_type->cloud_scale); this->cloud->setMaterialTexture(0,graphics->getVideoDriver()->getTexture(planet_type->cloud_map)); this->cloud->getMaterial(0).NormalizeNormals=true; this->cloud->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL); } if(planet_type->corona==true) { corona = graphics->getSceneManager()->addCubeSceneNode(3,0,-1,this->model->getPosition()); corona->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/textures/atmos.png")); corona->setScale(core::vector3df(planet_type->cloud_scale.X,planet_type->cloud_scale.Y,0)); corona->setRotation(graphics->getSceneManager()->getActiveCamera()->getRotation()); corona->setMaterialFlag(video::EMF_LIGHTING,false); corona->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL); } array_pos = graphics->getSceneManager()->getSceneCollisionManager()->getScreenCoordinatesFrom3DPosition(position,graphics->getSceneManager()->getActiveCamera()); target_array = graphics->getGUIEnvironment()->addImage(graphics->getVideoDriver()->getTexture("res/menu/target_array.png"),array_pos); } //This func is called by the gameManager loop void planet::rotate(f32 frameDeltaTime) { array_pos = graphics->getSceneManager()->getSceneCollisionManager()->getScreenCoordinatesFrom3DPosition(model->getPosition(),graphics->getSceneManager()->getActiveCamera()); target_array->setRelativePosition(vector2d<s32>(array_pos.X-32,array_pos.Y-32)); core::vector3df rot = model->getRotation(); rot.Y+=planet_type->rotation_speed*frameDeltaTime; model->setRotation(rot); if(planet_type->clouds==true) { core::vector3df tmp = cloud->getRotation(); tmp.Y-=planet_type->rotation_speed*frameDeltaTime; cloud->setRotation(tmp); } } //TODO: add planet capture system void planet::planetCapture() { } int planet::getFactionRelation() { return this->factionRelations; } void planet::setFactionRelation(int newrelation) { this->factionRelations = newrelation; } void planet::setFaction(ship_faction faction) { this->faction = faction; } ship_faction planet::getFaction() { return faction; } vector2d<int> planet::getArrayPos() { return this->array_pos; } void planet::setArrayVisible(bool visible) { target_array->setVisible(visible); } core::vector3df planet::getPos() { return this->model->getPosition(); } planet_base *planet::getPlanetType() { return this->planet_type; } void planet::setCloudsVisible(bool visible) { if(planet_type->clouds==true) cloud->setVisible(visible); } planet::~planet() { model->remove(); target_array->remove(); if(planet_type->clouds==true) { cloud->remove(); } if(planet_type->corona==true) { corona->remove(); } } void planet::drop() { delete this; }
/* * Copyright (c) 2020-2021 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_DETAIL_SIZED_ITERATOR_H_ #define CPPSORT_DETAIL_SIZED_ITERATOR_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <utility> #include "attributes.h" #include "iterator_traits.h" namespace cppsort { namespace detail { //////////////////////////////////////////////////////////// // Mostly a hack to avoid some gratuitous performance loss // by passing bidirectional iterators + size to a function // accepting a pair of iterators. It is worse than the // equivalent C++20 features, but should be good enough for // the internal use we make of it. // // NOTE: the full iterator features are not provided, this // is intentional to avoid unintentional uses of the // class in the library's internals. template<typename Iterator> class sized_iterator { public: //////////////////////////////////////////////////////////// // Public types using iterator_category = iterator_category_t<Iterator>; using iterator_type = Iterator; using value_type = value_type_t<Iterator>; using difference_type = difference_type_t<Iterator>; using pointer = pointer_t<Iterator>; using reference = reference_t<Iterator>; //////////////////////////////////////////////////////////// // Constructors sized_iterator() = default; constexpr sized_iterator(Iterator it, difference_type size): _it(std::move(it)), _size(size) {} //////////////////////////////////////////////////////////// // Members access CPPSORT_ATTRIBUTE_NODISCARD auto base() const -> iterator_type { return _it; } CPPSORT_ATTRIBUTE_NODISCARD auto size() const -> difference_type { return _size; } //////////////////////////////////////////////////////////// // Element access CPPSORT_ATTRIBUTE_NODISCARD auto operator*() const -> reference { return *_it; } CPPSORT_ATTRIBUTE_NODISCARD auto operator->() const -> pointer { return &(operator*()); } private: Iterator _it; difference_type _size; }; // Alternative to std::distance meant to be picked up by ADL in // specific places, uses the size of the *second* iterator template<typename Iterator> CPPSORT_ATTRIBUTE_NODISCARD constexpr auto distance(sized_iterator<Iterator>, sized_iterator<Iterator> last) -> difference_type_t<Iterator> { return last.size(); } template<typename Iterator> CPPSORT_ATTRIBUTE_NODISCARD auto make_sized_iterator(Iterator it, difference_type_t<Iterator> size) -> sized_iterator<Iterator> { return { it, size }; } }} #endif // CPPSORT_DETAIL_SIZED_ITERATOR_H_
#ifndef GET_SYS_INFO_H #define GET_SYS_INFO_H #if defined(OS_ANDROID) #include <sys/stat.h> #define PROCESS_ITEM 14//进程CPU时间开始的项数 typedef struct //声明一个occupy的结构体 { unsigned int user; //从系统启动开始累计到当前时刻,处于用户态的运行时间,不包含 nice值为负进程。 unsigned int nice; //从系统启动开始累计到当前时刻,nice值为负的进程所占用的CPU时间 unsigned int system;//从系统启动开始累计到当前时刻,处于核心态的运行时间 unsigned int idle; //从系统启动开始累计到当前时刻,除IO等待时间以外的其它等待时间iowait (12256) 从系统启动开始累计到当前时刻,IO等待时间(since 2.5.41) }total_cpu_occupy_t; typedef struct { pid_t pid;//pid号 unsigned int utime; //该任务在用户态运行的时间,单位为jiffies unsigned int stime; //该任务在核心态运行的时间,单位为jiffies unsigned int cutime;//所有已死线程在用户态运行的时间,单位为jiffies unsigned int cstime; //所有已死在核心态运行的时间,单位为jiffies }process_cpu_occupy_t; unsigned int get_cpu_total_occupy();//获取总的CPU时间 unsigned int get_cpu_process_occupy(const pid_t p);//获取进程的CPU时间 const char* get_items(const char* buffer,int ie);//取得缓冲区指定项的起始地址 #endif namespace youmecommon { unsigned int getCountOfCores(); float getCurrentProcessCPUUsed(); float getCurrentProcessMemoryUsed(); } #endif /* GET_SYS_INFO_H */
#include "ConnectGameState.h" #include "MenuGameState.h" namespace platformer { ConnectGameState::ConnectGameState(Game *game) : game(game) {} void ConnectGameState::onButtonAPress() { stop(); } void ConnectGameState::onButtonBPress() { stop(); } void ConnectGameState::onButtonABPress() { stop(); } void ConnectGameState::onMessage(ByteBuf &) { // No packets should be received in this state. } void ConnectGameState::run() { game->setMultiplayer(true); game->getMicroBit()->radio.enable(); while (game->getState() == this) { // Create and send the broadcast packet. ByteBuf out; out.writeInt(GAME_ID); out.writeInt(game->getId()); out.writeInt(0); out.writePacketType(PacketType::BROADCAST); game->sendPacket(out); // Display "CONNECTING" animation. game->getMicroBit()->display.scrollAsync("CONNECTING", SCROLL_SPEED); // Sleep until next tick should occur. game->getMicroBit()->sleep(TICK_RATE); } // Disable "CONNECTING" scrolling animation. game->getMicroBit()->display.stopAnimation(); MicroBitImage *face = game->getScreen(); face->clear(); if (game->isConnected()) { // Create a happy face. face->setPixelValue(1, 1, 255); face->setPixelValue(3, 1, 255); face->setPixelValue(0, 3, 255); face->setPixelValue(1, 4, 255); face->setPixelValue(2, 4, 255); face->setPixelValue(3, 4, 255); face->setPixelValue(4, 3, 255); } else { // Create a sad face. face->setPixelValue(1, 1, 255); face->setPixelValue(3, 1, 255); face->setPixelValue(0, 4, 255); face->setPixelValue(1, 3, 255); face->setPixelValue(2, 3, 255); face->setPixelValue(3, 3, 255); face->setPixelValue(4, 4, 255); } // Paste face to the screen. game->getMicroBit()->display.image.paste(*face); game->getMicroBit()->sleep(TICK_RATE); delete this; } void ConnectGameState::stop() { // Disable multiplayer. game->disconnect(); // Switch to the menu game state. auto *nextState = new MenuGameState(game); game->setState(nextState); }; }
/** * @file serialretiever.cpp * * @brief Definition of class defined in serialreriever.h * @version 0.1 * @date 2021-07-22 * * @copyright Copyright (c) 2021 * */ #include <Arduino.h> #include "globals.h" #include "serialretriever.h" #include "utils.h" #include "message.h" #include "printer.h" #ifndef SERIALRETIEVER_H #define SERIALRETIEVER_H void SerialRetriever::setupRetriever(){ Utils::LEDSerial::initializeSerial(); } void SerialRetriever::updateRetriever(){ // PRINT("Running Update Serial\n"); // First check if there is some new information available to be read. if(!Utils::LEDSerial::serialAvailable()) return; Message * messageBuffer = this->getMessageBuffer(); // get the message buffer Utils::LEDSerial::readSerialUntil(Utils::LEDSerial::finalSerialByte, messageBuffer->begin()); // read the data into the message buffer this->enqueue_message(messageBuffer); // Enqueue the new message } SerialRetriever::SerialRetriever(){} SerialRetriever::~SerialRetriever(){} #endif
#include <types.hpp> #include <iostream> #include <map> #include <vector> #include <string> #include <tuple> #include <algorithm> #include <random> #ifdef __linux__ #include <GLFW/glfw3.h> #elif __MINGW32__ #include <GLFW/glfw3.h> #elif __WIN32 #include <GL/glfw3.h> #endif #include <types.hpp> #include <property.hpp> #include <shaderman.h> #include <operations.hpp> Transforming::Transforming(const glm::vec3& t, const glm::vec3& a, const glm::vec3& s) : translation(t), rotation(a), scaling(s) { } Transforming::Transforming(float pitch, float yall, float roll) { this->translation = glm::vec3(0.0); this->rotation = glm::vec3(pitch, yall, roll); this->scaling = glm::vec3(1.0); } glm::mat4 Transforming::getMMat() { this->modelMat = glm::translate(this->translation) * glm::eulerAngleXYZ(this->rotation[0], this->rotation[1], this->rotation[2]) * glm::scale(this->scaling); return this->modelMat; } void Transforming::transform(const glm::vec3& t, const glm::vec3& ang, const glm::vec3& s) { this->translation += t; this->scaling += s; this->rotation += ang; } void Transforming::rotate(float pitch, float yall, float roll) { this->rotation += glm::vec3(pitch, yall, roll); } /* void Transforming::draw(const msg_t msg) { (void)msg; const ShaderMan *prog = this->getBindedShader(); prog->useProgram(); glUniformMatrix4fv( glGetUniformLocation(prog->getPid(), this->uniform.c_str()), 1, GL_FALSE, &this->modelMat[0][0]); } */