text
stringlengths
8
6.88M
#ifndef CBASEDATAVIEW_H #define CBASEDATAVIEW_H #include "statviewbase.h" class CBaseDataView : public CStatViewBase { public: explicit CBaseDataView(QWidget *parent = 0); virtual ~CBaseDataView(); protected: QVector <QString> m_vecBoxName; //virtual bool _getStatDataFromFile(QString statFilePath, StatDataPoints *points); }; #endif // CBASEDATAVIEW_H
class Solution { public: int lengthOfLongestSubstring(string s) { int max_length = 0; int hash[256]; fill_n(hash, 256, -1); for(int start=0, i=0;i<s.size();i++){ if(hash[s[i]] != -1){ while(start <= hash[s[i]]){ hash[s[start++]] = -1; } } hash[s[i]] = i; if(i-start+1 > max_length) max_length = i-start+1; } return max_length; } };
#include "stdafx.h" #include "MenuButton.h" #include "../GameCursor.h" MenuButton::~MenuButton() { DeleteGO(m_button); DeleteGO(m_moji); DeleteGO(m_dummy); } bool MenuButton::Start() { m_button = NewGO<SpriteRender>(27, "sp"); m_button->Init(L"Assets/sprite/simple_button.dds", 400.0f, 89.6f); m_dummy = NewGO<SpriteRender>(0, "sp"); m_dummy->Init(L"", 400.0f, 89.6f, true); m_button->SetPosition(m_pos); m_dummy->SetPosition(m_pos); CVector2 po2 = m_pos.ToTwo(); //po2.x -= 60; //po2.y += 40; //if (m_moji != nullptr) //m_moji->SetPosition(po2); return true; } void MenuButton::Update() { m_isClick = false; m_dummy->SetCollisionTarget(m_cursor->GetCursor()); if (m_dummy->isCollidingTarget()) { if (!m_isSelect) { m_button->Init(L"Assets/sprite/simple_button_blue.dds", 400.0f, 89.6f); m_isSelect = true; } if (g_pad[0].IsTrigger(enButtonA) || Mouse::isTrigger(enLeftClick)) { m_isClick = true; } } else { if (m_isSelect) { m_button->Init(L"Assets/sprite/simple_button.dds", 400.0f, 89.6f); m_isSelect = false; } } }
#ifndef IMU_MPU9250_H_ #define IMU_MPU9250_H_ #ifndef __cplusplus #error "Please define __cplusplus, because this is a c++ based file " #endif #include "stm32h7xx_hal.h" #include <array> #include <stdint.h> #include <main.h> using Vector3d = std::array<int16_t, 3>; #define SPI_POLLING_MODE 0 #define SPI_DMA_MODE 1 #define SPI_MODE SPI_POLLING_MODE #define SENSOR_DATA_LENGTH 7 #define IMU_SPI_CS_H HAL_GPIO_WritePin(IMUCS_GPIO_Port, IMUCS_Pin, GPIO_PIN_SET) #define IMU_SPI_CS_L HAL_GPIO_WritePin(IMUCS_GPIO_Port, IMUCS_Pin, GPIO_PIN_RESET) /* magenetometer update at about 100Hz, but the entire sensor data polling process is at 1KHz, should add prescaler for mag */ #define MAG_PRESCALER 4 /* magnetometer has bad noise bacause of the polling process, I think. So, we use a threshold filter method to remove the outlier */ class Imu { public: Imu(){} ~Imu(){} void init(SPI_HandleTypeDef* hspi); static const uint8_t GYRO_DLPF_CFG = 0x01;//0x04 //0: 250Hz, 0.97ms; 3: 41Hz, 5.9ms(kduino); 4: 20Hz: 9.9ms static const uint8_t ACC_DLPF_CFG = 0x03; //0x03: 41Hz, 11.80ms static const uint8_t MAG_ADDRESS = 0x0C; static const uint8_t MAG_DATA_REGISTER = 0x03; static const uint8_t GYRO_ADDRESS = 0x43; static const uint8_t ACC_ADDRESS = 0x3B; static const uint8_t MAG_SPI_ADDRESS = 0x49; static uint8_t adc_[SENSOR_DATA_LENGTH]; void update(); bool getUpdate() { return update_; } void setUpdate(bool update) { update_ = update; } Vector3d getAcc(){return acc_;} Vector3d getGyro(){return gyro_;} Vector3d getMag(){return mag_;} ImuData getData() { ImuData data; data.acc[0] = getAcc()[0]; data.acc[1] = getAcc()[1]; data.acc[2] = getAcc()[2]; data.gyro[0] = getGyro()[0]; data.gyro[1] = getGyro()[1]; data.gyro[2] = getGyro()[2]; data.mag[0] = getMag()[0]; data.mag[1] = getMag()[1]; data.mag[2] = getMag()[2]; return data; } private: SPI_HandleTypeDef* hspi_; Vector3d acc_, gyro_, mag_; uint8_t dummy_[SENSOR_DATA_LENGTH]; bool update_; void gyroInit(void); void accInit(void); void magInit(void); void pollingRead (void); void process (void); void mpuWrite(uint8_t address, uint8_t value); uint8_t mpuRead(uint8_t address); }; #endif
#include "NaivePar.h" std::string NaivePar::name() { return "Naive Algorithm, split range array"; } int* NaivePar::find(int min, int max, int* size) { int arraySize = max - min; bool* array = new bool[arraySize]; *size = 0; #pragma omp parallel { int localSize = 0; #pragma omp for schedule(dynamic) for (int i = 0; i < arraySize; i++) { if (checkPrime(min + i)) { array[i] = true; localSize++; } else array[i] = false; } #pragma omp atomic (*size) += localSize; } int* result = new int[*size]; int j = 0; for (int i = 0; i < arraySize; i++) { if (array[i]) result[j++] = min + i; } delete[] array; return result; }
#pragma once #include "../string_view.hh" #include <array> static const std::array<bool, 256> is_dropped = []() { std::array<bool, 256> delimiters{false}; const string_view DELIMITERS = " \t.,:;?!\"'[]{}|&*=+-_()#"; for (const auto c: DELIMITERS) delimiters[c] = true; return delimiters; }(); class Tokenizer { public: using InputIterator = const char*; InputIterator next; const InputIterator end; string_view get_next() { for (; next != end && is_dropped[*next]; ++next) { } const auto start = next; for (; next != end && !is_dropped[*next]; ++next) { } return string_view(&(*start), next-start); } };
/* -*- 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. ** psmaas - Patricia Aas */ #include "core/pch.h" #ifdef HISTORY_SUPPORT #include "modules/history/OpHistorySiteFolder.h" #include "modules/history/OpHistorySiteSubFolder.h" /*___________________________________________________________________________*/ /* CORE HISTORY MODEL SITE SUB FOLDER */ /*___________________________________________________________________________*/ /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS HistorySiteSubFolder::GetTitle(OpString & title) const { return GetSiteFolder()->GetTitle(title); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ const OpStringC & HistorySiteSubFolder::GetTitle() const { return GetSiteFolder()->GetTitle(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ const LexSplayKey * HistorySiteSubFolder::GetKey() const { return GetSiteFolder()->GetKey(); } #endif // HISTORY_SUPPORT
#pragma once #include "plbase/PluginBase.h" #pragma pack(push, 4) class PLUGIN_API CDoor { public: float m_fOpenAngle; float m_fClosedAngle; short m_nDirn; unsigned char m_nAxis; unsigned char m_nDoorState; float m_fAngle; float m_fPrevAngle; float m_fAngVel; }; #pragma pack(pop) VALIDATE_SIZE(CDoor, 0x18);
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2007 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef DBCS_ENCODER_H #define DBCS_ENCODER_H #if defined ENCODINGS_HAVE_TABLE_DRIVEN && (defined ENCODINGS_HAVE_CHINESE || defined ENCODINGS_HAVE_KOREAN) #include "modules/encodings/encoders/outputconverter.h" /** Convert UTF-16 into simple row-cell encoding */ class UTF16toDBCSConverter : public OutputConverter { public: enum encoding { #ifdef ENCODINGS_HAVE_CHINESE BIG5, ///< Use Big5 encoding GBK, ///< Use GBK (>= GB2312 = EUC-CN) encoding #endif #ifdef ENCODINGS_HAVE_KOREAN EUCKR ///< Use EUC-KR (= KSC 5 601) encoding #endif }; UTF16toDBCSConverter(enum encoding); virtual OP_STATUS Construct(); virtual ~UTF16toDBCSConverter(); virtual int Convert(const void *src, int len, void *dest, int maxlen, int *read); virtual const char *GetDestinationCharacterSet(); virtual int ReturnToInitialState(void *) { return 0; }; virtual int LongestSelfContainedSequenceForCharacter() { return 2; }; private: const unsigned char *m_maptable1, *m_maptable2; long m_table1start, m_table1top, m_table2len; enum encoding m_my_encoding; }; #endif // ENCODINGS_HAVE_TABLE_DRIVEN && (ENCODINGS_HAVE_CHINESE || ENCODINGS_HAVE_KOREAN) #endif // DBCS_ENCODER_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #ifdef SUPPORT_PROBETOOLS #include "modules/probetools/probetools_module.h" #include "modules/probetools/src/probehelper.h" #include "modules/probetools/src/probesnapshot.h" #include "modules/probetools/src/probereportwriter.h" #include "modules/url/url_man.h" ProbetoolsModule::ProbetoolsModule() : m_probehelper(OP_NEW(OpProbeHelper,())) { } void ProbetoolsModule::InitL(const OperaInitInfo& info) { OpProbeTimestamp now; now.timestamp_now(); LEAVE_IF_NULL(m_probehelper); OpString tmp; tmp.SetL(info.default_folders[OPFILE_HOME_FOLDER]); tmp.AppendL("probedata"); tmp.AppendL(PATHSEP); # if ENABLED_OP_PROBE_LOG int pos = tmp.Length(); tmp.AppendL("probelog.txt"); m_probelog_filename.SetL(tmp); tmp.Delete(pos); // remove after "probedata/" to append the new name: # endif //ENABLED_OP_PROBE_LOG tmp.AppendL("probereport.txt"); m_probereport_filename.TakeOver(tmp); } void ProbetoolsModule::Destroy() { if (m_probehelper->get_probe_graph()) { //Take probe snapshot and write the report. OpProbeSnapshot* probe_report_snapshot = OpProbeSnapshotBuilder::build_probetools_snapshot(m_probehelper->get_probe_graph()); if(probe_report_snapshot){ OpProbereportWriter probe_report_writer; probe_report_writer.write_report(probe_report_snapshot, m_probehelper->get_session_time(), m_probereport_filename, m_probelog_filename); OP_DELETE(probe_report_snapshot); }/* else { //We got OOM! }*/ } OP_DELETE(m_probehelper); m_probehelper = 0; } #endif // SUPPORT_PROBETOOLS
#ifndef SOLDIER_HPP #define SOLDIER_HPP class Soldier { SDL_Point center; SDL_Rect Pos, TestPos; Vector2Df Vel; int frame, anim; float health; double rad, deadangle; bool musflag; SDL_Rect Clip[4]; SoldierState state; std::vector<Bullet> bullets; int x, y; public: void Init(); void Update(int mouseX, int mouseY, std::vector<Zombie>* zombies); void Fire(); void Render(); SDL_Point getPos(); std::vector<Bullet>* getBulletVector(); int getHealth(); SDL_Rect* getRect(); void TestMove(); SoldierState getSolState(); }; #endif
/** * @file messageretriever.cpp * * @brief Defines some of the base class functionality for the classes that inhert this class to use. * @version 0.1 * @date 2021-06-23 * * @copyright Copyright (c) 2021 * */ #include "messageretriever.h" #include "message.h" #ifndef MESSAGERETRIEVER_CPP #define MESSAGERETRIEVER_CPP Message * MessageRetrieverBase::getMessageBuffer(){ Message * messageBuffer; // This is where we determine what kind of buffer we need. // We will always attempt to use the internal static buffer if it is free, // but in the case that it is not available, we will use a dynmic buffer. if(staticbufferAvailable){ staticbufferAvailable = false; // Will be freed upon deletion of this buffer messageBuffer = new Message(this->messageBuffer, Message::MessageType::StaticMessage, & staticbufferAvailable); }else{ messageBuffer = new Message(MessageRetrieverBase::getDynamicBuffer(), Message::MessageType::DynamicMessage, & throwaway); } return messageBuffer; } void MessageRetrieverBase::enqueue_message(Message * msgPtr){ if(messages.queue_full()) return msgPtr->DestroyMessage(); // Do nothing with the message if the queue is full. messages.push(msgPtr); } bool MessageRetrieverBase::isMessageAvailable(){ return messages.size() != 0; } Message * MessageRetrieverBase::getNewMessage(){ Message * tmpMsg = messages.next(); messages.pop(); return tmpMsg; } MessageRetrieverBase::~MessageRetrieverBase(){ } #endif
/**************************************************************** * TianGong RenderLab * * Copyright (c) Gaiyitp9. All rights reserved. * * This code is licensed under the MIT License (MIT). * *****************************************************************/ #pragma once #include <iostream> void OutputPPMImage() { const int imageWidth = 256; const int imageHeight = 256; std::cout << "P3\n" << imageWidth << ' ' << imageHeight << "\n255\n"; for (int j = imageHeight - 1; j >= 0; --j) { for (int i = 0; i < imageWidth; ++i) { double r = double(i) / (imageWidth - 1); double g = double(j) / (imageHeight - 1); double b = 0.25; int ir = static_cast<int>(255.999 * r); int ig = static_cast<int>(255.999 * g); int ib = static_cast<int>(255.999 * b); std::cout << ir << ' ' << ig << ' ' << ib << '\n'; } } }
// // Monitor.cpp // Odin.MacOSX // // Created by Daniel on 16/06/15. // Copyright (c) 2015 DG. All rights reserved. // #include "Monitor.h" namespace odin { namespace io { Monitor::Monitor(MonitorHandle* handle): m_handle(handle) { m_isPrimaryMonitor = (m_handle == lib::getPrimaryMonitor()); m_monitorName = lib::getMonitorName(m_handle); lib::getMonitorPhysicalSize(m_handle, m_physicalHeight, m_physicalWidth); m_supportedVideoModes = lib::getMonitorVideoModes(m_handle); } MonitorHandle* Monitor::getHandle() const { return m_handle; } const std::string& Monitor::getName() const { return m_monitorName; } bool Monitor::isPrimaryMonitor() const { return m_isPrimaryMonitor; } void Monitor::getPhysicalSize(int &height, int &width) const { height = m_physicalHeight; width = m_physicalWidth; } VideoMode Monitor::getCurrentVideoMode() const { return lib::getMonitorVideoMode(m_handle); } const std::vector<VideoMode>& Monitor::getSupportedVideoModes() const { return m_supportedVideoModes; } void Monitor::setGamma(float value) { lib::setMonitorGamma(m_handle, value); } } }
#include <string> #include <vector> //#include "stdafx.h" using namespace std; class TreeNode { public: TreeNode(); struct node{ string data; node* firstchild = NULL; node* sibling = NULL; }; node root; node decl; node func; node packages; node imports; node* createNode(string val); void traverse(node* parent, int depth); void insertNodes(node* parent, string val); void addSibling(node* sibling, node* child); };
#include<bits/stdc++.h> using namespace std; char a[6]={'a','a','b','b'}; int main(){ int n; cin>>n; int cnt=0; for(int i=0;i<n;i++){ printf("%c",a[cnt]); cnt++; if(cnt==4) cnt=0; } return 0; }
//算法:卡特兰数/递推/dp //题目要求 //对于一个栈 // 给定的n个数 //计算并输出由操作数序列1,2,…,n, //经过操作可能得到的输出序列的总数。 //很明显,就是卡特兰数 //直接递推即可 #include<cstdio> using namespace std; int n; int f[20]={1,1}; int main() { scanf("%d",&n); for(int i=2;i<=n;i++)//递推公式 for(int j=0;j<=i-1;j++) f[i]+=(f[j]*f[i-j-1]); printf("%d",f[n]); }
/************************************************************************/ /* 给定一整型数组,若数组中某个下标值大的元素值小于某个下标值比它小的元素值,称这是一个反序。 即:数组 a[]; 对于 i < j 且 a[i] > a[j],则称这是一个反序。 给定一个数组,要求写一个函数,计算出这个数组里所有反序的个数。 */ /************************************************************************/ #include <vector> using namespace std; class Solution{ public: Solution(){ number = 0; } void ReversePair(int Array[], int n){ Split(Array, 0, n - 1); } private: int number; void Split(int Array[], int start, int end){ if(start == end){ return; } int mid = int ((start + end) / 2); Split(Array, start, mid); Split(Array, mid + 1, end); Merge(Array, start, mid, end); } void Merge(int Array[], int start, int mid, int end){ vector<int> tempArray; int i = start, j = mid + 1; while(i <= mid && j <= end){ if(Array[i] <= Array[j]){ tempArray.push_back(Array[i]); ++i; } else{ tempArray.push_back(Array[j]); number += mid - i + 1; ++j; } } while(i <= mid){ tempArray.push_back(Array[i]); ++i; } while(j <= end){ tempArray.push_back(Array[j]); ++j; } for(int i = start; i <= end; ++i){ Array[i] = tempArray[i - start]; } } }; // //int main(){ // Solution solution; // int A[] = {7,6,5,4,3,2,1}; // solution.ReversePair(A, sizeof(A) / sizeof(A[0])); // return 0; //}
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * 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. */ #include "core/pch.h" #include "modules/probetools/probepoints.h" #include "modules/logdoc/logdoc_util.h" #include "modules/logdoc/logdoc.h" #include "modules/logdoc/html_att.h" #include "modules/logdoc/src/html5/html5tokenwrapper.h" #include "modules/logdoc/src/html5/html5attrcopy.h" #include "modules/logdoc/src/htmlattrentry.h" #ifndef HTML5_STANDALONE #include "modules/logdoc/htm_lex.h" // for LogdocXmlName #endif // HTML5_STANDALONE /*virtual*/ HTML5TokenWrapper::~HTML5TokenWrapper() { OP_DELETEA(m_attr_copies); #ifndef HTML5_STANDALONE OP_DELETEA(m_attr_entries); OP_DELETE(m_tag_name); #endif // HTML5_STANDALONE } void HTML5TokenWrapper::CreateAttributesCopyL(const HTML5TokenWrapper &src_token) { OP_ASSERT(!m_attr_copies); // we already have a copy array! BOOL src_has_copy = src_token.m_attr_copies != NULL; // in case src is the same as this, check what the value is before we allocate a new array m_attr_copies_length = src_token.GetAttrCount(); if (m_attr_copies_length) { m_attr_copies = OP_NEWA_L(HTML5AttrCopy, m_attr_copies_length); if (src_has_copy) { for (unsigned attr_i = 0; attr_i < m_attr_copies_length; attr_i++) m_attr_copies[attr_i].CopyL(&src_token.m_attr_copies[attr_i]); } else { for (unsigned attr_i = 0; attr_i < m_attr_copies_length; attr_i++) m_attr_copies[attr_i].CopyL(src_token.GetAttribute(attr_i)); } } else m_attr_copies = NULL; } void HTML5TokenWrapper::CopyL(HTML5TokenWrapper &src_token) { HTML5Token::TokenType type = src_token.GetType(); OP_ASSERT(type == HTML5Token::START_TAG); // only used for formating elements HTML5TokenBuffer *name = src_token.GetName(); InitializeL(0, 0); Reset(type); SetNameL(name); SetLineNum(src_token.GetLineNum()); SetLinePos(src_token.GetLinePos()); CreateAttributesCopyL(src_token); m_elm_type = src_token.m_elm_type; m_ns = src_token.m_ns; m_skipped_spaces = src_token.m_skipped_spaces; } void HTML5TokenWrapper::ResetWrapper() { m_elm_type = Markup::HTE_UNKNOWN; m_ns = Markup::HTML; m_skipped_spaces = 0; if (m_attr_copies) OP_DELETEA(m_attr_copies); m_attr_copies = NULL; m_attr_copies_length = 0; } BOOL HTML5TokenWrapper::HasAttribute(const uni_char *name, unsigned &attr_idx) { unsigned name_length = uni_strlen(name); if (m_attr_copies) { unsigned attr_count = m_attr_copies_length; for (unsigned i = 0; i < attr_count; i++) { HTML5AttrCopy *attr = &m_attr_copies[i]; if (attr->GetName()->IsEqualTo(name, name_length)) { attr_idx = i; return TRUE; } } } else { unsigned attr_count = GetAttrCount(); for (unsigned i = 0; i < attr_count; i++) { HTML5Attr *attr = GetAttribute(i); if (attr->GetName()->IsEqualTo(name, name_length)) { attr_idx = i; return TRUE; } } } return FALSE; } void HTML5TokenWrapper::SetAttributeValueL(unsigned attr_idx, const uni_char* value) { if (!m_attr_copies) // need to have a copy, don't want to change the original CreateAttributesCopyL(*this); if (attr_idx >= m_attr_copies_length) { OP_ASSERT(!"Don't try to set an attribute which doesn't already exist"); return; } m_attr_copies[attr_idx].SetValueL(value, uni_strlen(value)); } BOOL HTML5TokenWrapper::AttributeHasValue(unsigned attr_idx, const uni_char *value) { if (m_attr_copies) { OP_ASSERT(m_attr_copies_length > attr_idx); return uni_stri_eq(value, m_attr_copies[attr_idx].GetValue()); } else { OP_ASSERT(GetAttrCount() > attr_idx); if (HTML5Attr *attr = GetAttribute(attr_idx)) return attr->GetValue().Matches(value, FALSE); } return FALSE; } BOOL HTML5TokenWrapper::RemoveAttributeL(const uni_char *name) { // only implemented for m_attr_copies - need to make copies if we actually remove otherwise OP_ASSERT(m_attr_copies || HTML5Token::GetAttrCount() == 0); if (!m_attr_copies) return FALSE; unsigned attr_count = m_attr_copies_length; unsigned name_length = uni_strlen(name); for (unsigned i = 0; i < attr_count; i++) { HTML5AttrCopy *attr = &m_attr_copies[i]; if (attr->GetName()->IsEqualTo(name, name_length)) // this is the one to remove { // order doesn't matter for attributes, so copy the last attribute into // this position, and remove decrease array length if (i < attr_count - 1) { HTML5TokenBuffer *name_buffer = m_attr_copies[attr_count - 1].GetName(); attr->SetNameL(name_buffer); uni_char *attr_value = m_attr_copies[attr_count - 1].GetValue(); attr->SetValueL(attr_value, attr_value ? uni_strlen(attr_value) : 0); } m_attr_copies_length--; return TRUE; } } return FALSE; } unsigned HTML5TokenWrapper::GetAttrCount() const { if (m_attr_copies) return m_attr_copies_length; else return HTML5Token::GetAttrCount(); } BOOL HTML5TokenWrapper::GetAttributeL(unsigned index, HTML5TokenBuffer *&name, uni_char *&value, unsigned &value_len) { OP_PROBE7_L(OP_PROBE_HTML5TOKENWRAPPER_GETATTRIBUTEL); if (m_attr_copies) { OP_ASSERT(index < m_attr_copies_length); name = m_attr_copies[index].GetName(); value = m_attr_copies[index].GetValue(); value_len = value ? uni_strlen(value) : 0; return FALSE; } else { HTML5Attr *attr = GetAttribute(index); name = attr->GetName(); return attr->GetValue().GetBufferL(value, value_len, FALSE); } } BOOL HTML5TokenWrapper::GetAttributeValueL(const uni_char *name, uni_char *&value, unsigned &value_len, unsigned* attr_idx_param) { value = NULL; unsigned attr_index; if (HasAttribute(name, attr_index)) { if (attr_idx_param) *attr_idx_param = attr_index; HTML5TokenBuffer *dummy_name = NULL; return GetAttributeL(attr_index, dummy_name, value, value_len); } return FALSE; } #ifndef HTML5_STANDALONE uni_char* HTML5TokenWrapper::GetUnescapedAttributeValueL(const uni_char* attribute, unsigned* attr_idx) { uni_char* value; unsigned value_len; BOOL must_delete = GetAttributeValueL(attribute, value, value_len, attr_idx); if (value) { uni_char* link_str; if (!must_delete) // we don't own buffer, make a copy that we do own, so that we can replace characters link_str = UniSetNewStrN(value, value_len); else link_str = value; ReplaceEscapes(link_str, FALSE, FALSE, FALSE); return link_str; } return NULL; } /** * Adjusts casing of attribute names for elements in foreign content. * @param[out] hae The attribute entry to change if needed. */ static void AdjustForeignAttr(HtmlAttrEntry *hae) { const uni_char *attr_name = hae->name; if (*attr_name == 'x') { const uni_char *prefix_end = uni_strchr(attr_name, ':'); if (prefix_end) { int attr_ns_idx = Markup::HTML; if (uni_strncmp(attr_name, UNI_L("xlink"), prefix_end - attr_name) == 0) attr_ns_idx = NS_IDX_XLINK; else if (uni_strncmp(attr_name, UNI_L("xml"), prefix_end - attr_name) == 0) attr_ns_idx = NS_IDX_XML; else if (uni_strncmp(attr_name, UNI_L("xmlns"), prefix_end - attr_name) == 0) attr_ns_idx = NS_IDX_XMLNS; prefix_end++; // drop the ':' BOOL recognized = FALSE; if (attr_ns_idx == NS_IDX_XLINK) { recognized = uni_str_eq(prefix_end, UNI_L("actuate")) || uni_str_eq(prefix_end, UNI_L("arcrole")) || uni_str_eq(prefix_end, UNI_L("href")) || uni_str_eq(prefix_end, UNI_L("role")) || uni_str_eq(prefix_end, UNI_L("show")) || uni_str_eq(prefix_end, UNI_L("title")) || uni_str_eq(prefix_end, UNI_L("type")); } else if (attr_ns_idx == NS_IDX_XML) { recognized = uni_str_eq(prefix_end, UNI_L("base")) || uni_str_eq(prefix_end, UNI_L("lang")) || uni_str_eq(prefix_end, UNI_L("space")); } else if (attr_ns_idx == NS_IDX_XMLNS) recognized = uni_str_eq(prefix_end, UNI_L("xlink")); if (recognized) { hae->name = prefix_end; hae->ns_idx = attr_ns_idx; } } else if (uni_str_eq(attr_name, UNI_L("xmlns"))) hae->ns_idx = NS_IDX_XMLNS; } } HtmlAttrEntry* HTML5TokenWrapper::GetOrCreateAttrEntries(unsigned &token_attr_count, unsigned &extra_attr_count, LogicalDocument *logdoc) { token_attr_count = GetAttrCount(); // limit the number of attributes to copy because we only have // so many bits to store the attribute array size in the element. if (token_attr_count > HTML5TokenWrapper::kMaxAttributeCount) token_attr_count = HTML5TokenWrapper::kMaxAttributeCount; extra_attr_count = token_attr_count; if (m_elm_type == Markup::HTE_COMMENT) extra_attr_count += 1; // for content else if (m_elm_type == Markup::HTE_DOCTYPE) extra_attr_count += 3; // for name, pubid and sysid else if (m_elm_type == Markup::HTE_UNKNOWN) extra_attr_count += 1; // for tag name unsigned needed_attr_array_size = extra_attr_count + 1; if (needed_attr_array_size > m_attr_entries_length) { // +1 to make some room for the trailing ATTR_NULL HtmlAttrEntry *new_entries = OP_NEWA(HtmlAttrEntry, needed_attr_array_size); if (!new_entries) return NULL; OP_DELETEA(m_attr_entries); m_attr_entries = new_entries; m_attr_entries_length = needed_attr_array_size; } HtmlAttrEntry *hae = m_attr_entries; for (unsigned i = 0; i < token_attr_count; i++, hae++) { uni_char *attr_val; HTML5TokenBuffer *name_buf = NULL; hae->ns_idx = NS_IDX_DEFAULT; hae->is_specified = TRUE; hae->is_special = FALSE; hae->delete_after_use = GetAttributeL(i, name_buf, attr_val, hae->value_len); hae->name = name_buf->GetBuffer(); hae->name_len = name_buf->Length(); hae->value = attr_val; // substitute foreign attributes in foreign elements if (m_ns == Markup::HTML) hae->attr = g_html5_name_mapper->GetAttrTypeFromTokenBuffer(name_buf); else { AdjustForeignAttr(hae); hae->attr = g_html5_name_mapper->GetAttrTypeFromName(hae->name, FALSE, m_ns); } hae->is_id = hae->attr == Markup::HA_ID; } if (m_elm_type == Markup::HTE_COMMENT) { uni_char *data; hae->ns_idx = NS_IDX_DEFAULT; hae->is_specified = FALSE; hae->is_special = FALSE; hae->is_id = FALSE; hae->attr = Markup::HA_CONTENT; hae->delete_after_use = GetData().GetBufferL(data, hae->value_len, TRUE); hae->value = data; hae++; } else if (m_elm_type == Markup::HTE_DOCTYPE) { hae->ns_idx = NS_IDX_DEFAULT; hae->attr = Markup::HA_NAME; hae->is_specified = FALSE; hae->is_special = FALSE; hae->delete_after_use = FALSE; hae->is_id = FALSE; hae->value = GetNameStr(); hae->value_len = GetNameLength(); hae++; hae->ns_idx = SpecialNs::NS_LOGDOC; hae->attr = ATTR_PUB_ID; hae->is_specified = FALSE; hae->is_special = TRUE; hae->delete_after_use = FALSE; hae->is_id = FALSE; if (HasPublicIdentifier()) GetPublicIdentifier(hae->value, hae->value_len); else { hae->value = NULL; hae->value_len = 0; } hae++; hae->ns_idx = SpecialNs::NS_LOGDOC; hae->attr = ATTR_SYS_ID; hae->is_specified = FALSE; hae->is_special = TRUE; hae->delete_after_use = FALSE; hae->is_id = FALSE; if (HasSystemIdentifier()) { GetSystemIdentifier(hae->value, hae->value_len); if (!hae->value) { hae->value = UNI_L(""); hae->value_len = 0; } } else { hae->value = NULL; hae->value_len = 0; } logdoc->SetDoctype((hae - 2)->value, (hae - 1)->value, hae->value); hae++; } else if (m_elm_type == Markup::HTE_UNKNOWN) { hae->attr = ATTR_XML_NAME; hae->ns_idx = SpecialNs::NS_LOGDOC; hae->is_id = FALSE; hae->is_special = TRUE; hae->is_specified = FALSE; hae->delete_after_use = FALSE; hae->name = NULL; hae->name_len = 0; if (!m_tag_name) { m_tag_name = OP_NEW(LogdocXmlName, ()); if (m_tag_name == NULL) return NULL; } m_tag_name->SetName(GetNameStr(), GetNameLength(), FALSE); hae->value = reinterpret_cast<uni_char*>(m_tag_name); hae->value_len = 0; hae++; } hae->attr = ATTR_NULL; return m_attr_entries; } void HTML5TokenWrapper::DeleteAllocatedAttrEntries() { HtmlAttrEntry *hae = m_attr_entries; while (hae->attr != ATTR_NULL) { if (hae->delete_after_use) OP_DELETEA(const_cast<uni_char*>(hae->value)); hae++; } } #endif // HTML5_STANDALONE HTML5AttrCopy* HTML5TokenWrapper::GetLocalAttrCopy(unsigned index) { return &m_attr_copies[index]; } BOOL HTML5TokenWrapper::IsEqual(HTML5TokenWrapper &token) { // token should always be a non-copied token // and this should always be a copied one OP_ASSERT(!token.m_attr_copies); if (m_elm_type != token.GetElementType() || m_ns != token.GetElementNs()) return FALSE; unsigned attr_count = token.GetAttrCount(); if (attr_count != m_attr_copies_length) return FALSE; for (unsigned attr_i = 0; attr_i < m_attr_copies_length; attr_i++) { if (!m_attr_copies[attr_i].IsEqual(token.GetAttribute(attr_i))) return FALSE; } return TRUE; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2002 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef DOM_PROCINST_H #define DOM_PROCINST_H #include "modules/dom/src/domcore/chardata.h" class DOM_EnvironmentImpl; class DOM_ProcessingInstruction : public DOM_CharacterData { protected: friend class DOM_EnvironmentImpl; DOM_ProcessingInstruction(); public: static OP_STATUS Make(DOM_ProcessingInstruction *&procinst, DOM_Node *reference, const uni_char *target, const uni_char *data); virtual ES_GetState GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime); virtual ES_PutState PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime); virtual BOOL IsA(int type) { return type == DOM_TYPE_PROCESSINGINSTRUCTION || DOM_CharacterData::IsA(type); } }; #endif // DOM_PROCINST_H
//MyCat.cpp //Aaron Nicanor //anicanor #include <iostream> #include <fstream> #include <string> #include <assert.h> using namespace std; int main(int argc, char *argv[]){ if (argc < 3){ cerr << "Must specify input and output file." << endl; return 1; } if (argc > 3){ cerr << "Too many command line arguments specified." << endl; return 1; } ifstream my_ifile(argv[1], ios::in); ofstream my_ofile(argv[2], ios::out); if (!my_ofile){ cerr << "Could not open output file <" << argv[2] << ">." << endl; return 1; } if (!my_ifile){ cerr << "Could not open input file <" << argv[1]<< ">."<<endl; return 1; } string buffer; while (getline(my_ifile, buffer, '\n')){ my_ofile << buffer << endl; } return 0; }
// // LayeredSample.hpp // DrumConsole // // Created by Paolo Simonazzi on 22/01/2016. // // #ifndef LayeredSample_hpp #define LayeredSample_hpp const int numOfLayersUsed = 3; class LayeredSample : public AudioSource { public: LayeredSample ( void ); ~LayeredSample ( void ); void tryMe ( void ); void prepareToPlay ( int samplesPerBlockExpected, double sampleRate ) override; void releaseResources ( void ) override; void getNextAudioBlock ( const AudioSourceChannelInfo& bufferToFill ) override; void playSampleByVolume ( float volume ); void createSample ( int idx, const File& audioFile ); void start ( void ); void loadFileIntoSample ( int idx, const String& fileToLoad ); private: void playSample ( int idx, float volume ); AudioFormatManager formatManager; AudioTransportSource transportSampleSource; AudioSourcePlayer audioSourcePlayerSnare; AudioSourcePlayer audioSourcePlayerSnareLayered; File sampleFile[numOfLayersUsed]; AudioFormatReaderSource* readerSourceSamples[numOfLayersUsed]; MixerAudioSource samplesMixed; }; #endif /* LayeredSample_hpp */
#pragma once namespace eXistenZ { namespace Javascript { JSObject* CreateInputManagerObject(InputManager* manager); void DestroyInputManagerObject(InputManager* manager); } }
class 30Rnd_6x35_KAC: CA_Magazine { scope = 2; displayName = $STR_DZ_MAG_30RND_KACPDW_NAME; descriptionShort = $STR_DZ_MAG_30RND_KACPDW_DESC; picture = "\RH_pdw\inv\m_30pdw_ca.paa"; model = "\RH_pdw\RH_pdw_mag.p3d"; ammo = "B_6x35_Ball"; count = 30; initSpeed = 930; lastroundstracer = 0; class ItemActions { COMBINE_MAG }; };
// Created on: 2003-06-04 // Created by: Galina KULIKOVA // Copyright (c) 2003-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 _StepDimTol_ModifiedGeometricTolerance_HeaderFile #define _StepDimTol_ModifiedGeometricTolerance_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepDimTol_LimitCondition.hxx> #include <StepDimTol_GeometricTolerance.hxx> class TCollection_HAsciiString; class StepBasic_MeasureWithUnit; class StepDimTol_GeometricToleranceTarget; class StepRepr_ShapeAspect; class StepDimTol_ModifiedGeometricTolerance; DEFINE_STANDARD_HANDLE(StepDimTol_ModifiedGeometricTolerance, StepDimTol_GeometricTolerance) //! Representation of STEP entity ModifiedGeometricTolerance class StepDimTol_ModifiedGeometricTolerance : public StepDimTol_GeometricTolerance { public: //! Empty constructor Standard_EXPORT StepDimTol_ModifiedGeometricTolerance(); //! Initialize all fields (own and inherited) AP214 Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& theGeometricTolerance_Name, const Handle(TCollection_HAsciiString)& theGeometricTolerance_Description, const Handle(StepBasic_MeasureWithUnit)& theGeometricTolerance_Magnitude, const Handle(StepRepr_ShapeAspect)& theGeometricTolerance_TolerancedShapeAspect, const StepDimTol_LimitCondition theModifier); //! Initialize all fields (own and inherited) AP242 Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& theGeometricTolerance_Name, const Handle(TCollection_HAsciiString)& theGeometricTolerance_Description, const Handle(StepBasic_MeasureWithUnit)& theGeometricTolerance_Magnitude, const StepDimTol_GeometricToleranceTarget& theGeometricTolerance_TolerancedShapeAspect, const StepDimTol_LimitCondition theModifier); //! Returns field Modifier Standard_EXPORT StepDimTol_LimitCondition Modifier() const; //! Set field Modifier Standard_EXPORT void SetModifier (const StepDimTol_LimitCondition theModifier); DEFINE_STANDARD_RTTIEXT(StepDimTol_ModifiedGeometricTolerance,StepDimTol_GeometricTolerance) protected: private: StepDimTol_LimitCondition myModifier; }; #endif // _StepDimTol_ModifiedGeometricTolerance_HeaderFile
#pragma once #ifndef HEAPSORT_H #define HEAPSORT_H #include <vector> class Heapsort { public: Heapsort(); ~Heapsort(); int heapSort(std::vector<int> &vec); private: void heapify(std::vector<int> &vec, int n, int i); }; #endif
/* Author: Michael Martin CSCE 236 Embedded Systems - UNL Spring 2020 Semester Driver for robot obstacle avoidance project using Atmega 328p Distances were changed to pure values returned by ultrasonic sensor to greater increase the accuracy of measurement. */ #include "robotlib.h" #include "motors.h" #include <math.h> void setupForOAM(){ setupLED(); setupMotors(); setForwardSpeed(80); } volatile int f = 0; //front distance volatile int r = 0; // right distance volatile int rp = 0; //right previous distance bool turned = false; bool first = true; void AvoidanceMode(){ stopMotors(); rp = r; //save right previous distance LEDoff(); turnServoFront(); delay(50); detect(FORWARD); f = getDistance(FORWARD); turnServoRight(); detect(RIGHT); r = getDistance(RIGHT); Serial.println(r); if(first){ first = false; return; } //90 degree left turn when we reach an obstacle if(f <= 15*38){ RedON(); GreenON(); leftMotors(100); delay(250); turned = true; return; } //fwd clear and right clear, 90 degrees right turn if(r >= 20*38 && f > 20*38 && !turned){ RedON(); BlueON(); forwardMotors(); delay(800); stopMotors(); rightMotors(90); forwardMotors(); delay(1000); turned = true; } //turn left if too close to wall or closer than last scanned else if(((r < rp - 40) || (r < 220)) && !turned){ BlueON(); leftMotors(20); forwardMotors(); delay(300); LEDoff(); // turned = true; } //turn right if too far from wall or farther than last scanned. else if (((r > rp + 40) || (r > 500)) && !turned){ RedON(); rightMotors(20); forwardMotors(); delay(300); LEDoff(); // turned = true; } //other conditions not met, go forward and rescan else{ GreenON(); forwardMotors(); delay(1000); turned = false; } }
#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);} template<class T> inline bool chmax(T& a, T b) {if (a < b) {a = b; return true;} return false;} template<class T> inline bool chmin(T& a, T b) {if (a > b) {a = b; return true;} return false;} const int n_max = 200050; vector<vector<int>> tree(n_max); void bfs(vector<int> &bin){ int start = 0; queue<int> q; q.push(start); bin[start] = 1; while (!q.empty()){ int now = q.front(); q.pop(); for(auto next: tree[now]){ if (bin[next] != 0) continue; bin[next] = -bin[now]; q.push(next); } } } int main() { int n; cin >> n; vector<int> a(n); rep(i, n-1){ int a,b; cin >> a >> b; a--; b--; tree[a].push_back(b); tree[b].push_back(a); } vector<int> bin(n_max, 0); bfs(bin); vector<int> plus; vector<int> minus; rep(i, n){ if (bin[i] == 1) plus.push_back(i); else minus.push_back(i); } int plus_num = plus.size(); int minus_num = minus.size(); int div3_num = n/3; if (plus_num <= n/3 || minus_num <= n/3){ } else { } }
#include "zoomslider.h" // ___________________Class ZoomSlider___________________ ZoomSlider::ZoomSlider(QWidget *parent) : QWidget(parent) { hide(); m_layout = new QVBoxLayout; setLayout(m_layout); m_slider.setSingleStep(1); m_slider.setOrientation(Qt::Horizontal); m_slider.setMinimum(-4); m_slider.setMaximum(4); m_slider.setSliderPosition(0); m_map.insert(-4, 0.25); m_map.insert(-3, 0.33); m_map.insert(-2, 0.5); m_map.insert(-1, 0.75); m_map.insert(0, 1); m_map.insert(1, 2); m_map.insert(2, 4); m_map.insert(3, 8); m_map.insert(4, 16); onSliderMovedSlot(m_slider.value()); m_layout->addWidget(&m_slider); m_layout->addWidget(&m_label); connect(&m_slider, SIGNAL(valueChanged (int)), this, SLOT(onSliderMovedSlot(int))); } ZoomSlider::~ZoomSlider() { } void ZoomSlider::setZoomTitle(QString title) { setWindowTitle(title); } void ZoomSlider::onSliderMovedSlot(int nVal) { m_label.setText(QString("Zoom : X ")+QString::number(m_map.value(nVal))); emit onSliderMoved(m_map.value(nVal)); }
#include <DS18B20.h> const int ONE_WIRE_BUS= D4 ; const int garageControlPin = D6 ; const int garageIndicatorPin = D9 ; const int boardLed = D7; // This is the LED that is already on your device. const boolean debug = false ; const int MAXRETRY = 3; const char appVer[] = "v2.1-GarageDoorControl" ; int iterCount; int crcErrCount = 0; int failedTempRead = 0; char devShortID[4+1]; unsigned long old_time = 0; DS18B20 tempSensor(ONE_WIRE_BUS, true); void publishTemp( void ) ; //--------------------------------------------------------- void setup() { Serial.begin(14400); pinMode(garageControlPin, OUTPUT); digitalWrite(garageControlPin, HIGH); pinMode(garageIndicatorPin, OUTPUT); digitalWrite(garageIndicatorPin, LOW); pinMode(boardLed, OUTPUT); digitalWrite(boardLed, LOW); pinMode(ONE_WIRE_BUS, INPUT); Particle.function("trigGarDoor", triggerGarageDoor) ; Particle.function("trigGarLite", triggerGarageLight) ; Particle.variable("iterCount", iterCount ); Particle.variable("crcErrCount", crcErrCount ); Particle.variable("badTempRead", failedTempRead ); Particle.publish("AppVer", appVer, 60, PRIVATE); // Device Name Identification String devFullID = System.deviceID() ; Serial.printf("Full DevID: %s\n", devFullID.c_str() ); devFullID.substring(strlen(devFullID)-4, strlen(devFullID)).toUpperCase().toCharArray(devShortID,4+1) ; //Serial.println( devShortID ); tempSensor.setResolution(TEMP_11_BIT); // max = 12 } void loop() { if(millis() - old_time >= 5000){ digitalWrite(boardLed, HIGH); publishTemp() ; digitalWrite(boardLed, LOW); old_time = millis(); } } //--------------------------------------------------------- void publishTemp( void ) { float temp1=0; float temp2=0; float temp3=0; char outBuffer[32+1] ; temp1 = (float)getTemp(); temp2 = 0; temp3 = 0; //Voltage if( temp1 == 999 || temp2 == 999 || temp3 == 999) { char errMsg[128+1] ; sprintf(errMsg, "Invalid temp found! [%f] [%f] [%f]", temp1, temp2, temp3 ) ; Serial.println( errMsg ); if( debug ) Particle.publish("Error", errMsg, 60, PRIVATE ); failedTempRead++ ; } Particle.process() ; if ( ++iterCount > 999 ) iterCount = 0; sprintf(outBuffer, "%c%c,%03d,%04u,%04u,%04u", devShortID[2], devShortID[3], iterCount, (int16_t)(temp1*10), (int16_t)(temp2*10), (int16_t)(temp3*10) ); Mesh.publish("temps", outBuffer); Serial.printf("outBuffer: %s len: %d \n",outBuffer, strlen(outBuffer)); if( debug ) Particle.publish("tempDBG", outBuffer, 60, PRIVATE); } int triggerGarageDoor( String inString ) { flashRelay( garageControlPin, 150 ) ; Particle.publish("DOOR", "Triggered", 60, PRIVATE); return 0; } int triggerGarageLight( String inString ) { flashRelay( garageControlPin, 50 ) ; Particle.publish("LIGHT", "Triggered", 60, PRIVATE); return 0; } void flashRelay( int pin, int duration ) { digitalWrite(garageIndicatorPin, HIGH); digitalWrite(pin, LOW); delay(duration); digitalWrite(pin, HIGH); digitalWrite(garageIndicatorPin, LOW); } void blinkLED( int LEDPin, int times ) { for( int i=0; i < times; i++) { if( i > 0 ) delay( 200 ); digitalWrite(LEDPin, HIGH); delay( 150 ); digitalWrite(LEDPin, LOW); } } double getTemp(){ double tempOut = 999; float _temp; int i = 0; do { // Serial.println("Obtaining reading"); _temp = tempSensor.getTemperature(); if(!tempSensor.crcCheck()) { crcErrCount++ ; } else { break ; } } while ( MAXRETRY > i++); if (i < MAXRETRY) { tempOut = tempSensor.convertToFahrenheit(_temp); } else { Serial.println("Invalid reading"); } return tempOut ; }
/* -*- 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. */ #ifndef OP_GENERIC_THUMBNAIL_H #define OP_GENERIC_THUMBNAIL_H #include "modules/widgets/OpWidget.h" #include "adjunct/quick/animation/QuickWidgetHoverBlend.h" class GenericThumbnailContent; class OpButton; class OpProgressBar; /** * @author The people who made the original OpThumbnailWidget * @author Wojciech Dzierzanowski (wdzierzanowski) */ class GenericThumbnail : public OpWidget { public: struct Config { Config() : m_title_border_image(NULL) , m_close_border_image(NULL) , m_close_foreground_image(NULL) , m_busy_border_image(NULL) , m_busy_foreground_image(NULL) , m_drag_type(UNKNOWN_TYPE) { } const char* m_title_border_image; const char* m_close_border_image; const char* m_close_foreground_image; const char* m_busy_border_image; const char* m_busy_foreground_image; Type m_drag_type; }; GenericThumbnail(); OP_STATUS Init(const Config& config); /** * Replaces the current content (if any) with new content. Any old content * is deleted. * * @param content new content, ownership transferred * @return status */ OP_STATUS SetContent(GenericThumbnailContent* content); void SetSelected(BOOL selected); BOOL GetLocked() { return m_locked; } void SetLocked(BOOL lock) { m_locked = lock; } const uni_char* GetTitle() const; int GetNumber() const; void GetPadding(INT32& width, INT32& height); virtual Type GetType() { return WIDGET_TYPE_THUMBNAIL; } virtual void GetRequiredThumbnailSize(INT32& width, INT32& height); // OpWidget virtual void OnDeleted(); virtual void OnLayout(); virtual void GetRequiredSize(INT32& width, INT32& height); virtual void OnMouseMove(const OpPoint& point); virtual void OnMouseLeave(); virtual void OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks); virtual void OnMouseUp(const OpPoint& point, MouseButton button, UINT8 nclicks); // OpWidgetListener virtual BOOL OnContextMenu(OpWidget* widget, INT32 child_index, const OpPoint &menu_point, const OpRect *avoid_rect, BOOL keyboard_invoked); virtual void OnDragStart(OpWidget* widget, INT32 pos, INT32 x, INT32 y); virtual void OnDragMove(OpWidget* widget, OpDragObject* drag_object, INT32 pos, INT32 x, INT32 y); virtual void OnDragDrop(OpWidget* widget, OpDragObject* drag_object, INT32 pos, INT32 x, INT32 y); // OpToolTipListener virtual BOOL HasToolTipText(OpToolTip* tooltip); virtual void GetToolTipText(OpToolTip* tooltip, OpInfoText& text); // OpInputContext virtual BOOL OnInputAction(OpInputAction* action); // QuickOpWidgetBase virtual BOOL ScrollOnFocus() { return TRUE; } protected: GenericThumbnailContent* GetContent() const { return m_content; } OP_STATUS OnContentChanged(); private: OP_STATUS OnNewContent(); void SetHovered(BOOL hovered); void SetCloseButtonHovered(BOOL close_hovered); void DoLayout(); void ComputeRelativeLayoutRects(OpRect* rects); bool HasCloseButton() const; bool HasTitle() const { return OpStringC(GetTitle()).HasContent() ? true : false; } Config m_config; GenericThumbnailContent* m_content; OpButton* m_close_button; OpButton* m_title_button; OpProgressBar* m_busy_spinner; BOOL m_hovered; BOOL m_locked; BOOL m_close_hovered; QuickWidgetHoverBlend m_blend; }; #endif // OP_GENERIC_THUMBNAIL_H
#pragma once #include "FwdDecl.h" #include "Keng/ResourceSystem/IResourceFabric.h" namespace keng::graphics { class ShaderFabric : public core::RefCountImpl<resource::IResourceFabric> { public: virtual const char* GetNodeName() const override final; virtual const char* GetResourceType() const override final; virtual resource::IResourcePtr LoadResource(resource::IResourceSystem&, Archive& ar, const resource::IDevicePtr& device) const override final; }; }
// BEGIN CUT HERE // PROBLEM STATEMENT // // In a contest, we know the scores of all our competitors, // and we estimate that // our own score is equally likely to be any integer value // between low and high, // inclusive. We want to know what our rank will most likely // be. We define our // rank to be 1 + the number of competitors that beat us, so // our rank will be // number 1 if no one beats us (even if several tie us). // // Given a vector <int> scores, the scores of our // competitors, and ints low and high, return our most likely // rank. If there // is more than one most likely rank, return -1. // // // // DEFINITION // Class:MostLikely // Method:likelyRank // Parameters:vector <int>, int, int // Returns:int // Method signature:int likelyRank(vector <int> sc, int low, // int high) // // // CONSTRAINTS // -scores will contain between 1 and 50 elements, inclusive. // -Each element of scores will be between 0 and // 1,000,000,000, inclusive. // -low will be between 0 and 1,000,000,000, inclusive. // -high will be between low and 1,000,000,000, inclusive. // // // EXAMPLES // // 0) // {3,12,4} // 8 // 8 // // Returns: 2 // // // // It is certain that only the 12 will beat us, giving us // a rank of 2. // // // // 1) // {3,4,5} // 3 // 7 // // Returns: 1 // // // Our score is equally likely to be 3 or 4 or 5 or 6 or 7. // One of those scores (the 3) gives us a rank of 3. // Similarly, one of those // scores gives us a rank of 2. And the remaining 3 scores // all give us a // rank of 1 which is thus the most likely. // // // 2) // {3,4,5} // 2 // 5 // // Returns: -1 // // // Each of our possible scores gives us a different rank, // so all those // ranks are tied for most likely. // // END CUT HERE #line 84 "MostLikely.cpp" #include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <numeric> #include <functional> #include <map> #include <set> #include <cassert> #include <list> #include <deque> #include <iomanip> #include <cstring> #include <cmath> #include <cstdio> #include <cctype> using namespace std; #define fi(n) for(int i=0;i<(n);i++) #define fj(n) for(int j=0;j<(n);j++) #define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++) typedef vector <int> VI; typedef vector <string> VS; typedef vector <VI> VVI; class MostLikely { public: int likelyRank(vector <int> sc, int low, int high) { sort(sc.rbegin(), sc.rend()); int scprev = 2000000000; // [sc[i], scprev) [low, high] int arr[sc.size() + 1]; int n = sc.size(); memset(arr, 0, sizeof(arr)); fi(sc.size()) { if (high < sc[i] || low >=scprev) continue; arr[i] = min(scprev - 1, high) - max(low, sc[i]) + 1; scprev = sc[i]; } arr[n] = min(scprev - 1, high) - max(low, -1) + 1; int bi = 0; fi(n+1) { if (arr[i]>arr[bi]) bi=i; } fi(n+1) { if (arr[bi]==arr[i] && bi!=i) return -1; } return bi + 1; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {3,12,4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 8; int Arg2 = 8; int Arg3 = 2; verify_case(0, Arg3, likelyRank(Arg0, Arg1, Arg2)); } void test_case_1() { int Arr0[] = {3,4,5}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; int Arg2 = 7; int Arg3 = 1; verify_case(1, Arg3, likelyRank(Arg0, Arg1, Arg2)); } void test_case_2() { int Arr0[] = {3,4,5} ; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 5; int Arg3 = -1; verify_case(2, Arg3, likelyRank(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { MostLikely ___test; ___test.run_test(-1); } // END CUT HERE
class CfgPatches { class itc_exp_ieds { author = "ITC Addons Team"; authors[] = {"Herbiie","ToadBall","Yax","VKing"}; units[] = {"itc_exp_moduleIEDs"}; requiredVersion = 1.0; requiredAddons[] = {"A3_Modules_F","ace_interaction","ace_interact_menu","ace_common"}; weapons[] = {"itc_exp_ecmL","itc_exp_ecmM","itc_exp_ecmH"}; }; }; #include "configs\cfgFunctions.hpp" #include "configs\cfgWeapons.hpp" class CfgFactionClasses { class NO_CATEGORY; class itc_exp_modules: NO_CATEGORY { displayName = "ITC Experimental"; }; }; #include "configs\cfgVehicles.hpp"
/*#include <iostream> #include "Map.h" using namespace std; using namespace GraphWorld; int main() { string s1 = string("My Country"); Country* c1 = new Country(0, true,true, &s1); string s2 = "MakramLand"; Country* c2 = new Country(1, false,false, &s2); Country* c3 = new Country(2, false,true, &s2); Country* c4 = new Country(3, false,false, &s2); string s3 = "Avery's FUCKING MAP"; Map* graphy = new Map(&s3, 4, 1); graphy->addNode(c1); graphy->addNode(c2); graphy->addNode(c3); graphy->addNode(c4); graphy->addEdge(c1, c2, true); graphy->addEdge(c1, c3,true); graphy->addEdge(c1, c4,true); graphy->addEdge(c4, c2,true); graphy->printMap(); cout << "\nLinkedList Part:\n"; LinkedList* ll = new LinkedList(c1); ll->add(0, c2,true); ll->add(2, c3,true); ll->add(2, c4,false); Country* ct = ll->get(1); cout << ct->displayCountry(); cout << "\nRemoving Two Items\n"; ll->remove(0); ll->remove(3); ll->displayLinkedList(); delete ll; cout << "\n"; system("PAUSE"); return 0; } */
#include<iostream> #include<queue> #include<stack> using namespace std; #define N 5 int BFS_maze[5][5] = { { 0, 1, 1, 0, 0 }, { 0, 0, 1, 1, 0 }, { 0, 1, 1, 1, 0 }, { 1, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0 } }; int DFS_maze[5][5] = { { 0, 1, 1, 0, 0 }, { 0, 0, 1, 0, 1 }, { 0, 0, 1, 0, 0 }, { 1, 1, 0, 0, 1 }, { 0, 0, 1, 0, 0 } }; int visited_BFS[N]={0}; int visited_DFS[N]={0}; void BFS(int s){ queue<int> q; visited_BFS[s]=1; q.push(s); while (!q.empty()) { int curr=q.front(); cout<<curr<<endl; q.pop(); for(int i=0;i<N;i++){ if(!visited_BFS[i]&&BFS_maze[curr][i]==1){ visited_BFS[i]=1; q.push(i); } } } } void DFS(int a){ stack<int> s; if(!visited_DFS[a]){ s.push(a); } while(!s.empty()){ int cur=s.top(); for(int i=0;i<N;i++){//访问当前节点的所有下一节点 if(!visited_DFS[i]&&DFS_maze[cur][i]==1){ s.push(i); } } cur=s.top(); cout<<cur<<endl; visited_DFS[cur]=1; s.pop(); } } int main(){ // for(int i=0;i<5;i++){ // if(visited_BFS[i]){ // continue; // } // BFS(i); // } for(int i=0;i<5;i++){ if(visited_DFS[i]){ continue; } DFS(i); } return 0; }
/* * @Description: * @Author: Ren Qian * @Date: 2020-02-28 18:50:16 */ #include "lidar_localization/sensor_data/pose_data.hpp" namespace lidar_localization { Eigen::Quaternionf PoseData::GetQuaternion() { Eigen::Quaternionf q; q = pose.block<3,3>(0,0); return q; } }
#ifndef COMMON_SRC_PIMPL_H #define COMMON_SRC_PIMPL_H #include <memory> namespace common { namespace util { /*! * \brief The Pimpl class is a helper class to ease the use of the pimpl idiom. * * The idea is to use it like this: * \code * class MyClass * { * public: * void func(); * * private: * //Can be a struct or a class doesn't matter * struct Impl; * common::util::Pimpl<Impl> impl_; * } * \endcode */ template<typename T> class Pimpl { public: /*! * \brief Pimpl constructor. */ Pimpl(); /*! * \brief Pimpl constructor with arguments. */ template<typename ...Args> Pimpl(Args&& ...); /*! * \brief Pimpl copy constructor. * \param other The other instance to copy from. */ Pimpl(const Pimpl& other); /*! * \brief Pimpl destructor. */ ~Pimpl(); /*! * \brief Assignment operator. * \param other The other instance to assign from. * \return This object instance reference. */ Pimpl& operator=(const Pimpl& other); /*! * \brief Swap function. * \param other The other instance to swap with. */ void swap(Pimpl& other); /*! * \brief Non-const dereference operator. * \return Stored pointer to implementation. */ T* operator->(); /*! * \brief Const dereference operator. * \return Stored pointer to implementation with const access. */ const T* const operator->() const; /*! * \brief Return a reference to the underlying implementation. * \return The implementation object stored. */ T& operator*(); /*! * \brief Return a reference to the underlying implementation with const access. * \return The implementation object stored. */ const T& operator*() const; private: std::unique_ptr<T> impl_; //!< Implementation pointer managed by a smart pointer. }; } } #include "PimplImpl.h" #endif // COMMON_SRC_PIMPL_H
/* * @brief CPU timer for Unix * @author Deyuan Qiu * @date May 6, 2009 * @file timer.cpp */ #include "CTimer.h" void CTimer::init(void){ _lStart = 0; _lStop = 0; _lStart = timeGetTime(); } DWORD CTimer::getTime(void){ _lStop = timeGetTime(); return _lStop - _lStart; } void CTimer::reset(void){ init(); }
#include "exception.h" Exception::Exception(const std::string &arg, const char *file, int line) : std::runtime_error(arg) { std::ostringstream o; o << file << ":" << line << ": " << arg; msg = o.str(); } Exception::~Exception() throw() {} const char* Exception::what() const throw() { return msg.c_str(); }
#pragma once #include "../../Graphics/Shader/ShaderParameter/ShaderParameterVector2.h" #include "../../UI/Dependencies/IncludeImGui.h" namespace ae { namespace priv { namespace ui { inline void ShaderParameterVector2ToEditor( ShaderParameterVector2& _ShaderParameterVector2 ) { Vector2 Value = _ShaderParameterVector2.GetValue(); float ValueRaw[2] = { Value.X, Value.Y }; if( ImGui::DragFloat2( _ShaderParameterVector2.GetName().c_str(), ValueRaw, Cast( float, _ShaderParameterVector2.GetStep() ), _ShaderParameterVector2.GetMin(), _ShaderParameterVector2.GetMax() ) ) _ShaderParameterVector2.SetValue( Vector2( ValueRaw[0], ValueRaw[1] ) ); } } // ui } // priv } // ae
#include <bits/stdc++.h> using namespace std; int main() { int t, h, m; cin >> t; for (int i = 0; i < t; i++) { cin >> h >> m; int time = ((23 - h) * 60) + (60 - m); cout << time << endl; } return 0; }
#include <iostream> using namespace std; int main() { std::ios::sync_with_stdio(false); int T,x,avg,n,ans; cin>>T; while(T>0) { cin>>x>>avg; n=avg-x; ans=n*(avg+1)-n*(n-1)/2; cout<<ans<<endl; T--; } return 0; }
#ifndef SEARCHWIDGET_H #define SEARCHWIDGET_H #include <QWidget> #include <QCompleter> #include <QSortFilterProxyModel> #include <QStringListModel> #include <iofile.h> #include <QComboBox> #include <QLabel> #include <QMessageBox> namespace Ui { class SearchWidget; } class SearchWidget : public QWidget { Q_OBJECT public: explicit SearchWidget(QWidget *parent = nullptr); ~SearchWidget(); void setNameList(); void setTypeList(); signals: void emitSearchRequestData(QVector<float>,float,QVector<QVector<float>>); private slots: void on_searchButton_clicked(); private: Ui::SearchWidget *ui; QStringList nameList; QStringList typeList; QString name; QString type; float radius; IOFile *iofile = new IOFile(); }; #endif // SEARCHWIDGET_H
#include "m_pd.h" //IMPROVE - //IMPROVE - //TODO - hep file #include "elements/dsp/part.h" inline float constrain(float v, float vMin, float vMax) { return std::max<float>(vMin,std::min<float>(vMax, v)); } static t_class *lmnts_tilde_class; typedef struct _lmnts_tilde { t_object x_obj; t_float f_dummy; t_float f_gate; t_float f_pitch; t_float f_contour; t_float f_bow_level; t_float f_bow_timbre; t_float f_blow_level; t_float f_blow_flow; t_float f_blow_timbre; t_float f_strike_level; t_float f_strike_mallet; t_float f_strike_timbre; t_float f_resonator; t_float f_geometry; t_float f_brightness; t_float f_damping; t_float f_position; t_float f_space; t_float f_mod_pitch; t_float f_mod_depth; t_float f_seed; t_float f_bypass; t_float f_easter_egg; // CLASS_MAINSIGNALIN = in_strke t_inlet* x_in_blow; t_outlet* x_out_left; t_outlet* x_out_right; elements::Part part; elements::PerformanceState state; uint32_t seed=0; uint32_t resonator = 0; bool panic = false; const float kNoiseGateThreshold = 0.0001f; float strike_in_level = 0.0f; float blow_in_level = 0.0f; static const int ELEMENTS_SZ= 32768; uint16_t buffer[ELEMENTS_SZ]; float* blow; float* strike; int iobufsz; } t_lmnts_tilde; //define pure data methods extern "C" { t_int* lmnts_tilde_render(t_int *w); void lmnts_tilde_dsp(t_lmnts_tilde *x, t_signal **sp); void lmnts_tilde_free(t_lmnts_tilde *x); void* lmnts_tilde_new(t_floatarg f); void lmnts_tilde_setup(void); void lmnts_tilde_gate(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_pitch(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_contour(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_bow_level(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_bow_timbre(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_blow_level(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_blow_flow(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_blow_timbre(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_strike_level(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_strike_mallet(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_strike_timbre(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_resonator(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_geometry(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_brightness(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_damping(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_position(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_space(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_mod_pitch(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_mod_depth(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_seed(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_bypass(t_lmnts_tilde *x, t_floatarg f); void lmnts_tilde_easter_egg(t_lmnts_tilde *x, t_floatarg f); } // puredata methods implementation -start t_int *lmnts_tilde_render(t_int *w) { t_lmnts_tilde *x = (t_lmnts_tilde *)(w[1]); t_sample *in_strike = (t_sample *)(w[2]); t_sample *in_blow = (t_sample *)(w[3]); t_sample *out_left = (t_sample *)(w[4]); t_sample *out_right = (t_sample *)(w[5]); int n = (int)(w[6]); if (n > x->iobufsz) { delete [] x->strike; delete [] x->blow; x->iobufsz = n; x->strike = new float[ x->iobufsz]; x->blow = new float[ x->iobufsz]; } x->part.mutable_patch()->exciter_envelope_shape = constrain(x->f_contour ,0.0f, 1.0f); x->part.mutable_patch()->exciter_bow_level = constrain(x->f_blow_level ,0.0f, 1.0f); x->part.mutable_patch()->exciter_bow_timbre = constrain(x->f_bow_timbre ,0.0f, 0.9995f); x->part.mutable_patch()->exciter_blow_level = constrain(x->f_blow_level ,0.0f, 1.0f); x->part.mutable_patch()->exciter_blow_meta = constrain(x->f_blow_flow ,0.0f, 0.9995f); x->part.mutable_patch()->exciter_blow_timbre = constrain(x->f_blow_timbre ,0.0f, 0.9995f); x->part.mutable_patch()->exciter_strike_level = constrain(x->f_strike_level ,0.0f, 1.0f); x->part.mutable_patch()->exciter_strike_meta = constrain(x->f_strike_mallet ,0.0f, 0.9995f); x->part.mutable_patch()->exciter_strike_timbre = constrain(x->f_strike_timbre ,0.0f, 0.9995f); x->part.mutable_patch()->resonator_geometry = constrain(x->f_geometry ,0.0f, 0.9995f); x->part.mutable_patch()->resonator_brightness = constrain(x->f_brightness ,0.0f, 0.9995f); x->part.mutable_patch()->resonator_damping = constrain(x->f_damping ,0.0f, 0.9995f); x->part.mutable_patch()->resonator_position = constrain( x->f_position ,0.0f, 0.9995f); x->part.mutable_patch()->space = constrain(x->f_space * 2.0 ,0.0f, 2.0f); uint32_t nresonator = (int (x->f_resonator) % 3); if(x->resonator != nresonator) { x->resonator = nresonator; x->part.set_resonator_model(elements::ResonatorModel(x->resonator)); } uint32_t nseed = (uint32_t) x->f_seed; if(x->seed != nseed) { x->seed = nseed; x->part.Seed(&x->seed, 1); } x->part.set_bypass(x->f_bypass); x->part.set_easter_egg(x->f_easter_egg); for(int i=0;i<n;i++){ float blow_in_sample = in_blow[i]; float strike_in_sample = in_strike[i]; float error =0.0f, gain=1.0f; // error = strike_in_sample * strike_in_sample - strike_in_level; // strike_in_level += error * (error > 0.0f ? 0.1f : 0.0001f); // gain = strike_in_level <= kNoiseGateThreshold // ? (1.0f / kNoiseGateThreshold) * strike_in_level : 1.0f; x->strike[i] = gain * strike_in_sample; // error = blow_in_sample * blow_in_sample - blow_in_level; // blow_in_level += error * (error > 0.0f ? 0.1f : 0.0001f); // gain = blow_in_level <= kNoiseGateThreshold // ? (1.0f / kNoiseGateThreshold) * blow_in_level : 1.0f; x->blow[i] = gain * blow_in_sample; } x->state.gate = x->f_gate; x->state.note = constrain(x->f_pitch * 64.0f, -64.0f, 64.0f); x->state.strength = constrain(x->f_mod_depth ,0.0f, 1.0f); x->state.modulation = constrain(x->f_mod_pitch * 60.0f, -60.0f, 60.0f); x->part.Process(x->state, x->blow, x->strike, out_left, out_right, n); return (w + 7); // # args + 1 } void lmnts_tilde_dsp(t_lmnts_tilde *x, t_signal **sp) { // add the perform method, with all signal i/o dsp_add(lmnts_tilde_render, 6, x, sp[0]->s_vec, sp[1]->s_vec, sp[2]->s_vec, sp[3]->s_vec, // signal i/o (clockwise) sp[0]->s_n); } void lmnts_tilde_free(t_lmnts_tilde *x) { delete [] x->strike; delete [] x->blow; inlet_free(x->x_in_blow); outlet_free(x->x_out_left); outlet_free(x->x_out_right); } void *lmnts_tilde_new(t_floatarg) { t_lmnts_tilde *x = (t_lmnts_tilde *) pd_new(lmnts_tilde_class); x->part.Init(x->buffer); x->seed = 0; x->part.Seed(&x->seed, 1); x->resonator = 0; x->part.set_resonator_model(elements::ResonatorModel(x->resonator)); x->state.gate = false; x->state.note = 0.0f; x->state.modulation = 0.0f; x->state.strength = 0.0f; x->iobufsz = 64; x->strike = new float[ x->iobufsz]; x->blow = new float[ x->iobufsz]; //x_in_strike = main input x->x_in_blow = inlet_new(&x->x_obj, &x->x_obj.ob_pd, &s_signal, &s_signal); x->x_out_left = outlet_new(&x->x_obj, &s_signal); x->x_out_right = outlet_new(&x->x_obj, &s_signal); return (void *)x; } void lmnts_tilde_setup(void) { lmnts_tilde_class = class_new( gensym("lmnts~"), (t_newmethod)lmnts_tilde_new, 0, sizeof(t_lmnts_tilde), CLASS_DEFAULT, A_DEFFLOAT, A_NULL); class_addmethod( lmnts_tilde_class, (t_method)lmnts_tilde_dsp, gensym("dsp"), A_NULL); // represents strike input CLASS_MAINSIGNALIN(lmnts_tilde_class, t_lmnts_tilde, f_dummy); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_gate, gensym("gate"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_pitch, gensym("pitch"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_contour, gensym("contour"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_bow_level, gensym("bow_level"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_bow_timbre, gensym("bow_timbre"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_blow_level, gensym("blow_level"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_blow_flow, gensym("blow_flow"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_blow_timbre, gensym("blow_timbre"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_strike_level, gensym("strike_level"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_strike_mallet, gensym("strike_mallet"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_strike_timbre, gensym("strike_timbre"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_resonator, gensym("resonator"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_geometry, gensym("geometry"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_brightness, gensym("brightness"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_damping, gensym("damping"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_position, gensym("position"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_space, gensym("space"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_mod_pitch, gensym("mod_pitch"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_mod_depth, gensym("mod_depth"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_seed, gensym("seed"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_bypass, gensym("bypass"), A_DEFFLOAT,A_NULL); class_addmethod(lmnts_tilde_class, (t_method) lmnts_tilde_easter_egg, gensym("easter_egg"), A_DEFFLOAT,A_NULL); } void lmnts_tilde_gate(t_lmnts_tilde *x, t_floatarg f) { x->f_gate = f; } void lmnts_tilde_pitch(t_lmnts_tilde *x, t_floatarg f) { x->f_pitch = f; } void lmnts_tilde_contour(t_lmnts_tilde *x, t_floatarg f) { x->f_contour = f; } void lmnts_tilde_bow_level(t_lmnts_tilde *x, t_floatarg f) { x->f_bow_level = f; } void lmnts_tilde_bow_timbre(t_lmnts_tilde *x, t_floatarg f) { x->f_bow_timbre = f; } void lmnts_tilde_blow_level(t_lmnts_tilde *x, t_floatarg f) { x->f_blow_level = f; } void lmnts_tilde_blow_flow(t_lmnts_tilde *x, t_floatarg f) { x->f_blow_flow = f; } void lmnts_tilde_blow_timbre(t_lmnts_tilde *x, t_floatarg f) { x->f_blow_timbre = f; } void lmnts_tilde_strike_level(t_lmnts_tilde *x, t_floatarg f) { x->f_strike_level = f; } void lmnts_tilde_strike_mallet(t_lmnts_tilde *x, t_floatarg f) { x->f_strike_mallet = f; } void lmnts_tilde_strike_timbre(t_lmnts_tilde *x, t_floatarg f) { x->f_strike_timbre = f; } void lmnts_tilde_resonator(t_lmnts_tilde *x, t_floatarg f) { x->f_resonator = f; } void lmnts_tilde_geometry(t_lmnts_tilde *x, t_floatarg f) { x->f_geometry = f; } void lmnts_tilde_brightness(t_lmnts_tilde *x, t_floatarg f) { x->f_brightness = f; } void lmnts_tilde_damping(t_lmnts_tilde *x, t_floatarg f) { x->f_damping = f; } void lmnts_tilde_position(t_lmnts_tilde *x, t_floatarg f) { x->f_position = f; } void lmnts_tilde_space(t_lmnts_tilde *x, t_floatarg f) { x->f_space = f; } void lmnts_tilde_mod_pitch(t_lmnts_tilde *x, t_floatarg f) { x->f_mod_pitch = f; } void lmnts_tilde_mod_depth(t_lmnts_tilde *x, t_floatarg f) { x->f_mod_depth = f; } void lmnts_tilde_seed(t_lmnts_tilde *x, t_floatarg f) { x->f_seed = f; } void lmnts_tilde_bypass(t_lmnts_tilde *x, t_floatarg f) { x->f_bypass = f; } void lmnts_tilde_easter_egg(t_lmnts_tilde *x, t_floatarg f) { x->f_easter_egg = f; } // puredata methods implementation - end
#ifndef VENDEDOR_H #define VENDEDOR_H class Vendedor{ public: Vendedor(); void ObtenerVentasDelUsuario(); void establecerVentas(int, double); void imprimirVentasAnuales(); private: double totalVentasAnuales(); double ventas[12]; }; #endif
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 200000 #define LowerBit(k) (k&-k) int table[MAXN+5]; int FT[MAXN+5]; int total(int k){ int ans = 0; for(int i = k ; i > 0 ; i-=LowerBit(i) ) ans += FT[i]; return ans; } int main(int argc, char const *argv[]) { int num,a,b; int kase = 1; string action; while( ~scanf("%d",&num) && num ){ if( kase > 1 ) printf("\n"); printf("Case %d:\n",kase++); for(int i = 1 ; i <= num ; i++ ) scanf("%d",&table[i]); memset(FT,0,sizeof(FT)); for(int i = 1 ; i <= num ; i++ ) for(int j = i ; j <= num ; j+=LowerBit(j) ) FT[j] += table[i]; while( cin >> action && action != "END" ){ scanf("%d %d",&a,&b); if( action == "M" ){ printf("%d\n",total(b)-total(a-1)); } else{ for(int i = a ; i <= num ; i+=LowerBit(i) ) FT[i] += (b-table[a]); table[a] = b; } } } return 0; }
#ifndef MAP_H #define MAP_H #include "gif.h" #include "scenestate.h" #include "sceneinfo.h" #include "rankinfo.h" #include "classname.h" #include "collisioninspector.h" #include "updater.h" #include <QWidget> #include <QSet> #include <QMovie> #include <QPainter> #include <QSet> #include <QMap> #include <QDateTime> class Scene : public QWidget { Q_OBJECT protected: int gameState; // 游戏状态 int m_width, m_height, map_unit, placeAcc; // 场景的长宽,地图单位,放置精度 int fps; // 游戏帧率 bool loading; // 加载中 QCursor featherCursor; // 鼠标样式 clock_t gameTime, gamePassTime; // 游戏时间 QMap<QString, int>name2num; // className与数字的映射,方便switch QImage backgroundImage; // 背景图片 QImage successImage; // 过关图片 QImage gameOverImage; // 失败图片 QImage rankImage; // 积分榜图片 Gif loaderImage; // 加载图片 Player *player; // 玩家 Goal *goal; // 终点 QSet<BaseObject *>allWidgets; // 保存所有的指针 QSet<Terrain *>terrains; // 保存地形指针的基类数组 QSet<Trap *>traps; // 保存陷阱指针的基类数组 QSet<Monster *>monsters; // 保存怪物指针的基类数组 QSet<Buff *>buffs; // 保存Buff指针的基类数组 QSet<Values *>values; // 保存有分数物体的基类数组 QSet<FlyingProp *>flyingProps; // 保存飞行物的指针 QSet<MoveThing *>moveThings; // 保存会动的物体的指针 QSet<Launcher *>launchers; // 保存会发射物体的物体的指针 BaseObject *temp; // 保存临时指针,在放置物体的时候显示 CollisionInspector ci; // 碰撞检测类 Updater updater; // 更新场景的类 QString rankFile; // 排名文件 QVector<RankInfo>rankinfos; // 排名 bool isShowChooseWidget, isMovingThing; // 与编辑模式时的显示有关 void makeName2Num(); // 构造映射 void makeConnection(); // 构造连接 void initialize(); // 初始化 protected: void paintEvent(QPaintEvent *) override; // 绘图事件 void enterEvent(QEvent *) override; // 进入事件 void leaveEvent(QEvent *) override; // 离开事件 void mouseMoveEvent(QMouseEvent *) override; // 鼠标移动事件 void mouseReleaseEvent(QMouseEvent *) override; // 鼠标松开事件 void resizeEvent(QResizeEvent *) override; // 窗口变化事件 void addSceneWidget(int x, int y); // 增加组件 void eraseSceneWidget(BaseObject *object); // 擦除组件 void deleteSceneWidget(int x, int y); // 删除组件 void moveSceneWidget(int x, int y); // 移动组件 void readRankFile(); // 读取排名文件 void writeRankFile(); // 写入排名 public slots: void updateScene(const QSet<int>&); // 更新场景 void chooseSceneWidget(bool, const QString&); // 选择的组件 void newScene(); // 新建场景 void loadScene(const QString& scenePath); // 加载场景 void saveScene(const QString& scenePath); // 保存场景 void gameReload(); // 游戏恢复 void gameStart(); // 游戏开始 void gameRestart(); // 游戏重新开始 void gameSuccess(); // 游戏通关 void gameOver(); // 游戏结束 void loadOver(); // 加载结束 public: explicit Scene(QWidget *parent = nullptr); ~Scene(); int getFPS() const; // 返回帧率 int getGameState() const; // 返回游戏状态 void setGameState(int gameState); // 设置游戏状态 const Updater* getUpdater() const; // 返回Updater signals: void clearChooseSceneWidget(); // 右击清除已选择,返回信号给主窗口 void clearKeyPressed(); // 清楚键盘状态 void chooseSceneFile(); // 选择场景文件 void newSceneFile(); // 新建场景文件 void returnHome(); // 返回主页 }; #endif // MAP_H
#ifndef _MSG_0X84_UPDATETILEENTITY_STC_H_ #define _MSG_0X84_UPDATETILEENTITY_STC_H_ #include "mcprotocol_base.h" namespace MC { namespace Protocol { namespace Msg { class UpdateTileEntity : public BaseMessage { public: UpdateTileEntity(); UpdateTileEntity(int32_t _x, int16_t _y, int32_t _z, int8_t _action, int16_t _dataLength, const ByteArray& _data); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); int32_t getX() const; int16_t getY() const; int32_t getZ() const; int8_t getAction() const; int16_t getDataLength() const; const ByteArray& getData() const; void setX(int32_t _val); void setY(int16_t _val); void setZ(int32_t _val); void setAction(int8_t _val); void setDataLength(int16_t _val); void setData(const ByteArray& _val); private: int32_t _pf_x; int16_t _pf_y; int32_t _pf_z; int8_t _pf_action; int16_t _pf_dataLength; ByteArray _pf_data; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0X84_UPDATETILEENTITY_STC_H_
/********************************************************************* * Software License Agreement (BSD License) * Copyright (C) 2012 Ken Tossell * Copyright (c) 2022 Orbbec 3D Technology, Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the author nor other contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ #include "astra_camera/uvc_camera_driver.h" #include <cv_bridge/cv_bridge.h> #include <boost/optional.hpp> #include <opencv2/opencv.hpp> #include <string> #define libuvc_VERSION \ (libuvc_VERSION_MAJOR * 10000 + libuvc_VERSION_MINOR * 100 + libuvc_VERSION_PATCH) /** Converts an unaligned four-byte little-endian integer into an int32 */ #define DW_TO_INT(p) ((p)[0] | ((p)[1] << 8) | ((p)[2] << 16) | ((p)[3] << 24)) /** Converts an unaligned two-byte little-endian integer into an int16 */ #define SW_TO_SHORT(p) ((p)[0] | ((p)[1] << 8)) /** Converts an int16 into an unaligned two-byte little-endian integer */ #define SHORT_TO_SW(s, p) \ (p)[0] = (s); \ (p)[1] = (s) >> 8; /** Converts an int32 into an unaligned four-byte little-endian integer */ #define INT_TO_DW(i, p) \ (p)[0] = (i); \ (p)[1] = (i) >> 8; \ (p)[2] = (i) >> 16; \ (p)[3] = (i) >> 24; /** Selects the nth item in a doubly linked list. n=-1 selects the last item. */ #define DL_NTH(head, out, n) \ do { \ int dl_nth_i = 0; \ LDECLTYPE(head) dl_nth_p = (head); \ if ((n) < 0) { \ while (dl_nth_p && dl_nth_i > (n)) { \ dl_nth_p = dl_nth_p->prev; \ dl_nth_i--; \ } \ } else { \ while (dl_nth_p && dl_nth_i < (n)) { \ dl_nth_p = dl_nth_p->next; \ dl_nth_i++; \ } \ } \ (out) = dl_nth_p; \ } while (0); namespace astra_camera { std::ostream& operator<<(std::ostream& os, const UVCCameraConfig& config) { os << "vendor_id: " << std::hex << config.vendor_id << std::endl; os << "product_id: " << std::hex << config.product_id << std::endl; os << "width: " << std::dec << config.width << std::endl; os << "height: " << config.height << std::endl; os << "fps: " << config.fps << std::endl; os << "serial_number: " << config.serial_number << std::endl; os << "format: " << config.format << std::endl; return os; } UVCCameraDriver::UVCCameraDriver(ros::NodeHandle& nh, ros::NodeHandle& nh_private, const sensor_msgs::CameraInfo& camera_info, const std::string& serial_number) : nh_(nh), nh_private_(nh_private), camera_info_(camera_info) { auto err = uvc_init(&ctx_, nullptr); if (err != UVC_SUCCESS) { uvc_perror(err, "ERROR: uvc_init"); ROS_ERROR_STREAM("init uvc context failed, exit"); throw std::runtime_error("init uvc context failed"); } config_.serial_number = serial_number; device_num_ = nh_private_.param<int>("device_num", 1); uvc_flip_ = nh_private_.param<bool>("uvc_flip", false); config_.vendor_id = std::stoi(nh_private_.param<std::string>("uvc_vendor_id", "0x0"), nullptr, 16); config_.product_id = std::stoi(nh_private_.param<std::string>("uvc_product_id", "0x0"), nullptr, 16); config_.width = nh_private_.param<int>("color_width", 640); config_.height = nh_private_.param<int>("color_height", 480); config_.fps = nh_private_.param<int>("color_fps", 30); config_.format = nh_private.param<std::string>("uvc_camera_format", "mjpeg"); config_.retry_count = nh_private.param<int>("uvc_retry_count", 500); roi_.x = nh_private.param<int>("color_roi_x", -1); roi_.y = nh_private.param<int>("color_roi_y", -1); roi_.width = nh_private.param<int>("color_roi_width", -1); roi_.height = nh_private.param<int>("color_roi_height", -1); camera_name_ = nh_private.param<std::string>("camera_name", "camera"); config_.frame_id = camera_name_ + "_color_frame"; config_.optical_frame_id = camera_name_ + "_color_optical_frame"; camera_info_publisher_ = nh_.advertise<sensor_msgs::CameraInfo>("color/camera_info", 1, true); color_info_uri_ = nh_private.param<std::string>("color_info_uri", ""); color_info_manager_ = std::make_shared<camera_info_manager::CameraInfoManager>(nh_, "rgb_camera", color_info_uri_); std::lock_guard<decltype(device_lock_)> lock(device_lock_); image_publisher_ = nh_.advertise<sensor_msgs::Image>( "color/image_raw", 10, boost::bind(&UVCCameraDriver::imageSubscribedCallback, this), boost::bind(&UVCCameraDriver::imageUnsubscribedCallback, this)); setupCameraControlService(); openCamera(); auto info = getCameraInfo(); camera_info_publisher_.publish(info); } UVCCameraDriver::~UVCCameraDriver() { std::lock_guard<decltype(device_lock_)> lock(device_lock_); uvc_close(device_handle_); device_handle_ = nullptr; uvc_unref_device(device_); device_ = nullptr; uvc_exit(ctx_); ctx_ = nullptr; if (frame_buffer_) { uvc_free_frame(frame_buffer_); } frame_buffer_ = nullptr; } void UVCCameraDriver::openCamera() { ROS_INFO_STREAM("open uvc camera"); uvc_error_t err; auto serial_number = config_.serial_number.empty() ? nullptr : config_.serial_number.c_str(); CHECK(device_ == nullptr); std::lock_guard<decltype(device_lock_)> lock(device_lock_); err = uvc_find_device(ctx_, &device_, config_.vendor_id, config_.product_id, serial_number); if (err != UVC_SUCCESS && device_num_ == 1) { // retry serial number == nullptr err = uvc_find_device(ctx_, &device_, config_.vendor_id, config_.product_id, nullptr); } if (err != UVC_SUCCESS) { uvc_perror(err, "ERROR: uvc_find_device"); ROS_ERROR_STREAM("find uvc device failed, retry " << config_.retry_count << " times"); for (int i = 0; i < config_.retry_count; i++) { err = uvc_find_device(ctx_, &device_, config_.vendor_id, config_.product_id, serial_number); if (err == UVC_SUCCESS) { break; } usleep(100 * i); } } ROS_INFO_STREAM("uvc config: " << config_); if (err != UVC_SUCCESS) { std::stringstream ss; ss << "Find device error " << uvc_strerror(err) << " process will be exit"; ROS_ERROR_STREAM(ss.str()); uvc_unref_device(device_); throw std::runtime_error(ss.str()); } CHECK(device_handle_ == nullptr); err = uvc_open(device_, &device_handle_); if (err != UVC_SUCCESS) { if (UVC_ERROR_ACCESS == err) { ROS_ERROR("Permission denied opening /dev/bus/usb/%03d/%03d", uvc_get_bus_number(device_), uvc_get_device_address(device_)); } else { ROS_ERROR("Can't open /dev/bus/usb/%03d/%03d: %s (%d)", uvc_get_bus_number(device_), uvc_get_device_address(device_), uvc_strerror(err), err); } uvc_unref_device(device_); return; } uvc_set_status_callback(device_handle_, &UVCCameraDriver::autoControlsCallbackWrapper, this); CHECK_NOTNULL(device_handle_); CHECK_NOTNULL(device_); ROS_INFO_STREAM("open camera success"); is_camera_opened_ = true; } void UVCCameraDriver::updateConfig(const UVCCameraConfig& config) { config_ = config; } void UVCCameraDriver::setVideoMode() { std::lock_guard<decltype(device_lock_)> lock(device_lock_); auto uvc_format = UVCFrameFormatString(config_.format); int width = config_.width; int height = config_.height; int fps = config_.fps; uvc_error_t err; CHECK_NOTNULL(device_); CHECK_NOTNULL(device_handle_); for (int i = 0; i < 5; i++) { err = uvc_get_stream_ctrl_format_size(device_handle_, &ctrl_, uvc_format, width, height, fps); if (err == UVC_SUCCESS) { break; } } ROS_INFO_STREAM("set uvc mode " << width << "x" << height << "@" << fps << " format " << config_.format); if (err != UVC_SUCCESS) { ROS_ERROR_STREAM("set uvc ctrl error " << uvc_strerror(err)); uvc_close(device_handle_); device_handle_ = nullptr; uvc_unref_device(device_); device_ = nullptr; return; } } void UVCCameraDriver::imageSubscribedCallback() { ROS_INFO_STREAM("UVCCameraDriver image subscribed"); std::lock_guard<decltype(device_lock_)> lock(device_lock_); startStreaming(); } void UVCCameraDriver::imageUnsubscribedCallback() { ROS_INFO_STREAM("UVCCameraDriver image unsubscribed"); std::lock_guard<decltype(device_lock_)> lock(device_lock_); auto subscriber_count = image_publisher_.getNumSubscribers(); if (subscriber_count == 0) { stopStreaming(); } } void UVCCameraDriver::startStreaming() { if (is_streaming_started) { ROS_WARN_STREAM("UVCCameraDriver streaming is already started"); return; } if (!is_camera_opened_) { ROS_WARN_STREAM("UVCCameraDriver camera is not opened"); return; } CHECK_NOTNULL(device_); CHECK_NOTNULL(device_handle_); setVideoMode(); std::lock_guard<decltype(device_lock_)> lock(device_lock_); uvc_error_t stream_err = uvc_start_streaming(device_handle_, &ctrl_, &UVCCameraDriver::frameCallbackWrapper, this, 0); if (stream_err != UVC_SUCCESS) { ROS_ERROR_STREAM("uvc start streaming error " << uvc_strerror(stream_err) << " retry " << config_.retry_count << " times"); for (int i = 0; i < config_.retry_count; i++) { stream_err = uvc_start_streaming(device_handle_, &ctrl_, &UVCCameraDriver::frameCallbackWrapper, this, 0); if (stream_err == UVC_SUCCESS) { break; } usleep(100 * i); } } if (stream_err != UVC_SUCCESS) { uvc_perror(stream_err, "uvc_start_streaming"); uvc_close(device_handle_); uvc_unref_device(device_); return; } if (frame_buffer_) { uvc_free_frame(frame_buffer_); frame_buffer_ = nullptr; } frame_buffer_ = uvc_allocate_frame(config_.width * config_.height * 3); CHECK_NOTNULL(frame_buffer_); is_streaming_started.store(true); } void UVCCameraDriver::stopStreaming() noexcept { if (!is_streaming_started) { ROS_WARN_STREAM("streaming is already stopped"); return; } ROS_INFO_STREAM("stop uvc streaming"); uvc_stop_streaming(device_handle_); if (frame_buffer_) { uvc_free_frame(frame_buffer_); frame_buffer_ = nullptr; } is_streaming_started.store(false); } int UVCCameraDriver::getResolutionX() const { return config_.width; } int UVCCameraDriver::getResolutionY() const { return config_.height; } void UVCCameraDriver::setupCameraControlService() { get_uvc_exposure_srv_ = nh_.advertiseService<GetInt32Request, GetInt32Response>( "get_uvc_exposure", [this](auto&& request, auto&& response) { response.success = this->getUVCExposureCb(request, response); return response.success; }); set_uvc_exposure_srv_ = nh_.advertiseService<SetInt32Request, SetInt32Response>( "set_uvc_exposure", [this](auto&& request, auto&& response) { response.success = this->setUVCExposureCb(request, response); return response.success; }); get_uvc_gain_srv_ = nh_.advertiseService<GetInt32Request, GetInt32Response>( "get_uvc_gain", [this](auto&& request, auto&& response) { response.success = this->getUVCGainCb(request, response); return response.success; }); set_uvc_gain_srv_ = nh_.advertiseService<SetInt32Request, SetInt32Response>( "set_uvc_gain", [this](auto&& request, auto&& response) { response.success = this->setUVCGainCb(request, response); return response.success; }); get_uvc_white_balance_srv_ = nh_.advertiseService<GetInt32Request, GetInt32Response>( "get_uvc_white_balance", [this](auto&& request, auto&& response) { response.success = this->getUVCWhiteBalanceCb(request, response); return response.success; }); set_uvc_white_balance_srv_ = nh_.advertiseService<SetInt32Request, SetInt32Response>( "set_uvc_white_balance", [this](auto&& request, auto&& response) { response.success = this->setUVCWhiteBalanceCb(request, response); return response.success; }); set_uvc_auto_exposure_srv_ = nh_.advertiseService<std_srvs::SetBoolRequest, std_srvs::SetBoolResponse>( "set_uvc_auto_exposure", [this](auto&& request, auto&& response) { response.success = this->setUVCAutoExposureCb(request, response); return response.success; }); set_uvc_auto_white_balance_srv_ = nh_.advertiseService<std_srvs::SetBoolRequest, std_srvs::SetBoolResponse>( "set_uvc_auto_white_balance", [this](auto&& request, auto&& response) { response.success = this->setUVCAutoWhiteBalanceCb(request, response); return response.success; }); get_uvc_mirror_srv_ = nh_.advertiseService<GetInt32Request, GetInt32Response>( "get_uvc_mirror", [this](auto&& request, auto&& response) { response.success = this->getUVCMirrorCb(request, response); return response.success; }); set_uvc_mirror_srv_ = nh_.advertiseService<std_srvs::SetBoolRequest, std_srvs::SetBoolResponse>( "set_uvc_mirror", [this](auto&& request, auto&& response) { response.success = this->setUVCMirrorCb(request, response); return response.success; }); toggle_uvc_camera_srv_ = nh_.advertiseService<std_srvs::SetBoolRequest, std_srvs::SetBoolResponse>( "toggle_uvc_camera", [this](auto&& request, auto&& response) { response.success = this->toggleUVCCamera(request, response); return response.success; }); save_image_srv_ = nh_.advertiseService<std_srvs::EmptyRequest, std_srvs::EmptyResponse>( "save_uvc_image", [this](auto&& request, auto&& response) { return this->saveImageCallback(request, response); }); } sensor_msgs::CameraInfo UVCCameraDriver::getCameraInfo() { if (color_info_manager_ && color_info_manager_->isCalibrated()) { auto camera_info = color_info_manager_->getCameraInfo(); camera_info.header.frame_id = config_.optical_frame_id; camera_info.header.stamp = ros::Time::now(); return camera_info; } else { camera_info_.header.frame_id = config_.optical_frame_id; camera_info_.header.stamp = ros::Time::now(); return camera_info_; } } enum uvc_frame_format UVCCameraDriver::UVCFrameFormatString(const std::string& format) { if (format == "uncompressed") { return UVC_COLOR_FORMAT_UNCOMPRESSED; } else if (format == "compressed") { return UVC_COLOR_FORMAT_COMPRESSED; } else if (format == "yuyv") { return UVC_COLOR_FORMAT_YUYV; } else if (format == "uyvy") { return UVC_COLOR_FORMAT_UYVY; } else if (format == "rgb") { return UVC_COLOR_FORMAT_RGB; } else if (format == "bgr") { return UVC_COLOR_FORMAT_BGR; } else if (format == "mjpeg") { return UVC_COLOR_FORMAT_MJPEG; } else if (format == "gray8") { return UVC_COLOR_FORMAT_GRAY8; } else { ROS_WARN_STREAM("Invalid Video Mode: " << format); ROS_WARN_STREAM("Continue using video mode: uncompressed"); return UVC_COLOR_FORMAT_UNCOMPRESSED; } } void UVCCameraDriver::frameCallbackWrapper(uvc_frame_t* frame, void* ptr) { CHECK_NOTNULL(ptr); auto driver = static_cast<UVCCameraDriver*>(ptr); driver->frameCallback(frame); } void UVCCameraDriver::frameCallback(uvc_frame_t* frame) { CHECK_NOTNULL(frame); CHECK_NOTNULL(frame_buffer_); std::lock_guard<decltype(device_lock_)> lock(device_lock_); static constexpr int unit_step = 3; sensor_msgs::Image image; image.width = frame->width; image.height = frame->height; image.step = image.width * unit_step; image.header.frame_id = frame_id_; image.header.stamp = ros::Time::now(); image.data.resize(image.height * image.step); if (frame->frame_format == UVC_FRAME_FORMAT_BGR) { image.encoding = "bgr8"; memcpy(&(image.data[0]), frame->data, frame->data_bytes); } else if (frame->frame_format == UVC_FRAME_FORMAT_RGB) { image.encoding = "rgb8"; memcpy(&(image.data[0]), frame->data, frame->data_bytes); } else if (frame->frame_format == UVC_FRAME_FORMAT_UYVY) { image.encoding = "yuv422"; memcpy(&(image.data[0]), frame->data, frame->data_bytes); } else if (frame->frame_format == UVC_FRAME_FORMAT_YUYV) { // FIXME: uvc_any2bgr does not work on "yuyv" format, so use uvc_yuyv2bgr directly. uvc_error_t conv_ret = uvc_yuyv2bgr(frame, frame_buffer_); if (conv_ret != UVC_SUCCESS) { uvc_perror(conv_ret, "Couldn't convert frame to RGB"); return; } image.encoding = "bgr8"; memcpy(&(image.data[0]), frame_buffer_->data, frame_buffer_->data_bytes); } else if (frame->frame_format == UVC_FRAME_FORMAT_MJPEG) { // Enable mjpeg support despite uvs_any2bgr shortcoming // https://github.com/ros-drivers/libuvc_ros/commit/7508a09f uvc_error_t conv_ret = uvc_mjpeg2rgb(frame, frame_buffer_); if (conv_ret != UVC_SUCCESS) { uvc_perror(conv_ret, "Couldn't convert frame to RGB"); return; } image.encoding = "rgb8"; memcpy(&(image.data[0]), frame_buffer_->data, frame_buffer_->data_bytes); } else { uvc_error_t conv_ret = uvc_any2bgr(frame, frame_buffer_); if (conv_ret != UVC_SUCCESS) { uvc_perror(conv_ret, "Couldn't convert frame to RGB"); return; } image.encoding = "bgr8"; memcpy(&(image.data[0]), frame_buffer_->data, frame_buffer_->data_bytes); } if (roi_.x != -1 && roi_.y != -1 && roi_.width != -1 && roi_.height != -1) { auto cv_image_ptr = cv_bridge::toCvCopy(image); auto cv_img = cv_image_ptr->image; cv::Rect roi(roi_.x, roi_.y, roi_.width, roi_.height); cv::Mat dst(cv_image_ptr->image, roi); cv_image_ptr->image = dst; image = *(cv_image_ptr->toImageMsg()); } if (uvc_flip_) { auto cv_image_ptr = cv_bridge::toCvCopy(image); auto cv_img = cv_image_ptr->image; cv::flip(cv_img, cv_img, 1); cv_image_ptr->image = cv_img; image = *(cv_image_ptr->toImageMsg()); } auto camera_info = getCameraInfo(); camera_info.header.stamp = ros::Time::now(); camera_info_publisher_.publish(camera_info); image.header.frame_id = config_.optical_frame_id; image.header.stamp = camera_info.header.stamp; image_publisher_.publish(image); if (save_image_) { cv_bridge::CvImagePtr cv_image_ptr = cv_bridge::toCvCopy(image); auto now = std::time(nullptr); std::stringstream ss; ss << std::put_time(std::localtime(&now), "%Y%m%d_%H%M%S"); auto current_path = boost::filesystem::current_path().string(); std::string filename = current_path + "/image/uvc_color_" + std::to_string(image.width) + "x" + std::to_string(image.height) + "_" + ss.str() + ".jpg"; if (!boost::filesystem::exists(current_path + "/image")) { boost::filesystem::create_directory(current_path + "/image"); } ROS_INFO_STREAM("Saving image to " << filename); cv::imwrite(filename, cv_image_ptr->image); save_image_ = false; } } void UVCCameraDriver::autoControlsCallback(enum uvc_status_class status_class, int event, int selector, enum uvc_status_attribute status_attribute, void* data, size_t data_len) { char buff[256]; CHECK(data_len < 256); (void)data; sprintf(buff, "Controls callback. class: %d, event: %d, selector: %d, attr: %d, data_len: %zu\n", status_class, event, selector, status_attribute, data_len); ROS_INFO_STREAM(buff); } void UVCCameraDriver::autoControlsCallbackWrapper(enum uvc_status_class status_class, int event, int selector, enum uvc_status_attribute status_attribute, void* data, size_t data_len, void* ptr) { CHECK_NOTNULL(ptr); auto driver = static_cast<UVCCameraDriver*>(ptr); driver->autoControlsCallback(status_class, event, selector, status_attribute, data, data_len); } bool UVCCameraDriver::getUVCExposureCb(GetInt32Request& request, GetInt32Response& response) { (void)request; uint32_t data; uvc_error_t err = uvc_get_exposure_abs(device_handle_, &data, UVC_GET_CUR); if (err != UVC_SUCCESS) { auto msg = uvc_strerror(err); ROS_ERROR_STREAM("getUVCExposureCb " << msg); response.message = msg; return false; } response.data = static_cast<int>(data); return true; } bool UVCCameraDriver::setUVCExposureCb(SetInt32Request& request, SetInt32Response& response) { if (request.data == 0) { ROS_ERROR("set auto mode"); uvc_error_t err = uvc_set_ae_mode(device_handle_, 8); // 8才是自动8: aperture priority mode ROS_ERROR("ret :%d", (int)err); return true; } uint32_t max_expo, min_expo; uvc_get_exposure_abs(device_handle_, &max_expo, UVC_GET_MAX); uvc_get_exposure_abs(device_handle_, &min_expo, UVC_GET_MIN); if (request.data < static_cast<int>(min_expo) || request.data > static_cast<int>(max_expo)) { std::stringstream ss; ss << "Exposure value out of range. Min: " << min_expo << ", Max: " << max_expo; response.message = ss.str(); ROS_ERROR_STREAM(response.message); return false; } uvc_set_ae_mode( device_handle_, 1); // mode 1: manual mode; 2: auto mode; 4: shutter priority mode; 8: aperture priority mode uvc_error_t err = uvc_set_exposure_abs(device_handle_, request.data); if (err != UVC_SUCCESS) { auto msg = uvc_strerror(err); ROS_ERROR_STREAM("setUVCExposureCb " << msg); response.message = msg; return false; } return true; } bool UVCCameraDriver::getUVCGainCb(GetInt32Request& request, GetInt32Response& response) { (void)request; uint16_t gain; uvc_error_t err = uvc_get_gain(device_handle_, &gain, UVC_GET_CUR); response.data = gain; if (err != UVC_SUCCESS) { auto msg = uvc_strerror(err); ROS_ERROR_STREAM("getUVCGainCb " << msg); response.message = msg; return false; } return true; } bool UVCCameraDriver::setUVCGainCb(SetInt32Request& request, SetInt32Response& response) { uint16_t min_gain, max_gain; uvc_get_gain(device_handle_, &min_gain, UVC_GET_MIN); uvc_get_gain(device_handle_, &max_gain, UVC_GET_MAX); if (request.data < min_gain || request.data > max_gain) { std::stringstream ss; ss << "Gain must be between " << min_gain << " and " << max_gain; response.message = ss.str(); ROS_ERROR_STREAM(response.message); return false; } uvc_error_t err = uvc_set_gain(device_handle_, request.data); if (err != UVC_SUCCESS) { auto msg = uvc_strerror(err); ROS_ERROR_STREAM("setUVCGainCb " << msg); response.message = msg; return false; } return true; } bool UVCCameraDriver::getUVCWhiteBalanceCb(GetInt32Request& request, GetInt32Response& response) { (void)request; uint16_t data; uvc_error_t err = uvc_get_white_balance_temperature(device_handle_, &data, UVC_GET_CUR); response.data = data; if (err != UVC_SUCCESS) { auto msg = uvc_strerror(err); ROS_ERROR_STREAM("getUVCWhiteBalanceCb " << msg); response.message = msg; return false; } return true; } bool UVCCameraDriver::setUVCWhiteBalanceCb(SetInt32Request& request, SetInt32Response& response) { if (request.data == 0) { uvc_set_white_balance_temperature_auto(device_handle_, 1); return true; } uvc_set_white_balance_temperature_auto(device_handle_, 0); // 0: manual, 1: auto uint8_t data[4]; INT_TO_DW(request.data, data); int unit = uvc_get_processing_units(device_handle_)->bUnitID; int control = UVC_PU_WHITE_BALANCE_TEMPERATURE_CONTROL; int min_white_balance = UVCGetControl(control, unit, sizeof(int16_t), UVC_GET_MIN); int max_white_balance = UVCGetControl(control, unit, sizeof(int16_t), UVC_GET_MAX); if (request.data < min_white_balance || request.data > max_white_balance) { std::stringstream ss; ss << "Please set white balance between " << min_white_balance << " and " << max_white_balance; response.message = ss.str(); ROS_ERROR_STREAM(ss.str()); return false; } int ret = uvc_set_ctrl(device_handle_, unit, control, data, sizeof(int32_t)); if (ret != sizeof(int32_t)) { auto err = static_cast<uvc_error_t>(ret); std::stringstream ss; ss << "set white balance failed " << uvc_strerror(err); ROS_ERROR_STREAM(ss.str()); response.message = ss.str(); return false; } return true; } bool UVCCameraDriver::setUVCAutoExposureCb(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response) { (void)response; if (request.data) { uvc_set_ae_mode(device_handle_, 8); } else { uvc_set_ae_mode(device_handle_, 1); } return true; } bool UVCCameraDriver::setUVCAutoWhiteBalanceCb(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response) { if (request.data) { uvc_set_white_balance_temperature_auto(device_handle_, 1); } else { uvc_set_white_balance_temperature_auto(device_handle_, 0); } response.success = true; return true; } bool UVCCameraDriver::getUVCMirrorCb(GetInt32Request& request, GetInt32Response& response) { (void)request; int16_t mirror; uvc_error_t err = uvc_get_roll_abs(device_handle_, &mirror, UVC_GET_CUR); response.data = mirror; if (err != UVC_SUCCESS) { auto msg = uvc_strerror(err); ROS_ERROR_STREAM("getUVCMirrorCb " << msg); response.message = msg; return false; } return true; } bool UVCCameraDriver::setUVCMirrorCb(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response) { (void)response; uvc_flip_ = request.data; return true; } bool UVCCameraDriver::toggleUVCCamera(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response) { (void)response; if (request.data) { startStreaming(); } else { stopStreaming(); } return true; } bool UVCCameraDriver::saveImageCallback(std_srvs::EmptyRequest& request, std_srvs::EmptyResponse& response) { (void)request; (void)response; save_image_ = true; return true; } int UVCCameraDriver::UVCGetControl(int control, int unit, int len, uvc_req_code req_code) { uint8_t data[4]; int ret = uvc_get_ctrl(device_handle_, unit, control, data, len, req_code); if (ret < 0) { auto err = static_cast<uvc_error>(ret); ROS_ERROR("Failed to get control %d on unit %d: %s", control, unit, uvc_strerror(err)); return -1; } return SW_TO_SHORT(data); } } // namespace astra_camera
#include "stdafx.h" #include "Cage.h" #include "PhysxManager.h" #include "Components.h" #include "../OverlordProject/CourseObjects/Week 2/Character.h" #include "Projectile.h" #include "ContentManager.h" #include "Sparkler.h" #include "SoundManager.h" Cage::Cage(DirectX::XMFLOAT3 position): m_Position(position) { } void Cage::Initialize(const GameContext& gameContext) { SetTag(L"Cage"); UNREFERENCED_PARAMETER(gameContext); auto pRigidBody = new RigidBodyComponent(); pRigidBody->SetKinematic(true); pRigidBody->SetCollisionGroup(Group2); pRigidBody->SetCollisionIgnoreGroups(Group0); AddComponent(pRigidBody); auto physx = PhysxManager::GetInstance()->GetPhysics(); auto pDefaultMaterial = physx->createMaterial(0.f, 0.f, 1.f); // Model auto pModelComponent = new ModelComponent(L"./Resources/Meshes/Cage.ovm"); pModelComponent->SetMaterial(27); AddComponent(pModelComponent); // Physical collider physx::PxConvexMesh* convexMesh = ContentManager::Load<physx::PxConvexMesh>(L"./Resources/Meshes/Cage.ovpc"); std::shared_ptr<physx::PxGeometry> convexGeom(new physx::PxConvexMeshGeometry(convexMesh)); AddComponent(new ColliderComponent(convexGeom, *pDefaultMaterial)); // Hitbox collider std::shared_ptr<physx::PxGeometry> boxGeom(new physx::PxBoxGeometry(3.f,3.f,3.f)); const auto collider = new ColliderComponent(boxGeom, *pDefaultMaterial); AddComponent(collider); GetTransform()->Translate(m_Position); SetOnTriggerCallBack(PhysicsCallback{[this](GameObject* trigger, GameObject* other, GameObject::TriggerAction action) { if (action == GameObject::TriggerAction::ENTER) { if (trigger != other) { Projectile* projectile = dynamic_cast<Projectile*>(other); if (projectile) { --m_Health; FMOD::Sound* pSound; FMOD_RESULT sound; sound = SoundManager::GetInstance()->GetSystem()->createSound("./Resources/Sounds/CageHit.wav", FMOD_DEFAULT,NULL, &pSound); UNREFERENCED_PARAMETER(sound); SoundManager::GetInstance()->GetSystem()->playSound(pSound, NULL, false, 0); if (m_Health == 0 && !m_IsCollected) { m_Player = dynamic_cast<Character*>(projectile->GetParent()); m_Player->IncreaseCageCount(); m_IsCollected = true; } projectile->Die(); } } } } }); collider->EnableTrigger(true); } void Cage::Update(const GameContext& gameContext) { UNREFERENCED_PARAMETER(gameContext); if (m_IsCollected && m_Player != nullptr && GetTransform()->GetPosition().x != 0.f) { FMOD::Sound* pSound; FMOD_RESULT sound; sound = SoundManager::GetInstance()->GetSystem()->createSound("./Resources/Sounds/CageExplode.wav", FMOD_DEFAULT,NULL, &pSound); UNREFERENCED_PARAMETER(sound); SoundManager::GetInstance()->GetSystem()->playSound(pSound, NULL, false, 0); m_Player->CreateLum(GetTransform()->GetPosition()); auto sparkler1 = new Sparkler(GetTransform()->GetPosition(),{0.97f, 0.95f, 0.40f, 1.f}, 0.75f, L"./Resources/Textures/Sparkle.png", 5.f, 4.f, 3); AddChild(sparkler1); auto sparkler2 = new Sparkler(GetTransform()->GetPosition(),{1.f, 1.f, 1.f, 1.f}, 0.75f, L"./Resources/Textures/CageBreak.png", 5.f, 4.f, 3); AddChild(sparkler2); GetTransform()->Translate(0.f,0.f,0.f); } if (m_Player != nullptr) { if (m_IsCollected && m_Player->GetReset() ) { m_Health = 3; m_IsCollected = false; GetTransform()->Translate(m_Position); } } }
#ifndef WPP__QT__IMAGE_PICKER_H #define WPP__QT__IMAGE_PICKER_H #include <QQuickItem> #ifdef Q_OS_ANDROID #include <QAndroidActivityResultReceiver> #endif #include <QFutureWatcher> #include <QFuture> namespace wpp { namespace qt { #ifdef Q_OS_ANDROID class ImagePicker : public QQuickItem, QAndroidActivityResultReceiver #else class ImagePicker : public QQuickItem #endif { Q_OBJECT Q_PROPERTY(int maxPick READ maxPick WRITE setMaxPick NOTIFY maxPickChanged) public: explicit ImagePicker(QQuickItem *parent = 0); int m_maxPick; int maxPick() const { return m_maxPick; } void setMaxPick(int maxPick) { m_maxPick = maxPick; emit maxPickChanged(); } signals: void imagePathChanged(); void maxPickChanged(); void startedImageProcessing(); void accepted(const QStringList& paths); public slots: void open(); #ifdef Q_OS_IOS public slots: void onProcessImageFinished(); #endif private: void *m_delegate; public: #ifdef Q_OS_IOS void __hideUI(); void processImages(void *nsarray); #endif #ifdef Q_OS_ANDROID virtual void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject & data); #endif private: QFutureWatcher<void> *futureWatcher; QFuture<void> * future; }; } } #endif // IOSCAMERA_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2000-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * */ #include "core/pch.h" #include "modules/url/protocols/common.h" #include "modules/url/url_man.h" #include "modules/util/cleanse.h" #ifdef SUPPORT_AUTO_PROXY_CONFIGURATION void GetAutoProxyL(const uni_char *apcString, Base_request_st *request) { UniParameterList proxylist; ANCHOR(UniParameterList, proxylist); ServerName *candidate; unsigned short candidate_port; proxylist.SetValueL(apcString, PARAM_SEP_SEMICOLON | PARAM_NO_ASSIGN | PARAM_ONLY_SEP); UniParameters *param = proxylist.First(); PROXY_type current_type = PROXY_HTTP; ProxyListItem *item = NULL; #ifdef SOCKS_SUPPORT ServerName* socks_server_name = NULL; UINT socks_server_port = 0; #endif while(param && current_type != NO_PROXY && param->GetParametersL(PARAM_SEP_WHITESPACE | PARAM_NO_ASSIGN | PARAM_ONLY_SEP, KeywordIndex_Automatic_Proxy_Configuration)) { UniParameterList *apc_item = param->SubParameters(); UniParameters *apc_param = apc_item->First(); if(apc_param) switch(apc_param->GetNameID()) { case APC_Keyword_Type_Direct: item = OP_NEW_L(ProxyListItem, ()); item->type = current_type = NO_PROXY; item->proxy_candidate = request->origin_host; item->port = request->origin_port; item->Into(&request->connect_list); item = NULL; break; case APC_Keyword_Type_Proxy: current_type = PROXY_HTTP; apc_param = apc_param->Suc(); if(apc_param != NULL) { // Should possibly call prepareservername here. // Ask Yngve about this. OP_STATUS op_err = OpStatus::OK; candidate = urlManager->GetServerName(op_err, apc_param->Name(), candidate_port, TRUE);//FIXME:OOM (unable to report) LEAVE_IF_ERROR(op_err); if (!candidate) { LEAVE(OpStatus::ERR_NO_MEMORY); } if(candidate && candidate->MayBeUsedAsProxy(candidate_port)) { item = OP_NEW_L(ProxyListItem, ()); item->type = current_type; item->proxy_candidate = candidate; item->port = candidate_port; item->Into(&request->connect_list); } } break; #ifdef SOCKS_SUPPORT case APC_Keyword_Type_Socks: //SOCKS proxy (if any) is handled transparently (not chained as other proxies) OP_ASSERT(socks_server_name == NULL); apc_param = apc_param->Suc(); if(apc_param != NULL) { OP_STATUS op_err = OpStatus::OK; candidate = urlManager->GetServerName(op_err, apc_param->Name(), candidate_port, TRUE); LEAVE_IF_ERROR(op_err); if (!candidate) { LEAVE(OpStatus::ERR_NO_MEMORY); } if(candidate && candidate->MayBeUsedAsProxy(candidate_port)) { // substitute the (URL_Manager owned) candidate with a (SocksModule owned) copy: candidate = g_opera->socks_module.GetSocksServerName(candidate); socks_server_name = candidate; socks_server_port = candidate_port; } } break; #endif // SOCKS_SUPPORT } param = param->Suc(); } if(request->connect_list.Cardinal() == 1) { item = (ProxyListItem *) request->connect_list.First(); item->Out(); request->connect_host = item->proxy_candidate; request->connect_port = item->port; request->proxy = item->type; OP_DELETE(item); } else if(!request->connect_list.Empty()) { request->current_connect_host = item = (ProxyListItem *) request->connect_list.First(); request->connect_host = item->proxy_candidate; request->connect_port = item->port; request->proxy = item->type; } #ifdef SOCKS_SUPPORT if (socks_server_name != NULL) { request->connect_host->SetSocksServerName(socks_server_name); request->connect_host->SetSocksServerPort(socks_server_port); } else // flag that the autoconfig did not mention any socks: { request->connect_host->SetNoSocksServer(); } #endif } #endif //SUPPORT_AUTO_PROXY_CONFIGURATION authdata_st::authdata_st() { connect_host = NULL; origin_host = NULL; connect_port = 0; origin_port = 0; #ifdef _SUPPORT_PROXY_NTLM_AUTH_ session_based_support = FALSE; #endif auth_headers = OP_NEW(HeaderList, ()); //OOM: This is checked in CheckAuthData. } authdata_st::~authdata_st() { OP_DELETE(auth_headers); } #ifdef HTTP_DIGEST_AUTH void HTTP_Request_digest_data::ClearAuthentication() { if(used_A1) OPERA_cleanse(used_A1, op_strlen(used_A1)); if(used_cnonce) OPERA_cleanse(used_cnonce, op_strlen(used_cnonce)); if(used_nonce) OPERA_cleanse(used_nonce, op_strlen(used_nonce)); OP_DELETE(entity_hash); entity_hash = NULL; OP_DELETEA(used_A1); OP_DELETEA(used_cnonce); OP_DELETEA(used_nonce); used_A1 = NULL; used_cnonce = NULL; used_nonce = NULL; } #endif //HTTP_DIGEST_AUTH
#include "A.hpp" using namespace std; A::A(char d) { data = d; cout << "cons " << d << endl; } A::A(const A& other) { data = other.data; cout << "ccons " << data << endl; } A::~A() { cout << "dest " << data << endl; } A& A::operator=(const A& other) { cout << "cassign " << data << " = " << other.data << endl; data = other.data; return *this; } void A::show() { cout << "show " << data << endl; }
#include <sys/stat.h> #include <sys/types.h> #include <time.h> #include <sys/time.h> #include <jni.h> #include <android/log.h> #include "debuginfo.h" DebugLog* DebugLog::m_instance = NULL; DebugLog* DebugLog::GetInstance() { if(m_instance == NULL) { m_instance = new DebugLog(); } return m_instance; } DebugLog::DebugLog() { m_pflog = NULL; m_level = LEVEL_ERROR; m_target= TARGET_STDERR; pthread_mutex_init(&m_csLog, NULL); // if(mkdir(LOG_DIR, S_IRWXU | S_IRGRP | S_IXGRP| S_IROTH) !=0)//´´½¨ÐÂĿ¼ // { // WritrLog(LEVEL_ERROR, "mkdir %s failed\n", LOG_DIR); // } } DebugLog::~DebugLog() { if(m_pflog != NULL) { fclose(m_pflog); m_pflog = NULL; } } void DebugLog::LogV(const char *pszFmt,va_list argp) { if (NULL == pszFmt|| 0 == pszFmt[0]) return; vsnprintf(m_logstr,MAX_LOG_SIZE,pszFmt,argp); struct timeval tv; time_t nowtime; struct tm *nowtm; char tmbuf[64], buf[64]; gettimeofday(&tv, NULL); nowtime = tv.tv_sec; nowtm = localtime(&nowtime); strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", nowtm); snprintf(buf, sizeof buf, "[%s.%03d]", tmbuf, tv.tv_usec/1000); if(m_target == TARGET_LOGFILE) { if(NULL == m_pflog && m_logFile != NULL) { m_pflog = fopen(m_logFile, "a"); } if (NULL != m_pflog) { fprintf(m_pflog,"[%s] %s", buf, m_logstr); if (ftell(m_pflog) > MAX_LOG_SIZE) { fclose(m_pflog); m_pflog = NULL; if (rename(m_logFile, m_logFile2)) { remove(m_logFile2); rename(m_logFile, m_logFile2); } } else { fclose(m_pflog); m_pflog = NULL; } } } //fprintf(stdout,"[%s] %s",buf, m_logstr); __android_log_print(ANDROID_LOG_ERROR, "rtsp-jni", "%s", m_logstr); } void DebugLog::WritrLog(int level, const char *pszFmt,...) { if(level <= m_level) { va_list argp; pthread_mutex_lock(&m_csLog); { va_start(argp,pszFmt); LogV(pszFmt,argp); va_end(argp); } pthread_mutex_unlock(&m_csLog); } } void DebugLog::SetDebugInit(int level, int target, char* logFile) { if(logFile == NULL) { return; } if(strlen(logFile) >= 256) { return; } else { strncpy(m_logFile, logFile, strlen(logFile)); strncpy(m_logFile2, m_logFile, strlen(m_logFile)); strncat(m_logFile2, "2", 1); } m_level = level; m_target= target; }
#include <algorithm> #include "variable.h" variable::variable(int min_val, int max_val): _set(false) { for (int i = min_val; i <= max_val; i++) _domain.push_back(i); } variable::variable(const variable& obj) { _set = obj._set; _value = obj._value; _domain = std::vector<int>(obj._domain); } void variable::set_value(int value) { _set = true; _value = value; } int variable::get_value() { return _value; } bool variable::is_set() { return _set; } std::vector<int>& variable::get_domain() { return _domain; } void variable::remove_domain_value(int value) { auto it = std::find(_domain.begin(),_domain.end(),value); if (it != _domain.end()) _domain.erase(it); } void variable::add_domain_value(int value) { _domain.push_back(value); } int variable::get_domain_size() { return _domain.size(); } bool variable::is_domain_exhausted() { return !_set && _domain.size() == 0; }
/** * Copyright (c) 2017, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file text_format.cc */ #include <set> #include "text_format.hh" #include "config.h" #include "pcrepp/pcre2pp.hh" #include "yajl/api/yajl_parse.h" text_format_t detect_text_format(string_fragment sf, nonstd::optional<ghc::filesystem::path> path) { static const std::set<ghc::filesystem::path> FILTER_EXTS = { ".bz2", ".gz", ".lzma", ".xz", ".zst", }; static const auto C_EXTS = std::set<ghc::filesystem::path>{ ".h", ".hh", ".hpp", ".c", ".cc", ".cpp", ".tpp", }; static const auto PY_EXT = ghc::filesystem::path(".py"); static const auto RS_EXT = ghc::filesystem::path(".rs"); static const auto JAVA_EXT = ghc::filesystem::path(".java"); static const auto TOML_EXT = ghc::filesystem::path(".toml"); static const auto XML_EXT = ghc::filesystem::path(".xml"); static const auto YAML_EXT = ghc::filesystem::path(".yaml"); static const auto YML_EXT = ghc::filesystem::path(".yml"); static const auto MAKEFILE_STEM = ghc::filesystem::path("Makefile"); static const auto MD_EXT = ghc::filesystem::path(".md"); static const auto MARKDOWN_EXT = ghc::filesystem::path(".markdown"); static const auto MAN_MATCHERS = lnav::pcre2pp::code::from_const( R"(^[A-Za-z][A-Za-z\-_\+0-9]+\(\d\)\s+)", PCRE2_MULTILINE); // XXX This is a pretty crude way of detecting format... static const auto PYTHON_MATCHERS = lnav::pcre2pp::code::from_const( "(?:" "^\\s*def\\s+\\w+\\([^)]*\\):[^\\n]*$|" "^\\s*try:[^\\n]*$" ")", PCRE2_MULTILINE); static const auto RUST_MATCHERS = lnav::pcre2pp::code::from_const(R"( (?: ^\s*use\s+[\w+:\{\}]+;$| ^\s*(?:pub enum|pub const|(?:pub )?fn)\s+\w+.*$| ^\s*impl\s+\w+.*$ ) )", PCRE2_MULTILINE); static const auto JAVA_MATCHERS = lnav::pcre2pp::code::from_const( "(?:" "^package\\s+|" "^import\\s+|" "^\\s*(?:public)?\\s*class\\s*(\\w+\\s+)*\\s*{" ")", PCRE2_MULTILINE); static const auto C_LIKE_MATCHERS = lnav::pcre2pp::code::from_const( "(?:" "^#\\s*include\\s+|" "^#\\s*define\\s+|" "^\\s*if\\s+\\([^)]+\\)[^\\n]*$|" "^\\s*(?:\\w+\\s+)*class \\w+ {" ")", PCRE2_MULTILINE); static const auto SQL_MATCHERS = lnav::pcre2pp::code::from_const( "(?:" "select\\s+.+\\s+from\\s+|" "insert\\s+into\\s+.+\\s+values" ")", PCRE2_MULTILINE | PCRE2_CASELESS); static const auto XML_MATCHERS = lnav::pcre2pp::code::from_const( "(?:" R"(<\?xml(\s+\w+\s*=\s*"[^"]*")*\?>|)" R"(</?\w+(\s+\w+\s*=\s*"[^"]*")*\s*>)" ")", PCRE2_MULTILINE | PCRE2_CASELESS); if (path) { while (FILTER_EXTS.count(path->extension()) > 0) { path = path->stem(); } auto stem = path->stem(); auto ext = path->extension(); if (ext == MD_EXT || ext == MARKDOWN_EXT) { return text_format_t::TF_MARKDOWN; } if (C_EXTS.count(ext) > 0) { return text_format_t::TF_C_LIKE; } if (ext == PY_EXT) { return text_format_t::TF_PYTHON; } if (ext == RS_EXT) { return text_format_t::TF_RUST; } if (ext == TOML_EXT) { return text_format_t::TF_TOML; } if (ext == JAVA_EXT) { return text_format_t::TF_JAVA; } if (ext == YAML_EXT || ext == YML_EXT) { return text_format_t::TF_YAML; } if (ext == XML_EXT) { return text_format_t::TF_XML; } if (stem == MAKEFILE_STEM) { return text_format_t::TF_MAKEFILE; } } { auto_mem<yajl_handle_t> jhandle(yajl_free); jhandle = yajl_alloc(nullptr, nullptr, nullptr); if (yajl_parse(jhandle, sf.udata(), sf.length()) == yajl_status_ok) { return text_format_t::TF_JSON; } } if (MAN_MATCHERS.find_in(sf).ignore_error()) { return text_format_t::TF_MAN; } if (PYTHON_MATCHERS.find_in(sf).ignore_error()) { return text_format_t::TF_PYTHON; } if (RUST_MATCHERS.find_in(sf).ignore_error()) { return text_format_t::TF_RUST; } if (JAVA_MATCHERS.find_in(sf).ignore_error()) { return text_format_t::TF_JAVA; } if (C_LIKE_MATCHERS.find_in(sf).ignore_error()) { return text_format_t::TF_C_LIKE; } if (SQL_MATCHERS.find_in(sf).ignore_error()) { return text_format_t::TF_SQL; } if (XML_MATCHERS.find_in(sf).ignore_error()) { return text_format_t::TF_XML; } return text_format_t::TF_UNKNOWN; } nonstd::optional<text_format_meta_t> extract_text_meta(string_fragment sf, text_format_t tf) { static const auto MAN_NAME = lnav::pcre2pp::code::from_const( R"(^([A-Za-z][A-Za-z\-_\+0-9]+\(\d\))\s+)", PCRE2_MULTILINE); switch (tf) { case text_format_t::TF_MAN: { static thread_local auto md = lnav::pcre2pp::match_data::unitialized(); auto find_res = MAN_NAME.capture_from(sf).into(md).matches().ignore_error(); if (find_res) { return text_format_meta_t{ md.to_string(), }; } break; } default: break; } return nonstd::nullopt; }
#pragma once #include <SFML/Graphics.hpp> #include <memory> #include <stack> #include "Updatable.hpp" #include "SoundManager.hpp" class Game { public: Game(); ~Game(); void handleEvent(); void update(const sf::Time& deltaTime); void draw(); void stop(); void pushState(std::unique_ptr<Updatable> state); void popState(); void clearAllStates(); void playSound(SoundManager::SoundType soundType); bool isRunning(); static Game& getInstance(); const sf::RenderWindow& getWindow(); const sf::Font& getFont(); private: sf::RenderWindow window; sf::Font font; SoundManager soundManager; std::stack<std::unique_ptr<Updatable>> states; };
#include <bits/stdc++.h> using namespace std; int main() { unsigned int ano; bool f = false; int n; scanf("%d", &n); while(n--) { scanf("%u", &ano); if(ano>=2015) { f = true; ano-=2014; } else ano = 2015 - ano; if(f) printf("%u A.C.\n", ano); else printf("%u D.C.\n", ano); f = false; } return 0; }
// http://oj.leetcode.com/problems/scramble-string/ class Solution { public: bool isScramble(string s1, string s2) { if (s1.size() != s2.size()) return false; int size = s1.size(); int alpha[26]; memset(alpha, 0, 26 * sizeof(alpha[0])); for (int i = 0; i < size; i++) { alpha[s1[i]-'a']++; } for (int i = 0; i < size; i++) { alpha[s2[i]-'a']--; } for (int i = 0; i < 26; i++) { if (alpha[i] != 0) return false; } if (size == 1) return true; for (int i = 1; i < size; i++) { if (isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i), s2.substr(i))) { return true; } if (isScramble(s1.substr(0, i), s2.substr(size - i)) && isScramble(s1.substr(i), s2.substr(0, size - i))) { return true; } } return false; } };
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // UnityEngine.Texture2D struct Texture2D_t3884108195; // System.String struct String_t; // System.Object struct Il2CppObject; #include "mscorlib_System_Object4170816371.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // InitShare/<TakeScreenshot>c__Iterator0 struct U3CTakeScreenshotU3Ec__Iterator0_t1360893940 : public Il2CppObject { public: // System.Int32 InitShare/<TakeScreenshot>c__Iterator0::<width>__0 int32_t ___U3CwidthU3E__0_0; // System.Int32 InitShare/<TakeScreenshot>c__Iterator0::<height>__1 int32_t ___U3CheightU3E__1_1; // UnityEngine.Texture2D InitShare/<TakeScreenshot>c__Iterator0::<tex>__2 Texture2D_t3884108195 * ___U3CtexU3E__2_2; // System.String InitShare/<TakeScreenshot>c__Iterator0::<shareDefaultText>__3 String_t* ___U3CshareDefaultTextU3E__3_3; // System.Int32 InitShare/<TakeScreenshot>c__Iterator0::$PC int32_t ___U24PC_4; // System.Object InitShare/<TakeScreenshot>c__Iterator0::$current Il2CppObject * ___U24current_5; public: inline static int32_t get_offset_of_U3CwidthU3E__0_0() { return static_cast<int32_t>(offsetof(U3CTakeScreenshotU3Ec__Iterator0_t1360893940, ___U3CwidthU3E__0_0)); } inline int32_t get_U3CwidthU3E__0_0() const { return ___U3CwidthU3E__0_0; } inline int32_t* get_address_of_U3CwidthU3E__0_0() { return &___U3CwidthU3E__0_0; } inline void set_U3CwidthU3E__0_0(int32_t value) { ___U3CwidthU3E__0_0 = value; } inline static int32_t get_offset_of_U3CheightU3E__1_1() { return static_cast<int32_t>(offsetof(U3CTakeScreenshotU3Ec__Iterator0_t1360893940, ___U3CheightU3E__1_1)); } inline int32_t get_U3CheightU3E__1_1() const { return ___U3CheightU3E__1_1; } inline int32_t* get_address_of_U3CheightU3E__1_1() { return &___U3CheightU3E__1_1; } inline void set_U3CheightU3E__1_1(int32_t value) { ___U3CheightU3E__1_1 = value; } inline static int32_t get_offset_of_U3CtexU3E__2_2() { return static_cast<int32_t>(offsetof(U3CTakeScreenshotU3Ec__Iterator0_t1360893940, ___U3CtexU3E__2_2)); } inline Texture2D_t3884108195 * get_U3CtexU3E__2_2() const { return ___U3CtexU3E__2_2; } inline Texture2D_t3884108195 ** get_address_of_U3CtexU3E__2_2() { return &___U3CtexU3E__2_2; } inline void set_U3CtexU3E__2_2(Texture2D_t3884108195 * value) { ___U3CtexU3E__2_2 = value; Il2CppCodeGenWriteBarrier(&___U3CtexU3E__2_2, value); } inline static int32_t get_offset_of_U3CshareDefaultTextU3E__3_3() { return static_cast<int32_t>(offsetof(U3CTakeScreenshotU3Ec__Iterator0_t1360893940, ___U3CshareDefaultTextU3E__3_3)); } inline String_t* get_U3CshareDefaultTextU3E__3_3() const { return ___U3CshareDefaultTextU3E__3_3; } inline String_t** get_address_of_U3CshareDefaultTextU3E__3_3() { return &___U3CshareDefaultTextU3E__3_3; } inline void set_U3CshareDefaultTextU3E__3_3(String_t* value) { ___U3CshareDefaultTextU3E__3_3 = value; Il2CppCodeGenWriteBarrier(&___U3CshareDefaultTextU3E__3_3, value); } inline static int32_t get_offset_of_U24PC_4() { return static_cast<int32_t>(offsetof(U3CTakeScreenshotU3Ec__Iterator0_t1360893940, ___U24PC_4)); } inline int32_t get_U24PC_4() const { return ___U24PC_4; } inline int32_t* get_address_of_U24PC_4() { return &___U24PC_4; } inline void set_U24PC_4(int32_t value) { ___U24PC_4 = value; } inline static int32_t get_offset_of_U24current_5() { return static_cast<int32_t>(offsetof(U3CTakeScreenshotU3Ec__Iterator0_t1360893940, ___U24current_5)); } inline Il2CppObject * get_U24current_5() const { return ___U24current_5; } inline Il2CppObject ** get_address_of_U24current_5() { return &___U24current_5; } inline void set_U24current_5(Il2CppObject * value) { ___U24current_5 = value; Il2CppCodeGenWriteBarrier(&___U24current_5, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
#ifndef KEYBOARD_H #define KEYBOARD_H #include "xil_types.h" class Keyboard { public: Keyboard(uint32_t baseaddr); uint8_t IsKeyPressed(); uint8_t GetKey() const; private: uint32_t baseaddr; uint8_t key; }; #endif
#include <bits/stdc++.h> using namespace std; void bfs_result(vector<int>& levels, vector<int>& parents, int s) { for(int i=1; i<levels.size();++i) { if(i==s) continue; if(levels[i] == -1) { cout << "There is no path from " << s << " to " << i << endl; } else { int v = i; cout << "The path from " << s << " to " << i << " is : " << v; while(parents[v] != -1) { cout << "<-" << parents[v]; v = parents[v]; } cout << endl; } } } void digokey_result(vector<int>& levels, vector<int>& parents) { int n = levels.size()-1; if(levels[n] == -1) { cout << "-1" << endl; } else { cout << levels[n] << endl; vector<int> path; int v = n; while(parents[v] != -1) { path.push_back(v); v = parents[v]; } path.push_back(1); for_each(path.rbegin(), path.rend()-1, [](auto& el) { cout << el << " "; }); cout << endl; } } void bfs(const vector<vector<int>>& adj_list, vector<int>& levels, vector<int>& parents, int s) { auto frontier = make_shared<vector<int>>(); shared_ptr<vector<int>> next; frontier->push_back(s); levels[s] = 0; int i = 1; while(!frontier->empty()) { next = make_shared<vector<int>>(); for(auto& u : *frontier) { for(auto& v : adj_list[u]) { if(levels[v] == -1) { levels[v] = i; parents[v] = u; next->push_back(v); } } } frontier = next; ++i; } digokey_result(levels, parents); } template <typename T> void print_container(vector<T>& x) { for_each(x.begin(), x.end(), [](auto &el) { cout << el << "\t"; }); cout << endl; } int main() { ios::sync_with_stdio(0); cin.tie(0); freopen("treasures.txt", "r", stdin); int T; cin >> T; while(T--) { int N; cin >> N; vector<vector<int>> adj_lists(N+1); for(int i=1; i<N; ++i) { int Mi; cin >> Mi; for(int j=1;j<=Mi;++j) { int neighbor; cin >> neighbor; adj_lists[i].push_back(neighbor); sort(adj_lists[i].begin(), adj_lists[i].end()); } } vector<int> levels(adj_lists.size(), -1); vector<int> parents(adj_lists.size(), -1); bfs(adj_lists, levels, parents, 1); cout << endl; } fclose(stdin); return 0; }
// 1.16(화) Day 4 // 과제 : 숫자 야구 게임 만들기 // 중복되지 않는 숫자 #include <iostream> #include <time.h> using namespace std; void main() { srand(time(NULL)); int GameCount = 0; int number[10]; int baseBallNumber[4]; int selectNumber[4]; for (int i = 0; i < 10; i++) number[i] = i ; // 셔플 for (int i = 0; i < 1000; i++) { int des, src, temp; des = rand() % 10; src = rand() % 10; temp = number[des]; number[des] = number[src]; number[src] = temp; } // 테스트 //for (int i = 0; i < 10; i++) // cout << number[i] << " "; //cout << endl; // 셔플된 숫자 중 4개를 야구 숫자로 선택 for (int i = 0; i < 4; i++) baseBallNumber[i] = number[i]; while (true) { cout << GameCount << "번째 게임" << endl; // 치트 cout << "[치트] 정답 : "; for (int i = 0; i < 4; i++) cout << baseBallNumber[i] << " "; cout << endl; int strike, ball; strike = ball = 0; bool isCheck = false; cout << "\t중복되지 않는 4개의 숫자를 입력하세요 : "; // 4개의 입력값 받기 for (int i = 0; i < 4; i++) { cin >> selectNumber[i]; } // 입력값 예외 처리 // 잘못 입력된 예외 for (int i = 0; i < 4; i++) { if (selectNumber[i] < 0 || selectNumber[i] > 9) { cout << "\t잘 못 입력하였습니다. 다시 입력하세요" << endl; isCheck = true; break; } } if (isCheck == false) { // 중복된 예외 처리 for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { if (j == k) continue; else if (selectNumber[j] == selectNumber[k]) { cout << "\t중복된 값이 있습니다. 다시 입력하세요." << endl; isCheck = true; break; } } if (isCheck == true) break; } } if (isCheck == true) { continue; } // 선택한 숫자 비교 for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (baseBallNumber[i] == selectNumber[j]) { if (i == j) strike++; else ball++; } } } cout << "\t게임 결과 : " << "스트라이크 " << strike << "," << "볼 " << ball << ", " << "아웃 " << 4 - strike - ball << endl; if (strike == 4) { cout << "\t게임에서 승리하였습니다." << endl; break; } GameCount++; cout << endl; // 10번 이상시 패배 if (GameCount > 10) { cout << "패배 하였습니다." << endl; break; } } } // int 에 char 형 cin으로 받을시 안들어가는 거 같음 // 해결 방안 찾아보자
#pragma once #include "PBRPipeline.h" #include "AppFrameWork2.h" class App_PBR :public App { public: void Init() { render = new EGLRenderSystem; render->SetWandH(w, h); render->Initialize(); InitDevice(); InitPipeline(); CreateScene(); } void InitPipeline() { pipeline = new PBRPipeline2; pipeline->Init(); } void Render() { pipeline->Render(); } void CreateScene() { scene = new OctreeSceneManager("scene1", render); SceneContainer::getInstance().add(scene); SceneNode* pRoot = scene->GetSceneRoot(); camera = scene->CreateCamera("main"); camera->lookAt(Vector3(0, 0, 2.5), Vector3(0, 0, 0), Vector3(0, 1, 0)); float fovy = 45; camera->setPerspective(fovy, float(w) / float(h), 0.01, 100); loadModels(); } void loadModels() { SceneNode* root = scene->GetSceneRoot(); SceneNode* s; for (int i = 0; i < 8; i++) { stringstream ss; ss << "model/pbr_test/sphere" << i << ".obj"; s = LoadMeshtoSceneNode(ss.str(), "sphere" + to_string(i)); s->scale(0.15, 0.15, 0.15); s->translate(i*0.33 - 1.1, -0.2, 0); root->attachNode(s); } for (int i = 0; i < 8; i++) { stringstream ss; ss << "model/pbr_test/sphere" << i << "d.obj"; s = LoadMeshtoSceneNode(ss.str(), "sphere" + to_string(i)+"d"); s->scale(0.15, 0.15, 0.15); s->translate(i*0.33 - 1.1, 0.2, 0); root->attachNode(s); } } };
/* BEGIN LICENSE */ /***************************************************************************** * SKCore : the SK core library * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: skptr.h,v 1.8.4.3 2005/02/17 15:29:20 krys Exp $ * * Authors: Mathieu Poumeyrol <poumeyrol @at@ idm .dot. fr> * Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #ifndef __SKC_SKPTR_H_ #define __SKC_SKPTR_H_ #define err_skptr_invalid 101 template <class T> inline T* skPtrAssign(T** pp, T* lp) { // XXX This code is very critical when there are reference loops because // XXX the call to the Release() method may re-enter this function. // 1/ Increment the reference counter of the new pointer if (lp != NULL) lp->AddRef(); // 2/ Replace the pointer with the new one because it should be released // if the function is re-entered. The old pointer is saved so that we can // release it after. T* oldp = *pp; *pp = lp; // 3/ Release the old pointer _safely_. if (oldp) oldp->Release(); return lp; } template <class T> class _NoAddRefReleaseOnskPtr : public T { private: virtual long AddRef()=0; virtual long Release()=0; }; template <class T> class skPtr { public: typedef T _PtrClass; skPtr() { p=NULL; } skPtr(T* lp) { if ((p = lp) != NULL) p->AddRef(); } skPtr(const skPtr<T>& lp) { if ((p = lp.p) != NULL) p->AddRef(); } ~skPtr() { SKRefCount* pTemp = p; if (pTemp) { p = NULL; pTemp->Release(); } } void Release() { SKRefCount* pTemp = p; if (pTemp) { p = NULL; pTemp->Release(); } } operator T*() const { return (T*)p; } T& operator*() const { SK_ASSERT(p!=NULL); return *p; } // XXX This operator is an ** ATOMIC BOMB **. If you want to prevent // XXX the world from exploding then DON'T USE IT. // XXX -- bozo //The SK_ASSERT on operator& usually indicates a bug. If this is really //what is needed, however, take the address of the p member explicitly. /* T** operator&() { SK_ASSERT(p==NULL); return &p; }*/ _NoAddRefReleaseOnskPtr<T>* operator->() const { SK_ASSERT(p!=NULL); return (_NoAddRefReleaseOnskPtr<T>*)p; } inline T* AssignSafeIID(SKRefCount *lp); T* operator=(T* lp) { return (T*)skPtrAssign(&p, lp); } T* operator=(const skPtr<T>& lp) { return (T*)skPtrAssign(&p, lp.p); } bool operator!() const { return (p == NULL); } bool operator<(T* pT) const { return p < pT; } bool operator==(T* pT) const { return p == pT; } void Attach(T* p2) { if (p) p->Release(); p = p2; } T* Detach() { T* pt = p; p = NULL; return pt; } SKERR CopyTo(T** ppT) { if (ppT == NULL) return err_skptr_invalid; *ppT = p; if (p) p->AddRef(); return 0; } T** already_AddRefed() { Release(); return &p; } T* p; }; class skAutoLock { public: skAutoLock(SKRefCount *pObject, PRBool bNoLock = PR_FALSE) { m_bNoLock = bNoLock; if(pObject) { if(!m_bNoLock) pObject->Lock(); m_pObject = pObject; } } ~skAutoLock() { if(m_pObject && !m_bNoLock) { SKRefCount *pObject = m_pObject; pObject->AddRef(); m_pObject = NULL; pObject->ReleaseAndUnlock(); } } private: skPtr<SKRefCount> m_pObject; PRPackedBool m_bNoLock; }; #define SK_REFCOUNT_DECLARE_INTERFACE(_class, _iid) \ static const skIID &_class##_GetSKIID() \ { \ static const skIID iid = _iid; \ return iid; \ } \ template <> inline _class* skPtr<_class>::AssignSafeIID(SKRefCount *lp) \ { \ if(!lp) \ return (_class*)skPtrAssign(&p, (_class*)lp); \ Release(); \ lp->QuerySKInterface(_class##_GetSKIID(), (void **)&p); \ return p; \ } SK_REFCOUNT_DECLARE_INTERFACE(SKRefCount, SK_SKREFCOUNT_IID); #endif /* __SKC_SKPTR_H_ */
/* * @lc app=leetcode.cn id=26 lang=cpp * * [26] 删除排序数组中的重复项 */ // @lc code=start #include<iostream> #include<vector> using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { int n = nums.size(); if(n==0)return 0; int slow = 0; int fast = 1; while(fast < n) { if(nums[fast]!=nums[slow]) { slow++; nums[slow] = nums[fast]; } fast++; } return slow+1; } // int removeDuplicates(vector<int>& nums) { // if(nums.size()<=1)return nums.size(); // int pos = 1; // int pre = nums[0]; // for(int i=1;i<nums.size();i++){ // if(nums[i]==pre){ // continue; // }else{ // nums[pos++]=nums[i]; // pre = nums[i]; // } // } // return pos; // } }; // @lc code=end
// Alfred Shaker // accumulating_observer.h // cs33901 #ifndef ACCUMULATING_OBSERVER #define ACCUMULATING_OBSERVER #include "observer.h" #include "observable.h" #include <iostream> #include <vector> class AccumulatingObserver : public Observer { public: virtual void update(Observable*); void show_data(); private: std::vector<char> upperCase; }; #endif
#include "afficherfournisseur.h" #include "ui_afficherfournisseur.h" afficherfournisseur::afficherfournisseur(QWidget *parent) : QDialog(parent), ui(new Ui::afficherfournisseur) { ui->setupUi(this); ui->fornisseurView->hide(); } afficherfournisseur::~afficherfournisseur() { delete ui; } void afficherfournisseur::on_FournisseurPB_clicked() { ui->fornisseurView->show(); ui->fornisseurView->setModel(tmpCp.afficherfournisseur()); }
#include "message.h" Message::Message(){ subject = ""; to = ""; from = ""; body = ""; }
#include <cppunit/extensions/HelperMacros.h> #include "cppunit/BetterAssert.h" #include "di/DIDaemon.h" using namespace std; namespace BeeeOn { class TestableDIDaemon : public DIDaemon { public: TestableDIDaemon(): DIDaemon(About()) { } using DIDaemon::handleVersion; using DIDaemon::versionRequested; using DIDaemon::handleHelp; using DIDaemon::helpRequested; using DIDaemon::handleDefine; }; class DIDaemonTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(DIDaemonTest); CPPUNIT_TEST(testHandleVersion); CPPUNIT_TEST(testHandleHelp); CPPUNIT_TEST(testDefineKeyValue); CPPUNIT_TEST(testDefineKeyWithoutValue); CPPUNIT_TEST(testDefineKeyValueWithEqualsSign); CPPUNIT_TEST_SUITE_END(); public: void testHandleVersion(); void testHandleHelp(); void testDefineKeyValue(); void testDefineKeyWithoutValue(); void testDefineKeyValueWithEqualsSign(); }; CPPUNIT_TEST_SUITE_REGISTRATION(DIDaemonTest); void DIDaemonTest::testHandleVersion() { TestableDIDaemon daemon; CPPUNIT_ASSERT(!daemon.versionRequested()); daemon.handleVersion("version", ""); CPPUNIT_ASSERT(daemon.versionRequested()); } void DIDaemonTest::testHandleHelp() { TestableDIDaemon daemon; CPPUNIT_ASSERT(!daemon.helpRequested()); daemon.handleHelp("help", ""); CPPUNIT_ASSERT(daemon.helpRequested()); } void DIDaemonTest::testDefineKeyValue() { TestableDIDaemon daemon; CPPUNIT_ASSERT(!daemon.config().has("name")); daemon.handleDefine("define", "name=value"); CPPUNIT_ASSERT_EQUAL("value", daemon.config().getString("name")); CPPUNIT_ASSERT(!daemon.config().has("application.name")); daemon.handleDefine("define", "application.name=Test"); CPPUNIT_ASSERT_EQUAL("Test", daemon.config().getString("application.name")); } void DIDaemonTest::testDefineKeyWithoutValue() { TestableDIDaemon daemon; CPPUNIT_ASSERT(!daemon.config().has("name")); daemon.handleDefine("define", "name="); CPPUNIT_ASSERT(daemon.config().has("name")); CPPUNIT_ASSERT(daemon.config().getString("name").empty()); CPPUNIT_ASSERT(!daemon.config().has("name2")); daemon.handleDefine("define", "name2"); CPPUNIT_ASSERT(daemon.config().has("name2")); CPPUNIT_ASSERT(daemon.config().getString("name2").empty()); } void DIDaemonTest::testDefineKeyValueWithEqualsSign() { TestableDIDaemon daemon; CPPUNIT_ASSERT(!daemon.config().has("name")); daemon.handleDefine("define", "name=xxx=value"); CPPUNIT_ASSERT_EQUAL("xxx=value", daemon.config().getString("name")); } }
#include <cmath> #include <iostream> #include "predefine.h" #include "matrix_elements.h" #include "lorentz.h" #include "simpleLogger.h" ////////////////////// Hard Quark ////////////////////////// /// Q + q --> Q + q + g double M2_Qq2Qqg(const double * x_, void * params_){ // unpack variables, parameters and check integration range double * params = static_cast<double*>(params_); double s = params[0]; double sqrts = std::sqrt(s); double T = params[1]; double M2 = params[2]*params[2]; double Qmax = (s-M2)/2./sqrts; double log_1_ktT = x_[0], y_norm = x_[1], // in 3-body com frame---(1) costheta34 = x_[2], phi34 =x_[3]; // in p3-p4 com frame---(2) // (1) and (2) share the same z-direction, and are related by a boost // check bounds double kt = T*(std::exp(log_1_ktT)-1.); if (std::abs(costheta34)>=1.||phi34<=0.||phi34>=2.*M_PI||kt>=Qmax||kt<=0.||std::abs(y_norm)>=.999) return 0.; double ymax = std::acosh(Qmax/kt); double y = y_norm*ymax; // construct k^mu fourvec kmu{kt*std::cosh(y), kt, 0, kt*std::sinh(y)}; double s34 = s - 2.*sqrts*kmu.t(); double sqrts34 = std::sqrt(s34); double Q34 = (s34-M2)/2./sqrts34, E34 = (s34+M2)/2./sqrts34; // construct p3, p4 in (2) frame double cosphi34 = std::cos(phi34), sinphi34 = std::sin(phi34), sintheta34 = std::sqrt(1.-std::pow(costheta34,2)); fourvec p3mu{E34, Q34*sintheta34*cosphi34, Q34*sintheta34*sinphi34, Q34*costheta34}; fourvec p4mu{Q34, -Q34*sintheta34*cosphi34, -Q34*sintheta34*sinphi34, -Q34*costheta34}; // boost p3, p4 back to 3-body CoM Frame double V0 = sqrts - kmu.t(); double v34[3] = {-kmu.x()/V0, -kmu.y()/V0, -kmu.z()/V0}; p3mu = p3mu.boost_back(v34[0], v34[1], v34[2]); p4mu = p4mu.boost_back(v34[0], v34[1], v34[2]); // q-perp-vec, q = p2-p4, qperp = -p4perp double qx = -p4mu.x(), qy = -p4mu.y(); double kt2 = kmu.x()*kmu.x() + kmu.y()*kmu.y(); double t = -2.*Qmax*(p4mu.t()+p4mu.z()); if(y < 0){ qx = -p3mu.x(); qy = -p3mu.y(); t = -2.*Qmax*(p3mu.t()-p3mu.z()); } double mg2 = t_channel_mD2->get_mD2(T) / 2.; double xbar = (kmu.t()+std::abs(kmu.z()))/sqrts; double one_minus_xbar = 1. - xbar; double MA[2], MB[2], MC[2], A[2], B[2]; MA[0] = kmu.x() - qx; MA[1] = kmu.y() - qy; MB[0] = kmu.x() - xbar*qx; MB[1] = kmu.y() - xbar*qy; MC[0] = kmu.x(); MC[1] = kmu.y(); double DA = MA[0]*MA[0] + MA[1]*MA[1] + (1.-xbar)*mg2; double DB = MB[0]*MB[0] + MB[1]*MB[1] + (1.-xbar)*mg2; double DC = MC[0]*MC[0] + MC[1]*MC[1] + (1.-xbar)*mg2; A[0] = MA[0]/DA-MB[0]/DB; A[1] = MA[1]/DA-MB[1]/DB; B[0] = MA[0]/DA-MC[0]/DC; B[1] = MA[1]/DA-MC[1]/DC; double A2 = std::pow(A[0],2) + std::pow(A[1],2); double B2 = std::pow(B[0],2) + std::pow(B[1],2); double AB = A[0]*B[0] + A[1]*B[1]; double M2_elastic = M2_Qq2Qq(t, params); double Pg = alpha_s(kt2, T) * one_minus_xbar * (1. + std::pow(one_minus_xbar, 2)) / 2. * (CF*A2 + CF*B2 - (2.*CF-CA)*AB)/CA; // Jacobian double J = (1.0 - M2/s34) * M_PI/8./std::pow(2*M_PI,5) * kt * (kt + T) * ymax; // 2->3 = 2->2 * 1->2 return c48pi*M2_elastic*Pg*J; } /// Q + g --> Q + g + g double M2_Qg2Qgg(const double * x_, void * params_){ // unpack variables, parameters and check integration range double * params = static_cast<double*>(params_); double s = params[0]; double sqrts = std::sqrt(s); double T = params[1]; double M2 = params[2]*params[2]; double Qmax = (s-M2)/2./sqrts; double log_1_ktT = x_[0], y_norm = x_[1], // in 3-body com frame---(1) costheta34 = x_[2], phi34 =x_[3]; // in p3-p4 com frame---(2) // (1) and (2) share the same z-direction, and are related by a boost // check bounds double kt = T*(std::exp(log_1_ktT)-1.); if (std::abs(costheta34)>=1.||phi34<=0.||phi34>=2.*M_PI||kt>=Qmax||kt<=0.||std::abs(y_norm)>=.999) return 0.; double ymax = std::acosh(Qmax/kt); double y = y_norm*ymax; // construct k^mu fourvec kmu{kt*std::cosh(y), kt, 0, kt*std::sinh(y)}; double s34 = s - 2.*sqrts*kmu.t(); double sqrts34 = std::sqrt(s34); double Q34 = (s34-M2)/2./sqrts34, E34 = (s34+M2)/2./sqrts34; // construct p3, p4 in (2) frame double cosphi34 = std::cos(phi34), sinphi34 = std::sin(phi34), sintheta34 = std::sqrt(1.-std::pow(costheta34,2)); fourvec p3mu{E34, Q34*sintheta34*cosphi34, Q34*sintheta34*sinphi34, Q34*costheta34}; fourvec p4mu{Q34, -Q34*sintheta34*cosphi34, -Q34*sintheta34*sinphi34, -Q34*costheta34}; // boost p3, p4 back to 3-body CoM Frame double V0 = sqrts - kmu.t(); double v34[3] = {-kmu.x()/V0, -kmu.y()/V0, -kmu.z()/V0}; p3mu = p3mu.boost_back(v34[0], v34[1], v34[2]); p4mu = p4mu.boost_back(v34[0], v34[1], v34[2]); // q-perp-vec, q = p2-p4, qperp = -p4perp double qx = -p4mu.x(), qy = -p4mu.y(); double qt2 = qx*qx + qy*qy; double kt2 = kmu.x()*kmu.x() + kmu.y()*kmu.y(); double t = -2.*Qmax*(p4mu.t()+p4mu.z()); if(y < 0){ qx = -p3mu.x(); qy = -p3mu.y(); t = -2.*Qmax*(p3mu.t()-p3mu.z()); } double mg2 = t_channel_mD2->get_mD2(T) / 2.; double xbar = (kmu.t()+std::abs(kmu.z()))/sqrts; if (y<0 && xbar>0.5) return 0.; double one_minus_xbar = 1. - xbar; double MA[2], MB[2], MC[2], A[2], B[2]; MA[0] = kmu.x() - qx; MA[1] = kmu.y() - qy; MB[0] = kmu.x() - xbar*qx; MB[1] = kmu.y() - xbar*qy; MC[0] = kmu.x(); MC[1] = kmu.y(); double DA = MA[0]*MA[0] + MA[1]*MA[1] + (1.-xbar)*mg2; double DB = MB[0]*MB[0] + MB[1]*MB[1] + (1.-xbar)*mg2; double DC = MC[0]*MC[0] + MC[1]*MC[1] + (1.-xbar)*mg2; A[0] = MA[0]/DA-MB[0]/DB; A[1] = MA[1]/DA-MB[1]/DB; B[0] = MA[0]/DA-MC[0]/DC; B[1] = MA[1]/DA-MC[1]/DC; double A2 = std::pow(A[0],2) + std::pow(A[1],2); double B2 = std::pow(B[0],2) + std::pow(B[1],2); double AB = A[0]*B[0] + A[1]*B[1]; double M2_elastic = M2_Qg2Qg(t, params); double Pg = 1.; if (y>0){ Pg = alpha_s(kt2, T) * one_minus_xbar * (1. + std::pow(one_minus_xbar, 2)) / 2. * (CF*A2 + CF*B2 - (2.*CF-CA)*AB)/CA; } else { Pg = alpha_s(kt2, T) * xbar * one_minus_xbar * (1. + std::pow(xbar, 4) + std::pow(one_minus_xbar, 4)) / 2. * (A2 + B2 - AB); } // Jacobian double J = (1.0 - M2/s34) * M_PI/8./std::pow(2*M_PI,5) * kt * (kt + T) * ymax; // 2->3 = 2->2 * 1->2 return c48pi*M2_elastic*Pg*J; } //=============Basic for 3->2=========================================== // Not CoM frame of 1,2,k, but CoM frame of 1 and 2 // sampled final states within 3+4 CoM frame double M2_Qqg2Qq(const double * x_, void * params_){ // unpack variables costheta42 = x_[0] double costheta34 = x_[0], phi34 = x_[1]; if (costheta34<=-1. || costheta34>=1. || phi34 <=0. || phi34 >=2.*M_PI) return 0.; double sintheta34 = std::sqrt(1. - costheta34*costheta34), sinphi34 = std::sin(phi34), cosphi34 = std::cos(phi34); // unpack parameters double * params = static_cast<double*>(params_); // s12, T, M, k, costhetak double s = params[0]; double T = params[1]; double M = params[2]; double M2 = M*M; double s12 = params[3]*(s-M2) + M2; // 0 < params[3] = xinel = (s12-M2)/(s-M2) < 1 double s1k = (params[4]*(1-s12/s)*(1-M2/s12)+M2/s12)*s; // 0 < params[4] = yinel = (s1k/s-M2/s12)/(1-s12/s)/(1-M2/s12) < 1 double sqrts12 = std::sqrt(s12); double sqrts = std::sqrt(s); double E1 = (s12+M2)/2./sqrts12, p1 = (s12-M2)/2./sqrts12; double E3 = (s+M2)/2./sqrts, p3 = (s-M2)/2./sqrts; double k = (s-s12)/2./sqrts12; double costhetak = (M2 + 2.*E1*k - s1k)/2./p1/k; double sinthetak = std::sqrt(1. - costhetak*costhetak); double kt = k*sinthetak; double kt2 = kt*kt; double kz = k*costhetak; double x = (k+kz)/(sqrts12+k+kz), xbar = (k+std::abs(kz))/(sqrts12+k+std::abs(kz)); double mD2 = t_channel_mD2->get_mD2(T); // get final state fourvec Ptot{sqrts12+k, kt, 0., kz}; double vcom[3] = {Ptot.x()/Ptot.t(), Ptot.y()/Ptot.t(),Ptot.z()/Ptot.t()}; // final state in 34-com frame fourvec p3mu{E3, p3*sintheta34*cosphi34, p3*sintheta34*sinphi34, p3*costheta34}; fourvec p4mu{p3, -p3*sintheta34*cosphi34, -p3*sintheta34*sinphi34, -p3*costheta34}; // boost final state back to 12-com frame p3mu = p3mu.boost_back(vcom[0], vcom[1], vcom[2]); p4mu = p4mu.boost_back(vcom[0], vcom[1], vcom[2]); // 2->2 part fourvec qmu{p1-p4mu.t(), -p4mu.x(), -p4mu.y(), -p1-p4mu.z()}; double t = -2.*p1*(p4mu.t()+p4mu.z()); double qt2 = std::pow(qmu.x(),2) + std::pow(qmu.y(),2); double new_params[3] = {s, T, M}; double M2_elastic = M2_Qq2Qq(t, params); double x2M2 = x*x*M2; // 1->2 double iD1 = 1./(kt2 + (1.-xbar)*mD2/2.); double iD2 = 1./(kt2 + qt2 + 2.*kt*qmu.x() + (1.-xbar)*mD2/2.); double Pg = 48.*M_PI*alpha_s(kt2, T)*std::pow(1.-xbar, 2)*( kt2*std::pow(iD1-iD2, 2) + qt2*std::pow(iD2, 2) - 2.*kt*qmu.x()*(iD1-iD2)*iD2 ); double detail_balance_factor = 1./16.; double Jacobian = 1./std::pow(2*M_PI, 2)/8.*(1. - M2/s); // 2->3 = 2->2 * 1->2 return M2_elastic * Pg * Jacobian * detail_balance_factor; } double M2_Qgg2Qg(const double * x_, void * params_){ // unpack variables costheta42 = x_[0] double costheta34 = x_[0], phi34 = x_[1]; if (costheta34<=-1. || costheta34>=1. || phi34 <=0. || phi34 >=2.*M_PI) return 0.; double sintheta34 = std::sqrt(1. - costheta34*costheta34), sinphi34 = std::sin(phi34), cosphi34 = std::cos(phi34); // unpack parameters double * params = static_cast<double*>(params_); // s12, T, M, k, costhetak double s = params[0]; double T = params[1]; double M = params[2]; double M2 = M*M; double s12 = params[3]*(s-M2) + M2; // 0 < params[3] = xinel = (s12-M2)/(s-M2) < 1 double s1k = (params[4]*(1-s12/s)*(1-M2/s12)+M2/s12)*s; // 0 < params[4] = yinel = (s1k/s-M2/s12)/(1-s12/s)/(1-M2/s12) < 1 double sqrts12 = std::sqrt(s12); double sqrts = std::sqrt(s); double E1 = (s12+M2)/2./sqrts12, p1 = (s12-M2)/2./sqrts12; double E3 = (s+M2)/2./sqrts, p3 = (s-M2)/2./sqrts; double k = (s-s12)/2./sqrts12; double costhetak = (M2 + 2.*E1*k - s1k)/2./p1/k; double sinthetak = std::sqrt(1. - costhetak*costhetak); double kt = k*sinthetak; double kt2 = kt*kt; double kz = k*costhetak; double x = (k+kz)/(sqrts12+k+kz), xbar = (k+std::abs(kz))/(sqrts12+k+std::abs(kz)); double mD2 = t_channel_mD2->get_mD2(T); // get final state fourvec Ptot{sqrts12+k, kt, 0., kz}; double vcom[3] = {Ptot.x()/Ptot.t(), Ptot.y()/Ptot.t(),Ptot.z()/Ptot.t()}; // final state in 34-com frame fourvec p3mu{E3, p3*sintheta34*cosphi34, p3*sintheta34*sinphi34, p3*costheta34}; fourvec p4mu{p3, -p3*sintheta34*cosphi34, -p3*sintheta34*sinphi34, -p3*costheta34}; // boost final state back to 12-com frame p3mu = p3mu.boost_back(vcom[0], vcom[1], vcom[2]); p4mu = p4mu.boost_back(vcom[0], vcom[1], vcom[2]); // 2->2 part fourvec qmu{p1-p4mu.t(), -p4mu.x(), -p4mu.y(), -p1-p4mu.z()}; double t = -2.*p1*(p4mu.t()+p4mu.z()); double qt2 = std::pow(qmu.x(),2) + std::pow(qmu.y(),2); double new_params[3] = {s, T, M}; double M2_elastic = M2_Qg2Qg(t, params); double x2M2 = x*x*M2; // 1->2 double iD1 = 1./(kt2 + (1.-xbar)*mD2/2.); double iD2 = 1./(kt2 + qt2 + 2.*kt*qmu.x() + (1.-xbar)*mD2/2.); double Pg = 48.*M_PI*alpha_s(kt2, T)*std::pow(1.-xbar, 2)*( kt2*std::pow(iD1-iD2, 2) + qt2*std::pow(iD2, 2) - 2.*kt*qmu.x()*(iD1-iD2)*iD2 ); double detail_balance_factor = 1./16.; double Jacobian = 1./std::pow(2*M_PI, 2)/8.*(1. - M2/s); // 2->3 = 2->2 * 1->2 return M2_elastic * Pg * Jacobian * detail_balance_factor; } ////////////////// Hard Gluon //////////////////////////////// /// g + q --> g + q + g double M2_gq2gqg(const double * x_, void * params_){ // unpack variables, parameters and check integration range double * params = static_cast<double*>(params_); double s = params[0]; double sqrts = std::sqrt(s); double T = params[1]; double M2 = params[2]*params[2]; double Qmax = (s-M2)/2./sqrts; double log_1_ktT = x_[0], y_norm = x_[1], // in 3-body com frame---(1) costheta34 = x_[2], phi34 =x_[3]; // in p3-p4 com frame---(2) // (1) and (2) share the same z-direction, and are related by a boost // check bounds double kt = T*(std::exp(log_1_ktT)-1.); if (std::abs(costheta34)>=1.||phi34<=0.||phi34>=2.*M_PI||kt>=Qmax||kt<=0.||std::abs(y_norm)>.999) return 0.; double ymax = std::acosh(Qmax/kt); double y = y_norm*ymax; // construct k^mu fourvec kmu{kt*std::cosh(y), kt, 0, kt*std::sinh(y)}; double s34 = s - 2.*sqrts*kmu.t(); double sqrts34 = std::sqrt(s34); double Q34 = (s34-M2)/2./sqrts34, E34 = (s34+M2)/2./sqrts34; // construct p3, p4 in (2) frame double cosphi34 = std::cos(phi34), sinphi34 = std::sin(phi34), sintheta34 = std::sqrt(1.-std::pow(costheta34,2)); fourvec p3mu{E34, Q34*sintheta34*cosphi34, Q34*sintheta34*sinphi34, Q34*costheta34}; fourvec p4mu{Q34, -Q34*sintheta34*cosphi34, -Q34*sintheta34*sinphi34, -Q34*costheta34}; // boost p3, p4 back to 3-body CoM Frame double V0 = sqrts - kmu.t(); double v34[3] = {-kmu.x()/V0, -kmu.y()/V0, -kmu.z()/V0}; p3mu = p3mu.boost_back(v34[0], v34[1], v34[2]); p4mu = p4mu.boost_back(v34[0], v34[1], v34[2]); // q-perp-vec, q = p2-p4, qperp = -p4perp double qx = -p4mu.x(), qy = -p4mu.y(); double qt2 = qx*qx + qy*qy; double kt2 = kmu.x()*kmu.x() + kmu.y()*kmu.y(); double t = -2.*Qmax*(p4mu.t()+p4mu.z()); double mg2 = t_channel_mD2->get_mD2(T) / 2.; double xbar = (kmu.t()+std::abs(kmu.z()))/sqrts; double one_minus_xbar = 1.-xbar; if (y>0 && xbar>0.5) return 0.0; if(y < 0){ qx = -p3mu.x(); qy = -p3mu.y(); t = -2.*Qmax*(p3mu.t()-p3mu.z()); } double MA[2], MB[2], MC[2], A[2], B[2]; MA[0] = kmu.x() - xbar*qx; MA[1] = kmu.y() - xbar*qy; MB[0] = kmu.x() - qx; MB[1] = kmu.y() - qy; MC[0] = kmu.x(); MC[1] = kmu.y(); double DA = MA[0]*MA[0] + MA[1]*MA[1] + (1.-xbar+xbar*xbar)*mg2; double DB = MB[0]*MB[0] + MB[1]*MB[1] + (1.-xbar+xbar*xbar)*mg2; double DC = MC[0]*MC[0] + MC[1]*MC[1] + (1.-xbar+xbar*xbar)*mg2; A[0] = MA[0]/DA-MB[0]/DB; A[1] = MA[1]/DA-MB[1]/DB; B[0] = MA[0]/DA-MC[0]/DC; B[1] = MA[1]/DA-MC[1]/DC; double A2 = std::pow(A[0],2) + std::pow(A[1],2); double B2 = std::pow(B[0],2) + std::pow(B[1],2); double AB = A[0]*B[0] + A[1]*B[1]; double M2_elastic = M2_gq2gq(t, params); double Pg = 1.; if (y > 0.){ Pg = alpha_s(kt2, T) * (1. + std::pow(xbar, 4) + std::pow(one_minus_xbar, 4)) / 2. * (A2 + B2 - AB); }else{ Pg = alpha_s(kt2, T) * one_minus_xbar * (1. + std::pow(one_minus_xbar, 2)) / 2. * (CF*A2 + CF*B2 - (2.*CF-CA)*AB)/CA; } // Jacobian double J = (1.0 - M2/s34) * M_PI/8./std::pow(2*M_PI,5) * kt * (kt + T) * ymax; // 2->3 = 2->2 * 1->2 return c48pi*M2_elastic*Pg*J; } /// g + g --> g + g + g double M2_gg2ggg(const double * x_, void * params_){ // unpack variables, parameters and check integration range double * params = static_cast<double*>(params_); double s = params[0]; double sqrts = std::sqrt(s); double T = params[1]; double M2 = params[2]*params[2]; double Qmax = (s-M2)/2./sqrts; double log_1_ktT = x_[0], y_norm = x_[1], // in 3-body com frame---(1) costheta34 = x_[2], phi34 =x_[3]; // in p3-p4 com frame---(2) // (1) and (2) share the same z-direction, and are related by a boost // check bounds double kt = T*(std::exp(log_1_ktT)-1.); if (std::abs(costheta34)>=1.||phi34<=0.||phi34>=2.*M_PI||kt>=Qmax||kt<=0.||std::abs(y_norm)>.999) return 0.; double ymax = std::acosh(Qmax/kt); double y = y_norm*ymax; // construct k^mu fourvec kmu{kt*std::cosh(y), kt, 0, kt*std::sinh(y)}; double s34 = s - 2.*sqrts*kmu.t(); double sqrts34 = std::sqrt(s34); double Q34 = (s34-M2)/2./sqrts34, E34 = (s34+M2)/2./sqrts34; // construct p3, p4 in (2) frame double cosphi34 = std::cos(phi34), sinphi34 = std::sin(phi34), sintheta34 = std::sqrt(1.-std::pow(costheta34,2)); fourvec p3mu{E34, Q34*sintheta34*cosphi34, Q34*sintheta34*sinphi34, Q34*costheta34}; fourvec p4mu{Q34, -Q34*sintheta34*cosphi34, -Q34*sintheta34*sinphi34, -Q34*costheta34}; // boost p3, p4 back to 3-body CoM Frame double V0 = sqrts - kmu.t(); double v34[3] = {-kmu.x()/V0, -kmu.y()/V0, -kmu.z()/V0}; p3mu = p3mu.boost_back(v34[0], v34[1], v34[2]); p4mu = p4mu.boost_back(v34[0], v34[1], v34[2]); // q-perp-vec, q = p2-p4, qperp = -p4perp double qx = -p4mu.x(), qy = -p4mu.y(); double qt2 = qx*qx + qy*qy; double kt2 = kmu.x()*kmu.x() + kmu.y()*kmu.y(); double t = -2.*Qmax*(p4mu.t()+p4mu.z()); double mg2 = t_channel_mD2->get_mD2(T) / 2.; double xbar = (kmu.t()+std::abs(kmu.z()))/sqrts; double one_minus_xbar = 1.-xbar; if (y>0 && xbar>0.5) return 0.0; if (y<0 && xbar>0.5) return 0.0; if(y < 0){ qx = -p3mu.x(); qy = -p3mu.y(); t = -2.*Qmax*(p3mu.t()-p3mu.z()); } double MA[2], MB[2], MC[2], A[2], B[2]; MA[0] = kmu.x() - xbar*qx; MA[1] = kmu.y() - xbar*qy; MB[0] = kmu.x() - qx; MB[1] = kmu.y() - qy; MC[0] = kmu.x(); MC[1] = kmu.y(); double DA = MA[0]*MA[0] + MA[1]*MA[1] + (1.-xbar+xbar*xbar)*mg2; double DB = MB[0]*MB[0] + MB[1]*MB[1] + (1.-xbar+xbar*xbar)*mg2; double DC = MC[0]*MC[0] + MC[1]*MC[1] + (1.-xbar+xbar*xbar)*mg2; A[0] = MA[0]/DA-MB[0]/DB; A[1] = MA[1]/DA-MB[1]/DB; B[0] = MA[0]/DA-MC[0]/DC; B[1] = MA[1]/DA-MC[1]/DC; double A2 = std::pow(A[0],2) + std::pow(A[1],2); double B2 = std::pow(B[0],2) + std::pow(B[1],2); double AB = A[0]*B[0] + A[1]*B[1]; double M2_elastic = M2_gg2gg(t, params); double Pg = alpha_s(kt2, T) * (1. + std::pow(xbar, 4) + std::pow(one_minus_xbar, 4)) / 2. * (A2 + B2 - AB ); // Jacobian double J = (1.0 - M2/s34) * M_PI/8./std::pow(2*M_PI,5) * kt * (kt + T) * ymax; // 2->3 = 2->2 * 1->2 return c48pi*M2_elastic*Pg*J; } //=============Basic for 3->2=========================================== // Not CoM frame of 1,2,k, but CoM frame of 1 and 2 // sampled final states within 3+4 CoM frame double M2_gqg2gq(const double * x_, void * params_){ // unpack variables costheta42 = x_[0] double costheta34 = x_[0], phi34 = x_[1]; if (costheta34<=-1. || costheta34>=1. || phi34 <=0. || phi34 >=2.*M_PI) return 0.; double sintheta34 = std::sqrt(1. - costheta34*costheta34), sinphi34 = std::sin(phi34), cosphi34 = std::cos(phi34); // unpack parameters double * params = static_cast<double*>(params_); // s12, T, M, k, costhetak double s = params[0]; double T = params[1]; double M = params[2]; double M2 = M*M; double s12 = params[3]*(s-M2) + M2; // 0 < params[3] = xinel = (s12-M2)/(s-M2) < 1 double s1k = (params[4]*(1-s12/s)*(1-M2/s12)+M2/s12)*s; // 0 < params[4] = yinel = (s1k/s-M2/s12)/(1-s12/s)/(1-M2/s12) < 1 double sqrts12 = std::sqrt(s12); double sqrts = std::sqrt(s); double E1 = (s12+M2)/2./sqrts12, p1 = (s12-M2)/2./sqrts12; double E3 = (s+M2)/2./sqrts, p3 = (s-M2)/2./sqrts; double k = (s-s12)/2./sqrts12; double costhetak = (M2 + 2.*E1*k - s1k)/2./p1/k; double sinthetak = std::sqrt(1. - costhetak*costhetak); double kt = k*sinthetak; double kt2 = kt*kt; double kz = k*costhetak; double x = (k+kz)/(sqrts12+k+kz), xbar = (k+std::abs(kz))/(sqrts12+k+std::abs(kz)); double mD2 = t_channel_mD2->get_mD2(T); // get final state fourvec Ptot{sqrts12+k, kt, 0., kz}; double vcom[3] = {Ptot.x()/Ptot.t(), Ptot.y()/Ptot.t(),Ptot.z()/Ptot.t()}; // final state in 34-com frame fourvec p3mu{E3, p3*sintheta34*cosphi34, p3*sintheta34*sinphi34, p3*costheta34}; fourvec p4mu{p3, -p3*sintheta34*cosphi34, -p3*sintheta34*sinphi34, -p3*costheta34}; // boost final state back to 12-com frame p3mu = p3mu.boost_back(vcom[0], vcom[1], vcom[2]); p4mu = p4mu.boost_back(vcom[0], vcom[1], vcom[2]); // 2->2 part fourvec qmu{p1-p4mu.t(), -p4mu.x(), -p4mu.y(), -p1-p4mu.z()}; double t = -2.*p1*(p4mu.t()+p4mu.z()); double qt2 = std::pow(qmu.x(),2) + std::pow(qmu.y(),2); double new_params[3] = {s, T, M}; double M2_elastic = M2_gq2gq(t, params); double x2M2 = x*x*M2; // 1->2 double iD1 = 1./(kt2 + (1.-xbar)*mD2/2.); double iD2 = 1./(kt2 + qt2 + 2.*kt*qmu.x() + (1.-xbar)*mD2/2.); double Pg = 48.*M_PI*alpha_s(kt2, T)*std::pow(1.-xbar, 2)*( kt2*std::pow(iD1-iD2, 2) + qt2*std::pow(iD2, 2) - 2.*kt*qmu.x()*(iD1-iD2)*iD2 ); double detail_balance_factor = 1./16.; double Jacobian = 1./std::pow(2*M_PI, 2)/8.*(1. - M2/s); // 2->3 = 2->2 * 1->2 return M2_elastic * Pg * Jacobian * detail_balance_factor; } double M2_ggg2gg(const double * x_, void * params_){ // unpack variables costheta42 = x_[0] double costheta34 = x_[0], phi34 = x_[1]; if (costheta34<=-1. || costheta34>=1. || phi34 <=0. || phi34 >=2.*M_PI) return 0.; double sintheta34 = std::sqrt(1. - costheta34*costheta34), sinphi34 = std::sin(phi34), cosphi34 = std::cos(phi34); // unpack parameters double * params = static_cast<double*>(params_); // s12, T, M, k, costhetak double s = params[0]; double T = params[1]; double M = params[2]; double M2 = M*M; double s12 = params[3]*(s-M2) + M2; // 0 < params[3] = xinel = (s12-M2)/(s-M2) < 1 double s1k = (params[4]*(1-s12/s)*(1-M2/s12)+M2/s12)*s; // 0 < params[4] = yinel = (s1k/s-M2/s12)/(1-s12/s)/(1-M2/s12) < 1 double sqrts12 = std::sqrt(s12); double sqrts = std::sqrt(s); double E1 = (s12+M2)/2./sqrts12, p1 = (s12-M2)/2./sqrts12; double E3 = (s+M2)/2./sqrts, p3 = (s-M2)/2./sqrts; double k = (s-s12)/2./sqrts12; double costhetak = (M2 + 2.*E1*k - s1k)/2./p1/k; double sinthetak = std::sqrt(1. - costhetak*costhetak); double kt = k*sinthetak; double kt2 = kt*kt; double kz = k*costhetak; double x = (k+kz)/(sqrts12+k+kz), xbar = (k+std::abs(kz))/(sqrts12+k+std::abs(kz)); double mD2 = t_channel_mD2->get_mD2(T); // get final state fourvec Ptot{sqrts12+k, kt, 0., kz}; double vcom[3] = {Ptot.x()/Ptot.t(), Ptot.y()/Ptot.t(),Ptot.z()/Ptot.t()}; // final state in 34-com frame fourvec p3mu{E3, p3*sintheta34*cosphi34, p3*sintheta34*sinphi34, p3*costheta34}; fourvec p4mu{p3, -p3*sintheta34*cosphi34, -p3*sintheta34*sinphi34, -p3*costheta34}; // boost final state back to 12-com frame p3mu = p3mu.boost_back(vcom[0], vcom[1], vcom[2]); p4mu = p4mu.boost_back(vcom[0], vcom[1], vcom[2]); // 2->2 part fourvec qmu{p1-p4mu.t(), -p4mu.x(), -p4mu.y(), -p1-p4mu.z()}; double t = -2.*p1*(p4mu.t()+p4mu.z()); double qt2 = std::pow(qmu.x(),2) + std::pow(qmu.y(),2); double new_params[3] = {s, T, M}; double M2_elastic = M2_gg2gg(t, params); double x2M2 = x*x*M2; // 1->2 double iD1 = 1./(kt2 + (1.-xbar)*mD2/2.); double iD2 = 1./(kt2 + qt2 + 2.*kt*qmu.x() + (1.-xbar)*mD2/2.); double Pg = 48.*M_PI*alpha_s(kt2, T)*std::pow(1.-xbar, 2)*( kt2*std::pow(iD1-iD2, 2) + qt2*std::pow(iD2, 2) - 2.*kt*qmu.x()*(iD1-iD2)*iD2 ); double detail_balance_factor = 1./16.; double Jacobian = 1./std::pow(2*M_PI, 2)/8.*(1. - M2/s); // 2->3 = 2->2 * 1->2 return M2_elastic * Pg * Jacobian * detail_balance_factor; } /////////// Gluon to q qbar ///////////////// /// g + g --> q + g + qbar double M2_gg2qgqbar(const double * x_, void * params_){ // unpack variables, parameters and check integration range double * params = static_cast<double*>(params_); double s = params[0]; double sqrts = std::sqrt(s); double T = params[1]; double M2 = params[2]*params[2]; double Qmax = (s-M2)/2./sqrts; double log_1_ktT = x_[0], y_norm = x_[1], // in 3-body com frame---(1) costheta34 = x_[2], phi34 =x_[3]; // in p3-p4 com frame---(2) // (1) and (2) share the same z-direction, and are related by a boost // check bounds double kt = T*(std::exp(log_1_ktT)-1.); if (std::abs(costheta34)>=1.||phi34<=0.||phi34>=2.*M_PI||kt>=Qmax||kt<=0.||std::abs(y_norm)>.999) return 0.; double ymax = std::acosh(Qmax/kt); double y = y_norm*ymax; // construct k^mu fourvec kmu{kt*std::cosh(y), kt, 0, kt*std::sinh(y)}; double s34 = s - 2.*sqrts*kmu.t(); double sqrts34 = std::sqrt(s34); double Q34 = (s34-M2)/2./sqrts34, E34 = (s34+M2)/2./sqrts34; // construct p3, p4 in (2) frame double cosphi34 = std::cos(phi34), sinphi34 = std::sin(phi34), sintheta34 = std::sqrt(1.-std::pow(costheta34,2)); fourvec p3mu{E34, Q34*sintheta34*cosphi34, Q34*sintheta34*sinphi34, Q34*costheta34}; fourvec p4mu{Q34, -Q34*sintheta34*cosphi34, -Q34*sintheta34*sinphi34, -Q34*costheta34}; // boost p3, p4 back to 3-body CoM Frame double V0 = sqrts - kmu.t(); double v34[3] = {-kmu.x()/V0, -kmu.y()/V0, -kmu.z()/V0}; p3mu = p3mu.boost_back(v34[0], v34[1], v34[2]); p4mu = p4mu.boost_back(v34[0], v34[1], v34[2]); // q-perp-vec, q = p2-p4, qperp = -p4perp double qx = -p4mu.x(), qy = -p4mu.y(); double kt2 = kmu.x()*kmu.x() + kmu.y()*kmu.y(); double t = -2.*Qmax*(p4mu.t()+p4mu.z()); double mg2 = t_channel_mD2->get_mD2(T)/2.; double xbar = 2*kmu.t()/sqrts; double one_minus_xbar = 1.-xbar; if(y < 0){ return 0.; } double MA[2], MB[2], MC[2], A[2], B[2]; MA[0] = kmu.x() - xbar*qx; MA[1] = kmu.y() - xbar*qy; MB[0] = kmu.x() - qx; MB[1] = kmu.y() - qy; MC[0] = kmu.x(); MC[1] = kmu.y(); double DA = MA[0]*MA[0] + MA[1]*MA[1] + (1-CA/CF*xbar+CA/CF*xbar*xbar)*mg2; double DB = MB[0]*MB[0] + MB[1]*MB[1] + (1-CA/CF*xbar+CA/CF*xbar*xbar)*mg2; double DC = MC[0]*MC[0] + MC[1]*MC[1] + (1-CA/CF*xbar+CA/CF*xbar*xbar)*mg2; A[0] = MA[0]/DA-MB[0]/DB; A[1] = MA[1]/DA-MB[1]/DB; B[0] = MA[0]/DA-MC[0]/DC; B[1] = MA[1]/DA-MC[1]/DC; double A2 = std::pow(A[0],2) + std::pow(A[1],2); double B2 = std::pow(B[0],2) + std::pow(B[1],2); double AB = A[0]*B[0] + A[1]*B[1]; double M2_elastic = M2_gg2gg(t, params); double Pg = alpha_s(kt2, T) * one_minus_xbar * xbar * (std::pow(xbar,2) + std::pow(one_minus_xbar, 2))/ 2. * ( CF*A2 + CF*B2 - (2*CF-CA)*AB ) / 2.; // Jacobian double J = (1.0 - M2/s34) * M_PI/8./std::pow(2*M_PI,5) * kt * (kt + T) * ymax; // 2->3 = 2->2 * 1->2 return c48pi*M2_elastic*Pg*J; } /// g + q --> q + q + qbar double M2_gq2qqqbar(const double * x_, void * params_){ // unpack variables, parameters and check integration range double * params = static_cast<double*>(params_); double s = params[0]; double sqrts = std::sqrt(s); double T = params[1]; double M2 = params[2]*params[2]; double Qmax = (s-M2)/2./sqrts; double log_1_ktT = x_[0], y_norm = x_[1], // in 3-body com frame---(1) costheta34 = x_[2], phi34 =x_[3]; // in p3-p4 com frame---(2) // (1) and (2) share the same z-direction, and are related by a boost // check bounds double kt = T*(std::exp(log_1_ktT)-1.); if (std::abs(costheta34)>=1.||phi34<=0.||phi34>=2.*M_PI||kt>=Qmax||kt<=0.||std::abs(y_norm)>.999) return 0.; double ymax = std::acosh(Qmax/kt); double y = y_norm*ymax; // construct k^mu fourvec kmu{kt*std::cosh(y), kt, 0, kt*std::sinh(y)}; double s34 = s - 2.*sqrts*kmu.t(); double sqrts34 = std::sqrt(s34); double Q34 = (s34-M2)/2./sqrts34, E34 = (s34+M2)/2./sqrts34; // construct p3, p4 in (2) frame double cosphi34 = std::cos(phi34), sinphi34 = std::sin(phi34), sintheta34 = std::sqrt(1.-std::pow(costheta34,2)); fourvec p3mu{E34, Q34*sintheta34*cosphi34, Q34*sintheta34*sinphi34, Q34*costheta34}; fourvec p4mu{Q34, -Q34*sintheta34*cosphi34, -Q34*sintheta34*sinphi34, -Q34*costheta34}; // boost p3, p4 back to 3-body CoM Frame double V0 = sqrts - kmu.t(); double v34[3] = {-kmu.x()/V0, -kmu.y()/V0, -kmu.z()/V0}; p3mu = p3mu.boost_back(v34[0], v34[1], v34[2]); p4mu = p4mu.boost_back(v34[0], v34[1], v34[2]); // q-perp-vec, q = p2-p4, qperp = -p4perp double qx = -p4mu.x(), qy = -p4mu.y(); double qt2 = qx*qx + qy*qy; double kt2 = kmu.x()*kmu.x() + kmu.y()*kmu.y(); double t = -2.*Qmax*(p4mu.t()+p4mu.z()); double mg2 = t_channel_mD2->get_mD2(T)/2.; double xbar = 2*kmu.t()/sqrts; double one_minus_xbar = 1.-xbar; if (y<0) return 0.; double MA[2], MB[2], MC[2], A[2], B[2]; MA[0] = kmu.x() - xbar*qx; MA[1] = kmu.y() - xbar*qy; MB[0] = kmu.x() - qx; MB[1] = kmu.y() - qy; MC[0] = kmu.x(); MC[1] = kmu.y(); double DA = MA[0]*MA[0] + MA[1]*MA[1] + (1-CA/CF*xbar+CA/CF*xbar*xbar)*mg2; double DB = MB[0]*MB[0] + MB[1]*MB[1] + (1-CA/CF*xbar+CA/CF*xbar*xbar)*mg2; double DC = MC[0]*MC[0] + MC[1]*MC[1] + (1-CA/CF*xbar+CA/CF*xbar*xbar)*mg2; A[0] = MA[0]/DA-MB[0]/DB; A[1] = MA[1]/DA-MB[1]/DB; B[0] = MA[0]/DA-MC[0]/DC; B[1] = MA[1]/DA-MC[1]/DC; double A2 = std::pow(A[0],2) + std::pow(A[1],2); double B2 = std::pow(B[0],2) + std::pow(B[1],2); double AB = A[0]*B[0] + A[1]*B[1]; double M2_elastic = M2_gq2gq(t, params); double Pg = alpha_s(kt2, T) * one_minus_xbar * xbar * (std::pow(xbar,2) + std::pow(one_minus_xbar, 2))/ 2. * ( CF*A2 + CF*B2 - (2*CF-CA)*AB ) / 2.; // Jacobian double J = (1.0 - M2/s34) * M_PI/8./std::pow(2*M_PI,5) * kt * (kt + T) * ymax; // 2->3 = 2->2 * 1->2 return c48pi*M2_elastic*Pg*J; }
/* * Created by Peng Qixiang on 2018/7/24. */ /* * 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字 * 例如 1 2 3 4 * 5 6 7 8 * 9 10 11 12 * 13 14 15 16 * 依次打出 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10。 * */ # include <iostream> # include <vector> using namespace std; vector<int> printMatrix(vector<vector<int> > matrix) { vector<int> res; int height = matrix.size(), width = matrix[0].size(); int start_height = 0, end_height = height; int start_width = 0, end_width = width; int index = 0; int change_num = 0; while(index < height * width){ // change width if(change_num % 2 == 0){ //positive direction if((change_num / 2) % 2 == 0){ for(int i = start_width; i < end_width; i++){ res.push_back(matrix[start_height][i]); index++; } start_height++; } else{ for(int i = end_width - 1; i >= start_width; i--){ res.push_back(matrix[end_height-1][i]); index++; } end_height--; } } // change height else{ // positive direction if(((change_num - 1) / 2) % 2 == 0){ for(int i = start_height; i < end_height; i++){ res.push_back(matrix[i][end_width-1]); index++; } end_width--; } else{ for(int i = end_height - 1; i >= start_height; i--){ res.push_back(matrix[i][start_width]); index++; } start_width++; } } change_num++; } return res; } int main(){ vector< vector<int> > test(2, vector<int>(2, 0)); test[0] = {1, 2}; test[1] = {3, 4}; int height = test.size(); int width = test[0].size(); vector<int> res = printMatrix(test); for(int i = 0; i < height * width; i++){ cout << res[i] << endl; } return 0; }
#ifndef BONUSLIFE_H #define BONUSLIFE_H #include "Element.h" #include "xil_types.h" class BonusLife : public Element { public: BonusLife(); void Init() override; uint8_t IsCollidable() const override; uint8_t IsFireCollidable() const override; uint8_t Code() const override; }; #endif
#include<cstdio> #include<iostream> #include<string> #include<cstring> #include<queue> #include<map> using namespace std; string word; map<string,int> M; int Dabiao(){ int cnt=1; for(char a='a';a<='z';a++){ string w; w=a; M[w]=cnt; cnt++; } for(char a='a';a<='z';a++) for(char b=a+1;b<='z';b++){ string w; w=a; w+=b; M[w]=cnt; cnt++; } for(char a='a';a<='z';a++) for(char b=a+1;b<='z';b++) for(char c=b+1;c<='z';c++){ string w; w=a; w+=b; w+=c; M[w]=cnt; cnt++; } for(char a='a';a<='z';a++) for(char b=a+1;b<='z';b++) for(char c=b+1;c<='z';c++) for(char d=c+1;d<='z';d++){ string w; w=a; w+=b; w+=c; w+=d; M[w]=cnt; cnt++; } for(char a='a';a<='z';a++) for(char b=a+1;b<='z';b++) for(char c=b+1;c<='z';c++) for(char d=c+1;d<='z';d++) for(char e=d+1;e<='z';e++){ string w; w=a; w+=b; w+=c; w+=d; w+=e; M[w]=cnt; cnt++; } } int main(){ Dabiao(); while(cin>>word){ printf("%d\n",M[word]); } return 0; }
#include "Solver.h" Solver::Solver() { } Solver::~Solver() { free( rungeKutta ); free( adamsBashforth ); free( orthoBuilder ); } //SolInfo::SolInfo() //{ // o.resize( EQ_NUM * EQ_NUM, 0.0 ); // z1.resize( EQ_NUM ); // z2.resize( EQ_NUM ); // z3.resize( EQ_NUM ); // z4.resize( EQ_NUM ); // z5.resize( EQ_NUM ); // // C.resize( EQ_NUM / 2 ); //} //void SolInfo::flushO() //{ // for( int i = 0; i < o.size(); ++i ) // { // o[i] = 0.0; // } //} // //SolInfo::~SolInfo() //{ // //} void Solver::loadPlate( Plate* _plate ) { plate = _plate; //al = plate->rho; al = 1; } void Solver::endTask() { free( rungeKutta ); free( orthoBuilder ); } void Solver::setTask( PL_NUM _J0, PL_NUM _tauJ ) { ofstream of1( "test_sol.txt" ); of1.close(); tauP = 0.01; if( _tauJ != 0.0l ) { tauJ = _tauJ; } else { tauJ = 1.0l; } rad = 0.0021 / 10.0; eq_num = 8; cur_t = 0.0; curTimeStep = 0; J0 = complex<long double>( _J0.real() * 100000000/*/ plate->a.real() / plate->h.real() * 1000.0l*/, _J0.imag() ); omega = (long double)M_PI / tauJ; p0 = 100.0; stress_type = stress_whole; current_type = current_sin; By0 = 0.1l; eps_0 = 0.000000000008854; eps_x = 0.0000000002501502912; Km = 10001; Kt = 3; dt = 0.0001; dx = al.real() * plate->a / Km; ++Km; betta = 0.25; rungeKutta = new RungeKutta( eq_num ); orthoBuilder = new OrthoBuilderGSh(); //orthoBuilder = new OrthoBuilderGodunov(); orthoBuilder->setParams( Km ); mesh.resize( 0 ); mesh.resize( Km ); for( int i = 0; i < mesh.size(); ++i ){ mesh[i].setup( eq_num ); } //solInfoMap.resize( Km ); //nonlin_matr_A.resize( eq_num * eq_num, 0.0 ); //nonlin_vect_f.resize( eq_num, 0.0 ); for( int i = 0; i < EQ_NUM; ++i ) { for( int j = 0; j < EQ_NUM; ++j ) { nonlin_matr_A( i, j ) = 0.0; } nonlin_vect_f( i ) = 0.0; } //lin_matr_A.resize( eq_num * eq_num, 0.0 ); //lin_vect_f.resize( eq_num, 0.0 ); newmark_A.resize( eq_num, 0.0 ); newmark_B.resize( eq_num, 0.0 ); for( int i = 0; i < EQ_NUM; ++i ) { newmark_A[i] = 0.0; newmark_B[i] = 0.0; N1( i ) = 0.0; N2( i ) = 0.0; N3( i ) = 0.0; N4( i ) = 0.0; N5( i ) = 0.0; } //N1.resize( eq_num, 0.0 ); //N2.resize( eq_num, 0.0 ); //N3.resize( eq_num, 0.0 ); //N4.resize( eq_num, 0.0 ); //N5.resize( eq_num, 0.0 ); } void Solver::calcConsts() { if( plate == 0 ) { cout << "Solver error: plate is null\n"; return; } B11 = plate->E1 * plate->E1 / ( plate->E1 - plate->nu21 * plate->nu21 * plate->E2 ); B22 = plate->E2 / ( 1.0l - plate->nu21 * plate->nu21 * plate->E2 / plate->E1 ); B12 = plate->nu21 * plate->E2 * plate->E1 / ( plate->E1 - plate->nu21 * plate->nu21 * plate->E2 ); By1 = 2.0l * By0; // in considered boundary-value problem By2 = 0.0; eps_x_0 = eps_x - eps_0; } void Solver::calc_Newmark_AB( int _x, int mode ) { if( mode == 0 ) { for( int i = 0; i < eq_num; ++i) { newmark_A[i] = -mesh[_x].Nk0[i] / betta / dt / dt - mesh[_x].d1N0[i] / betta / dt - ( 0.5l - betta ) / betta * mesh[_x].d2N0[i]; newmark_B[i] = -0.5l * mesh[_x].Nk0[i] / betta / dt + ( 1.0l - 0.5l / betta ) * mesh[_x].d1N0[i] - 0.5l * dt * ( 1.0l- 1.0l / betta * ( 0.5l - betta ) ) * mesh[_x].d2N0[i]; } /*newmark_A[0] = -mesh[_x].Nk0[0] / betta / dt / dt - mesh[_x].d1N0[0] / betta / dt - ( 0.5 - betta ) / betta * mesh[_x].d2N0[0]; newmark_A[1] = -mesh[_x].Nk0[1] / betta / dt - mesh[_x].d1N0[1] / betta - ( 0.5 - betta ) / betta * dt * mesh[_x].d2N0[1]; newmark_A[2] = -mesh[_x].Nk0[2] / betta / dt / dt - mesh[_x].d1N0[2] / betta / dt - ( 0.5 - betta ) / betta * mesh[_x].d2N0[2]; newmark_A[7] = -mesh[_x].Nk0[7] / betta / dt / dt - mesh[_x].d1N0[7] / betta / dt - ( 0.5 - betta ) / betta * mesh[_x].d2N0[7]; newmark_B[0] = -0.5 * mesh[_x].Nk0[0] / betta / dt + ( 1.0 - 0.5 / betta ) * mesh[_x].d1N0[0] - 0.5 * dt * ( 1.0 - 1.0 / betta * ( 0.5 - betta ) ) * mesh[_x].d2N0[0]; newmark_B[1] = -0.5 * mesh[_x].Nk0[1] / betta / dt + ( 1.0 - 0.5 / betta ) * mesh[_x].d1N0[1] - 0.5 * dt * ( 1.0 - 1.0 / betta * ( 0.5 - betta ) ) * mesh[_x].d2N0[1]; newmark_B[2] = -0.5 * mesh[_x].Nk0[2] / betta / dt + ( 1.0 - 0.5 / betta ) * mesh[_x].d1N0[2] - 0.5 * dt * ( 1.0 - 1.0 / betta * ( 0.5 - betta ) ) * mesh[_x].d2N0[2]; newmark_B[7] = -0.5 * mesh[_x].Nk0[7] / betta / dt + ( 1.0 - 0.5 / betta ) * mesh[_x].d1N0[7] - 0.5 * dt * ( 1.0 - 1.0 / betta * ( 0.5 - betta ) ) * mesh[_x].d2N0[7];*/ } else { for( int i = 0; i < eq_num; ++i) { newmark_A[i] = -mesh[_x].Nk1[i] / betta / dt / dt - mesh[_x].d1N[i] / betta / dt - ( 0.5l - betta ) / betta * mesh[_x].d2N[i]; newmark_B[i] = -0.5l * mesh[_x].Nk1[i] / betta / dt + ( 1.0l - 0.5l / betta ) * mesh[_x].d1N[i] - 0.5l * dt * ( 1.0l - 1.0l / betta * ( 0.5l - betta ) ) * mesh[_x].d2N[i]; } /*newmark_A[0] = -mesh[_x].Nk1[0] / betta / dt / dt - mesh[_x].d1N[0] / betta / dt - ( 0.5 - betta ) / betta * mesh[_x].d2N[0]; newmark_A[1] = -mesh[_x].Nk1[1] / betta / dt - mesh[_x].d1N[1] / betta - ( 0.5 - betta ) / betta * dt * mesh[_x].d2N[1]; newmark_A[2] = -mesh[_x].Nk1[2] / betta / dt / dt - mesh[_x].d1N[2] / betta / dt - ( 0.5 - betta ) / betta * mesh[_x].d2N[2]; newmark_A[7] = -mesh[_x].Nk1[7] / betta / dt / dt - mesh[_x].d1N[7] / betta / dt - ( 0.5 - betta ) / betta * mesh[_x].d2N[7]; newmark_B[0] = -0.5 * mesh[_x].Nk1[0] / betta / dt + ( 1.0 - 0.5 / betta ) * mesh[_x].d1N[0] - 0.5 * dt * ( 1.0 - 1.0 / betta * ( 0.5 - betta ) ) * mesh[_x].d2N[0]; newmark_B[1] = -0.5 * mesh[_x].Nk1[1] / betta / dt + ( 1.0 - 0.5 / betta ) * mesh[_x].d1N[1] - 0.5 * dt * ( 1.0 - 1.0 / betta * ( 0.5 - betta ) ) * mesh[_x].d2N[1]; newmark_B[2] = -0.5 * mesh[_x].Nk1[2] / betta / dt + ( 1.0 - 0.5 / betta ) * mesh[_x].d1N[2] - 0.5 * dt * ( 1.0 - 1.0 / betta * ( 0.5 - betta ) ) * mesh[_x].d2N[2]; newmark_B[7] = -0.5 * mesh[_x].Nk1[7] / betta / dt + ( 1.0 - 0.5 / betta ) * mesh[_x].d1N[7] - 0.5 * dt * ( 1.0 - 1.0 / betta * ( 0.5 - betta ) ) * mesh[_x].d2N[7];*/ } } void Solver::calc_nonlin_system( int _x ) { if( plate == 0 ){ cout << "Error in solver: plate is zero\n"; return; } PL_NUM h = plate->h; PL_NUM rho = plate->rho; PL_NUM sigma_x = plate->sigma_x; PL_NUM sigma_x_mu = plate->sigma_x_mu; PL_NUM Jx = 0.0; if( current_type == current_const ) { Jx = J0; } else if( current_type == current_sin ) { Jx = J0 * sin( omega * ( cur_t + dt ) ); } else if( current_type == current_exp_sin ) { Jx = J0 * exp( -( cur_t + dt ) / tauJ ) * sin( omega * ( cur_t + dt ) ); } PL_NUM Pimp = 0.0l; if( stress_type == stress_centered ) { if( ( cur_t + dt ).real() < tauP.real() && fabs( (long double)_x * dx.real() - plate->a / 2.0 ) < rad.real() ) { Pimp = p0 * sqrt( 1 - fabs( (long double)_x * dx.real() - plate->a / 2.0l ) * fabs( (long double)_x * dx.real() - plate->a / 2.0 ) / rad.real() / rad.real() ) * sin( (long double)M_PI * ( cur_t + dt ) / tauP ); } } else if( stress_type == stress_whole ) { Pimp = p0; } //long r; nonlin_matr_A( 0, 3 ) = 1.0l / al / h / B22; nonlin_matr_A( 1, 2 ) = 1.0l / al; nonlin_matr_A( 2, 5 ) = -12.0l /al / h / h / h / B22; nonlin_matr_A( 3, 0 ) = rho / al * h / betta / dt / dt + sigma_x * h / 2.0l / betta / dt / al * mesh[_x].Nk[7] * mesh[_x].Nk[7]; nonlin_matr_A( 3, 1 ) = -sigma_x * h / 4.0l / betta / dt / al * By1 * mesh[_x].Nk[7]; nonlin_matr_A( 3, 2 ) = -eps_x_0 / 4.0l / betta / dt / al * h * By1 * mesh[_x].Nk[6]; nonlin_matr_A( 3, 3 ) = eps_x_0 / 2.0l / betta / dt / B22 / al * h * mesh[_x].Nk[6] * mesh[_x].Nk[7]; nonlin_matr_A( 3, 6 ) = 1.0l / al * ( sigma_x * h * mesh[_x].Nk[7] + eps_x_0 * h / B22 * mesh[_x].Nk[7] * ( 1.0 / 2.0l / betta / dt * mesh[_x].Nk[3] + newmark_B[3] ) - eps_x_0 / 2.0l * h * By1 * ( 1.0l / 2.0l / betta / dt * mesh[_x].Nk[2] + newmark_B[2] ) ); nonlin_matr_A( 3, 7 ) = 1.0l / al * ( sigma_x * h * mesh[_x].Nk[6] + 2.0l * sigma_x * h * mesh[_x].Nk[7] * ( 1.0 / 2.0l / betta / dt * mesh[_x].Nk[0] + newmark_B[0] ) - sigma_x * h / 2.0l * By1 * ( 1.0l / 2.0l / betta / dt * mesh[_x].Nk[1] + newmark_B[1] ) + eps_x_0 * h / B22 * mesh[_x].Nk[6] * ( 1.0 / 2.0l / betta / dt * mesh[_x].Nk[3] + newmark_B[3] ) + h * Jx ); nonlin_matr_A( 4, 0 ) = -sigma_x * h / 4.0l / betta / dt / al * By1 * mesh[_x].Nk[7]; nonlin_matr_A( 4, 1 ) = rho / al * h / betta / dt / dt + sigma_x * h / 8.0l / betta / al / dt * ( By1 * By1 + 1.0 / 3.0l * By2 * By2 ); nonlin_matr_A( 4, 2 ) = 1.0 / 2.0l / betta / al * ( sigma_x * h * h / 12.0l * By2 * mesh[_x].Nk[7] - eps_x_0 * h * mesh[_x].Nk[6] * mesh[_x].Nk[7] ) / dt; nonlin_matr_A( 4, 6 ) = -1.0l / al * ( sigma_x * h / 2.0l * By1 + eps_x_0 * h * mesh[_x].Nk[7] * ( 1.0 / 2.0l / betta * mesh[_x].Nk[2] / dt + newmark_B[2] ) ); nonlin_matr_A( 4, 7 ) = -1.0l / al * ( sigma_x * h / 2.0l * By1 * ( 1.0 / 2.0l / betta * mesh[_x].Nk[0] / dt + newmark_B[0] ) - ( sigma_x / 12.0l * h * h * By2 - eps_x_0 * h * mesh[_x].Nk[6] ) * ( 1.0 / 2.0l / betta * mesh[_x].Nk[2] / dt + newmark_B[2] ) ); nonlin_matr_A( 5, 1 ) = -sigma_x * h * h / 24.0l / betta / dt / al * By2 * mesh[_x].Nk[7]; nonlin_matr_A( 5, 2 ) = -1.0 / 2.0l / betta / dt / al * ( sigma_x * h * h * h / 12.0l * mesh[_x].Nk[7] * mesh[_x].Nk[7] + eps_x_0 / 12.0l * h * h * By2 * mesh[_x].Nk[6] ) - h * h * h / 12.0l / betta / dt / dt * rho / al; nonlin_matr_A( 5, 4 ) = 1.0l / al; nonlin_matr_A( 5, 5 ) = eps_x_0 / 2.0l / betta / B22 / dt / al * mesh[_x].Nk[6] * mesh[_x].Nk[7]; nonlin_matr_A( 5, 6 ) = -eps_x_0 / al * ( h * h / 12.0l * By2 * ( 1.0l / 2.0l / betta / dt * mesh[_x].Nk[2] + newmark_B[2] ) - mesh[_x].Nk[7] / B22 * ( 1.0l / 2.0l / betta / dt * mesh[_x].Nk[5] + newmark_B[5] ) ); nonlin_matr_A( 5, 7 ) = -1.0l / al * ( sigma_x * h * h / 12.0l * By2 * ( 1.0 / 2.0l / betta / dt * mesh[_x].Nk[1] + newmark_B[1]) + sigma_x * h * h * h / 6.0l * mesh[_x].Nk[7] * ( 1.0l / 2.0l / betta / dt * mesh[_x].Nk[2] + newmark_B[2] ) - eps_x_0 / B22 * mesh[_x].Nk[6] * ( 1.0l / 2.0l / betta / dt * mesh[_x].Nk[5] + newmark_B[5] ) ); nonlin_matr_A( 6, 7 ) = 1.0l / 2.0l / ( betta * al * dt ); nonlin_matr_A( 7, 0 ) = sigma_x_mu / 2.0l / betta / ( dt * al ) * mesh[_x].Nk[7]; nonlin_matr_A( 7, 1 ) = -sigma_x_mu / 4.0l / betta / ( dt * al ) * By1; nonlin_matr_A( 7, 6 ) = sigma_x_mu / al; nonlin_matr_A( 7, 7 ) = sigma_x_mu / al * ( 1.0 / 2.0l / betta / dt * mesh[_x].Nk[0] + newmark_B[0]); nonlin_vect_f(3) = rho / al * h * newmark_A[0] + 1.0l / al * ( -sigma_x * h * mesh[_x].Nk[6] * mesh[_x].Nk[7] - sigma_x * h / betta / dt * mesh[_x].Nk[7] * mesh[_x].Nk[7] * mesh[_x].Nk[0] - sigma_x * h * mesh[_x].Nk[7] * mesh[_x].Nk[7] * newmark_B[0] + sigma_x * h / 4.0l / betta / dt * By1 * mesh[_x].Nk[7] * mesh[_x].Nk[1] - eps_x_0 * h / betta / dt / B22 * mesh[_x].Nk[6] * mesh[_x].Nk[7] * mesh[_x].Nk[3] - eps_x_0 * h / B22 * mesh[_x].Nk[6] * mesh[_x].Nk[7] * newmark_B[3] + eps_x_0 * h / 4.0l / betta / dt * By1 * mesh[_x].Nk[6] * mesh[_x].Nk[2] ); nonlin_vect_f(4) = rho / al * h * newmark_A[1] + Pimp / al + 1.0l / al * ( sigma_x * h / 4.0l / betta * By1 / dt //55454 h * mesh[_x].Nk[7] * mesh[_x].Nk[0] + sigma_x * h / 4.0l * ( By1 * By1 + 1.0l / 3.0l * By2 * By2 ) * newmark_B[1] - sigma_x * h * h / 24.0l / betta / dt * By2 * mesh[_x].Nk[7] * mesh[_x].Nk[2] + eps_x_0 * h / betta / dt * mesh[_x].Nk[6] * mesh[_x].Nk[7] * mesh[_x].Nk[2] + eps_x_0 * h * mesh[_x].Nk[6] * mesh[_x].Nk[7] * newmark_B[2] - h / 2.0l * Jx * By1 ); //By1 nonlin_vect_f(5) = 1.0l / al * ( sigma_x * h * h / 24.0l / betta / dt * By2 * mesh[_x].Nk[7] * mesh[_x].Nk[1] + sigma_x * h * h * h / 12.0l / betta / dt * mesh[_x].Nk[7] * mesh[_x].Nk[7] * mesh[_x].Nk[2] + sigma_x * h * h * h / 12.0l * mesh[_x].Nk[7] * mesh[_x].Nk[7] * newmark_B[2] + eps_x_0 / 24.0l / betta / dt * h * h * By2 * mesh[_x].Nk[6] * mesh[_x].Nk[2] - eps_x_0 / betta / dt / B22 * mesh[_x].Nk[6] * mesh[_x].Nk[7] * mesh[_x].Nk[5] - eps_x_0 / B22 * mesh[_x].Nk[6] * mesh[_x].Nk[7] * newmark_B[5] ) - h * h * h / 12.0l * newmark_A[2] * rho / al; nonlin_vect_f(6) = newmark_B[7] / al; nonlin_vect_f(7) = 1.0l / al * ( By2 / h - sigma_x_mu / 2.0l / betta / dt * mesh[_x].Nk[7] * mesh[_x].Nk[0] - 0.5l * sigma_x_mu * By1 * newmark_B[1] ); } PL_NUM Solver::do_step() { cout << "cur time is " << cur_t.real() << endl; //cout << "time step number " << curTimeStep << endl; //cout << "calculating solution for the next time step\n\n"; int iter = 0; int preLin = 0; int cont = 1; do{ if( iter == 0 && curTimeStep == 0 ) { preLin = 0; } else { preLin = 1; } calc_Newmark_AB( 0, 1 ); //solInfoMap[0].flushO(); orthoBuilder->flushO( 0 ); N1( 0 ) = 0.0; N1( 1 ) = 0.0; N1( 2 ) = 1.0; N1( 3 ) = 0.0; N1( 4 ) = 0.0; N1( 5 ) = 0.0; N1( 6 ) = 0.0; N1( 7 ) = 0.0; N2( 0 ) = 0.0; N2( 1 ) = 0.0; N2( 2 ) = 0.0; N2( 3 ) = 1.0; N2( 4 ) = 0.0; N2( 5 ) = 0.0; N2( 6 ) = 0.0; N2( 7 ) = 0.0; N3( 0 ) = 0.0; N3( 1 ) = 0.0; N3( 2 ) = 0.0; N3( 3 ) = 0.0; N3( 4 ) = 1.0; N3( 5 ) = 0.0; N3( 6 ) = 0.0; N3( 7 ) = 0.0; N4( 0 ) = 0.0; N4( 1 ) = 0.0; N4( 2 ) = 0.0; N4( 3 ) = 0.0; N4( 4 ) = 0.0; N4( 5 ) = 0.0; if( preLin == 0 ) { N4( 6 ) = 0.0; } else { N4( 6 ) = mesh[0].Nk1[0] / 2.0l / betta / dt + newmark_B[0]; } N4( 7 ) = -1.0; N5( 0 ) = 0.0; N5( 1 ) = 0.0; N5( 2 ) = 0.0; N5( 3 ) = 0.0; N5( 4 ) = 0.0; N5( 5 ) = 0.0; if( preLin == 0 ) { N5( 6 ) = 0.0; N5( 7 ) = 0.0; } else { N5( 6 ) = ( newmark_B[0] * mesh[0].Nk1[7] - newmark_B[1] * By0 ); N5( 7 ) = -mesh[0].Nk1[7]; } /*for( int i = 0; i < eq_num; ++i ) { solInfoMap[0].z1[i] = N1[i]; solInfoMap[0].z2[i] = N2[i]; solInfoMap[0].z3[i] = N3[i]; solInfoMap[0].z4[i] = N4[i]; solInfoMap[0].z5[i] = N5[i]; }*/ orthoBuilder->setInitVects( N1, N2, N3, N4, N5 ); //#pragma omp parallel for for( int x = 0; x < Km; ++x ) { for( int i = 0; i < eq_num; ++i ) { mesh[x].Nk[i] = mesh[x].Nk1[i]; } } for( int x = 0; x < Km - 1; ++x ) { orthoBuilder->flushO( x + 1 ); calc_Newmark_AB( x, 0 ); calc_nonlin_system( x ); rungeKutta->calc( nonlin_matr_A, nonlin_vect_f, dx, 0, &N1 ); rungeKutta->calc( nonlin_matr_A, nonlin_vect_f, dx, 0, &N2 ); rungeKutta->calc( nonlin_matr_A, nonlin_vect_f, dx, 0, &N3 ); rungeKutta->calc( nonlin_matr_A, nonlin_vect_f, dx, 0, &N4 ); rungeKutta->calc( nonlin_matr_A, nonlin_vect_f, dx, 1, &N5 ); orthoBuilder->orthonorm( 1, x, &N1 ); orthoBuilder->orthonorm( 2, x, &N2 ); orthoBuilder->orthonorm( 3, x, &N3 ); orthoBuilder->orthonorm( 4, x, &N4 ); orthoBuilder->orthonorm( 5, x, &N5 ); } orthoBuilder->buildSolution( &mesh ); if( preLin != 0 ) { cont = checkConv(); } ++iter; cout << " : " << iter << endl; }while( cont == 1 ); cout << "approximation to the solution on the time step done in " << iter << " steps\n"; //#pragma omp parallel for for( int x = 0; x < Km; ++x ) { for( int i = 0; i < eq_num; ++i ) { mesh[x].d2N[i] = ( mesh[x].Nk1[i] - mesh[x].Nk0[i] ) / betta / dt / dt - mesh[x].d1N0[i] / betta / dt - ( 0.5l - betta ) / betta * mesh[x].d2N0[i]; mesh[x].d1N[i] = mesh[x].d1N0[i] + 0.5l * dt * ( mesh[x].d2N0[i] + mesh[x].d2N[i] ); mesh[x].Nk0[i] = mesh[x].Nk1[i]; mesh[x].d1N0[i] = mesh[x].d1N[i]; mesh[x].d2N0[i] = mesh[x].d2N[i]; } } return mesh[ ( Km - 1 ) / 2 ].Nk1[1]; } int Solver::checkConv() { for( int x = 1; x < Km; ++x ) { for( int i = 0; i < eq_num; ++i ) { if( mesh[x].Nk[i].real() != 0.0 ) { if( fabs( ( mesh[x].Nk1[i].real() - mesh[x].Nk[i].real() ) / mesh[x].Nk[i].real() ) < ALMOST_ZERO ) { return 0; } } else { if( fabs( mesh[x].Nk1[i].real() ) < ALMOST_ZERO ) { return 0; } } } } return 1; } void Solver::dump_sol() { ofstream dumpSol; stringstream ss; ss << "sol_" << cur_t << ".txt"; dumpSol.open ( ss.str() ); for( int x = 0; x < Km; ++x ) { for( int i = 0; i < eq_num; ++i ) { dumpSol << mesh[x].Nk1[i] << " "; } dumpSol << endl; } dumpSol.close(); return; } void Solver::dump_check_sol( int fNum ) { PL_NUM sum = 0.0; PL_NUM h = plate->h; PL_NUM a = plate->a; PL_NUM rho = plate->rho; PL_NUM t = cur_t; int minusOne = -1; for( int i = 0; i <= 1000000; ++i ) { PL_NUM omg = (long double)( M_PI * M_PI * ( 2 * i + 1 ) * ( 2 * i + 1 ) ) * h / 2.0l / a / a * sqrt( B22 / 3.0l / rho ); minusOne = -minusOne; sum = sum + (long double)minusOne / ( 2 * i + 1 ) / ( 2 * i + 1 ) / ( 2 * i + 1 ) / ( 2 * i + 1 ) / ( 2 * i + 1 ) * cos( omg * t ); } PL_NUM wTheor; wTheor = - p0 * a * a * a * a / h / h / h / B22 * ( 5.0l / 32.0l - 48.0l / M_PI / M_PI / M_PI / M_PI / M_PI * sum ); stringstream ss; ss << "test_sol_" << fNum << ".txt"; ofstream of1( ss.str(), ofstream::app ); of1 << cur_t.real() << " ; " << mesh[ ( Km - 1 ) / 2 ].Nk1[1].real() << " ; " << wTheor.real() << " ; " << fabs( ( wTheor.real() - mesh[ ( Km - 1 ) / 2 ].Nk1[1] ).real() / wTheor.real() ) << endl; of1.close(); } void Solver::dump_left_border_vals() { ofstream of1( "sol_left_border.txt", ofstream::app ); of1 << "v : " << mesh[0].Nk1[0] << "\tw : " << mesh[0].Nk1[1] << "\tW : " << mesh[0].Nk1[2] << "\tMyy : " << mesh[0].Nk1[5] << "\tNyy : " << mesh[0].Nk1[3] << "\tNyz : " << mesh[0].Nk1[4] << endl; of1.close(); } void Solver::dumpMatrA() { ofstream of( "MatrA.txt", ofstream::app ); for( int i = 0; i < EQ_NUM; ++i ) { for( int j = 0; j < EQ_NUM; ++j ) { of << nonlin_matr_A( i, j ) << " "; } of << endl; } of << "\n============================================\n"; }
#include "task.h" #include "Vector.h" #ifndef _INPUT_ #define _INPUT_ enum possibleInputContexts { NormalInput = 0, ConsoleInput, PersonelMenu, BuildMenu, EditMode, Sailing }; class Input : public Task { public: Input(void); ~Input(void); void run(); void SetKeyState(int key, int state); int GetKeyState(int key); bool GetKeyDown(int key); bool GetKeyPressed(int key); bool GetKeyReleased(int key); bool GetMButtonState(int button) { return (mousebuttons[button] == 1); } void SetMButtonState(int button, bool state) { mousebuttons[button] = state; } bool GetMButtonPushed(int button) { return ((GetMButtonState(button)) && lastbuttons[button] != mousebuttons[button]); } bool GetMButtonReleased(int button) { return ((!GetMButtonState(button)) && lastbuttons[button] != mousebuttons[button]); } int laststate[512]; int keystate[512]; int lastbuttons[6]; int mousebuttons[6]; Vector mousePosition; Vector mouseAbsolute; Vector mouseMovement; Vector mouse3dPosition; Vector mouseVector; int inputContext; #define LeftMouseClick 1 #define MiddleMouseClick 2 #define RightMouseClick 3 private: int priority; }; #endif
#include <bits/stdc++.h> using namespace std; vector <string> v; int main(){ int n,m; string s; cin >> n >> m; for(int i=0; i<n; i++){ cin>>s; v.push_back(s); } int max=0; int count=0; for(int i=0; i<n-1; i++){ for(int j=i+1; j<n; j++){ int val = 0; for(int k=0; k<m; k++){ if(v[i][k]=='1' || v[j][k]=='1'){ val++; } if(max<val){max = val; count = 1; } else if(max==val){count++; } } } } cout<<max<<endl<<count; }
#include<iostream> using namespace std; int main() { //first test Init //test push return 0; }
// Test program for server infrastructure #include <iostream> #include <fstream> #include <thread> #include <mutex> #include <condition_variable> #include <chrono> #include <string> #include <vector> #include <atomic> #include <cmath> #include <cstdint> std::string pretty(uint64_t u) { if (u == 0) { return "0"; } std::string r; int c = 0; while (u > 0) { if (c == 3) { r = "," + r; c = 0; } r = std::to_string(u % 10) + r; u /= 10; ++c; } return r; } class Work { size_t howmuch; size_t sum; public: Work(size_t h) : howmuch(h), sum(0) { } void dowork() { size_t s = 0; for (size_t i = 0; i < howmuch; ++i) { s += i * i; } sum += s; } size_t get() { return sum; } }; double workTime = 0.0; // time in seconds for one piece of work, will be // gauged at beginning of program void singleThread(Work* work, std::atomic<int>* stop, uint64_t* count) { // simply work until stop is signalled: uint64_t c = 0; size_t perRound = ceill(1e-5 / workTime); while (stop->load() == 0) { for (size_t i = 0; i < perRound; ++i) { work->dowork(); ++c; } } *count = c; } void multipleThreads(Work* work, std::mutex* mutex, std::atomic<int>* stop, uint64_t* count) { // simply work until stop is signalled, but with a mutex: uint64_t c = 0; size_t perRound = ceill(1e-5 / workTime); while (stop->load() == 0) { for (size_t i = 0; i < perRound; ++i) { { std::unique_lock<std::mutex> guard(*mutex); work->dowork(); } ++c; } } *count = c; } class Server { public: struct alignas(128) Client { std::atomic<int> what; // starts as 0, which means nothing to do // a positive number indicates that the client // wants a job to be done, when done, the server // sets it to the negative of the job id Work* work; Client(Work* w) : what(0), work(w) { } }; private: std::mutex mutex; size_t maxNrClients; Client** clients; std::atomic<size_t> nrClients; bool started; std::thread server; public: Server(size_t m) : maxNrClients(m), clients(new Client*[m]), nrClients(0), started(false), server(&Server::run, this) { } ~Server() { if (nrClients > 0) { std::cout << "Warning: Server has clients on destruction!" << std::endl; } server.join(); } bool registerClient(Client* c) { std::unique_lock<std::mutex> guard(mutex); if (nrClients >= maxNrClients) { return false; } clients[nrClients] = c; ++nrClients; started = true; return true; } private: void unregisterClient(size_t pos) { std::unique_lock<std::mutex> guard(mutex); clients[pos] = clients[nrClients-1]; --nrClients; } void run() { while (true) { size_t nr = nrClients; if (nr == 0) { if (started) { return; } //std::this_thread::sleep_for(std::chrono::duration<double>(0.001)); } else { for (size_t i = 0; i < nr; ++i) { int what = clients[i]->what.load(std::memory_order_acquire); if (what > 0) { switch (what) { case 1: unregisterClient(i); --nr; break; case 2: clients[i]->work->dowork(); break; } clients[i]->what.store(-what, std::memory_order_release); } } } } } }; void clientThread(Server* server, Work* work, std::atomic<int>* stop, uint64_t* count) { Server::Client cl(work); server->registerClient(&cl); // simply work as client until stop is signalled: uint64_t c = 0; size_t perRound = ceill(1e-5 / workTime); while (stop->load() == 0) { for (size_t i = 0; i < perRound; ++i) { cl.what = 2; while (cl.what.load(std::memory_order_acquire) != -2) { std::this_thread::yield(); } ++c; } } *count = c; cl.what = 1; while (cl.what.load(std::memory_order_acquire) != -1) { std::this_thread::yield(); } } int main(int argc, char* argv[]) { // Command line arguments: if (argc < 4) { std::cout << "Usage: servertest DIFFICULTY TESTTIME THREADS" << std::endl; return 0; } size_t howmuch = std::stoul(std::string(argv[1])); double testTime = std::stoul(std::string(argv[2])); int threads = std::stol(std::string(argv[3])); std::cout << "Difficulty: " << howmuch << std::endl; std::cout << "Test time : " << testTime << std::endl; std::cout << "Maximal number of threads: " << threads << "\n" << std::endl; // Work generator: Work work(howmuch); std::chrono::high_resolution_clock clock; // Measure a single workload: { std::cout << "Measuring a single workload..." << std::endl; size_t repeats = 100; std::chrono::duration<double> runTime; while (true) { auto startTime = clock.now(); for (size_t i = 0; i < repeats; ++i) { work.dowork(); } auto endTime = clock.now(); runTime = endTime - startTime; if (runTime > std::chrono::duration<double>(1)) { break; } repeats *= 3; } workTime = runTime.count() / repeats; std::cout << "Work time for one unit of work: " << floor(workTime * 1e9) << " ns\n" << std::endl; } // Now measure how many workloads a single thread can do in a given time: { std::cout << "Running in a single thread without any locking..." << std::endl; std::atomic<int> stop(0); uint64_t count; auto startTime = clock.now(); std::thread t(singleThread, &work, &stop, &count); std::this_thread::sleep_for(std::chrono::duration<double>(testTime)); stop.store(1); t.join(); auto endTime = clock.now(); std::chrono::duration<double> runTime = endTime - startTime; std::cout << " time=" << runTime.count() << "s " << pretty(count) << " iterations, time per iteration: " << floorl(runTime.count() / static_cast<double>(count) * 1e9) << " ns" << "\n" << std::endl; } // Now measure how multiple threads fare when using a normal mutex: { std::cout << "Using multiple threads and a std::mutex..." << std::endl; for (int j = 1; j <= threads; ++j) { std::cout << "Using " << j << " threads:" << std::endl; std::vector<std::thread> ts; std::vector<uint64_t> counts; std::mutex mutex; counts.reserve(j); for (int i = 0; i < j; ++i) { counts.push_back(0); } ts.reserve(j); std::atomic<int> stop(0); auto startTime = clock.now(); for (int i = 0; i < j; ++i) { ts.emplace_back(multipleThreads, &work, &mutex, &stop, &counts[i]); } std::this_thread::sleep_for(std::chrono::duration<double>(testTime)); stop.store(1); for (int i = 0; i < j; ++i) { ts[i].join(); } auto endTime = clock.now(); std::chrono::duration<double> runTime = endTime - startTime; uint64_t count = 0; for (int i = 0; i < j; ++i) { count += counts[i]; } std::cout << " time=" << runTime.count() << "s " << pretty(count) << " iterations, time per iteration: " << floorl(runTime.count() / static_cast<double>(count) * 1e9) << " ns" << std::endl; std::cout << " thread counts:"; for (int i = 0; i < j; ++i) { std::cout << " " << pretty(counts[i]); } std::cout << "\n" << std::endl; } } // Measure a delegating server: { std::cout << "Running in a single thread with delegation..." << std::endl; Server server(threads); // start the server thread std::atomic<int> stop(0); uint64_t count; auto startTime = clock.now(); std::thread t(clientThread, &server, &work, &stop, &count); std::this_thread::sleep_for(std::chrono::duration<double>(testTime)); stop.store(1); t.join(); auto endTime = clock.now(); std::chrono::duration<double> runTime = endTime - startTime; std::cout << " time=" << runTime.count() << "s " << pretty(count) << " iterations, time per iteration: " << floorl(runTime.count() / static_cast<double>(count) * 1e9) << " ns" << std::endl; } // Write out dummy result to convince compiler not to optimize everything out { std::fstream dummys("/dev/null", std::ios_base::out); dummys << work.get() << std::endl; } }
// 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 _BRepExtrema_DistShapeShape_HeaderFile #define _BRepExtrema_DistShapeShape_HeaderFile #include <Bnd_Array1OfBox.hxx> #include <BRepExtrema_SeqOfSolution.hxx> #include <BRepExtrema_SolutionElem.hxx> #include <BRepExtrema_SupportType.hxx> #include <Extrema_ExtAlgo.hxx> #include <Extrema_ExtFlag.hxx> #include <Message_ProgressRange.hxx> #include <TopoDS_Shape.hxx> #include <Standard_OStream.hxx> #include <Standard_DefineAlloc.hxx> #include <TopTools_IndexedMapOfShape.hxx> //! This class provides tools to compute minimum distance //! between two Shapes (Compound,CompSolid, Solid, Shell, Face, Wire, Edge, Vertex). class BRepExtrema_DistShapeShape { public: DEFINE_STANDARD_ALLOC //! create empty tool Standard_EXPORT BRepExtrema_DistShapeShape(); //! create tool and computation of the minimum distance (value and pair of points) //! using default deflection in single thread mode. <br> //! Default deflection value is Precision::Confusion(). <br> //! @param Shape1 - the first shape for distance computation //! @param Shape2 - the second shape for distance computation //! @param F and @param A are not used in computation and are obsolete. //! @param theRange - the progress indicator of algorithm Standard_EXPORT BRepExtrema_DistShapeShape(const TopoDS_Shape& Shape1, const TopoDS_Shape& Shape2, const Extrema_ExtFlag F = Extrema_ExtFlag_MINMAX, const Extrema_ExtAlgo A = Extrema_ExtAlgo_Grad, const Message_ProgressRange& theRange = Message_ProgressRange()); //! create tool and computation of the minimum distance //! (value and pair of points) in single thread mode. <br> //! Default deflection value is Precision::Confusion(). <br> //! @param Shape1 - the first shape for distance computation //! @param Shape2 - the second shape for distance computation //! @param theDeflection - the presition of distance computation //! @param F and @param A are not used in computation and are obsolete. //! @param theRange - the progress indicator of algorithm Standard_EXPORT BRepExtrema_DistShapeShape(const TopoDS_Shape& Shape1, const TopoDS_Shape& Shape2, const Standard_Real theDeflection, const Extrema_ExtFlag F = Extrema_ExtFlag_MINMAX, const Extrema_ExtAlgo A = Extrema_ExtAlgo_Grad, const Message_ProgressRange& theRange = Message_ProgressRange()); //! Sets deflection to computation of the minimum distance <br> void SetDeflection(const Standard_Real theDeflection) { myEps = theDeflection; } //! load first shape into extrema <br> Standard_EXPORT void LoadS1(const TopoDS_Shape& Shape1); //! load second shape into extrema <br> Standard_EXPORT void LoadS2(const TopoDS_Shape& Shape1); //! computation of the minimum distance (value and <br> //! couple of points). Parameter theDeflection is used <br> //! to specify a maximum deviation of extreme distances <br> //! from the minimum one. <br> //! Returns IsDone status. <br> //! theRange - the progress indicator of algorithm Standard_EXPORT Standard_Boolean Perform(const Message_ProgressRange& theRange = Message_ProgressRange()); //! True if the minimum distance is found. <br> Standard_Boolean IsDone() const { return myIsDone; } //! Returns the number of solutions satisfying the minimum distance. <br> Standard_Integer NbSolution() const { return mySolutionsShape1.Length(); } //! Returns the value of the minimum distance. <br> Standard_EXPORT Standard_Real Value() const; //! True if one of the shapes is a solid and the other shape <br> //! is completely or partially inside the solid. <br> Standard_Boolean InnerSolution() const { return myInnerSol; } //! Returns the Point corresponding to the <N>th solution on the first Shape <br> const gp_Pnt & PointOnShape1(const Standard_Integer N) const { return mySolutionsShape1.Value(N).Point(); } //! Returns the Point corresponding to the <N>th solution on the second Shape <br> const gp_Pnt & PointOnShape2(const Standard_Integer N) const { return mySolutionsShape2.Value(N).Point(); } //! gives the type of the support where the Nth solution on the first shape is situated: <br> //! IsVertex => the Nth solution on the first shape is a Vertex <br> //! IsOnEdge => the Nth soluion on the first shape is on a Edge <br> //! IsInFace => the Nth solution on the first shape is inside a face <br> //! the corresponding support is obtained by the method SupportOnShape1 <br> BRepExtrema_SupportType SupportTypeShape1(const Standard_Integer N) const { return mySolutionsShape1.Value(N).SupportKind(); } //! gives the type of the support where the Nth solution on the second shape is situated: <br> //! IsVertex => the Nth solution on the second shape is a Vertex <br> //! IsOnEdge => the Nth soluion on the secondt shape is on a Edge <br> //! IsInFace => the Nth solution on the second shape is inside a face <br> //! the corresponding support is obtained by the method SupportOnShape2 <br> BRepExtrema_SupportType SupportTypeShape2(const Standard_Integer N) const { return mySolutionsShape2.Value(N).SupportKind(); } //! gives the support where the Nth solution on the first shape is situated. <br> //! This support can be a Vertex, an Edge or a Face. <br> Standard_EXPORT TopoDS_Shape SupportOnShape1(const Standard_Integer N) const; //! gives the support where the Nth solution on the second shape is situated. <br> //! This support can be a Vertex, an Edge or a Face. <br> Standard_EXPORT TopoDS_Shape SupportOnShape2(const Standard_Integer N) const; //! gives the corresponding parameter t if the Nth solution <br> //! is situated on an Edge of the first shape <br> Standard_EXPORT void ParOnEdgeS1(const Standard_Integer N,Standard_Real& t) const; //! gives the corresponding parameter t if the Nth solution <br> //! is situated on an Edge of the first shape <br> Standard_EXPORT void ParOnEdgeS2(const Standard_Integer N,Standard_Real& t) const; //! gives the corresponding parameters (U,V) if the Nth solution <br> //! is situated on an face of the first shape <br> Standard_EXPORT void ParOnFaceS1(const Standard_Integer N,Standard_Real& u,Standard_Real& v) const; //! gives the corresponding parameters (U,V) if the Nth solution <br> //! is situated on an Face of the second shape <br> Standard_EXPORT void ParOnFaceS2(const Standard_Integer N,Standard_Real& u,Standard_Real& v) const; //! Prints on the stream o information on the current state of the object. <br> Standard_EXPORT void Dump(Standard_OStream& o) const; //! Sets unused parameter //! Obsolete void SetFlag(const Extrema_ExtFlag F) { myFlag = F; } //! Sets unused parameter //! Obsolete void SetAlgo(const Extrema_ExtAlgo A) { myAlgo = A; } //! If isMultiThread == Standard_True then computation will be performed in parallel. void SetMultiThread(Standard_Boolean theIsMultiThread) { myIsMultiThread = theIsMultiThread; } //! Returns Standard_True then computation will be performed in parallel //! Default value is Standard_False Standard_Boolean IsMultiThread() const { return myIsMultiThread; } private: //! computes the minimum distance between two maps of shapes (Face,Edge,Vertex) <br> Standard_Boolean DistanceMapMap(const TopTools_IndexedMapOfShape& Map1, const TopTools_IndexedMapOfShape& Map2, const Bnd_Array1OfBox& LBox1, const Bnd_Array1OfBox& LBox2, const Message_ProgressRange& theRange); //! computes the minimum distance between two maps of vertices <br> Standard_Boolean DistanceVertVert(const TopTools_IndexedMapOfShape& theMap1, const TopTools_IndexedMapOfShape& theMap2, const Message_ProgressRange& theRange); Standard_Boolean SolidTreatment(const TopoDS_Shape& theShape, const TopTools_IndexedMapOfShape& theMap, const Message_ProgressRange& theRange); private: Standard_Real myDistRef; Standard_Boolean myIsDone; BRepExtrema_SeqOfSolution mySolutionsShape1; BRepExtrema_SeqOfSolution mySolutionsShape2; Standard_Boolean myInnerSol; Standard_Real myEps; TopoDS_Shape myShape1; TopoDS_Shape myShape2; TopTools_IndexedMapOfShape myMapV1; TopTools_IndexedMapOfShape myMapV2; TopTools_IndexedMapOfShape myMapE1; TopTools_IndexedMapOfShape myMapE2; TopTools_IndexedMapOfShape myMapF1; TopTools_IndexedMapOfShape myMapF2; Standard_Boolean myIsInitS1; Standard_Boolean myIsInitS2; Extrema_ExtFlag myFlag; Extrema_ExtAlgo myAlgo; Bnd_Array1OfBox myBV1; Bnd_Array1OfBox myBV2; Bnd_Array1OfBox myBE1; Bnd_Array1OfBox myBE2; Bnd_Array1OfBox myBF1; Bnd_Array1OfBox myBF2; Standard_Boolean myIsMultiThread; }; #endif
//http://demon-school.webuda.com #include "funct.cpp" int main(){ int comand,m=1,m1=0,m2=0,m3=0; char fname[10]; nod *t=NULL; while(1){ while(m){m=0; system("cls"); fflush(stdin); printf("Meniu:\n\n"); printf("[ 1 ] Manual\n"); printf("[ 2 ] Fisier\n\n"); printf("[ 0 ] Exit\n\n"); printf("Comand >> "); scanf("%d",&comand); system("cls"); switch(comand){ case 0: exit(0); break; case 1: printf("Crearea arborelui :\n\n"); printf("[ 1 ] Folosind coada\n"); printf("[ 2 ] Folosind stiva\n"); printf("[ 3 ] Folosind functie recursiva\n\n"); printf("[ 0 ] Exit\n\n"); printf("Comand >> "); fflush(stdin); scanf("%d",&comand); system("cls"); switch(comand){ case 0: exit(0); break; case 1: find_error(creat_q()); break; case 2: find_error(creat_s()); break; case 3: creat_r(); break; default: printf("\a\nAti introdus o comanda gresita!\n"); m=1; break; } break; case 2: printf("Introduceti numele fisierului : "); scanf("%s",&fname); fflush(stdin); strcat(fname,".txt"); find_error(read_file(fname)); break; default: printf("\a\nAti introdus o comanda gresita!\n"); m=1; break; } pause } system("cls"); fflush(stdin); printf("Alegeti modul de lucru :\n"); printf("[ 1 ] Coada\n"); printf("[ 2 ] Stiva\n"); printf("[ 3 ] Recursie\n"); printf("[ 4 ] Meniul de introducere a datelor\n"); printf("[ 5 ] Afisarea vizuala\n"); printf("[ 6 ] Salveaza in fisier\n\n"); printf("[ 0 ] Exit\n\n"); printf("Comand >> "); scanf("%d",&comand); system("cls"); switch(comand){ case 0: exit(0); break; case 1: m1=1; break; case 2: m2=1; break; case 3: m3=1; break; case 4: m=1; break; case 5: print(root); pause break; case 6: printf("Introdu numele fisierului cu extensia .txt\n"); scanf("%s",&fname); write_file(fname); break; default: printf("\a\nAti introdus o comanda gresita!\n"); break; } while(m1){ system("cls"); fflush(stdin); printf("Operatii - Coada!\n\n"); printf("[ 1 ] Afisare\n"); printf("[ 2 ] Cautare\n"); printf("[ 3 ] Marimea arborelui\n"); printf("[ 4 ] Inaltimea !\n"); printf("[ 5 ] Eliberarea memoriei\n"); printf("[ 6 ] Alege modul de lucru\n\n"); printf("[ 0 ] Exit\n\n"); printf("Comand >> "); scanf("%d",&comand); system("cls"); switch(comand){ case 0: exit(0); break; case 1: printf("Afisare in largime\n"); find_error(show_q()); break; case 2: printf("Introdu Numele pentru cautare : "); fflush(stdin); scanf("%s",&fname); t=search_q(fname); if(t){ printf("***************************************\n\n"); printf("Numele %s\n",t->num); printf("Prenume %s\n",t->pre); printf("Specialitatea %s\n",t->spec); printf("Anul %d\n",t->anu); printf("Media %.2f\n",t->med); } else { printf("Nu sa gasit nici un student cu asa nume!\a"); } break; case 3: printf("Arborele are noduri "); find_error(size_q()); break; case 4: printf("Inaltimea arborelui este %d",height_r(root)); break; case 5: find_error(freemem_q()); root=NULL; break; case 6: m1=0; break; default: printf("\a\nAti introdus o comanda gresita!\n"); break; } pause } while(m2){ system("cls"); fflush(stdin); printf("Operatii - Stiva!\n\n"); printf("[ 1 ] Afisare\n"); printf("[ 2 ] Cautare\n"); printf("[ 3 ] Marimea arborelui\n"); printf("[ 4 ] Inaltimea !\n"); printf("[ 5 ] Eliberarea memoriei\n"); printf("[ 6 ] Alege modul de lucru\n\n"); printf("[ 0 ] Exit\n\n"); printf("Comand >> "); scanf("%d",&comand); system("cls"); switch(comand){ case 0: exit(0); break; case 1: printf("Afisare in adincime\n"); find_error(show_s()); break; case 2: printf("Introdu Numele pentru cautare : "); fflush(stdin); scanf("%s",&fname); t=search_s(fname); if(t){ printf("***************************************\n\n"); printf("Numele %s\n",t->num); printf("Prenume %s\n",t->pre); printf("Specialitatea %s\n",t->spec); printf("Anul %d\n",t->anu); printf("Media %.2f\n",t->med); } else { printf("Nu sa gasit nici un student cu asa nume!\a"); } break; case 3: printf("Arborele are noduri "); find_error(size_s()); break; case 4: printf("Inaltimea arborelui este %d",height_r(root)); break; case 5:find_error(freemem_s()); root=NULL; break; case 6: m2=0; break; default: printf("\a\nAti introdus o comanda gresita!\n"); break; } pause } while(m3){ system("cls"); fflush(stdin); printf("Operatii - Recursie!\n\n"); printf("[ 1 ] Afisare\n"); printf("[ 2 ] Cautare\n"); printf("[ 3 ] Marimea arborelui\n"); printf("[ 4 ] Inaltimea !\n"); printf("[ 5 ] Eliberarea memoriei\n"); printf("[ 6 ] Alege modul de lucru\n\n"); printf("[ 0 ] Exit\n\n"); printf("Comand >> "); scanf("%d",&comand); system("cls"); switch(comand){ case 0: exit(0); break; case 1: printf("Afisare in adincime\n\n"); show_r(root); break; case 2: printf("Introdu Numele pentru cautare : "); fflush(stdin); scanf("%s",&fname); t=search_r(root,fname); if(t){ printf("***************************************\n\n"); printf("Numele %s\n",t->num); printf("Prenume %s\n",t->pre); printf("Specialitatea %s\n",t->spec); printf("Anul %d\n",t->anu); printf("Media %.2f\n",t->med); } else { printf("Nu sa gasit nici un student cu asa nume!\a"); } break; case 3: printf("Arborele are noduri "); find_error(size_r(root)); break; case 4: printf("Inaltimea arborelui este %d",height_r(root)); break; case 5: freemem_r(root); root=NULL; printf("Eliberarea memoriei a avut loc cu succes!\a"); break; case 6: m3=0; break; default: printf("\a\nAti introdus o comanda gresita!\n"); break; } pause } } return 0; }
#pragma once class AudioMarkupNavigator { public: AudioMarkupNavigator(); virtual ~AudioMarkupNavigator(); public: virtual bool requestMarkerId(int& markerId); };
#pragma once #include <WiFiClientSecure.h> #include <Arduino.h> #include "mumble_base.h" #include "mumble_messages.h" #define BUF_LEN 2048 #ifdef DEBUG // #define DEBUG_SEND_PACKAGE // #define DEBUG_SEND // #define DEBUG_READ // #define DEBUG_UPDATE #endif union MumbleVersion { uint32_t combined; struct { uint8_t patch; uint8_t minor; uint8_t major; uint8_t reserved; } version; }; class MumbleConnection : public MumbleMessageProvider { private: //server connection const char *hostname; int port; WiFiClientSecure * client; // Memory reserved for mumble messages MumbleMessageMem message; void inline reset_message() { memset(&message, 0, sizeof(MumbleMessageMem));} //Predefined Messages: MumbleProto_Version versionMsg; MumbleProto_Ping pingMsg; MumbleProto_Authenticate authMsg; //last handled message MessageType messageType; int messageBytes; //send and receive buffer char buffer[BUF_LEN]; int parse_incomming_message(char* data, int length); void send_msg(MessageType type); public: MumbleConnection(const char *hostname, int port, const char *username, WiFiClientSecure * client); ~MumbleConnection(); void connect(); void send_ping(); int read_available(); };
#include<bits/stdc++.h> using namespace std; #define maxn 100010 using ll=long long; pair<ll,ll> p[maxn]; int n; ll l_max[maxn]; ll l_min[maxn]; ll r_max[maxn]; ll r_min[maxn]; bool judge(ll m){ int ind=1; for(int i=1;i<n;i++){ while(ind+1<=n&&p[ind+1].first-p[i].first<=m) ind++; if(max(l_max[i-1],r_max[ind+1])-min(l_min[i-1],r_min[ind+1])<=m) return true; } return false; } ll b_search(ll l,ll r){ if(l==r) return l; ll m=(l+r)>>1; if(judge(m)) return b_search(l,m); else return b_search(m+1,r); } int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>n; for(int i=1;i<=n;i++){ ll x,y; cin>>x>>y; p[i].first=x+y; p[i].second=x-y; } sort(p+1,p+n+1); l_max[0]=l_max[n+1]=r_max[0]=r_max[n+1]=LLONG_MIN; l_min[0]=l_min[n+1]=r_min[0]=r_min[n+1]=LLONG_MAX; for(int i=1;i<=n;i++){ l_min[i]=min(l_min[i-1],p[i].second); l_max[i]=max(l_max[i-1],p[i].second); } for(int i=n;i>0;i--){ r_min[i]=min(r_min[i+1],p[i].second); r_max[i]=max(r_max[i+1],p[i].second); } cout<<setiosflags(ios::fixed)<<setprecision(8)<<1.0*b_search(0,10000000000ll)/2; return 0; }
#ifndef GLOBALCONFIG_H #define GLOBALCONFIG_H #include <Arduino.h> class Globalconfig{ public: const static int MAP_SIZE = 16; const static int DIMENSION_X = 4; const static int DIMENSION_Y = 4; }; #endif
/* * RedisConnPool.h * * Created on: Oct 10, 2017 * Author: root */ #ifndef REDIS_REDISCONNPOOL_H_ #define REDIS_REDISCONNPOOL_H_ #include <hiredis/hiredis.h> #include <string> #include "../Common.h" #include <list> #include <map> #include "../define.h" #include "../Memory/MemAllocator.h" using namespace std; namespace CommBaseOut { enum E_RedisResult { eRedisSuccess=0, //成功 // eSeleNULL, //查询结果为0个数据 eRedisHandleNULL, //数据库连接句柄为空 // eExeError, //执行错误 // eResError, //返回结果错误 // eBefExeError, //上一次执行失败 // eCreateConError, //新建连接错误 eConnRedisError, //连接Redis失败 }; /* * Redis抛出的异常 */ class RedisException : public std::exception { public : RedisException(string &dec):m_what(dec){} virtual ~RedisException() throw() {} virtual const char* what() const throw() { return m_what.c_str(); } private: string m_what; }; /* *单个连接,封装Redis操作 */ class CRedisConn #ifdef USE_MEMORY_POOL : public MemoryBase #endif { public: CRedisConn(); ~CRedisConn(); /* * 连接数据库 * return : 主机名或者ip 端口 * param : */ bool Connect(string &host, int port = 0); string Hget(const char* key,const char* hkey); int Hset(const char* key, const char* hkey, const char* value); int Hset(const char* key,const char* hkey,const char* hvalue, size_t hvaluelen); int Del(const char* key); int ExistsKey(const char* id); bool ExecuteCommandV(const char *format, va_list ap); bool ExecuteCommandArgv(int argc, const char **argv, const size_t *argvlen); bool ExecuteCommandInPipelineV(const char *format, va_list ap); bool GetReplyInPipeline(); public: bool Status() const; bool Error() const; bool Integer() const; bool Nil() const; bool String() const; bool Array() const; const char* GetStatus(const char* szNullValue=""); const char* GetError(const char* szNullValue=""); int64 GetInteger(int64 nNullValue=0); const char* GetString(const char* szNullValue=""); const redisReply* GetArray(); bool GetArryToList(vector<string>& valueList); bool GetArryToMap(map<string,string>& valueMap); public: /* * 设置和获取唯一标识 * return : * param : */ void SetKey(unsigned int key) { m_key = key; } unsigned int GetKey() { return m_key; } void Clear() { if(m_reply) { freeReplyObject(m_reply); m_reply = NULL; } } private: redisContext* m_connect; redisReply* m_reply; unsigned int m_key; int m_pending_reply_count; }; /* * 数据库连接池单例类 * 管理数据库连接 * */ class CRedisConnPool #ifdef USE_MEMORY_POOL : public MemoryBase #endif { public: static CRedisConnPool* GetInstance() { if(NULL == m_instance) { m_instance = NEW CRedisConnPool(); } return m_instance; } void DestroyInstance() { GUARD(CSimLock, obj, &m_idleMutex); map<unsigned int, CRedisConn *>::iterator it = m_usedConn.begin(); for(; it!=m_usedConn.end(); ++it) { delete it->second; it->second = NULL; } m_usedConn.clear(); list<CRedisConn *>::iterator itList = m_idleConn.begin(); for(; itList!=m_idleConn.end(); ++itList) { delete (*itList); (*itList) = NULL; } m_idleConn.clear(); obj.UnLock(); if(m_instance) { delete m_instance; } m_instance = NULL; } /* *初始化连接池 *return :初始化是否成功 *param :host主机 pwd密码 port端口 size连接池初始大小 rate连接池大小增量 */ int Init(string &host, string &pwd, int port, short int size, short int rate); /* * 获取一个连接 * return : * param : */ CRedisConn *GetConnection(); /* * 释放一个连接 * return : * param : */ void ReleaseConn(unsigned int onlyID); private: CRedisConnPool(); ~CRedisConnPool(); /* * 增加一定数目的连接 * return :E_SQLResult * param : */ int AddConnecton(short int count); /* * 得到一个key值 * return : * param ; */ unsigned int GetKey() { GUARD(CSimLock, obj, &m_keyMutex); if(m_key >= 1000000000) { m_key = 1; } unsigned int res = m_key++; return res; } private: static CRedisConnPool * m_instance; short int m_poolSize; //连接的个数 short int m_rate; //连接增量,用于连接池为空时,一次性增加的连接个数 string m_host; //连接主机 string m_pwd; //密码 int m_port; //端口 map<unsigned int, CRedisConn *> m_usedConn; //使用的连接 // CSimLock m_usedMutex; //使用中的连接锁 list<CRedisConn *> m_idleConn; //空闲连接 CSimLock m_idleMutex; //空闲的连接锁 unsigned int m_key; //唯一id值 CSimLock m_keyMutex; //空闲的连接锁 }; } #endif /* REDIS_REDISCONNPOOL_H_ */
/* * Action.h * * Created on: May 18, 2014 * Author: florent */ #ifndef ACTION_H_ #define ACTION_H_ #include "Client.h" namespace Donnees { enum TypeAction { DEPLACEMENT, DEPOT }; class Action { private: TypeAction t; Client* start; Client* end; Commande* comm; public: Action(Client* s, Client* e); Action(Client* cli, Commande* co); TypeAction getType(); Client* getStart(); Client* getEnd(); Commande* getCommande(); virtual ~Action(); bool operator==(Action & a); }; } #endif /* ACTION_H_ */
#include<float.h> #include<math.h> #include<stdbool.h> #include<stddef.h> #include<stdint.h> #include<stdio.h> #include<string.h> #include<ap_int.h> #include<hls_stream.h> #ifndef BURST_WIDTH #define BURST_WIDTH 64 #endif//BURST_WIDTH #ifdef UNROLL_FACTOR #if UNROLL_FACTOR != 4 #error UNROLL_FACTOR != 4 #endif//UNROLL_FACTOR != 4 #endif//UNROLL_FACTOR #ifdef TILE_SIZE_DIM_0 #if TILE_SIZE_DIM_0 != 32 #error TILE_SIZE_DIM_0 != 32 #endif//TILE_SIZE_DIM_0 != 32 #endif//TILE_SIZE_DIM_0 #ifdef BURST_WIDTH #if BURST_WIDTH != 64 #error BURST_WIDTH != 64 #endif//BURST_WIDTH != 64 #endif//BURST_WIDTH template<typename T> struct Data { T data; bool ctrl; }; template<typename To, typename From> inline To Reinterpret(const From& val) { return reinterpret_cast<const To&>(val); } template<typename T> inline bool ReadData(T* data, hls::stream<Data<T>>* from) { #pragma HLS inline const Data<T>& tmp = from->read(); *data = tmp.data; return tmp.ctrl; } template<typename T> inline void WriteData(hls::stream<Data<T>>* to, const T& data, bool ctrl) { #pragma HLS inline Data<T> tmp; tmp.data = data; tmp.ctrl = ctrl; to->write(tmp); } void BurstRead(hls::stream<Data<ap_uint<BURST_WIDTH>>>* to, ap_uint<BURST_WIDTH>* from, uint64_t data_num) { load_epoch: for (uint64_t epoch = 0; epoch < data_num;) { #pragma HLS pipeline II=1 const uint64_t next_epoch = epoch + 1; WriteData(to, from[epoch], next_epoch < data_num); epoch = next_epoch; } } void BurstWrite(ap_uint<BURST_WIDTH>* to, hls::stream<Data<ap_uint<BURST_WIDTH>>>* from, uint64_t data_num) { store_epoch: for (uint64_t epoch = 0; epoch < data_num; ++epoch) { #pragma HLS pipeline II=1 ap_uint<BURST_WIDTH> buf; ReadData(&buf, from); to[epoch] = buf; } } void Module0Func( /*output*/ hls::stream<Data<uint16_t>>* fifo_st_0, /*output*/ hls::stream<Data<uint16_t>>* fifo_st_1, /*output*/ hls::stream<Data<uint16_t>>* fifo_st_2, /*output*/ hls::stream<Data<uint16_t>>* fifo_st_3, /* input*/ hls::stream<Data<ap_uint<64>>>* dram_input_bank_1_fifo) { #pragma HLS data_pack variable = fifo_st_0 #pragma HLS data_pack variable = fifo_st_1 #pragma HLS data_pack variable = fifo_st_2 #pragma HLS data_pack variable = fifo_st_3 #pragma HLS data_pack variable = dram_input_bank_1_fifo module_0_epoch: for (bool enable = true; enable;) { #pragma HLS pipeline II=1 if (!dram_input_bank_1_fifo->empty()) { ap_uint<64> dram_input_bank_1_buf; const bool dram_input_bank_1_buf_enable = ReadData(&dram_input_bank_1_buf, dram_input_bank_1_fifo); const bool enabled = dram_input_bank_1_buf_enable; enable = enabled; WriteData(fifo_st_0, Reinterpret<uint16_t>(static_cast<ap_uint<16>>(dram_input_bank_1_buf(63, 48))), enabled); WriteData(fifo_st_1, Reinterpret<uint16_t>(static_cast<ap_uint<16>>(dram_input_bank_1_buf(47, 32))), enabled); WriteData(fifo_st_2, Reinterpret<uint16_t>(static_cast<ap_uint<16>>(dram_input_bank_1_buf(31, 16))), enabled); WriteData(fifo_st_3, Reinterpret<uint16_t>(static_cast<ap_uint<16>>(dram_input_bank_1_buf(15, 0))), enabled); } // if not empty } // for module_0_epoch } // Module0Func void Module1Func( /*output*/ hls::stream<Data<uint16_t>>* fifo_st_0, /* input*/ hls::stream<Data<uint16_t>>* fifo_ld_0) { #pragma HLS data_pack variable = fifo_st_0 #pragma HLS data_pack variable = fifo_ld_0 module_1_epoch: for (bool enable = true; enable;) { #pragma HLS pipeline II=1 if (!fifo_ld_0->empty()) { uint16_t fifo_ref_0; const bool fifo_ref_0_enable = ReadData(&fifo_ref_0, fifo_ld_0); const bool enabled = fifo_ref_0_enable; enable = enabled; WriteData(fifo_st_0, uint16_t(fifo_ref_0), enabled); } // if not empty } // for module_1_epoch } // Module1Func void Module2Func( /*output*/ hls::stream<Data<uint16_t>>* fifo_st_0, /* input*/ hls::stream<Data<uint16_t>>* fifo_ld_0) { #pragma HLS data_pack variable = fifo_st_0 #pragma HLS data_pack variable = fifo_ld_0 module_2_epoch: for (bool enable = true; enable;) { #pragma HLS pipeline II=1 if (!fifo_ld_0->empty()) { uint16_t fifo_ref_0; const bool fifo_ref_0_enable = ReadData(&fifo_ref_0, fifo_ld_0); const bool enabled = fifo_ref_0_enable; enable = enabled; WriteData(fifo_st_0, uint16_t((fifo_ref_0 + 1)), enabled); } // if not empty } // for module_2_epoch } // Module2Func void Module3Func( /*output*/ hls::stream<Data<ap_uint<64>>>* dram_pointwise_bank_1_fifo, /* input*/ hls::stream<Data<uint16_t>>* fifo_ld_0, /* input*/ hls::stream<Data<uint16_t>>* fifo_ld_1, /* input*/ hls::stream<Data<uint16_t>>* fifo_ld_2, /* input*/ hls::stream<Data<uint16_t>>* fifo_ld_3) { #pragma HLS data_pack variable = dram_pointwise_bank_1_fifo #pragma HLS data_pack variable = fifo_ld_0 #pragma HLS data_pack variable = fifo_ld_1 #pragma HLS data_pack variable = fifo_ld_2 #pragma HLS data_pack variable = fifo_ld_3 module_3_epoch: for (bool enable = true; enable;) { #pragma HLS pipeline II=1 if (!fifo_ld_0->empty() && !fifo_ld_1->empty() && !fifo_ld_2->empty() && !fifo_ld_3->empty()) { uint16_t fifo_ref_0; uint16_t fifo_ref_1; uint16_t fifo_ref_2; uint16_t fifo_ref_3; ap_uint<64> dram_pointwise_bank_1_buf; const bool fifo_ref_0_enable = ReadData(&fifo_ref_0, fifo_ld_0); const bool fifo_ref_1_enable = ReadData(&fifo_ref_1, fifo_ld_1); const bool fifo_ref_2_enable = ReadData(&fifo_ref_2, fifo_ld_2); const bool fifo_ref_3_enable = ReadData(&fifo_ref_3, fifo_ld_3); const bool enabled = fifo_ref_0_enable && fifo_ref_1_enable && fifo_ref_2_enable && fifo_ref_3_enable; enable = enabled; dram_pointwise_bank_1_buf(63, 48) = Reinterpret<ap_uint<16>>(fifo_ref_0); dram_pointwise_bank_1_buf(47, 32) = Reinterpret<ap_uint<16>>(fifo_ref_1); dram_pointwise_bank_1_buf(31, 16) = Reinterpret<ap_uint<16>>(fifo_ref_2); dram_pointwise_bank_1_buf(15, 0) = Reinterpret<ap_uint<16>>(fifo_ref_3); WriteData(dram_pointwise_bank_1_fifo, dram_pointwise_bank_1_buf, enabled); } // if not empty } // for module_3_epoch } // Module3Func extern "C" { void pointwise_kernel( ap_uint<64>* bank_1_pointwise, ap_uint<64>* bank_1_input, uint64_t coalesced_data_num) { #pragma HLS interface m_axi port=bank_1_pointwise offset=slave depth=65536 bundle=pointwise_bank_1 #pragma HLS interface m_axi port=bank_1_input offset=slave depth=65536 bundle=input_bank_1 #pragma HLS interface s_axilite port=bank_1_pointwise bundle=control #pragma HLS interface s_axilite port=bank_1_input bundle=control #pragma HLS interface s_axilite port=coalesced_data_num bundle=control #pragma HLS interface s_axilite port=return bundle=control hls::stream<Data<ap_uint<64>>> bank_1_input_buf("bank_1_input_buf"); #pragma HLS stream variable=bank_1_input_buf depth=32 #pragma HLS data_pack variable=bank_1_input_buf hls::stream<Data<ap_uint<64>>> bank_1_pointwise_buf("bank_1_pointwise_buf"); #pragma HLS stream variable=bank_1_pointwise_buf depth=32 #pragma HLS data_pack variable=bank_1_pointwise_buf hls::stream<Data<uint16_t>> from_super_source_to_input_offset_0("from_super_source_to_input_offset_0"); #pragma HLS stream variable=from_super_source_to_input_offset_0 depth=32 #pragma HLS data_pack variable=from_super_source_to_input_offset_0 hls::stream<Data<uint16_t>> from_super_source_to_input_offset_1("from_super_source_to_input_offset_1"); #pragma HLS stream variable=from_super_source_to_input_offset_1 depth=32 #pragma HLS data_pack variable=from_super_source_to_input_offset_1 hls::stream<Data<uint16_t>> from_super_source_to_input_offset_2("from_super_source_to_input_offset_2"); #pragma HLS stream variable=from_super_source_to_input_offset_2 depth=32 #pragma HLS data_pack variable=from_super_source_to_input_offset_2 hls::stream<Data<uint16_t>> from_super_source_to_input_offset_3("from_super_source_to_input_offset_3"); #pragma HLS stream variable=from_super_source_to_input_offset_3 depth=32 #pragma HLS data_pack variable=from_super_source_to_input_offset_3 hls::stream<Data<uint16_t>> from_input_offset_0_to_pointwise_pe_3("from_input_offset_0_to_pointwise_pe_3"); #pragma HLS stream variable=from_input_offset_0_to_pointwise_pe_3 depth=32 #pragma HLS data_pack variable=from_input_offset_0_to_pointwise_pe_3 hls::stream<Data<uint16_t>> from_input_offset_1_to_pointwise_pe_2("from_input_offset_1_to_pointwise_pe_2"); #pragma HLS stream variable=from_input_offset_1_to_pointwise_pe_2 depth=32 #pragma HLS data_pack variable=from_input_offset_1_to_pointwise_pe_2 hls::stream<Data<uint16_t>> from_input_offset_2_to_pointwise_pe_1("from_input_offset_2_to_pointwise_pe_1"); #pragma HLS stream variable=from_input_offset_2_to_pointwise_pe_1 depth=32 #pragma HLS data_pack variable=from_input_offset_2_to_pointwise_pe_1 hls::stream<Data<uint16_t>> from_input_offset_3_to_pointwise_pe_0("from_input_offset_3_to_pointwise_pe_0"); #pragma HLS stream variable=from_input_offset_3_to_pointwise_pe_0 depth=32 #pragma HLS data_pack variable=from_input_offset_3_to_pointwise_pe_0 hls::stream<Data<uint16_t>> from_pointwise_pe_3_to_super_sink("from_pointwise_pe_3_to_super_sink"); #pragma HLS stream variable=from_pointwise_pe_3_to_super_sink depth=32 #pragma HLS data_pack variable=from_pointwise_pe_3_to_super_sink hls::stream<Data<uint16_t>> from_pointwise_pe_2_to_super_sink("from_pointwise_pe_2_to_super_sink"); #pragma HLS stream variable=from_pointwise_pe_2_to_super_sink depth=32 #pragma HLS data_pack variable=from_pointwise_pe_2_to_super_sink hls::stream<Data<uint16_t>> from_pointwise_pe_1_to_super_sink("from_pointwise_pe_1_to_super_sink"); #pragma HLS stream variable=from_pointwise_pe_1_to_super_sink depth=32 #pragma HLS data_pack variable=from_pointwise_pe_1_to_super_sink hls::stream<Data<uint16_t>> from_pointwise_pe_0_to_super_sink("from_pointwise_pe_0_to_super_sink"); #pragma HLS stream variable=from_pointwise_pe_0_to_super_sink depth=32 #pragma HLS data_pack variable=from_pointwise_pe_0_to_super_sink #pragma HLS dataflow BurstRead(&bank_1_input_buf, bank_1_input, coalesced_data_num); Module0Func( /*output*/ &from_super_source_to_input_offset_0, /*output*/ &from_super_source_to_input_offset_1, /*output*/ &from_super_source_to_input_offset_2, /*output*/ &from_super_source_to_input_offset_3, /* input*/ &bank_1_input_buf); Module1Func( /*output*/ &from_input_offset_0_to_pointwise_pe_3, /* input*/ &from_super_source_to_input_offset_0); Module1Func( /*output*/ &from_input_offset_1_to_pointwise_pe_2, /* input*/ &from_super_source_to_input_offset_1); Module1Func( /*output*/ &from_input_offset_2_to_pointwise_pe_1, /* input*/ &from_super_source_to_input_offset_2); Module1Func( /*output*/ &from_input_offset_3_to_pointwise_pe_0, /* input*/ &from_super_source_to_input_offset_3); Module2Func( /*output*/ &from_pointwise_pe_3_to_super_sink, /* input*/ &from_input_offset_0_to_pointwise_pe_3); Module2Func( /*output*/ &from_pointwise_pe_2_to_super_sink, /* input*/ &from_input_offset_1_to_pointwise_pe_2); Module2Func( /*output*/ &from_pointwise_pe_1_to_super_sink, /* input*/ &from_input_offset_2_to_pointwise_pe_1); Module2Func( /*output*/ &from_pointwise_pe_0_to_super_sink, /* input*/ &from_input_offset_3_to_pointwise_pe_0); Module3Func( /*output*/ &bank_1_pointwise_buf, /* input*/ &from_pointwise_pe_3_to_super_sink, /* input*/ &from_pointwise_pe_2_to_super_sink, /* input*/ &from_pointwise_pe_1_to_super_sink, /* input*/ &from_pointwise_pe_0_to_super_sink); BurstWrite(bank_1_pointwise, &bank_1_pointwise_buf, coalesced_data_num); } }//extern "C"
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "GameFramework/ProjectileMovementComponent.h" #include "SMITElabs/Public/SLGod.h" #include "SMITElabs/Public/SLAgni.h" #include "SLAgniFlameWave.generated.h" class ASLGod; class ASLAgni; class UProjectileMovementComponent; UCLASS() class SMITELABS_API ASLAgniFlameWave : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ASLAgniFlameWave(); void SetOrigin(ASLGod* Val); void SetDamage(float Val); void SetScaling(float Val); void SetBHasCombustion(bool Val); protected: // Called when the game starts or when spawned UFUNCTION() void DestroyWave(); virtual void BeginPlay() override; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Scene") USceneComponent* SceneComponent; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Mesh") UStaticMeshComponent* StaticMeshComponent; FTimerHandle DestroyWaveTimerHandle; FTimerDelegate DestroyWaveTimerDelegate; ASLGod* Origin; TArray<ASLGod*> HitGods; FVector StartingLocation; bool bHasCombustion; float Damage; float Scaling; float ProjectileSpeed{ 150 }; float ProjectileRange{ 50 }; UFUNCTION() void OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& Hit); public: // Called every frame virtual void Tick(float DeltaTime) override; };
#include<iostream> int fib( int num) { if( 1 >= num ) { return num; } else { return fib( num - 1 ) + fib( num - 2); } } int main() { int num = 0; std::cout << " Input the index of Fibonacci sequance : "; std::cin >> num; std::cout << "\n The Fibonacci number is : " << fib( num ) << std::endl; return 0; }
// Created on: 1995-03-16 // Created by: Christian CAILLET // 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 _XSControl_FuncShape_HeaderFile #define _XSControl_FuncShape_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> #include <TopTools_HSequenceOfShape.hxx> #include <Standard_CString.hxx> class XSControl_WorkSession; class TCollection_AsciiString; //! Defines additional commands for XSControl to : //! - control of initialisation (xinit, xnorm, newmodel) //! - analyse of the result of a transfer (recorded in a //! TransientProcess for Read, FinderProcess for Write) : //! statistics, various lists (roots,complete,abnormal), what //! about one specific entity, producing a model with the //! abnormal result //! //! This appendix of XSControl is compiled separately to distinguish //! basic features from user callable forms class XSControl_FuncShape { public: DEFINE_STANDARD_ALLOC //! Defines and loads all functions which work on shapes for XSControl (as ActFunc) Standard_EXPORT static void Init(); //! Analyses a name as designating Shapes from a Vars or from //! XSTEP transfer (last Transfer on Reading). <name> can be : //! "*" : all the root shapes produced by last Transfer (Read) //! i.e. considers roots of the TransientProcess //! a name : a name of a variable DRAW //! //! Returns the count of designated Shapes. Their list is put in //! <list>. If <list> is null, it is firstly created. Then it is //! completed (Append without Clear) by the Shapes found //! Returns 0 if no Shape could be found Standard_EXPORT static Standard_Integer MoreShapes (const Handle(XSControl_WorkSession)& session, Handle(TopTools_HSequenceOfShape)& list, const Standard_CString name); //! Analyses given file name and variable name, with a default //! name for variables. Returns resulting file name and variable //! name plus status "file to read"(True) or "already read"(False) //! In the latter case, empty resfile means no file available //! //! If <file> is null or empty or equates ".", considers Session //! and returned status is False //! Else, returns resfile = file and status is True //! If <var> is neither null nor empty, resvar = var //! Else, the root part of <resfile> is considered, if defined //! Else, <def> is taken Standard_EXPORT static Standard_Boolean FileAndVar (const Handle(XSControl_WorkSession)& session, const Standard_CString file, const Standard_CString var, const Standard_CString def, TCollection_AsciiString& resfile, TCollection_AsciiString& resvar); protected: private: }; #endif // _XSControl_FuncShape_HeaderFile
#pragma once #include <core/Parse.h> #include <core/Result.h> #include <core/Union.h> #include <core/cli/Arguments.h> #include <launcher/cli/Options.h> #include <launcher/cli/error/BadOption.h> #include <launcher/cli/error/NotEnoughArguments.h> namespace core { template<> struct Parse<launcher::cli::Options, For<cli::Arguments>> { Result< launcher::cli::Options, Union< launcher::cli::error::BatOption, launcher::cli::error::NotEnoughArguments > > operator()(cli::Arguments a) const noexcept; }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "modules/layout/content/multicol.h" #include "modules/layout/box/blockbox.h" #include "modules/layout/box/flexitem.h" #include "modules/layout/box/tables.h" #include "modules/layout/content/content.h" #include "modules/layout/traverse/traverse.h" /** Set to be vertical layout. */ void ColumnBoundaryElement::Set(VerticalLayout* vertical_layout, Container* c) { OP_ASSERT(c); type = VERTICAL_LAYOUT; this->vertical_layout = vertical_layout; container = c; } /** Set to be vertical layout. */ void ColumnBoundaryElement::Set(BlockBox* block_box) { type = VERTICAL_LAYOUT; vertical_layout = block_box; container = NULL; } /** Set to be table list element. */ void ColumnBoundaryElement::Set(TableListElement* table_list_element) { type = TABLE_LIST_ELEMENT; this->table_list_element = table_list_element; container = NULL; } /** Set to be table row. */ void ColumnBoundaryElement::Set(TableRowBox* table_row_box) { type = TABLE_ROW_BOX; this->table_row_box = table_row_box; container = NULL; } /** Set to be column row. */ void ColumnBoundaryElement::Set(ColumnRow* column_row, MultiColumnContainer* mc) { type = COLUMN_ROW; this->column_row = column_row; container = mc; } /** Set to be flex item. */ void ColumnBoundaryElement::Set(FlexItemBox* flex_item_box) { type = FLEX_ITEM_BOX; this->flex_item_box = flex_item_box; container = NULL; } /** Return the HTML_Element associated with this start/end element, if there is one. */ HTML_Element* ColumnBoundaryElement::GetHtmlElement() const { switch (type) { case VERTICAL_LAYOUT: if (vertical_layout->IsBlock()) return ((BlockBox*) vertical_layout)->GetHtmlElement(); else if (vertical_layout->IsLayoutBreak()) return ((LayoutBreak*) vertical_layout)->GetHtmlElement(); else return container->GetHtmlElement(); case TABLE_LIST_ELEMENT: return table_list_element->GetHtmlElement(); case TABLE_ROW_BOX: return table_row_box->GetHtmlElement(); case COLUMN_ROW: return container->GetHtmlElement(); case FLEX_ITEM_BOX: return flex_item_box->GetHtmlElement(); default: OP_ASSERT(!"Unhandled type"); case NOT_SET: return NULL; } } /** Attach a float to this page or column. */ void Column::AddFloat(FloatedPaneBox* box) { PaneFloatEntry* first_bottom; for (first_bottom = floats.First(); first_bottom; first_bottom = first_bottom->Suc()) if (!first_bottom->GetBox()->IsTopFloat()) break; box->IntoPaneFloatList(floats, first_bottom); } /** Position top-aligned floats. */ void Column::PositionTopFloats() { LayoutCoord float_y = LayoutCoord(0); for (PaneFloatEntry* entry = floats.First(); entry; entry = entry->Suc()) { FloatedPaneBox* box = entry->GetBox(); if (!box->IsTopFloat()) break; float_y += box->GetMarginTop(); box->SetY(float_y); float_y += box->GetMarginBottom() + box->GetHeight(); } } /** Position bottom-aligned floats. */ void Column::PositionBottomFloats(LayoutCoord row_height) { LayoutCoord float_y = row_height; for (PaneFloatEntry* entry = floats.Last(); entry; entry = entry->Pred()) { FloatedPaneBox* box = entry->GetBox(); if (box->IsTopFloat()) break; float_y -= box->GetMarginBottom() + box->GetHeight(); box->SetY(float_y); float_y -= box->GetMarginTop(); } } /** Return TRUE if the specified float lives in this column. */ BOOL Column::HasFloat(FloatedPaneBox* box) { for (PaneFloatEntry* entry = floats.First(); entry; entry = entry->Suc()) if (entry->GetBox() == box) return TRUE; return FALSE; } /** Move the row down by the specified amount. */ void ColumnRow::MoveDown(LayoutCoord amount) { y += amount; } /** Get the height of this row. */ LayoutCoord ColumnRow::GetHeight() const { if (!columns.First()) return LayoutCoord(0); LayoutCoord row_height = LayoutCoord(0); for (Column* column = (Column*) columns.First(); column; column = column->Suc()) { LayoutCoord column_height = column->GetHeight() + column->GetTopFloatsHeight() + column->GetBottomFloatsHeight(); if (row_height < column_height) row_height = column_height; } return row_height; } /** Traverse the row. */ void ColumnRow::Traverse(MultiColumnContainer* multicol_container, TraversalObject* traversal_object, LayoutProperties* layout_props) { LayoutCoord old_pane_x_tr; LayoutCoord old_pane_y_tr; traversal_object->GetPaneTranslation(old_pane_x_tr, old_pane_y_tr); TargetTraverseState target_traversal; TraverseInfo traverse_info; BOOL target_done = FALSE; traversal_object->StoreTargetTraverseState(target_traversal); traversal_object->Translate(LayoutCoord(0), y); for (Column* column = GetFirstColumn(); column; column = column->Suc()) { traversal_object->SetPaneClipRect(OpRect(SHRT_MIN / 2, LayoutCoord(column->GetTopFloatsHeight()), SHRT_MAX, column->GetHeight())); // Set up the traversal object for column traversal. traversal_object->SetCurrentPane(column); traversal_object->SetPaneDone(FALSE); traversal_object->SetPaneStartOffset(column->GetStartOffset()); traversal_object->SetPaneStarted(FALSE); /* Restore target traversal state before traversing this column. The target element may live in multiple columns. */ traversal_object->RestoreTargetTraverseState(target_traversal); traversal_object->Translate(column->GetX(), column->GetY()); traversal_object->SetPaneTranslation(traversal_object->GetTranslationX(), traversal_object->GetTranslationY()); traversal_object->Translate(LayoutCoord(0), column->GetTranslationY()); if (traversal_object->EnterPane(layout_props, column, TRUE, traverse_info)) { multicol_container->Container::Traverse(traversal_object, layout_props); traversal_object->LeavePane(traverse_info); } traversal_object->Translate(-column->GetX(), -column->GetY() - column->GetTranslationY()); if (!target_done) target_done = traversal_object->IsTargetDone(); } traversal_object->Translate(LayoutCoord(0), -y); if (target_done) // We found the target while traversing one or more of these columns traversal_object->SwitchTarget(layout_props->html_element); traversal_object->SetPaneTranslation(old_pane_x_tr, old_pane_y_tr); } Columnizer::Columnizer(Columnizer* ancestor, BOOL ancestor_columnizer_in_same_element, const LayoutInfo& layout_info, ColumnRowStack& rows, MultiColBreakpoint* first_break, SpannedElm* first_spanned_elm, LayoutCoord max_height, int column_count, LayoutCoord column_width, LayoutCoord content_width, LayoutCoord column_gap, LayoutCoord column_y_stride, LayoutCoord top_offset, LayoutCoord virtual_height, LayoutCoord floats_virtual_height, BOOL height_restricted, #ifdef SUPPORT_TEXT_DIRECTION BOOL is_rtl, #endif // SUPPORT_TEXT_DIRECTION BOOL balance) : layout_info(layout_info), column_count(column_count), column_width(column_width), content_width(content_width), column_gap(column_gap), column_y_stride(column_y_stride), virtual_height(virtual_height), remaining_floats_virtual_height(floats_virtual_height), max_height(max_height), always_balance(balance), ancestor_columnizer(ancestor), ancestor_columnizer_in_same_element(ancestor_columnizer_in_same_element), descendant_multicol(NULL), rows(rows), next_break(first_break), next_spanned_elm(first_spanned_elm), pending_start_offset(0), virtual_y(0), committed_virtual_y(0), pending_virtual_y_start(0), col_virtual_y_start(0), earliest_break_virtual_y(0), stack_offset(-top_offset), initial_row_height(0), current_row_height(0), max_row_height(0), top_floats_height(0), bottom_floats_height(0), pending_margin(0), current_column_num(0), column_y(0), y_translation(-top_offset), span_all(FALSE), #ifdef SUPPORT_TEXT_DIRECTION is_rtl(is_rtl), #endif // SUPPORT_TEXT_DIRECTION balance_current_row(balance), allow_column_stretch(FALSE), column_open(FALSE), row_open(FALSE), height_restricted(height_restricted), reached_max_height(FALSE), row_has_spanned_floats(FALSE), trial(FALSE) #ifdef PAGED_MEDIA_SUPPORT , last_allowed_page_break_after(NULL), page_break_policy_after_previous(BREAK_AVOID), page_break_policy_before_current(BREAK_AVOID), page_open(TRUE) #endif // PAGED_MEDIA_SUPPORT { OP_ASSERT(ancestor || !ancestor_columnizer_in_same_element); } /** Cancel the break caused by this spanned element. */ void SpannedElm::CancelBreak() { if (breakpoint) { breakpoint->Out(); OP_DELETE(breakpoint); breakpoint = NULL; } } /** Get the block box established by the spanned element. */ BlockBox* SpannedElm::GetSpannedBox() const { if (Box* box = html_element->GetLayoutBox()) if (box->IsBlockBox()) return (BlockBox*) box; return NULL; } /** Update row and/or container height. */ /* virtual */ void Columnizer::UpdateHeight(LayoutCoord height) { if (balance_current_row && current_row_height < height) { current_row_height = height; if (current_row_height > max_row_height) { current_row_height = max_row_height; reached_max_height = TRUE; } } } /** Return the position of the current row, if any. */ LayoutCoord Columnizer::GetRowPosition() const { LayoutCoord cur_row_y; if (ColumnRow* last_row = rows.Last()) { cur_row_y = last_row->GetPosition(); if (!row_open) cur_row_y += last_row->GetHeight() + pending_margin; } else cur_row_y = LayoutCoord(0); return cur_row_y; } /** Get the current (non-virtual) bottom, relative to the first row. */ LayoutCoord Columnizer::GetBottom(LayoutCoord some_virtual_y) const { LayoutCoord row_pos(0); if (ColumnRow* row = GetCurrentRow()) row_pos = row->GetPosition(); return row_pos + some_virtual_y - col_virtual_y_start + top_floats_height + bottom_floats_height; } /** Set virtual position of the earliest break, if later than already set. */ void Columnizer::SetEarliestBreakPosition(LayoutCoord local_virtual_y) { LayoutCoord new_virtual_y = local_virtual_y + stack_offset; if (earliest_break_virtual_y < new_virtual_y) earliest_break_virtual_y = new_virtual_y; } /** Get accumulated height occupied by floats in the current column. */ LayoutCoord Columnizer::GetFloatsHeight() { LayoutCoord top_height = LAYOUT_COORD_MIN; LayoutCoord bottom_height = LAYOUT_COORD_MIN; int min_span = 1; for (Column* column = GetCurrentColumn(); column; column = column->Pred(), min_span++) for (PaneFloatEntry* entry = column->GetFirstFloatEntry(); entry; entry = entry->Suc()) { FloatedPaneBox* box = entry->GetBox(); if (box->GetColumnSpan() >= min_span) if (box->IsTopFloat()) { LayoutCoord bottom = box->GetHeight() + box->GetMarginTop() + box->GetMarginBottom(); if (top_height < bottom) top_height = bottom; } else { /* Bottom floats have not yet got their final position; they are currently positioned as if row height were 0. */ // FIXME: this is wrong, but will work fine as long as there's only one bottom float. LayoutCoord height = box->GetHeight() + box->GetMarginTop() + box->GetMarginBottom(); if (bottom_height < height) bottom_height = height; } } // No top/bottom floats means 0 height. if (top_height == LAYOUT_COORD_MIN) top_height = LayoutCoord(0); if (bottom_height == LAYOUT_COORD_MIN) bottom_height = LayoutCoord(0); return top_height + bottom_height; } /** Prepare content for addition. */ void Columnizer::AllocateContent(LayoutCoord local_virtual_y, const ColumnBoundaryElement& elm, LayoutCoord start_offset) { LayoutCoord new_virtual_y = local_virtual_y + stack_offset; if (!first_uncommitted_element.IsSet()) { if (allow_column_stretch && GetCurrentColumn()) { LayoutCoord bottom = col_virtual_y_start + current_row_height; if (pending_virtual_y_start < bottom && new_virtual_y >= bottom) /* Walked past the assumed bottom of the column, thanks to a margin. We can ignore margins that cross column boundaries, so don't let it stretch the current column. */ allow_column_stretch = FALSE; } first_uncommitted_element = elm; pending_start_offset = start_offset; if (GetCurrentColumn()) pending_virtual_y_start = new_virtual_y; } last_allocated_element = elm; if (ancestor_columnizer) ancestor_columnizer->AllocateContent(GetBottom(new_virtual_y), elm, start_offset); } /** Return TRUE if we can create taller columns by advancing to a next row or a next page. */ BOOL Columnizer::MoreSpaceAhead() const { if (column_open && GetSpaceUsed() > 0) return TRUE; if (ancestor_columnizer) return ancestor_columnizer->MoreSpaceAhead(); #ifdef PAGED_MEDIA_SUPPORT else if (!trial && layout_info.paged_media != PAGEBREAK_OFF) /* If the current row doesn't start at the top of the page, we can get taller columns by advancing to the next page. Note that this doesn't accurately answer the question we meant to ask. If height or max-height properties have constrained max_row_height, we should really return FALSE here (then there isn't really any more "space ahead"). But moving to the next page instead of continuing to the left or right of the page's boundaries is probably better anyway. */ return max_row_height < LayoutCoord(layout_info.doc->GetRelativePageBottom() - layout_info.doc->GetRelativePageTop()); #endif // PAGED_MEDIA_SUPPORT return FALSE; } /** Calculate X position of new column to be added. */ LayoutCoord Columnizer::CalculateColumnX() const { LayoutCoord accumulated_gap; if (column_gap == 0 || column_count < 2) accumulated_gap = LayoutCoord(current_column_num) * column_gap; else { /* If column-gap is non-zero, we allow distribution of any column width rounding error there, so that the far column will be flush with the multicol container's content edge. */ LayoutCoord total_column_gap = column_gap * LayoutCoord(column_count - 1); LayoutCoord error = content_width - (column_width * LayoutCoord(column_count) + total_column_gap); total_column_gap += error; accumulated_gap = total_column_gap * LayoutCoord(current_column_num) / LayoutCoord(column_count - 1); } #ifdef SUPPORT_TEXT_DIRECTION if (is_rtl) return content_width - LayoutCoord(current_column_num + 1) * column_width - accumulated_gap; #endif // SUPPORT_TEXT_DIRECTION return LayoutCoord(current_column_num) * column_width + accumulated_gap; } #ifdef PAGED_MEDIA_SUPPORT /** Create a new page. */ BOOL Columnizer::GetNewPage(LayoutCoord& y_offset) { OP_ASSERT(!ancestor_columnizer); LayoutCoord y_pos(0); if (last_allowed_page_break_after) y_pos = last_allowed_page_break_after->GetPosition() + last_allowed_page_break_after->GetHeight(); y_offset = LayoutCoord(0); if (page_open) ClosePage(); BREAK_POLICY break_policy = CombineBreakPolicies(page_break_policy_after_previous, page_break_policy_before_current); do { PageDescription* page_description = layout_info.doc->AdvancePage(y_pos); if (!page_description) return FALSE; switch (break_policy) { case BREAK_LEFT: if (page_description->GetNumber() % 2 == 1) break_policy = BREAK_ALLOW; else break_policy = BREAK_ALWAYS; // need one blank page, so that the next page is a left-page. break; case BREAK_RIGHT: if (page_description->GetNumber() % 2 == 0) break_policy = BREAK_ALLOW; else break_policy = BREAK_ALWAYS; // need one blank page, so that the next page is a right-page. break; default: break_policy = BREAK_ALLOW; } } while (break_policy != BREAK_ALLOW); LayoutCoord this_page_top = LayoutCoord(layout_info.doc->GetRelativePageTop()); y_offset = this_page_top - y_pos; max_row_height = LayoutCoord(layout_info.doc->GetRelativePageBottom()) - this_page_top; page_open = TRUE; // Move all elements that follow the page break down to the new page. for (ColumnRow* row = last_allowed_page_break_after ? last_allowed_page_break_after->Suc() : rows.First(); row; row = row->Suc()) row->MoveDown(y_offset); return TRUE; } #endif // PAGED_MEDIA_SUPPORT /** Create a new column. */ BOOL Columnizer::GetNewColumn(const ColumnBoundaryElement& start_element, LayoutCoord minimum_height, BOOL add_queued_floats) { if (column_open) // Implicit column break. CloseColumn(); BOOL need_new_ancestor_column = FALSE; /* Should the potential new pane started on the ancestor columnizer begin with the first uncommitted element in the ancestor? This is the case when the ancestor starts its first pane, however not if the ancestor distributes the same content as this (e.g. paged overflow and multiple columns in the same element). In such case the first_uncommitted_element might not be yet set in the ancestor or using it as a start element could lead to skipping floats when rendering. */ BOOL use_ancestors_first_uncommitted_element = FALSE; if (ancestor_columnizer && (!row_open || GetCurrentRow()->GetPosition() + current_row_height < max_height)) { /* Nested columnization, and there's still height availble in the inner multicol. Need to consult with the ancestor multicol. */ BOOL ancestor_has_no_column = !ancestor_columnizer->GetCurrentColumn(); need_new_ancestor_column = ancestor_has_no_column || GetColumnsLeft() == 0; use_ancestors_first_uncommitted_element = ancestor_has_no_column && !ancestor_columnizer_in_same_element; if (!need_new_ancestor_column && (!row_open || minimum_height > current_row_height)) { /* There is an open column in the ancestor, and we're not out of columns down here yet, either. However, the minimum height of this column is larger than the current row height, so we have to check if there is enough space for that. Does the ancestor column have enough space for us? And if we have created a row previously, does it have enough space as well? */ LayoutCoord space_used = ancestor_columnizer->stack_offset + GetRowPosition() - ancestor_columnizer->col_virtual_y_start; LayoutCoord available_space; if (ancestor_columnizer->balance_current_row) available_space = ancestor_columnizer->current_row_height - space_used; else available_space = ancestor_columnizer->max_row_height - space_used; if (row_open && available_space > max_row_height) available_space = max_row_height; if (available_space < minimum_height) /* No, either the ancestor doesn't have enough space for us, or the current row cannot be stretched to make the new content fit. Create a new column, but only if it is likely that doing so will mitigate the space shortage. */ need_new_ancestor_column = MoreSpaceAhead(); } if (need_new_ancestor_column) { /* The outer multicol container either still has no column, or its current column is full, or all columns in this inner multicol container have been filled, or the current row height of the inner multicol container is too short (and we can improve it). Advance to the next ancestor column, and start a new row down here. */ if (row_open) // Unleash the floats that were waiting for a new row. for (PaneFloatEntry* entry = float_queue.First(); entry; entry = entry->Suc()) entry->GetBox()->ResetIsForNextRow(); CloseRow(TRUE); if (ColumnRow* row = rows.Last()) { /* The next outer column's virtual Y start position will be just below the bottom of the current one's. During columnization virtual Y start candidates have been propagated to the ancestor columnizer, but they cannot really be trusted. */ ancestor_columnizer->pending_virtual_y_start = ancestor_columnizer->stack_offset + row->GetPosition() + row->GetHeight(); ancestor_columnizer->committed_virtual_y = ancestor_columnizer->pending_virtual_y_start; } } } #ifdef PAGED_MEDIA_SUPPORT else if (!trial && layout_info.paged_media != PAGEBREAK_OFF) { BOOL create_new_page = FALSE; if (GetColumnsLeft() == 0) { if (ColumnRow* current_row = rows.Last()) { int height = current_row->GetHeight(); if (height < current_row_height) height = current_row_height; create_new_page = current_row->GetPosition() + height < max_height; } if (create_new_page) last_allowed_page_break_after = rows.Last(); } if (!create_new_page) if (row_open) create_new_page = minimum_height > current_row_height && MoreSpaceAhead(); else if (ColumnRow* row = rows.Last()) { int start_position = row->GetPosition() + row->GetHeight() + pending_margin; if (start_position + minimum_height > (int) layout_info.doc->GetRelativePageBottom() && start_position > (int) layout_info.doc->GetRelativePageTop()) create_new_page = MoreSpaceAhead(); } if (create_new_page) /* All columns on the current page have been filled (and we have more vertical space available), or the row height is too short (and we can improve it). Advance to the next page (just close the current page for now; actual page creation takes place further down). */ ClosePage(); } #endif // PAGED_MEDIA_SUPPORT if (!row_open) { // No open row. Prepare a new one. ColumnRow* last_row = rows.Last(); LayoutCoord new_row_y; if (last_row) new_row_y = last_row->GetPosition() + last_row->GetHeight(); else new_row_y = LayoutCoord(0); new_row_y += pending_margin; y_translation -= pending_margin; pending_margin = LayoutCoord(0); #ifdef PAGED_MEDIA_SUPPORT if (!page_open) { // No open page. Prepare for a new one. LayoutCoord offset; OP_ASSERT(layout_info.paged_media != PAGEBREAK_OFF); if (!GetNewPage(offset)) return FALSE; new_row_y += offset; last_allowed_page_break_after = last_row; } else #endif // PAGED_MEDIA_SUPPORT max_row_height = max_height - (MAX(new_row_y, LayoutCoord(0))); ColumnRow* new_row = OP_NEW(ColumnRow, (new_row_y)); if (!new_row) return FALSE; new_row->Into(&rows); if (need_new_ancestor_column) { if (ColumnRow* prev_row = new_row->Pred()) if (ColumnRow* outer_row = ancestor_columnizer->GetCurrentRow()) if (Column* outer_column = outer_row->GetLastColumn()) outer_column->SetStopAfterElement(ColumnBoundaryElement(prev_row, ancestor_columnizer->descendant_multicol)); /* If we are about to make the new column begin with ancestor_columnizer->first_uncommitted_element, we must assert it is set. And we can do that, because at least the element that this Columnizer distributes content of should have been allocated already (providing that the ancestor columnizer distributes the content of some ancestor element). */ OP_ASSERT(!use_ancestors_first_uncommitted_element || ancestor_columnizer->first_uncommitted_element.IsSet()); ColumnBoundaryElement start_element = use_ancestors_first_uncommitted_element ? ancestor_columnizer->first_uncommitted_element : ColumnBoundaryElement(new_row, ancestor_columnizer->descendant_multicol); if (!ancestor_columnizer->GetNewColumn(start_element, minimum_height)) return FALSE; } #ifdef PAGED_MEDIA_SUPPORT if (!trial && !ancestor_columnizer && layout_info.paged_media != PAGEBREAK_OFF) { LayoutCoord remaining_page_height = LayoutCoord(layout_info.doc->GetRelativePageBottom()) - new_row_y; if (max_row_height > remaining_page_height) max_row_height = remaining_page_height; if (BreakAllowedBetween(page_break_policy_after_previous, page_break_policy_before_current)) last_allowed_page_break_after = last_row; } #endif // PAGED_MEDIA_SUPPORT balance_current_row = always_balance; MultiColBreakpoint* bp; LayoutCoord row_virtual_y_stop = virtual_height; int relevant_explicit_breaks = 0; for (bp = next_break; bp; bp = bp->Suc()) { // Reset any previous balancing calculation attempts. bp->ResetAssumedImplicitBreaks(); if (pending_virtual_y_start > next_break->GetVirtualY()) { /* Discrepancy between explicit break list and columnizer break handling. We have missed a break. */ OP_ASSERT(!"We're already past this break."); remaining_floats_virtual_height += next_break->GetPaneFloatsVirtualHeight(); next_break = bp->Suc(); continue; } if (bp->IsRowBreak()) { // The row stops here (because a spanned box or a page break). row_virtual_y_stop = bp->GetVirtualY(); if (bp->IsSpannedElement()) // A spanned element requires us to balance earlier content. balance_current_row = TRUE; break; } else relevant_explicit_breaks++; } /* To get column balancing right, add the total virtual height that would have been occupied by the remaining floats (the pane-attached floats that still haven't been added to any column) if they were regular content. */ row_virtual_y_stop += remaining_floats_virtual_height; MultiColBreakpoint* new_next_break = bp ? bp->Suc() : NULL; // First break in next row int free_breaks = 0; if (balance_current_row) { /* We may want to balance the columns - either because the CSS properties say so, or because there's a spanned box ahead. Find the number of available implicit breaks for this row. If there are still too many explicit breaks ahead, there will be no implicit breaks available (and there's going to need another row after this one), in which case column balancing will be futile. */ if (!span_all) free_breaks = (column_count - 1) - relevant_explicit_breaks; if (free_breaks <= 0) balance_current_row = FALSE; } if (free_breaks > 0) { /* We have at least one free column break to use for implicit column breaking, and we're supposed to balance the columns as best we can. Calculate a suitable row height. May be increased later if necessary and allowed. */ OP_ASSERT(balance_current_row); if (relevant_explicit_breaks > 0) { /* There are explicit column breaks to consider. Figure out where it's best to put the implicit breaks (as many as specified by free_breaks), to calculate an initial row height. */ int trailing_implicit_breaks = 0; // implicit breaks after the last explicit break int implicit_breaks; for (implicit_breaks = 0; implicit_breaks < free_breaks; implicit_breaks ++) { MultiColBreakpoint* break_following_tallest_col = NULL; LayoutCoord prev_break_virtual_y = pending_virtual_y_start; LayoutCoord max_column_height = LAYOUT_COORD_MIN; MultiColBreakpoint* b; for (b = next_break; b != new_next_break; b = b->Suc()) { LayoutCoord next_break_virtual_y = b->GetVirtualY(); int implicit_breaks = b->GetAssumedImplicitBreaksBefore(); LayoutCoord column_height = (next_break_virtual_y - prev_break_virtual_y + LayoutCoord(implicit_breaks)) / LayoutCoord(implicit_breaks + 1); if (max_column_height < column_height) { max_column_height = column_height; break_following_tallest_col = b; } prev_break_virtual_y = next_break_virtual_y; } if (!b && max_column_height < (row_virtual_y_stop - prev_break_virtual_y) / (trailing_implicit_breaks + 1)) // The longest distance is after the last explicit break. trailing_implicit_breaks ++; else { OP_ASSERT(break_following_tallest_col); if (break_following_tallest_col) /* Assume an(other) implicit column break before this explicit break. */ break_following_tallest_col->AssumeImplicitBreakBefore(); } } /* All implicit column breaks have been distributed. Now find the tallest column. */ for (implicit_breaks = 0; implicit_breaks < free_breaks; implicit_breaks ++) { LayoutCoord prev_break_virtual_y = pending_virtual_y_start; LayoutCoord max_column_height = LAYOUT_COORD_MIN; MultiColBreakpoint* b; for (b = next_break; b != new_next_break; b = b->Suc()) { LayoutCoord next_break_virtual_y = b->GetVirtualY(); int implicit_breaks = b->GetAssumedImplicitBreaksBefore(); LayoutCoord column_height = (next_break_virtual_y - prev_break_virtual_y + LayoutCoord(implicit_breaks)) / LayoutCoord(implicit_breaks + 1); if (max_column_height < column_height) max_column_height = column_height; prev_break_virtual_y = next_break_virtual_y; } LayoutCoord trailing_height = (row_virtual_y_stop - prev_break_virtual_y) / LayoutCoord(trailing_implicit_breaks + 1); if (!b && max_column_height < trailing_height) // The longest distance is after the last explicit break. max_column_height = trailing_height; initial_row_height = max_column_height; } } else // No explicit column breaks. initial_row_height = (row_virtual_y_stop - pending_virtual_y_start + LayoutCoord(free_breaks)) / LayoutCoord(free_breaks + 1); } else /* We are either not supposed to balance the columns, or there are page breaks or just too many explicit column breaks ahead to do column balancing. Use as much space as possible and allowed. */ initial_row_height = row_virtual_y_stop - pending_virtual_y_start; if (ancestor_columnizer) { /* Clamp row height and max row height to what's available in the ancestor multicol. If balancing is disabled, stretch row height to what's available in the ancestor. */ LayoutCoord space_used = ancestor_columnizer->stack_offset + new_row_y - ancestor_columnizer->col_virtual_y_start + ancestor_columnizer->GetFloatsHeight(); LayoutCoord space = ancestor_columnizer->current_row_height - space_used; LayoutCoord max_space = ancestor_columnizer->max_row_height - space_used; if (balance_current_row) { if (initial_row_height > space) initial_row_height = space; } else if (initial_row_height < space) initial_row_height = space; if (max_row_height > max_space) max_row_height = max_space; } if (initial_row_height > max_row_height) initial_row_height = max_row_height; current_row_height = initial_row_height; row_open = TRUE; row_has_spanned_floats = FALSE; } // Cut margins crossing column boundaries. LayoutCoord margin_gap = pending_virtual_y_start - committed_virtual_y; if (margin_gap > 0) { if (balance_current_row && current_column_num < column_count) /* Reduce the row height. A part of some margin was skipped. This wasn't accounted for in the initial row height calculation, so reduce the height now. This means that the columns that we have already created probably are too tall already, but let's at least balance the content for the rest, instead of ending up with unused or mostly empty column at the end. */ IncreaseRowHeight(-(margin_gap / LayoutCoord(column_count - current_column_num))); /* Eat margins between last commit and the top of the column we're about to create. */ y_translation -= margin_gap; } LayoutCoord column_x = CalculateColumnX(); ColumnRow* current_row = GetCurrentRow(); Column* new_column = OP_NEW(Column, (start_element, pending_virtual_y_start, pending_start_offset, column_x, column_y, y_translation)); if (!new_column) return FALSE; current_row->AddColumn(new_column); col_virtual_y_start = pending_virtual_y_start; column_open = TRUE; top_floats_height = LAYOUT_COORD_MIN; bottom_floats_height = LAYOUT_COORD_MIN; if (row_has_spanned_floats) { int i = 0; for (Column* column = current_row->GetFirstColumn(); column != new_column; column = column->Suc(), i++) { LayoutCoord this_col_top_floats_height(0); for (PaneFloatEntry* entry = column->GetFirstFloatEntry(); entry; entry = entry->Suc()) { FloatedPaneBox* box = entry->GetBox(); int column_span = box->GetColumnSpan(); this_col_top_floats_height += box->GetHeight() + box->GetMarginTop() + box->GetMarginBottom(); if (current_column_num - i < column_span) // This previous float affects this column. if (box->IsTopFloat()) { if (top_floats_height < this_col_top_floats_height) top_floats_height = this_col_top_floats_height; } else { LayoutCoord this_col_bottom_floats_height(0); for (; entry; entry = entry->Suc()) { box = entry->GetBox(); this_col_bottom_floats_height += box->GetHeight() + box->GetMarginTop() + box->GetMarginBottom(); } if (bottom_floats_height < this_col_bottom_floats_height) bottom_floats_height = this_col_bottom_floats_height; break; } } } } // No top/bottom floats means 0 height. if (top_floats_height == LAYOUT_COORD_MIN) top_floats_height = LayoutCoord(0); if (bottom_floats_height == LAYOUT_COORD_MIN) bottom_floats_height = LayoutCoord(0); for (Columnizer* columnizer = this; columnizer; columnizer = columnizer->ancestor_columnizer) { columnizer->pending_start_offset = LayoutCoord(0); columnizer->allow_column_stretch = TRUE; } if (add_queued_floats) { if (!AddQueuedFloats(COLUMNS_NONE)) return FALSE; if (!GetCurrentColumn() || top_floats_height + bottom_floats_height > 0 && max_row_height - (top_floats_height + bottom_floats_height) < minimum_height) { /* Floats in the way. No room for any content in this column. Give up fitting any content here and get a new one straight away. */ new_column->SetContentLess(); return GetNewColumn(start_element, minimum_height, add_queued_floats); } } return TRUE; } /** Enter a spanned box before columnizing it. */ BOOL Columnizer::EnterSpannedBox(BlockBox* box, Container* container) { /* We already have a list of pending spanned boxes. They were created as spanned boxes were encountered during layout. It's done like this in order to store each spanned box's vertical margins. A different solution could have been to create designated box classes for spanned boxes, but that would require at least 3 new classes (regular block, list item, opacity!=1), so I decided against it. */ SpannedElm* spanned_elm = next_spanned_elm; OP_ASSERT(spanned_elm); if (spanned_elm) { OP_ASSERT(spanned_elm->GetSpannedBox() == box); LayoutCoord stack_position = box->GetStackPosition(); /* Advance past the bottom margin of the last element in column, so it gets committed. */ AdvanceHead(stack_position - spanned_elm->GetMarginTop()); if (!FinalizeColumn()) return FALSE; SetStopBefore(box); if (!AddQueuedFloats(COLUMNS_ANY)) return FALSE; CloseRow(); /* Collapse margins between the top of this spanned element and the bottom of the previous adjacent spanned element (if any). */ LayoutCoord margin_top = spanned_elm->GetMarginTop(); LayoutCoord total_margin = pending_margin + margin_top; if (pending_margin >= 0) { if (pending_margin < margin_top) pending_margin = margin_top; else if (margin_top < 0) pending_margin += margin_top; } else if (pending_margin > margin_top) pending_margin = margin_top; else if (margin_top > 0) pending_margin += margin_top; /* The adjacent spanned elements were laid out as if no margin collapsing occurred. Compensate for that, now that we know the final result. */ y_translation -= total_margin - pending_margin; #ifdef PAGED_MEDIA_SUPPORT if (!trial && !ancestor_columnizer && layout_info.paged_media != PAGEBREAK_OFF) { page_break_policy_before_current = box->GetPageBreakPolicyBefore(); if (BreakAllowedBetween(page_break_policy_after_previous, page_break_policy_before_current)) last_allowed_page_break_after = rows.Last(); } #endif // PAGED_MEDIA_SUPPORT AllocateContent(stack_position, box); AdvanceHead(stack_position); committed_virtual_y = virtual_y; pending_virtual_y_start = virtual_y; OP_ASSERT(next_break); if (next_break) { // Skip past the break caused by this spanned element. OP_ASSERT(next_break->IsSpannedElement()); remaining_floats_virtual_height += next_break->GetPaneFloatsVirtualHeight(); next_break = next_break->Suc(); } span_all = TRUE; } return TRUE; } /** Leave a spanned box after having columnized it. */ BOOL Columnizer::LeaveSpannedBox(BlockBox* box, Container* container) { SpannedElm* spanned_elm = next_spanned_elm; OP_ASSERT(spanned_elm); if (spanned_elm) { OP_ASSERT(spanned_elm->GetSpannedBox() == box); /* This was a spanned element. If we somehow end up with more than one column, things are going to look stupid. */ OP_ASSERT(!GetCurrentRow() || GetCurrentRow()->GetColumnCount() == 1); last_allocated_element = box; if (!FinalizeColumn()) return FALSE; CloseRow(); pending_margin = spanned_elm->GetMarginBottom(); AdvanceHead(box->GetStackPosition() + box->GetLayoutHeight() + pending_margin); committed_virtual_y = virtual_y; pending_virtual_y_start = virtual_y; next_spanned_elm = (SpannedElm*) next_spanned_elm->Suc(); span_all = FALSE; } return TRUE; } /** Skip a spanned box. */ void Columnizer::SkipSpannedBox(BlockBox* box) { SpannedElm* spanned_elm = next_spanned_elm; OP_ASSERT(spanned_elm); if (spanned_elm) { OP_ASSERT(spanned_elm->GetSpannedBox() == box); next_spanned_elm = (SpannedElm*) spanned_elm->Suc(); } } /** Add pane-attached (GCPM) floating box. */ void Columnizer::AddPaneFloat(FloatedPaneBox* box) { int start_pane = -1; if (box->IsFarCornerFloat()) start_pane = column_count - box->GetColumnSpan(); BOOL in_next_row = FALSE; #ifdef PAGED_MEDIA_SUPPORT if (box->IsForNextPage()) if (ancestor_columnizer) /* Note: we're not checking if the ancestor is a paginator, so if it isn't, the "next page" thing will really mean "next column". Nice or bad side-effect? */ in_next_row = TRUE; else start_pane = current_column_num + 1; #endif // PAGED_MEDIA_SUPPORT box->IntoPaneFloatList(float_queue, start_pane, in_next_row); } /** Find space for pending content. */ BOOL Columnizer::FindSpace(LayoutCoord new_virtual_y) { if (GetCurrentColumn()) { LayoutCoord uncommitted_height = new_virtual_y - committed_virtual_y; if (GetSpaceLeft() < uncommitted_height) { /* Content doesn't fit in the current column given the current row height. But we may be able to stretch it. */ if (ancestor_columnizer) // Does the ancestor allow us to stretch as much as we would need? if (!ancestor_columnizer->FindSpace(GetBottom(new_virtual_y) + ancestor_columnizer->stack_offset)) // No. We're out of space, then. return FALSE; if (!StretchColumn(uncommitted_height)) /* Couldn't stretch the column to make the content fit. We're out of space. */ return FALSE; } } return TRUE; } /** Commit pending content to one or more columns. */ BOOL Columnizer::CommitContent(BOOL check_available_space) { if (first_uncommitted_element.IsSet() && virtual_y >= earliest_break_virtual_y) { // We have something to commit, and we are even allowed to do it. if (!GetCurrentColumn() || check_available_space && !FindSpace(virtual_y)) // Need new column if (!GetNewColumn(first_uncommitted_element, virtual_y - pending_virtual_y_start)) return FALSE; if (ancestor_columnizer) { LayoutCoord new_ancestor_virtual_y = GetBottom(virtual_y) + ancestor_columnizer->stack_offset; if (ancestor_columnizer->virtual_y < new_ancestor_virtual_y) ancestor_columnizer->virtual_y = new_ancestor_virtual_y; if (!ancestor_columnizer->CommitContent(FALSE)) return FALSE; } GetCurrentColumn()->SetStopAfterElement(last_allocated_element); committed_virtual_y = virtual_y; pending_virtual_y_start = virtual_y; pending_start_offset = LayoutCoord(0); first_uncommitted_element.Reset(); if (!AddQueuedFloats(COLUMNS_NONE)) return FALSE; } return TRUE; } /** Flush pane floats in ancestors. */ void Columnizer::FlushFloats(LayoutCoord virtual_bottom) { virtual_bottom += stack_offset; if (virtual_y < virtual_bottom) { virtual_y = virtual_bottom; committed_virtual_y = virtual_y; pending_virtual_y_start = virtual_y; if (ancestor_columnizer) ancestor_columnizer->FlushFloats(GetBottom(virtual_y)); } } /** Fill up with any queued floats that might fit in the current column. */ BOOL Columnizer::AddQueuedFloats(ColumnCreationPolicy policy) { const ColumnBoundaryElement null_elm; BOOL allow_new_columns = policy != COLUMNS_NONE; if (span_all) return TRUE; while (PaneFloatEntry* entry = float_queue.First()) { FloatedPaneBox* box = entry->GetBox(); if (ancestor_columnizer && !box->IsForNextRow() && current_column_num > 0 && box->GetStartPane() != -1 && box->GetStartPane() < current_column_num) { /* Not enough columns left for this float. Move to next row (and next outer pane) and continue processing the floats queue from the head. Moving one float to the next row may move it backwards in the queue and reveal others that are already ready for addition. */ box->MoveToNextRow(); continue; } if (policy == COLUMNS_ANY || policy == COLUMNS_ONE_ROW) { /* In this mode we are allowed (and supposed to, if necessary) add new column / pages if a float cannot live on the current one. This typically happens when we finish columnization and there are still floats in the queue that haven't got a suitable column or page to live in yet. */ if (policy == COLUMNS_ANY && ancestor_columnizer && box->IsForNextRow()) { /* Float is for the next row. Create columns until we end up on a new row. */ ColumnRow* current_row = GetCurrentRow(); if (!current_row) { /* No row created yet, which also means no column yet. Creating a new column should solve that. */ if (!GetNewColumn(null_elm, LayoutCoord(0), FALSE)) return FALSE; current_row = GetCurrentRow(); OP_ASSERT(current_row); } do // Create columns until we get a new row. if (!GetNewColumn(null_elm, LayoutCoord(0), FALSE)) return FALSE; while (current_row == GetCurrentRow()); } if (box->GetStartPane() != -1 && !box->IsForNextRow()) /* Float has a designated start pane number in this row. Create new columns until we get there. */ while (current_column_num < box->GetStartPane()) if (!GetNewColumn(null_elm, LayoutCoord(0), FALSE)) return FALSE; } else if (box->IsForNextRow() || box->GetStartPane() > current_column_num) /* We have reached a float that we are not yet ready to add (it's either for the next row, or we haven't reached its start pane yet). Stop for now. */ break; LayoutCoord height = box->GetHeight() + box->GetMarginTop() + box->GetMarginBottom(); BOOL new_column = FALSE; if (!GetCurrentColumn()) if (allow_new_columns) { new_column = TRUE; if (!GetNewColumn(box, height, FALSE)) return FALSE; if (policy == COLUMNS_ONE) // That was it. Now we cannot add any more. allow_new_columns = FALSE; } else break; if (new_column || GetSpaceUsed() == 0 || FindSpace(virtual_y + height)) { int column_span = box->GetColumnSpan(); if (column_span > 1) row_has_spanned_floats = TRUE; remaining_floats_virtual_height -= height * LayoutCoord(column_span); entry->Out(); GetCurrentColumn()->AddFloat(box); if (box->IsTopFloat()) top_floats_height += height; else bottom_floats_height += height; #ifdef PAGED_MEDIA_SUPPORT if (box->IsPageBreakAfterForced()) { if (!ExplicitlyBreakPage(null_elm, TRUE)) return FALSE; } else #endif // PAGED_MEDIA_SUPPORT if (box->IsColumnBreakAfterForced()) { int remaining_columns = column_count - (current_column_num + column_span); int span_left = column_span; do { if (balance_current_row && remaining_columns > 0) // Compensate for the space wasted because of the forced break. IncreaseRowHeight(GetSpaceLeft() / LayoutCoord(remaining_columns)); if (!ExplicitlyBreakColumn(null_elm, TRUE)) return FALSE; if (--span_left > 0) { /* Skip empty columns that the float spans. We don't check if we're allowed to create new columns here, but there's no need to care in this case. */ if (!GetNewColumn(null_elm, LayoutCoord(0), FALSE)) return FALSE; continue; } break; } while (1); } } else if (policy == COLUMNS_ANY || policy == COLUMNS_ONE_ROW) { CloseColumn(); if (current_column_num == column_count) { if (policy == COLUMNS_ONE_ROW) break; CloseRow(); for (PaneFloatEntry* entry = float_queue.First(); entry; entry = entry->Suc()) entry->GetBox()->ResetIsForNextRow(); } continue; } break; } return TRUE; } /** Add and the empty parts of a block, and split it into multiple columns, if necessary. */ BOOL Columnizer::AddEmptyBlockContent(BlockBox* block, Container* container) { LayoutCoord layout_height = block->GetLayoutHeight(); if (virtual_y < earliest_break_virtual_y) { // Adjacent to unbreakable content. LayoutCoord unbreakable_amount = earliest_break_virtual_y - stack_offset; if (unbreakable_amount >= layout_height) { AdvanceHead(layout_height); /* Since something unbreakable already sticks at least as deep as this block, there's no point in continuing; we are not going to be able to split this block into multiple columns. */ return TRUE; } else // Move past adjacent unbreakable content. AdvanceHead(unbreakable_amount); } if (virtual_y < stack_offset) /* Empty block and positive top margin. Let's walk to the top border edge. Margins shouldn't be columnized. */ AdvanceHead(LayoutCoord(0)); LayoutCoord height_processed = virtual_y - stack_offset; if (height_processed < layout_height) { /* If we didn't manage to go through the whole block (due to lack of natural potential break points (e.g. when there is little or no child content at all)), split the remaining part of the block into columns (if necessary) now. */ last_allocated_element = block; if (!CommitContent()) return FALSE; if (!GetCurrentRow()) // This happens when a spanned element is the last child of this block. if (!GetNewColumn(block, LayoutCoord(0))) return FALSE; if (current_row_height <= 0) { /* In constrained height situations, row height may become zero. Distributing the block over an infinite number of columns is obviously not the solution then. */ AdvanceHead(layout_height); return TRUE; } do { LayoutCoord advancement = GetSpaceLeft(); if (advancement <= 0) { /* We are out of space. Close the current column. We don't want to stretch it or anything like that. */ CloseColumn(); advancement = current_row_height; } AllocateContent(height_processed, block, height_processed); height_processed += advancement; if (height_processed > layout_height) height_processed = layout_height; AdvanceHead(height_processed); if (height_processed < layout_height) // The current column cannot hold all remaining content. if (!CommitContent()) return FALSE; } while (height_processed < layout_height); } return TRUE; } /** Attempt to stretch the column to make some element fit. */ BOOL Columnizer::StretchColumn(LayoutCoord element_height) { /* If we're in the last column (and there's no ancestor to create another row in), be a bit more lenient. Allow as much stretching as requested, as long as it doesn't exceed the row maximum height. This comes in handy when our initial height guess was too low. As long as the height limit (if any) isn't reached, we should not use more columns than specified. If we're not in the last column, on the other hand, be more strict when it comes to stretching: */ if (ancestor_columnizer || current_column_num + 1 < column_count) { if (!allow_column_stretch) return FALSE; allow_column_stretch = FALSE; if (GetSpaceUsed() >= initial_row_height) /* We're already past the initial row height, so don't stretch any further. */ return FALSE; } // Stretch the row, but not beyond its max height. current_row_height = GetSpaceUsed() + element_height; if (current_row_height > max_row_height) { /* We may may have stretched it to maximum, but that was not enough for the content to fit. */ current_row_height = max_row_height; reached_max_height = TRUE; return FALSE; } return TRUE; } /** Increase current row height. */ void Columnizer::IncreaseRowHeight(LayoutCoord increase) { current_row_height += increase; if (current_row_height > max_row_height) { current_row_height = max_row_height; reached_max_height = TRUE; } if (current_row_height < 0) current_row_height = LayoutCoord(0); } /** Explicitly break (end) the current page (and therefore column and row as well). */ /* virtual */ BOOL Columnizer::ExplicitlyBreakPage(const ColumnBoundaryElement& stop_before, BOOL closed_by_pane_float, BOOL has_child_columnizer) { if (!closed_by_pane_float) { if (!FinalizeColumn()) return FALSE; if (!has_child_columnizer) { // Must do this before closing the row. SetStopBefore(stop_before); /* Row is soon closing. If there are any floats still queued for this row, add them now. */ if (!AddQueuedFloats(COLUMNS_ONE_ROW)) return FALSE; } } CloseRow(); if (ancestor_columnizer) // Break columns in all ancestor columnizers and get the page closed. if (!ancestor_columnizer->ExplicitlyBreakPage(stop_before, FALSE, TRUE)) return FALSE; #ifdef PAGED_MEDIA_SUPPORT if (!trial) ClosePage(); #endif // PAGED_MEDIA_SUPPORT if (!closed_by_pane_float && !has_child_columnizer) { OP_ASSERT(next_break); if (next_break) { // Skip past the page break. OP_ASSERT(next_break->IsRowBreak() && !next_break->IsSpannedElement()); remaining_floats_virtual_height += next_break->GetPaneFloatsVirtualHeight(); next_break = next_break->Suc(); } } return TRUE; } /** Explicitly break (end) the current column. */ /* virtual */ BOOL Columnizer::ExplicitlyBreakColumn(const ColumnBoundaryElement& stop_before, BOOL closed_by_pane_float) { if (closed_by_pane_float) CloseColumn(); else { if (!FinalizeColumn()) return FALSE; OP_ASSERT(next_break); if (next_break) { // Skip past the column break. OP_ASSERT(!next_break->IsRowBreak()); remaining_floats_virtual_height += next_break->GetPaneFloatsVirtualHeight(); next_break = next_break->Suc(); } SetStopBefore(stop_before); } return TRUE; } /** Get the row we're currently at, or NULL if none. */ ColumnRow* Columnizer::GetCurrentRow() const { if (!row_open) return NULL; return rows.Last(); } /** Get the column we're currently at, or NULL if none. */ Column* Columnizer::GetCurrentColumn() const { if (!column_open) return NULL; if (ColumnRow* row = GetCurrentRow()) return row->GetLastColumn(); return NULL; } /** Finish and close current column. */ void Columnizer::CloseColumn() { if (Column* current_column = GetCurrentColumn()) { LayoutCoord column_height = GetSpaceUsed(); LayoutCoord floats_height = top_floats_height + bottom_floats_height; current_column->SetTopFloatsHeight(top_floats_height); current_column->SetBottomFloatsHeight(bottom_floats_height); current_column->TranslateY(top_floats_height); current_column->SetHeight(column_height - floats_height); current_column->PositionTopFloats(); UpdateHeight(column_height); column_y += column_y_stride; y_translation -= column_height - floats_height; current_column_num ++; if (ancestor_columnizer && top_floats_height + bottom_floats_height) /* Pane floats are never committed, so we need to make sure that they are accounted for. */ ancestor_columnizer->FlushFloats(GetBottom(committed_virtual_y)); } column_open = FALSE; } /** Finish and close current row. */ void Columnizer::CloseRow(BOOL stretch_to_ancestor) { if (ColumnRow* current_row = GetCurrentRow()) { CloseColumn(); column_y = LayoutCoord(0); current_column_num = 0; LayoutCoord row_height = current_row->GetHeight(); if (stretch_to_ancestor && ancestor_columnizer && ancestor_columnizer->height_restricted) if (row_height < max_row_height) row_height = max_row_height; for (Column* column = current_row->GetFirstColumn(); column; column = column->Suc()) column->PositionBottomFloats(row_height); } row_open = FALSE; } #ifdef PAGED_MEDIA_SUPPORT /** Finish and close current page. */ /* virtual */ void Columnizer::ClosePage() { CloseRow(); if (ancestor_columnizer) ancestor_columnizer->ClosePage(); else if (!trial) page_open = FALSE; } /** Set page breaking policy before the element that is about to be added. */ void Columnizer::SetPageBreakPolicyBeforeCurrent(BREAK_POLICY page_break_policy) { if (!first_uncommitted_element.IsSet() && !ancestor_columnizer) page_break_policy_before_current = page_break_policy; } /** Set page breaking policy after the element that was just added. */ void Columnizer::SetPageBreakPolicyAfterPrevious(BREAK_POLICY page_break_policy) { if ((row_open || !first_uncommitted_element.IsSet()) && !ancestor_columnizer) page_break_policy_after_previous = page_break_policy; } #endif // PAGED_MEDIA_SUPPORT /** Finalize column. Commit pending content. */ BOOL Columnizer::FinalizeColumn() { if (virtual_y < earliest_break_virtual_y) // Pull ourselves past all content. virtual_y = earliest_break_virtual_y; if (!CommitContent()) return FALSE; if (!AddQueuedFloats(COLUMNS_ONE)) return FALSE; CloseColumn(); return TRUE; } /** Finalize columnization. Commit pending content and floats. */ BOOL Columnizer::Finalize(BOOL stretch_to_ancestor) { if (!FinalizeColumn()) return FALSE; if (!AddQueuedFloats(COLUMNS_ANY)) return FALSE; CloseRow(stretch_to_ancestor); return TRUE; } /** Set the element before which the last column added shall stop. */ void Columnizer::SetStopBefore(const ColumnBoundaryElement& elm) { if (ColumnRow* row = GetCurrentRow()) { if (Column* last_column = row->GetLastColumn()) /* Need to stop right before the spanned box. If the spanned box is the first child of some block, there's no element after which to stop. So we stop before this spanned box instead. */ last_column->SetStopBeforeElement(elm); if (ancestor_columnizer) ancestor_columnizer->SetStopBefore(elm); } } #ifdef PAGED_MEDIA_SUPPORT Paginator::Paginator(const LayoutInfo& layout_info, LayoutCoord max_height, LayoutCoord page_width, LayoutCoord column_y_stride, LayoutCoord top_offset, LayoutCoord vertical_padding, BOOL height_restricted) : Columnizer(NULL, FALSE, layout_info, page_list_holder, NULL, NULL, max_height, INT_MAX, page_width, page_width, LayoutCoord(0), column_y_stride, top_offset, LAYOUT_COORD_MAX, LayoutCoord(0), height_restricted, #ifdef SUPPORT_TEXT_DIRECTION FALSE, #endif // SUPPORT_TEXT_DIRECTION FALSE), vertical_padding(vertical_padding), page_height_auto(column_y_stride == CONTENT_HEIGHT_AUTO) { } /** Update row and/or container height. */ /* virtual */ void Paginator::UpdateHeight(LayoutCoord height) { Columnizer::UpdateHeight(height); if (!page_height_auto) return; LayoutCoord new_column_y_stride = height - (top_floats_height + bottom_floats_height) + vertical_padding; if (column_y_stride < new_column_y_stride) { if (Column* col = GetCurrentRow()->GetFirstColumn()) { // Increased page height in vertical pagination; update page positions. col = col->Suc(); if (col) { LayoutCoord increase = new_column_y_stride - column_y_stride; LayoutCoord acc_increase = increase; OP_ASSERT(column_y_stride != CONTENT_HEIGHT_AUTO); for (; col; col = col->Suc(), acc_increase += increase) { col->MoveDown(acc_increase); column_y += increase; } } } column_y_stride = new_column_y_stride; } } /** Explicitly break (end) the current page (and therefore column and row as well). */ /* virtual */ BOOL Paginator::ExplicitlyBreakPage(const ColumnBoundaryElement& stop_before, BOOL closed_by_pane_float, BOOL has_child_columnizer) { if (closed_by_pane_float) CloseColumn(); else { if (!FinalizeColumn()) return FALSE; SetStopBefore(stop_before); } return TRUE; } /** Explicitly break (end) the current column. */ /* virtual */ BOOL Paginator::ExplicitlyBreakColumn(const ColumnBoundaryElement& stop_before, BOOL closed_by_pane_float) { OP_ASSERT(!"Attempting to insert a column break while not inside a multicol container"); return TRUE; } /** Finish and close current page. */ /* virtual */ void Paginator::ClosePage() { /* "WTF - nothing?", you say? Yeah, I know... This is for the paged mode done in printing, which is a completely different machinery from the one that assists a paged container (this class). Some wonderful day we should consolidate the two of them. */ } /** Get page height. */ LayoutCoord Paginator::GetPageHeight() const { if (ColumnRow* all_pages = page_list_holder.Last()) { OP_ASSERT(!all_pages->Pred()); return all_pages->GetHeight(); } return LayoutCoord(0); } /** Update bottom floats when final paged container height is known. */ void Paginator::UpdateBottomFloats(LayoutCoord content_height) { OP_ASSERT(page_list_holder.Empty() || page_list_holder.Cardinal() == 1); if (ColumnRow* last_row = page_list_holder.Last()) { /* The bottom edge of the last row should be the same as the bottom content edge of the multi-pane container. */ LayoutCoord row_y = last_row->GetPosition(); LayoutCoord stretched_row_height = content_height - row_y; for (Column* column = last_row->GetFirstColumn(); column; column = column->Suc()) column->PositionBottomFloats(stretched_row_height); } } /** Move all pages created during pagination into 'pages'. */ void Paginator::GetAllPages(PageStack& pages) { OP_ASSERT(!pages.GetFirstColumn()); if (ColumnRow* all_pages = page_list_holder.Last()) { OP_ASSERT(!all_pages->Pred()); while (Column* page = all_pages->GetFirstColumn()) { page->Out(); pages.AddColumn(page); } } } #endif // PAGED_MEDIA_SUPPORT ColumnFinder::ColumnFinder(const Box* box, ColumnRow* first_row, LayoutCoord top_border_padding, ColumnFinder* ancestor_cf) : box(box), ancestor_cf(ancestor_cf), cur_row(first_row), cur_column(NULL), start_row(NULL), start_column(NULL), box_translation_x(0), box_translation_y(0), start_offset_from_top(0), end_row(NULL), end_column(NULL), virtual_y(0), stack_offset(-top_border_padding), descendant_translation_y(0), descendant_translation_x(0) { OP_ASSERT(cur_row); OP_ASSERT(box); if (cur_row) cur_column = cur_row->GetFirstColumn(); border_rect.left = 0; border_rect.right = 0; border_rect.top = 0; border_rect.bottom = 0; if (box->IsFloatedPaneBox()) /* Look for the first column that is occupied the pane-attached float. It may not live in this multi-pane container at all, but rather in some descendant multi-pane container, but if we do find it here, we're actually done, and wont't have to traverse through the layout tree. */ for (ColumnRow* row = first_row; row; row = row->Suc()) for (Column* column = row->GetFirstColumn(); column; column = column->Suc()) if (column->HasFloat((FloatedPaneBox*) box)) { cur_column = column; cur_row = row; SetBoxStartFound(); SetBoxEndFound(); border_rect.bottom = box->GetHeight(); } } /** Update the union of the border area in each column in which the target box lives. */ void ColumnFinder::UpdateBorderRect(LayoutCoord virtual_y) { if (start_row && !box->IsFloatedPaneBox()) { LayoutCoord virtual_start_y(cur_column->GetVirtualY()); LayoutCoord x(cur_column->GetX() - start_column->GetX()); LayoutCoord y = (cur_row->GetPosition() + cur_column->GetY()) - (start_row->GetPosition() + start_column->GetY()) + virtual_y - virtual_start_y - start_offset_from_top; if (border_rect.left > x) border_rect.left = x; if (border_rect.right < x) border_rect.right = x; if (border_rect.top > y) border_rect.top = y; if (border_rect.bottom < y) border_rect.bottom = y; } } /** Set position of the current element we're examining. */ void ColumnFinder::SetPosition(LayoutCoord local_virtual_y) { virtual_y = stack_offset + local_virtual_y; /* Advance to next column/spanned element as long as the virtual Y position is beyond the bounds of the current one. */ do { if (cur_column && cur_column->Suc()) { Column* next_column = cur_column->Suc(); if (virtual_y >= next_column->GetVirtualY()) { // Record the bottom of the column we're about to leave: UpdateBorderRect(next_column->GetVirtualY()); cur_column = next_column; // Record the top of the column we just entered: UpdateBorderRect(next_column->GetVirtualY()); continue; } } else { if (ColumnRow* next_row = cur_row->Suc()) { if (Column* next_column = next_row->GetFirstColumn()) { if (virtual_y >= next_column->GetVirtualY()) { // Record the bottom of the column we're about to leave: UpdateBorderRect(next_column->GetVirtualY()); cur_column = next_column; cur_row = next_row; // Record the top of the column we just entered: UpdateBorderRect(next_column->GetVirtualY()); } } else OP_ASSERT(!"Row with no columns"); if (cur_row == next_row) { if (ancestor_cf) /* We advanced to the next row (or spanned element). Notify the ancestor, since this may mean that the ancestor needs to move to the next column. */ ancestor_cf->SetPosition(cur_row->GetPosition()); continue; } } } break; // Didn't advance. We're done. } while (1); } /** Found the start of the box. */ void ColumnFinder::SetBoxStartFound() { OP_ASSERT(cur_row); OP_ASSERT(!start_row); start_column = cur_column; start_row = cur_row; box_translation_x = cur_column->GetX(); box_translation_y = cur_row->GetPosition() + cur_column->GetY(); if (!box->IsFloatedPaneBox()) box_translation_y += cur_column->GetTranslationY(); if (cur_column) start_offset_from_top = virtual_y - cur_column->GetVirtualY(); if (ancestor_cf) ancestor_cf->SetBoxStartFound(); } /** Found the end of the box. We're done. */ void ColumnFinder::SetBoxEndFound() { OP_ASSERT(cur_row); OP_ASSERT(!end_row); end_column = cur_column; end_row = cur_row; // Record the end position of the target box. UpdateBorderRect(virtual_y); if (ancestor_cf) ancestor_cf->SetBoxEndFound(); }
#include<vector> #include<iostream> #include<algorithm> #include<math.h> using namespace std; class Solution { public: int superPow(int a, vector<int>& b) { //基本思想:快速幂算法+取模运算性质 //a^b%p=((a%p)^b)%p int res=1; a=a%1337; for(int i=int(b.size())-1;i>=0;i--) { res=res*myPow(a,b[i])%1337; a=myPow(a,10)%1337; } return res; } int myPow(int a,int n) { int res=1; while(n>0) { if(n%2==1) res=res*a%1337; n>>=1; a=a*a%1337; } return res; } }; int main() { int a=2147483647; vector<int> b={2,0,0}; Solution solute; cout<<solute.superPow(a,b)<<endl; return 0; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int maxn = 1e5 + 10; int prime[10010],n = 0; bool vis[maxn + 10]; void init() { memset(vis,0,sizeof(vis)); for (int i = 2;i <= maxn; i++) if (!vis[i]) { prime[n++] = i; for (int j = i+i;j <= maxn;j += i) vis[j] = true; } } int bsearch(int k) { int l = 0,r = n-1; while (l < r) { int mid = ((l+r) >> 1) + 1; if (prime[mid] > k) r = mid -1; else l = mid; } return l; } int main() { init(); int m;double a,b; while (scanf("%d%lf%lf",&m,&a,&b) != EOF && m) { int l = 1,h = 1; for (int i = 0;i < n; i++) { if (prime[i]*prime[i] > m) break; int k1 = bsearch(floor(prime[i]*b/a)); int k2 = bsearch(floor(m/prime[i])); k1 = min(k1,k2); if (prime[i]*prime[k1] > l*h) { l = prime[i];h = prime[k1]; } } printf("%d %d\n",l,h); } return 0; }
// @(#)73 1.2 src/htx/usr/lpp/htx/inc/hxfcpp_wrap.H, htx_libhtx, htxubuntu 6/4/04 14:36:26 extern "C" { # include <hxihtx.h> # include <htxlibdef.h> } class cHtxLib { public: cHtxLib (char *pExerName, char *pDevName, char *pRunType); void start (); void finish (); void sendMsg (int, int, char *); int hxfohft (int); int hxfpat (char *, char *, size_t); void setRunType (char *type = "OTH"); ~cHtxLib (); private: struct htx_data htx_data; };
class ServletFactory { static map<string, IServlet> url_servlet_mapping; public static bool register(string url_pattern, IServlet servlet) { if (url_servlet_map.find(url_pattern) == url_servlet_map.end()) { url_servlet_map.insert(make_pair(url_pattern, servlet)); return true; } printf("%s pattern is already registered", url_pattern); return false; } public static bool deregister(string url_pattern) { if (url_servlet_map.find(url_pattern) == url_servlet_map.end()) { url_servlet.remove(url_pattern); return true; } printf("%s pattern not found to deregister", url_pattern); return false; } public static getServlet(string url_pattern) { map<string, IServlet>::iterator it = url_servlet_mapping.find(url_pattern); if (it != url_servlet_mapping.end()) { return it->second(); } return null; } }
// Created on: 1993-01-09 // Created by: CKY / Contract Toubro-Larsen ( TCD ) // 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 _IGESGeom_OffsetCurve_HeaderFile #define _IGESGeom_OffsetCurve_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <gp_XYZ.hxx> #include <IGESData_IGESEntity.hxx> class gp_Vec; class IGESGeom_OffsetCurve; DEFINE_STANDARD_HANDLE(IGESGeom_OffsetCurve, IGESData_IGESEntity) //! defines IGESOffsetCurve, Type <130> Form <0> //! in package IGESGeom //! An OffsetCurve entity contains the data necessary to //! determine the offset of a given curve C. This entity //! points to the base curve to be offset and contains //! offset distance and other pertinent information. class IGESGeom_OffsetCurve : public IGESData_IGESEntity { public: Standard_EXPORT IGESGeom_OffsetCurve(); //! This method is used to set the fields of the class //! OffsetCurve //! - aBaseCurve : The curve entity to be offset //! - anOffsetType : Offset distance flag //! 1 = Single value, uniform distance //! 2 = Varying linearly //! 3 = As a specified function //! - aFunction : Curve entity, one coordinate of which //! describes offset as a function of its //! parameter (0 unless OffsetType = 3) //! - aFunctionCoord : Particular coordinate of curve //! describing offset as function of its //! parameters. (used if OffsetType = 3) //! - aTaperedOffsetType : Tapered offset type flag //! 1 = Function of arc length //! 2 = Function of parameter //! (Only used if OffsetType = 2 or 3) //! - offDistance1 : First offset distance //! (Only used if OffsetType = 1 or 2) //! - arcLength1 : Arc length or parameter value of //! first offset distance //! (Only used if OffsetType = 2) //! - offDistance2 : Second offset distance //! - arcLength2 : Arc length or parameter value of //! second offset distance //! (Only used if OffsetType = 2) //! - aNormalVec : Unit vector normal to plane containing //! curve to be offset //! - anOffsetParam : Start parameter value of offset curve //! - anotherOffsetParam : End parameter value of offset curve Standard_EXPORT void Init (const Handle(IGESData_IGESEntity)& aBaseCurve, const Standard_Integer anOffsetType, const Handle(IGESData_IGESEntity)& aFunction, const Standard_Integer aFunctionCoord, const Standard_Integer aTaperedOffsetType, const Standard_Real offDistance1, const Standard_Real arcLength1, const Standard_Real offDistance2, const Standard_Real arcLength2, const gp_XYZ& aNormalVec, const Standard_Real anOffsetParam, const Standard_Real anotherOffsetParam); //! returns the curve to be offset Standard_EXPORT Handle(IGESData_IGESEntity) BaseCurve() const; //! returns the offset distance flag //! 1 = Single value offset (uniform distance) //! 2 = Offset distance varying linearly //! 3 = Offset distance specified as a function Standard_EXPORT Standard_Integer OffsetType() const; //! returns the function defining the offset if at all the offset //! is described as a function or Null Handle. Standard_EXPORT Handle(IGESData_IGESEntity) Function() const; //! returns True if function defining the offset is present. Standard_EXPORT Standard_Boolean HasFunction() const; //! returns particular coordinate of the curve which describes offset //! as a function of its parameters. (only used if OffsetType() = 3) Standard_EXPORT Standard_Integer FunctionParameter() const; //! returns tapered offset type flag (only used if OffsetType() = 2 or 3) //! 1 = Function of arc length //! 2 = Function of parameter Standard_EXPORT Standard_Integer TaperedOffsetType() const; //! returns first offset distance (only used if OffsetType() = 1 or 2) Standard_EXPORT Standard_Real FirstOffsetDistance() const; //! returns arc length or parameter value (depending on value of //! offset distance flag) of first offset distance //! (only used if OffsetType() = 2) Standard_EXPORT Standard_Real ArcLength1() const; //! returns the second offset distance Standard_EXPORT Standard_Real SecondOffsetDistance() const; //! returns arc length or parameter value (depending on value of //! offset distance flag) of second offset distance //! (only used if OffsetType() = 2) Standard_EXPORT Standard_Real ArcLength2() const; //! returns unit vector normal to plane containing curve to be offset Standard_EXPORT gp_Vec NormalVector() const; //! returns unit vector normal to plane containing curve to be offset //! after applying Transf. Matrix Standard_EXPORT gp_Vec TransformedNormalVector() const; Standard_EXPORT void Parameters (Standard_Real& StartParam, Standard_Real& EndParam) const; //! returns Start Parameter value of the offset curve Standard_EXPORT Standard_Real StartParameter() const; //! returns End Parameter value of the offset curve Standard_EXPORT Standard_Real EndParameter() const; DEFINE_STANDARD_RTTIEXT(IGESGeom_OffsetCurve,IGESData_IGESEntity) protected: private: Handle(IGESData_IGESEntity) theBaseCurve; Standard_Integer theOffsetType; Handle(IGESData_IGESEntity) theFunction; Standard_Integer theFunctionCoord; Standard_Integer theTaperedOffsetType; Standard_Real theOffsetDistance1; Standard_Real theArcLength1; Standard_Real theOffsetDistance2; Standard_Real theArcLength2; gp_XYZ theNormalVector; Standard_Real theOffsetParam1; Standard_Real theOffsetParam2; }; #endif // _IGESGeom_OffsetCurve_HeaderFile
#pragma once #include "RelayThread.h" #include "ContiguousQueue.h" #include "Helpers.h" #include <array> #include <thread> #include <functional> static const int THREAD_COUNT = 1024; struct RelayThreadController { bool valid; std::shared_ptr<Semaphore> mutex = std::make_shared<Semaphore>(); void join() const { mutex->acquire(); mutex->release(); } }; class RelayThreadPool { public: explicit RelayThreadPool() = default; RelayThreadController run(std::function<void()>&& function); private: std::array<RelayThread, THREAD_COUNT> m_threads; };