blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
36578d529a8a2ba1cefb6371f8251d34d28d80da | 13d94803bb40b0c5107a695c3d4476744c7e5bfa | /Project/include/material.h | 2f9fe2eb027faa805373d9adb15b37d3cff2e297 | [] | no_license | OlmoPrieto/EngineV3 | 07b2eaba52ebe597cddc392a83a4584d7b057ffc | 990c22a0e5f84c6608807396e6cb7254e1b53ac1 | refs/heads/master | 2022-07-13T23:26:11.154931 | 2022-03-19T16:12:44 | 2022-03-19T16:12:44 | 169,894,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,060 | h | material.h | #pragma once
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "attribute.h"
#include "program.h"
class Shader;
class Program;
class MaterialInstance;
class Material {
public:
Material(const std::string& _sName, const std::string& _sMaterialDefinitionPath);
~Material();
// TODO: placeholder
static std::shared_ptr<MaterialInstance> CreateSpriteMaterial();
std::string getName() const { return m_sName; }
const std::vector<Shader>& getShaders() const { return m_vctShaders; }
std::vector<Shader>& getShaders() { return m_vctShaders; }
Program& getProgram() { return m_oProgram; }
private:
friend class MaterialInstance;
Material();
std::unordered_map<std::string, ValueType> m_dctAttributesTable;
std::vector<Shader> m_vctShaders;
Program m_oProgram;
std::string m_sName;
std::string m_sMaterialDefinitionPath;
static const float m_fVersion;
// Attributes will be defined *here* by the asset file
/* possible appereance of attributes:
{
Type (enum class EAttributeType)
Name (std::string)
}
*/
};
class MaterialInstance
{
public:
MaterialInstance(std::shared_ptr<Material> _spMaterial);
~MaterialInstance();
const std::shared_ptr<Material>& getReferenceMaterial() const { return m_spMaterial; }
bool checkReady();
std::vector<std::unique_ptr<Attribute>>& getAttributes() { return m_vctAttributes; }
std::unique_ptr<Attribute>& getAttribute(const std::string& _sName);
// void setAttributeValue(name, value);
// any getAttributeValue(name);
private:
friend class Material;
std::vector<std::unique_ptr<Attribute>> m_vctAttributes;
std::shared_ptr<Material> m_spMaterial;
bool m_bReady = false; // Will be true when the Shaders and the Programs are ready
// std::vector<attributes the material has> m_vctAttributes;
/* possible appereance of attributes:
{
Type (enum class EAttributeType)
Name (std::string)
Value (void*)
}
*/
}; |
063c6e9b50428cd996bce7b86ee7ff2f7912a544 | cf77526b7bfdb6b05beae4d147f4d0773df70c05 | /ToolkitNF/Widgets/MenuItemWidget.cpp | cf8b3c68b6188c8a6eac9953d8fa7d8a3351524b | [
"MIT"
] | permissive | SlyVTT/Widget_NF_Nspire_and_PC | 7cd61f89b7686904ca1fb24ebe3063747af664e4 | cdf921cc931eaa99ed765d1640253e060bc259cb | refs/heads/main | 2023-08-17T14:37:29.345813 | 2021-09-22T19:48:52 | 2021-09-22T19:48:52 | 408,216,702 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,128 | cpp | MenuItemWidget.cpp | #include "MenuItemWidget.hpp"
#include "MenuPaneWidget.hpp"
#include "../Managers/KeyManager.hpp"
#include "../Managers/MouseManager.hpp"
#include "../Renderers/ScreenRenderer.hpp"
#include "../Engines/ColorEngine.hpp"
#include "../Engines/FontEngine.hpp"
MenuItemWidget::MenuItemWidget()
{
widgettype = "MenuItem";
};
MenuItemWidget::MenuItemWidget( std::string l, unsigned int x, unsigned int y, unsigned int w, unsigned int h, Widget *p ) : MiniButtonWidget( l, x, y, w, h, p )
{
widgettype = (char*) "MenuItem";
};
MenuItemWidget::~MenuItemWidget()
{
//dtor
}
unsigned int MenuItemWidget::GetFullTextWidth( void )
{
return width_full_text;
}
void MenuItemWidget::Drop( void )
{
is_dropped = true;
is_visible = true;
//is_pressed = false;
}
void MenuItemWidget::Undrop( void )
{
is_dropped = false;
is_visible = false;
is_pressed = false;
}
bool MenuItemWidget::IsPressed( void )
{
return is_pressed;
}
void MenuItemWidget::Logic( void )
{
if (is_enabled && is_visible)
{
is_hovering = CursorOn( );
bool currently_pressed = (MouseManager::GetB() || KeyManager::kbSCRATCH() ) && is_hovering;
if(currently_pressed && !is_pressed)
{
if (clickfunction)
clickfunction( (char*) "test" );
is_pressed = true;
}
else if(!currently_pressed && is_pressed)
{
if (releasefunction)
releasefunction( (char*) "test" );
is_pressed = false;
}
else if(is_hovering)
{
if (hoverfunction)
hoverfunction( (char*) "test" );
is_pressed = false;
}
else
{
is_pressed = false;
}
//is_pressed = currently_pressed;
if (is_pressed && (children.size()!=0))
{
for ( auto& c : children )
{
//TODO : working on that part of the code for correct overlapping of the menus
if (parent)
if (parent->GetWidgetType() == "MenuPane")
dynamic_cast<MenuPaneWidget*>(parent)->SetChildDropped();
if (c->GetWidgetType() == "MenuPane")
{
c->SetVisible();
dynamic_cast<MenuPaneWidget*>(c)->Drop();
}
else
{
c->SetVisible();
}
}
}
else if (is_pressed && (children.size()==0))
{
if (parent)
if (parent->GetWidgetType() == "MenuPane")
{
dynamic_cast<MenuPaneWidget*>(parent)->UnsetChildDropped();
dynamic_cast<MenuPaneWidget*>(parent)->Undrop();
}
}
for (auto& c : children )
c->Logic( );
}
else
{
// DEBUG : test to see if it actually works
for (auto& c : children )
c->Logic( );
is_pressed = false;
}
}
void MenuItemWidget::Render( void )
{
labelarrow = label;
FontEngine::SetCurrentFontSet( FontEngine::Widget_Text_Enable );
width_full_text = FontEngine::GetStringWidth( labelarrow );
if (is_visible)
{
if (is_enabled)
{
ScreenRenderer::DrawFilledRoundedRectangle( xpos, ypos, xpos+width, ypos+height-2, 3, ColorEngine::GetColor(ColorEngine::Widget_Filling_Enable) );
if (!is_hovering)
{
//ScreenRenderer::DrawRoundedRectangle( xpos, ypos, xpos+width, ypos+height, 3, ColorEngine::GetColor(ColorEngine::Widget_Border_Enable) );
}
else
{
ScreenRenderer::DrawRoundedRectangle( xpos, ypos, xpos+width, ypos+height-2, 3, ColorEngine::GetColor(ColorEngine::Widget_Border_Cursoron) );
}
// THIS IS THE PART OF THE ROUTINE THAT CHECK IF THE TEXT TO BE RENDERED IS TOO LONG AND IF SO THAT REDUCES IT TO THE DRAWABLE LENGTH
FontEngine::SetCurrentFontSet( FontEngine::Widget_Text_Enable );
drawablecharlabel = FontEngine::AssertStringLength( label, width-2-2 );
labelarrow = label;
width_full_text = FontEngine::GetStringWidth( labelarrow );
if (drawablecharlabel!=0)
{
drawablelabel = label; //fonts->reducestringtovisible( label, width-2 -2 );
int sl = FontEngine::GetStringWidth( drawablelabel );
int sh = FontEngine::GetStringHeight( drawablelabel );
FontEngine::DrawStringLeft( drawablelabel, xpos+2, ypos+(height-sh)/2, ColorEngine::GetColor(ColorEngine::Widget_Text_Enable) );
// create a mark to indicate that there is a submenu
if (parent)
{
// if the parent is a menubar, there is no need for the arrow indicator, it is absolutely logic to have a submenu
if (parent->GetWidgetType() != "MenuBar")
{
if (children.size()!=0)
{
for(auto& c : children)
{
if (c->GetWidgetType() == "MenuPane")
{
FontEngine::DrawCharLeft( (char) '\u0010', xpos+sl+5, ypos+(height-sh)/2, ColorEngine::GetColor(ColorEngine::Widget_Border_Enable) );
}
}
}
}
}
}
}
else
{
ScreenRenderer::DrawFilledRoundedRectangle( xpos, ypos, xpos+width, ypos+height-2, 3, ColorEngine::GetColor(ColorEngine::Widget_Filling_Disable) );
//Border of the button is black cause it is disabled
//roundedRectangleRGBA( screen, xpos, ypos, xpos+width, ypos+height, 3, colors->widget_border_disable.R, colors->widget_border_disable.G, colors->widget_border_disable.B, colors->widget_border_disable.A);
// THIS IS THE PART OF THE ROUTINE THAT CHECK IF THE TEXT TO BE RENDERED IS TOO LONG AND IF SO THAT REDUCES IT TO THE DRAWABLE LENGTH
FontEngine::SetCurrentFontSet( FontEngine::Widget_Text_Disable );
drawablecharlabel = FontEngine::AssertStringLength( label, width-2-2 );
labelarrow = label;
width_full_text = FontEngine::GetStringWidth( labelarrow );
if (drawablecharlabel!=0)
{
drawablelabel = label; //fonts->reducestringtovisible( label, width-2 -2 );
//int sl = FontEngine::GetStringWidth( drawablelabel );
int sh = FontEngine::GetStringHeight( drawablelabel );
FontEngine::DrawStringLeft( drawablelabel, xpos+2, ypos+(height-sh)/2, ColorEngine::GetColor(ColorEngine::Widget_Text_Disable) );
}
}
for (auto& c : children )
c->Render( );
}
}
|
8a6aeef5227e889a618a5ceccfafeab7f8950d81 | d939ea588d1b215261b92013e050993b21651f9a | /ie/src/v20200304/model/MuxInfo.cpp | c5495d63051384767688e51c56a38b81a8b2a04a | [
"Apache-2.0"
] | permissive | chenxx98/tencentcloud-sdk-cpp | 374e6d1349f8992893ded7aa08f911dd281f1bda | a9e75d321d96504bc3437300d26e371f5f4580a0 | refs/heads/master | 2023-03-27T05:35:50.158432 | 2021-03-26T05:18:10 | 2021-03-26T05:18:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,081 | cpp | MuxInfo.cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/ie/v20200304/model/MuxInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ie::V20200304::Model;
using namespace rapidjson;
using namespace std;
MuxInfo::MuxInfo() :
m_deleteStreamHasBeenSet(false)
{
}
CoreInternalOutcome MuxInfo::Deserialize(const Value &value)
{
string requestId = "";
if (value.HasMember("DeleteStream") && !value["DeleteStream"].IsNull())
{
if (!value["DeleteStream"].IsString())
{
return CoreInternalOutcome(Error("response `MuxInfo.DeleteStream` IsString=false incorrectly").SetRequestId(requestId));
}
m_deleteStream = string(value["DeleteStream"].GetString());
m_deleteStreamHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void MuxInfo::ToJsonObject(Value &value, Document::AllocatorType& allocator) const
{
if (m_deleteStreamHasBeenSet)
{
Value iKey(kStringType);
string key = "DeleteStream";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_deleteStream.c_str(), allocator).Move(), allocator);
}
}
string MuxInfo::GetDeleteStream() const
{
return m_deleteStream;
}
void MuxInfo::SetDeleteStream(const string& _deleteStream)
{
m_deleteStream = _deleteStream;
m_deleteStreamHasBeenSet = true;
}
bool MuxInfo::DeleteStreamHasBeenSet() const
{
return m_deleteStreamHasBeenSet;
}
|
53126d2b4ea3a87bb0b9ddca8ec3d68e2577febc | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/f0/ac8d18655c4cfd/main.cpp | db1097188408737ac6ebced5ea1d3f85fd93ef39 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 68 | cpp | main.cpp | class A {
public:
A(int i = 4) {}
};
int main () {A a;} |
8cfb2c752ec7bc0bba04a7c403cb8113204d674d | f6cf14142621b8c4709c6f2073172f39577b1964 | /common/lib/rec/robotino3/iocom/tag/GetIpAddressFwd.h | 68a09e5654d68eb983f5c3e51ee6e43348481f97 | [] | no_license | BusHero/robotino_api2 | f3eef6c1ace2ff5a8b93db691aa779db8a9ce3a1 | 9757814871aa90977c2548a8a558f4b2cb015e5d | refs/heads/master | 2021-06-18T21:32:14.390621 | 2021-02-18T15:21:48 | 2021-02-18T15:21:48 | 165,231,765 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 364 | h | GetIpAddressFwd.h | #ifndef _REC_ROBOTINO3_IOCOM_TAG_GetIpAddressFWD_H_
#define _REC_ROBOTINO3_IOCOM_TAG_GetIpAddressFWD_H_
#include <QtCore>
namespace rec
{
namespace robotino3
{
namespace iocom
{
namespace tag
{
class GetIpAddress;
typedef QSharedPointer< GetIpAddress > GetIpAddressPointer;
}
}
}
}
#endif //_REC_ROBOTINO3_IOCOM_TAG_GetIpAddressFWD_H_
|
6fe1bbe5a8531772d7c1b4a33363f0758dbd33b5 | a120d86965878749a6f132c949c85797ba1a7b70 | /module_3/task_1/SetGraph.cpp | 24e0632169c734678dc454a0f09e65d7feb96827 | [] | no_license | timoninas/algorithms-n-data-structures | 409b354730b894f2ca101cfbaaa6cc06e3422b83 | d1b00c25715acaf404f78ef948a11e795b4a38d0 | refs/heads/master | 2023-02-06T10:53:37.309588 | 2020-12-30T17:27:32 | 2020-12-30T17:27:32 | 204,346,964 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,071 | cpp | SetGraph.cpp | #include "SetGraph.hpp"
SetGraph::SetGraph(const IGraph& sendedGraph) {
graph.resize(sendedGraph.VerticesCount());
for (int i = 0; i < sendedGraph.VerticesCount(); i++) {
for (auto child: sendedGraph.GetNextVertices(i)) {
graph[i].insert(child);
}
}
}
int SetGraph::VerticesCount() const {
return graph.size();
}
void SetGraph::AddEdge(int from, int to) {
assert(from < graph.size());
assert(to < graph.size());
assert(from >= 0);
assert(to >= 0);
graph[from].insert(to);
}
std::vector<int> SetGraph::GetNextVertices(int vertex) const {
std::vector<int> result;
for (auto val: graph[vertex]) {
result.push_back(val);
}
return result;
}
std::vector<int> SetGraph::GetPrevVertices(int vertex) const {
std::vector<int> result;
for(size_t i = 0; i < graph.size(); i++) {
for (auto child: graph[i]) {
if (child == vertex) {
result.push_back(i);
break;
}
}
}
return result;
}
|
b6089ae92494caf54c5cd55ddf54613a5cafba86 | 60421df8b2bf6b2a159052ac787318aaad635e3f | /SumRootToLeafNumbers.cpp | 9ff99da4a0db16db5a960b1c74f492bbb83642ad | [] | no_license | ssdemajia/LeetCode | 5d359d5868f2b39a55e2b225dba69d36bc23c3ac | 9239166ae7da12e29a6c2c6416bfada2027315b8 | refs/heads/master | 2021-01-16T21:41:53.814584 | 2019-05-06T15:17:07 | 2019-05-06T15:17:07 | 100,246,179 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 705 | cpp | SumRootToLeafNumbers.cpp | #include "inc.h"
//129. Sum Root to Leaf Numbers
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
int result = 0;
helper(root, 0, result);
return result;
}
void helper(TreeNode* root, int num, int&result) {
if (!root) return;
num*=10;
num+=root->val;
if (!root->left && !root->right) {
result+=num;
return;
}
helper(root->left, num, result);
helper(root->right, num, result);
}
}; |
15d7100b2610935e328d067c9e2ad34f6e98b4eb | 89cfc849a109b6335daabbb2b9c2ea61bb1415fe | /aeronode-runtime/include/aeronode/tcp_client.h | 7814dc40a80b00875674b9f43f62a08af2fb63ce | [] | no_license | Pokerpoke/aero-node | 9b6ef3d0a4abe514f7c9be26fd517eedffb5e770 | 51f3cc6627f109faf505377c577f19b34f398c96 | refs/heads/master | 2021-10-22T14:49:41.209209 | 2019-03-11T13:57:41 | 2019-03-11T13:57:41 | 96,872,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,097 | h | tcp_client.h | /**
*
* Copyright (c) 2017-2018 南京航空航天大学 航空通信网络研究室
*
* @file
* @author 姜阳 (j824544269@gmail.com)
* @date 2017-07
* @brief 建立tcp连接并传递数据信息
* @version 0.0.1
*
* Last Modified: 2017-12-12
* Modified By: 姜阳 (j824544269@gmail.com)
*
* @example qa_tcp_client.cc
*
*/
#ifndef _TCP_CLIENT_H_
#define _TCP_CLIENT_H_
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
namespace an
{
namespace core
{
/**
* @brief TCP客户端
* @todo 心跳保持连接
*
*/
class TCPClient
{
public:
/**
* @brief 构造函数
*
* @param[in] dest_ip 目标IP地址
* @param[in] dest_port 目标端口
*
*/
TCPClient(const char *dest_ip,
const int dest_port);
/**
* @brief 析构函数
*
* 关闭套接字
*
*/
~TCPClient();
/**
* @brief 发送数据信息
*
* @param[in] input_buffer 输入缓存
* @return 发送状态
* @retval 0 发送成功
* @retval -1 发送失败,打印错误信息
*
*/
int write(const char *input_buffer);
/**
* @brief 发送数据信息
*
* @param[in] input_buffer 输入缓存
* @param[in] input_buffer_size 输入缓存大小
* @return 发送状态
* @retval 0 发送成功
* @retval -1 发送失败,打印错误信息
*
*/
int write(const char *input_buffer,
const int input_buffer_size);
/**
* @brief 连接状态
*
* 检测连接状态
*
* @retval true 已连接
* @retval false 未连接
*
*/
bool is_connected();
private:
/**
* @brief 尝试连接
*
* @return 连接状态
* @retval 0 成功
* @retval -1 连接失败
*
*/
int try_to_connect();
/// 套接字
int _socket;
/// 错误代码
int _err;
/// 目标ip
const char *_dest_ip;
/// 目标端口
const int _dest_port;
/// 服务端地址
struct sockaddr_in _server_addr;
/// 是否连接
bool _IS_CONNECTED;
/// 用以检测套接字创建是否成功
bool _SOCKET_CREATED;
};
}
}
#endif // !_TCP_CLIENT_H_ |
21d7b20d179ac338735650dc081205d8c223cd5a | 88c03118312f57680557755aac1cf9a6b4e2fc6f | /core/src/db/engine/ExecutionEngine.h | 4c24ce07559f787c474ee32bb6b1d8425724d289 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"Zlib",
"LGPL-2.1-only",
"BSD-3-Clause",
"JSON",
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | XuPeng-SH/milvus | a0f500678b2b540baff8e1483635ec2e4525fda6 | 8fd17fe6f7d44952e297c68dbfa381f6af992bb3 | refs/heads/master | 2022-03-09T05:07:54.042309 | 2020-11-16T03:41:33 | 2020-11-16T03:41:33 | 215,312,877 | 1 | 0 | Apache-2.0 | 2020-06-01T09:04:54 | 2019-10-15T13:59:32 | C++ | UTF-8 | C++ | false | false | 1,554 | h | ExecutionEngine.h | // Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "db/Types.h"
#include "query/GeneralQuery.h"
#include "utils/Status.h"
namespace milvus {
namespace engine {
using TargetFields = std::set<std::string>;
struct ExecutionEngineContext {
query::QueryPtr query_ptr_;
QueryResultPtr query_result_;
TargetFields target_fields_; // for build index task, which field should be build
};
using ExecutionEngineContextPtr = std::shared_ptr<ExecutionEngineContext>;
class ExecutionEngine {
public:
virtual Status
Load(ExecutionEngineContext& context) = 0;
virtual Status
CopyToGpu(uint64_t device_id) = 0;
virtual Status
Search(ExecutionEngineContext& context) = 0;
virtual Status
BuildIndex(uint64_t device_id) = 0;
};
using ExecutionEnginePtr = std::shared_ptr<ExecutionEngine>;
} // namespace engine
} // namespace milvus
|
74c5f2f72cc4186dd14c1e007724bf5bd6e861ea | 1ab4c2857862bb9c0ea6f9f5d727600b04f004a9 | /oskachkov/operators/shared_ptr.h | 0251050856b42ce6df94fd83296d57e88148cfab | [] | no_license | askachkov/learncpp | 17e3b50979b39ad1993698ac9fe98a57b68699f8 | ecb990309133a44b757757d4e778071364af8cc1 | refs/heads/master | 2020-07-06T10:55:05.176771 | 2019-12-13T17:18:02 | 2019-12-13T17:18:02 | 202,993,202 | 0 | 2 | null | 2019-09-09T11:59:54 | 2019-08-18T11:13:46 | C++ | UTF-8 | C++ | false | false | 1,156 | h | shared_ptr.h | #ifndef SHARED_PTR
#define SHARED_PTR
#include "weak_ptr.h"
template<typename T>
class SharedPtr: public WeakPtr<T>
{
union {
int & m_ShRefCounter;
int * m_pShRefCounter;
};
bool m_IsArray;
public:
SharedPtr(T * ptr = 0, bool isArray = false):
WeakPtr(new T*(ptr), new int(1)),
m_pShRefCounter(new int(1)),
m_IsArray(isArray)
{
}
SharedPtr(const SharedPtr & o):
WeakPtr(o),
m_pShRefCounter(o.m_pShRefCounter),
m_IsArray(o.m_IsArray)
{
m_ShRefCounter++;
}
SharedPtr& operator=(const SharedPtr & o)
{
free();
WeakPtr::operator =(o);
m_pShRefCounter = o.m_pShRefCounter;
m_ShRefCounter++;
m_IsArray = o.m_IsArray;
return *this;
}
~SharedPtr()
{
free();
}
void free()
{
if ( m_Ptr && *m_Ptr && --m_ShRefCounter == 0 ){
delete m_pShRefCounter;
if ( m_IsArray ){
delete[] *m_Ptr;
}else{
delete *m_Ptr;
}
*m_Ptr = 0;
}
}
};
#endif // SHARED_PTR
|
1038d9ea4863aa1988843e0b174a2cf3d390fe26 | 1f49df904649fd99e2c63a53c73ba3d56541d71c | /src/fasta/faidx.cc | 8aabeb9230fdcee5bd2053f179302a40092650b5 | [
"GPL-3.0-or-later",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"Zlib",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"bzip2-1.0.6",
"LicenseRef-scancode-proprietary-lic... | permissive | sakkayaphab/bolt | 6cec7e693d4cbc29f748ffb76c35772abb0b2574 | 75cfd6fdb7399e141e93008c5382ae23bc99d90d | refs/heads/master | 2020-06-30T04:11:54.775819 | 2020-02-11T23:26:39 | 2020-02-11T23:26:39 | 139,722,229 | 1 | 0 | MIT | 2018-07-26T11:48:02 | 2018-07-04T12:56:20 | Go | UTF-8 | C++ | false | false | 4,459 | cc | faidx.cc | #include "faidx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <math.h>
Faidx::Faidx()
{
}
void Faidx::initialize()
{
std::ifstream file(indexfilepath);
std::string line;
while (std::getline(file, line))
{
std::istringstream iss(line);
std::string token;
FileFormat fftoken;
int i = 0;
while (std::getline(iss, token, '\t'))
{
if (i == 0)
{
fftoken.NAME = token;
}
else if (i == 1)
{
fftoken.LENGTH = strtoll(token.c_str(), NULL, 10);
}
else if (i == 2)
{
fftoken.OFFSET = strtoll(token.c_str(), NULL, 10);
}
else if (i == 3)
{
fftoken.LINEBASES = strtoll(token.c_str(), NULL, 10);
}
else if (i == 4)
{
fftoken.LINEWIDTH = strtoll(token.c_str(), NULL, 10);
faidxlist.push_back(fftoken);
}
else
{
std::cerr << "fasta index error because it has tab more than normal" << std::endl;
exit(1);
}
i++;
}
}
}
bool Faidx::hasChromosomeName(std::string chr)
{
for (int i = 0; i < faidxlist.size(); i++)
{
if (faidxlist.at(i).NAME == chr)
{
return true;
}
}
return false;
}
int64_t Faidx::getLengthbyChromosome(std::string chr)
{
for (int i = 0; i < faidxlist.size(); i++)
{
if (faidxlist.at(i).NAME == chr)
{
return faidxlist.at(i).LENGTH;
}
}
return 0;
}
int64_t Faidx::getOffsetbyChromosome(std::string chr)
{
for (int i = 0; i < faidxlist.size(); i++)
{
if (faidxlist.at(i).NAME == chr)
{
return faidxlist.at(i).OFFSET;
}
}
return 0;
}
int64_t Faidx::getLinebasesbyChromosome(std::string chr)
{
for (int i = 0; i < faidxlist.size(); i++)
{
if (faidxlist.at(i).NAME == chr)
{
return faidxlist.at(i).LINEBASES;
}
}
return 0;
}
int64_t Faidx::getLinewidthbyChromosome(std::string chr)
{
for (int i = 0; i < faidxlist.size(); i++)
{
if (faidxlist.at(i).NAME == chr)
{
return faidxlist.at(i).LINEWIDTH;
}
}
return 0;
}
int64_t Faidx::getQualoffsetbyChromosome(std::string chr)
{
for (int i = 0; i < faidxlist.size(); i++)
{
if (faidxlist.at(i).NAME == chr)
{
return faidxlist.at(i).QUALOFFSET;
}
}
return 0;
}
void Faidx::setIndexFilePath(std::string t_indexfilepath)
{
indexfilepath = t_indexfilepath;
}
std::string Faidx::getIndexFilePath()
{
return indexfilepath;
}
int64_t Faidx::getApproximateLineStart(std::string chromosome, int64_t start)
{
return floor(start / getLinebasesbyChromosome(chromosome));
}
int64_t Faidx::getApproximateLineEnd(std::string chromosome, int64_t end)
{
return ceil(end / getLinebasesbyChromosome(chromosome)) + 1;
}
int64_t Faidx::getApproximateOffsetStart(std::string chromosome, int64_t start)
{
int64_t apppointstart = getApproximateLineStart(chromosome, start);
int64_t diff = start - apppointstart * getLinebasesbyChromosome(chromosome);
return apppointstart * getLinewidthbyChromosome(chromosome) + diff;
}
int64_t Faidx::getApproximateOffsetEnd(std::string chromosome, int64_t end)
{
int64_t apppointend = getApproximateLineEnd(chromosome, end);
int64_t diff = apppointend * getLinebasesbyChromosome(chromosome) - end;
return (apppointend * getLinewidthbyChromosome(chromosome) - 1) - diff;
}
int64_t Faidx::getOffsetEndByPosition(std::string chromosome, int64_t end)
{
if (!hasChromosomeName(chromosome))
{
std::cout << "not found this chromosome : " << chromosome << std::endl;
}
int64_t startoffset = getOffsetbyChromosome(chromosome);
return startoffset + getApproximateOffsetEnd(chromosome, end);
}
int64_t Faidx::getOffsetStartByPosition(std::string chromosome, int64_t start)
{
if (!hasChromosomeName(chromosome))
{
std::cout << "not found this chromosome : " << chromosome << std::endl;
}
int64_t startoffset = getOffsetbyChromosome(chromosome);
return startoffset + getApproximateOffsetStart(chromosome, start);
} |
8f12cd1e3455c51bdc7bd36622c19623335cd191 | 14166b68775d4758460fb5ea2184e20cf1f20bf8 | /facebz/KjjDlg.h | cea008c54b56475c3a386db34e1fa0b0c5f5b178 | [] | no_license | miluof/wisdomlabel | 2c1a73e4e6649dadfcc974543cdd6ec1ab99a3df | c41a021fd96ccaadbd06fc7b326232f627a1c63c | refs/heads/main | 2023-02-25T23:55:01.422015 | 2021-01-26T10:47:15 | 2021-01-26T10:47:15 | 332,964,242 | 4 | 0 | null | null | null | null | GB18030 | C++ | false | false | 762 | h | KjjDlg.h | #pragma once
#include "afxcmn.h"
#include <map>
using namespace std;
// CKjjDlg 对话框
struct Kjj{
CStringA Cmd;
CStringA Title;
int Id;
CStringA KjjJs;
Kjj(){
};
Kjj(CStringA cmd,CStringA title,int id){
Cmd=cmd;
Title=title;
Id =id;
};
Kjj(CStringA cmd,CStringA title,int id,CStringA js){
Cmd=cmd;
Title=title;
Id =id;
KjjJs=js;
};
};
class CKjjDlg : public CDialogEx
{
DECLARE_DYNAMIC(CKjjDlg)
public:
CKjjDlg(CWnd* pParent = NULL); // 标准构造函数
virtual ~CKjjDlg();
// 对话框数据
enum { IDD = IDD_KJJDLG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
CListCtrl m_KjjListCtrl;
map<CStringA,Kjj>*m_KjjMap;
virtual BOOL OnInitDialog();
};
|
57aac1bee79d76c848ecc10771a56de949acfba0 | 006331088d86048cdfa7c4d13882b3038df2f7c9 | /src/Encrypt.cpp | 09f8589e0464104cd4f6d257df6f25099082c79d | [
"Apache-2.0"
] | permissive | miniwing/libsecurity | 850a3bbd169205e2d9064c72ad2317de237c4796 | 749a1dc4a1115af4d24ab4dfa9245fdc73e1dae0 | refs/heads/master | 2022-04-11T04:29:16.850912 | 2020-02-02T09:43:11 | 2020-02-02T09:43:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | cpp | Encrypt.cpp | #include "security.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
int main(int argc, char *argv[])
{
const char* pInData = argv[1];
uint32_t nInLen = strlen(pInData);
char* pOut;
uint32_t nOutLen;
EncryptMsg(pInData, nInLen, &pOut, nOutLen);
//cout<<pOut;
printf("%s", pOut);
Free(pOut);
return 0;
} |
8522cc7da1e569d634a40702a226d273c3a12e66 | b70a87140882a37d0f0841dc0ec461f759373e5a | /src/core/tests/vector_tests.cpp | 6f450866c5c4f20fddc953e77ab3a681bc9275b9 | [
"Zlib",
"BSD-2-Clause",
"MIT"
] | permissive | corefan/Engine-1 | d775413321ff4fd31f4f7cd4ce56f438539ee9a9 | 9ade300d24c740fdad4d87451de2f7a61fc821ee | refs/heads/master | 2021-01-19T19:01:51.876471 | 2017-07-13T12:48:20 | 2017-07-13T12:48:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,171 | cpp | vector_tests.cpp | #include "core/array.h"
#include "core/vector.h"
#include "catch.hpp"
using namespace Core;
namespace
{
struct CtorDtorTest
{
static i32 numAllocs_;
CtorDtorTest(i32 value = -1)
: value_(value)
{
numAllocs_++;
}
CtorDtorTest(const CtorDtorTest& other)
: value_(other.value_)
{
numAllocs_++;
}
CtorDtorTest(CtorDtorTest&& other)
{
using std::swap;
swap(other.value_, value_);
numAllocs_++;
}
~CtorDtorTest()
{
--numAllocs_;
value_ = -2;
}
CtorDtorTest& operator=(CtorDtorTest&& other)
{
using std::swap;
swap(other.value_, value_);
return *this;
}
operator i32() const { return value_; }
i32 value_ = -1;
};
i32 CtorDtorTest::numAllocs_ = 0;
struct AllocatorTest : public Core::Allocator
{
static i32 numBytes_;
void* allocate(index_type count, index_type size)
{
numBytes_ += count * size;
return Core::Allocator::allocate(count, size);
}
void deallocate(void* mem, index_type count, index_type size)
{
numBytes_ -= count * size;
Core::Allocator::deallocate(mem, count, size);
}
};
i32 AllocatorTest::numBytes_ = 0;
typedef i32 index_type;
template<typename TYPE, index_type ARRAY_SIZE>
void VectorTestSize()
{
Vector<TYPE> TestArray;
REQUIRE(TestArray.size() == 0);
REQUIRE(TestArray.capacity() >= TestArray.size());
TestArray.resize(ARRAY_SIZE);
REQUIRE(TestArray.size() == ARRAY_SIZE);
REQUIRE(TestArray.capacity() >= TestArray.size());
}
template<typename TYPE, index_type ARRAY_SIZE>
void VectorTestFill(TYPE(IdxToVal)(index_type))
{
Vector<TYPE> TestArray;
TestArray.resize(ARRAY_SIZE);
bool Success = true;
const index_type FILL_VAL = 123;
TestArray.fill(IdxToVal(FILL_VAL));
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
Success &= (TestArray[Idx] == IdxToVal(FILL_VAL));
REQUIRE(Success);
}
template<typename TYPE, index_type ARRAY_SIZE>
void VectorTestPushBack(TYPE(IdxToVal)(index_type))
{
Vector<TYPE> TestArray;
bool Success = true;
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
TestArray.push_back(IdxToVal(Idx));
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
Success &= (TestArray[Idx] == IdxToVal(Idx));
REQUIRE(Success);
}
template<typename TYPE, index_type ARRAY_SIZE>
void VectorTestPushBackReserve(TYPE(IdxToVal)(index_type))
{
Vector<TYPE> TestArray;
TestArray.reserve(ARRAY_SIZE);
REQUIRE(TestArray.capacity() >= ARRAY_SIZE);
bool Success = true;
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
TestArray.push_back(IdxToVal(Idx));
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
Success &= (TestArray[Idx] == IdxToVal(Idx));
REQUIRE(Success);
}
template<typename TYPE, index_type ARRAY_SIZE>
void VectorTestOperatorAssignment(TYPE(IdxToVal)(index_type))
{
Vector<TYPE> TestArray;
TestArray.resize(ARRAY_SIZE);
bool Success = true;
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
TestArray[Idx] = IdxToVal(Idx);
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
Success &= (TestArray[Idx] == IdxToVal(Idx));
REQUIRE(Success);
}
template<typename TYPE, index_type ARRAY_SIZE>
void VectorTestCopy(TYPE(IdxToVal)(index_type))
{
Vector<TYPE> TestArray;
Vector<TYPE> TestArray2;
TestArray.resize(ARRAY_SIZE);
bool Success = true;
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
TestArray[Idx] = IdxToVal(Idx);
TestArray2 = TestArray;
REQUIRE(TestArray.size() == ARRAY_SIZE);
REQUIRE(TestArray2.size() == ARRAY_SIZE);
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
Success &= (TestArray2[Idx] == IdxToVal(Idx));
REQUIRE(Success);
}
template<typename TYPE, index_type ARRAY_SIZE>
void VectorTestMove(TYPE(IdxToVal)(index_type))
{
Vector<TYPE> TestArray;
Vector<TYPE> TestArray2;
TestArray.resize(ARRAY_SIZE);
bool Success = true;
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
TestArray[Idx] = IdxToVal(Idx);
TestArray2 = std::move(TestArray);
REQUIRE(TestArray.size() == 0);
REQUIRE(TestArray2.size() == ARRAY_SIZE);
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
Success &= (TestArray2[Idx] == IdxToVal(Idx));
REQUIRE(Success);
}
template<typename TYPE, index_type ARRAY_SIZE>
void VectorTestDataAssignment(TYPE(IdxToVal)(index_type))
{
Vector<TYPE> TestArray;
TestArray.resize(ARRAY_SIZE);
bool Success = true;
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
TestArray.data()[Idx] = IdxToVal(Idx);
for(index_type Idx = 0; Idx < ARRAY_SIZE; ++Idx)
Success &= (TestArray[Idx] == IdxToVal(Idx));
REQUIRE(Success);
}
template<typename TYPE, index_type ARRAY_SIZE>
void VectorTestIteratorAssignment(TYPE(IdxToVal)(index_type))
{
Vector<TYPE> TestArray;
TestArray.resize(ARRAY_SIZE);
bool Success = true;
index_type Idx = 0;
for(auto& It : TestArray)
It = IdxToVal(Idx++);
for(Idx = 0; Idx < ARRAY_SIZE; ++Idx)
Success &= (TestArray[Idx] == IdxToVal(Idx));
REQUIRE(Success);
}
template<typename TYPE, index_type ARRAY_SIZE>
void VectorTestShrinkToFit(TYPE(IdxToVal)(index_type))
{
Vector<TYPE> TestArray;
TestArray.resize(ARRAY_SIZE);
TestArray.push_back(TYPE());
TestArray.shrink_to_fit();
REQUIRE(TestArray.size() == TestArray.capacity());
}
template<typename TYPE, index_type ARRAY_SIZE>
void VectorTestErase(TYPE(IdxToVal)(index_type))
{
Vector<TYPE> TestArray;
// Erase from beginning.
{
TestArray.resize(ARRAY_SIZE);
index_type Idx = 0;
for(auto& It : TestArray)
It = IdxToVal(Idx++);
auto It = TestArray.begin();
Idx = 0;
bool Success = true;
while(It != TestArray.end())
{
Success &= (TestArray[0] == IdxToVal(Idx));
Success &= (*It == IdxToVal(Idx));
It = TestArray.erase(It);
++Idx;
}
REQUIRE(Success);
}
// Erase from end.
{
TestArray.resize(ARRAY_SIZE);
index_type Idx = 0;
for(auto& It : TestArray)
It = IdxToVal(Idx++);
Idx = TestArray.size() - 1;
auto It = TestArray.begin() + Idx;
bool Success = true;
Success &= (TestArray.back() == IdxToVal(Idx));
Success &= (*It == IdxToVal(Idx));
It = TestArray.erase(It);
Success &= It == TestArray.end();
REQUIRE(Success);
}
// Erase from middle.
{
TestArray.resize(ARRAY_SIZE);
index_type Idx = 0;
for(auto& It : TestArray)
It = IdxToVal(Idx++);
Idx = TestArray.size() / 2;
auto It = TestArray.begin() + Idx;
bool Success = true;
while(It != TestArray.end())
{
Success &= (*It == IdxToVal(Idx));
It = TestArray.erase(It);
++Idx;
}
REQUIRE(Success);
}
}
index_type IdxToVal_index_type(index_type Idx) { return Idx; }
std::string IdxToVal_string(index_type Idx)
{
char Buffer[1024] = {0};
sprintf_s(Buffer, sizeof(Buffer), "%u", (int)Idx);
return Buffer;
}
}
TEST_CASE("vector-tests-size")
{
VectorTestSize<index_type, 0x1>();
VectorTestSize<index_type, 0x2>();
VectorTestSize<index_type, 0xff>();
VectorTestSize<index_type, 0x100>();
VectorTestSize<index_type, 0xffff>();
VectorTestSize<index_type, 0x10000>();
}
TEST_CASE("vector-tests-fill")
{
SECTION("trivial")
{
VectorTestFill<index_type, 0x1>(IdxToVal_index_type);
VectorTestFill<index_type, 0x2>(IdxToVal_index_type);
VectorTestFill<index_type, 0xff>(IdxToVal_index_type);
VectorTestFill<index_type, 0x100>(IdxToVal_index_type);
}
SECTION("non-trivial")
{
VectorTestFill<std::string, 0x1>(IdxToVal_string);
VectorTestFill<std::string, 0x2>(IdxToVal_string);
VectorTestFill<std::string, 0xff>(IdxToVal_string);
VectorTestFill<std::string, 0x100>(IdxToVal_string);
}
}
TEST_CASE("vector-tests-push-back")
{
SECTION("trivial")
{
VectorTestPushBack<index_type, 0x1>(IdxToVal_index_type);
VectorTestPushBack<index_type, 0x2>(IdxToVal_index_type);
VectorTestPushBack<index_type, 0xff>(IdxToVal_index_type);
VectorTestPushBack<index_type, 0x100>(IdxToVal_index_type);
}
SECTION("non-trivial")
{
VectorTestPushBack<std::string, 0x1>(IdxToVal_string);
VectorTestPushBack<std::string, 0x2>(IdxToVal_string);
VectorTestPushBack<std::string, 0xff>(IdxToVal_string);
VectorTestOperatorAssignment<std::string, 0x100>(IdxToVal_string);
}
}
TEST_CASE("vector-tests-emplace-back")
{
SECTION("trivial")
{
Core::Vector<i32> vec;
vec.emplace_back(0);
vec.emplace_back(1);
vec.emplace_back(2);
REQUIRE(vec[0] == 0);
REQUIRE(vec[1] == 1);
REQUIRE(vec[2] == 2);
}
SECTION("trivial-params")
{
struct TestType
{
TestType() = default;
TestType(int a, int b)
: a_(a)
, b_(b)
{
}
bool operator==(const TestType& other) { return a_ == other.a_ && b_ == other.b_; }
int a_ = 0;
int b_ = 0;
};
Core::Vector<TestType> vec;
vec.emplace_back(0, 1);
vec.emplace_back(1, 2);
vec.emplace_back(2, 4);
REQUIRE(vec[0] == TestType(0, 1));
REQUIRE(vec[1] == TestType(1, 2));
REQUIRE(vec[2] == TestType(2, 4));
}
SECTION("non-trivial")
{
Core::Vector<std::string> vec;
vec.emplace_back("0");
vec.emplace_back("1");
vec.emplace_back("2");
REQUIRE(vec[0] == "0");
REQUIRE(vec[1] == "1");
REQUIRE(vec[2] == "2");
}
}
TEST_CASE("vector-tests-push-back-reserve")
{
SECTION("trivial")
{
VectorTestPushBackReserve<index_type, 0x1>(IdxToVal_index_type);
VectorTestPushBackReserve<index_type, 0x2>(IdxToVal_index_type);
VectorTestPushBackReserve<index_type, 0xff>(IdxToVal_index_type);
VectorTestPushBackReserve<index_type, 0x100>(IdxToVal_index_type);
}
SECTION("non-trivial")
{
VectorTestPushBackReserve<std::string, 0x1>(IdxToVal_string);
VectorTestPushBackReserve<std::string, 0x2>(IdxToVal_string);
VectorTestPushBackReserve<std::string, 0xff>(IdxToVal_string);
VectorTestPushBackReserve<std::string, 0x100>(IdxToVal_string);
}
}
TEST_CASE("vector-tests-operator-assignment")
{
SECTION("trivial")
{
VectorTestOperatorAssignment<index_type, 0x1>(IdxToVal_index_type);
VectorTestOperatorAssignment<index_type, 0x2>(IdxToVal_index_type);
VectorTestOperatorAssignment<index_type, 0xff>(IdxToVal_index_type);
VectorTestOperatorAssignment<index_type, 0x100>(IdxToVal_index_type);
}
SECTION("non-trivial")
{
VectorTestOperatorAssignment<std::string, 0x1>(IdxToVal_string);
VectorTestOperatorAssignment<std::string, 0x2>(IdxToVal_string);
VectorTestOperatorAssignment<std::string, 0xff>(IdxToVal_string);
VectorTestOperatorAssignment<std::string, 0x100>(IdxToVal_string);
}
}
TEST_CASE("vector-tests-copy")
{
SECTION("trivial")
{
VectorTestCopy<index_type, 0x1>(IdxToVal_index_type);
VectorTestCopy<index_type, 0x2>(IdxToVal_index_type);
VectorTestCopy<index_type, 0xff>(IdxToVal_index_type);
VectorTestCopy<index_type, 0x100>(IdxToVal_index_type);
}
SECTION("non-trivial")
{
VectorTestCopy<std::string, 0x1>(IdxToVal_string);
VectorTestCopy<std::string, 0x2>(IdxToVal_string);
VectorTestCopy<std::string, 0xff>(IdxToVal_string);
VectorTestCopy<std::string, 0x100>(IdxToVal_string);
}
}
TEST_CASE("vector-tests-move")
{
SECTION("trivial")
{
VectorTestMove<index_type, 0x1>(IdxToVal_index_type);
VectorTestMove<index_type, 0x2>(IdxToVal_index_type);
VectorTestMove<index_type, 0xff>(IdxToVal_index_type);
VectorTestMove<index_type, 0x100>(IdxToVal_index_type);
}
SECTION("non-trivial")
{
VectorTestMove<std::string, 0x1>(IdxToVal_string);
VectorTestMove<std::string, 0x2>(IdxToVal_string);
VectorTestMove<std::string, 0xff>(IdxToVal_string);
VectorTestMove<std::string, 0x100>(IdxToVal_string);
}
}
TEST_CASE("vector-tests-data-assignment")
{
SECTION("trivial")
{
VectorTestDataAssignment<index_type, 0x1>(IdxToVal_index_type);
VectorTestDataAssignment<index_type, 0x2>(IdxToVal_index_type);
VectorTestDataAssignment<index_type, 0xff>(IdxToVal_index_type);
VectorTestDataAssignment<index_type, 0x100>(IdxToVal_index_type);
}
SECTION("non-trivial")
{
VectorTestDataAssignment<std::string, 0x1>(IdxToVal_string);
VectorTestDataAssignment<std::string, 0x2>(IdxToVal_string);
VectorTestDataAssignment<std::string, 0xff>(IdxToVal_string);
VectorTestDataAssignment<std::string, 0x100>(IdxToVal_string);
}
}
TEST_CASE("vector-tests-iterator-assignment")
{
SECTION("trivial")
{
VectorTestIteratorAssignment<index_type, 0x1>(IdxToVal_index_type);
VectorTestIteratorAssignment<index_type, 0x2>(IdxToVal_index_type);
VectorTestIteratorAssignment<index_type, 0xff>(IdxToVal_index_type);
VectorTestIteratorAssignment<index_type, 0x100>(IdxToVal_index_type);
}
SECTION("non-trivial")
{
VectorTestIteratorAssignment<std::string, 0x1>(IdxToVal_string);
VectorTestIteratorAssignment<std::string, 0x2>(IdxToVal_string);
VectorTestIteratorAssignment<std::string, 0xff>(IdxToVal_string);
VectorTestIteratorAssignment<std::string, 0x100>(IdxToVal_string);
}
}
TEST_CASE("vector-tests-erase")
{
SECTION("trivial")
{
VectorTestErase<index_type, 0x1>(IdxToVal_index_type);
VectorTestErase<index_type, 0x2>(IdxToVal_index_type);
VectorTestErase<index_type, 0xff>(IdxToVal_index_type);
VectorTestErase<index_type, 0x100>(IdxToVal_index_type);
}
SECTION("non-trivial")
{
VectorTestErase<std::string, 0x1>(IdxToVal_string);
VectorTestErase<std::string, 0x2>(IdxToVal_string);
VectorTestErase<std::string, 0xff>(IdxToVal_string);
VectorTestErase<std::string, 0x100>(IdxToVal_string);
}
}
TEST_CASE("vector-tests-ctor-dtor-test")
{
using TestVector = Core::Vector<CtorDtorTest>;
SECTION("resize")
{
{
TestVector vec;
vec.resize(1);
REQUIRE(CtorDtorTest::numAllocs_ == 1);
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
{
TestVector vec;
vec.resize(100);
REQUIRE(CtorDtorTest::numAllocs_ == 100);
vec.resize(200);
REQUIRE(CtorDtorTest::numAllocs_ == 200);
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
{
TestVector vec;
vec.resize(200);
REQUIRE(CtorDtorTest::numAllocs_ == 200);
vec.resize(100);
REQUIRE(CtorDtorTest::numAllocs_ == 100);
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
}
SECTION("copy")
{
{
TestVector vec;
vec.resize(100);
REQUIRE(CtorDtorTest::numAllocs_ == 100);
TestVector vec2;
vec2 = vec;
REQUIRE(CtorDtorTest::numAllocs_ == 200);
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
}
SECTION("push_back")
{
{
TestVector vec;
for(i32 i = 0; i < 1; ++i)
{
vec.push_back(i);
REQUIRE(CtorDtorTest::numAllocs_ == i + 1);
}
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
{
TestVector vec;
for(i32 i = 0; i < 100; ++i)
{
vec.push_back(i);
REQUIRE(CtorDtorTest::numAllocs_ == i + 1);
}
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
{
TestVector vec;
for(i32 i = 0; i < 200; ++i)
{
vec.push_back(i);
REQUIRE(CtorDtorTest::numAllocs_ == i + 1);
}
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
}
SECTION("emplace_back")
{
{
TestVector vec;
for(i32 i = 0; i < 1; ++i)
{
vec.emplace_back(i);
REQUIRE(CtorDtorTest::numAllocs_ == i + 1);
}
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
{
TestVector vec;
for(i32 i = 0; i < 100; ++i)
{
vec.emplace_back(i);
REQUIRE(CtorDtorTest::numAllocs_ == i + 1);
}
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
{
TestVector vec;
for(i32 i = 0; i < 200; ++i)
{
vec.emplace_back(i);
REQUIRE(CtorDtorTest::numAllocs_ == i + 1);
}
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
}
SECTION("erase")
{
{
TestVector vec;
vec.emplace_back(0);
REQUIRE(CtorDtorTest::numAllocs_ == 1);
vec.emplace_back(1);
REQUIRE(CtorDtorTest::numAllocs_ == 2);
vec.emplace_back(2);
REQUIRE(CtorDtorTest::numAllocs_ == 3);
REQUIRE(vec[0] == 0);
REQUIRE(vec[1] == 1);
REQUIRE(vec[2] == 2);
vec.erase(vec.begin() + 1);
REQUIRE(CtorDtorTest::numAllocs_ == 2);
REQUIRE(vec[0] == 0);
REQUIRE(vec[1] == 2);
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
}
SECTION("fill")
{
{
TestVector vec;
vec.resize(100);
REQUIRE(CtorDtorTest::numAllocs_ == 100);
vec.fill(10);
REQUIRE(CtorDtorTest::numAllocs_ == 100);
}
REQUIRE(CtorDtorTest::numAllocs_ == 0);
}
}
TEST_CASE("vector-tests-allocator-test")
{
using TestVector = Core::Vector<i32, AllocatorTest>;
SECTION("resize")
{
{
TestVector vec;
vec.resize(1);
REQUIRE(AllocatorTest::numBytes_ == sizeof(i32) * 1);
}
REQUIRE(AllocatorTest::numBytes_ == 0);
{
TestVector vec;
vec.resize(100);
REQUIRE(AllocatorTest::numBytes_ == sizeof(i32) * 100);
vec.resize(200);
REQUIRE(AllocatorTest::numBytes_ == sizeof(i32) * 200);
}
REQUIRE(AllocatorTest::numBytes_ == 0);
{
TestVector vec;
vec.resize(200);
REQUIRE(AllocatorTest::numBytes_ == sizeof(i32) * 200);
vec.resize(100);
REQUIRE(AllocatorTest::numBytes_ == sizeof(i32) * 100);
}
REQUIRE(AllocatorTest::numBytes_ == 0);
}
SECTION("copy")
{
{
TestVector vec;
vec.resize(100);
REQUIRE(AllocatorTest::numBytes_ == sizeof(i32) * 100);
TestVector vec2;
vec2 = vec;
REQUIRE(AllocatorTest::numBytes_ == sizeof(i32) * 200);
}
REQUIRE(AllocatorTest::numBytes_ == 0);
}
SECTION("push_back")
{
{
TestVector vec;
for(i32 i = 0; i < 1; ++i)
{
vec.push_back(i);
REQUIRE(AllocatorTest::numBytes_ >= sizeof(i32) * (i + 1));
}
}
REQUIRE(AllocatorTest::numBytes_ == 0);
{
TestVector vec;
for(i32 i = 0; i < 100; ++i)
{
vec.push_back(i);
REQUIRE(AllocatorTest::numBytes_ >= sizeof(i32) * (i + 1));
}
}
REQUIRE(AllocatorTest::numBytes_ == 0);
{
TestVector vec;
for(i32 i = 0; i < 200; ++i)
{
vec.push_back(i);
REQUIRE(AllocatorTest::numBytes_ >= sizeof(i32) * (i + 1));
}
}
REQUIRE(AllocatorTest::numBytes_ == 0);
}
SECTION("emplace_back")
{
{
TestVector vec;
for(i32 i = 0; i < 1; ++i)
{
vec.emplace_back(i);
REQUIRE(AllocatorTest::numBytes_ >= sizeof(i32) * (i + 1));
}
}
REQUIRE(AllocatorTest::numBytes_ == 0);
{
TestVector vec;
for(i32 i = 0; i < 100; ++i)
{
vec.emplace_back(i);
REQUIRE(AllocatorTest::numBytes_ >= sizeof(i32) * (i + 1));
}
}
REQUIRE(AllocatorTest::numBytes_ == 0);
{
TestVector vec;
for(i32 i = 0; i < 200; ++i)
{
vec.emplace_back(i);
REQUIRE(AllocatorTest::numBytes_ >= sizeof(i32) * (i + 1));
}
}
REQUIRE(AllocatorTest::numBytes_ == 0);
}
SECTION("erase")
{
{
TestVector vec;
vec.emplace_back(0);
REQUIRE(AllocatorTest::numBytes_ >= sizeof(i32) * 1);
vec.emplace_back(1);
REQUIRE(AllocatorTest::numBytes_ >= sizeof(i32) * 2);
vec.emplace_back(2);
REQUIRE(AllocatorTest::numBytes_ >= sizeof(i32) * 3);
auto totalBytes = AllocatorTest::numBytes_;
REQUIRE(vec[0] == 0);
REQUIRE(vec[1] == 1);
REQUIRE(vec[2] == 2);
vec.erase(vec.begin() + 1);
REQUIRE(AllocatorTest::numBytes_ == totalBytes);
REQUIRE(vec[0] == 0);
REQUIRE(vec[1] == 2);
}
REQUIRE(AllocatorTest::numBytes_ == 0);
}
SECTION("fill")
{
{
TestVector vec;
vec.resize(100);
REQUIRE(AllocatorTest::numBytes_ == sizeof(i32) * 100);
vec.fill(10);
REQUIRE(AllocatorTest::numBytes_ == sizeof(i32) * 100);
}
REQUIRE(AllocatorTest::numBytes_ == 0);
}
} |
47e85cccbab0a72e5b870833cdf7c519d58add3e | 471a26e50d685197ff46d2ec05ef3879f67f6b30 | /C++_Programming/1st_Term_Project_(Bank_System)/BankSystem(Dev_C++).cpp | 92c709574eb48f9058c755c6e63f8c3076fb6f98 | [] | no_license | Pipaolo/School_Stuff | ee3fb38e16387ffdc460aa0456b1c0f7acee2f9b | 8e55f5cd2d8d2830694a2939ccd928928cd12687 | refs/heads/master | 2021-06-14T15:40:55.144248 | 2019-08-30T00:54:17 | 2019-08-30T00:54:17 | 145,854,985 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,500 | cpp | BankSystem(Dev_C++).cpp | #include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <windows.h>
using namespace std;
void registerUser();
void loginUser();
int main() {
char input;
cout << "<--Welcome to Ctrl-Alt-Elite Banking Services-->" << endl;
Sleep(1000);
start:
system("cls");
cout << "------------------------------------------------" << endl;
cout << " MAIN MENU" << endl;
cout << "------------------------------------------------" << endl;
cout << "1. Login" << endl;
cout << "2. Register" << endl;
cout << "3. Exit" << endl;
cout << "Enter choice: ";
cin >> input;
switch (input)
{
case '1':
loginUser();
break;
case '2':
registerUser();
break;
case '3':
return 0;
default:
cerr << "Invalid Input. Please Try Again." << endl;
system("pause");
goto start;
break;
}
}
void deposit(string accHolder)
{
string accHolderLog = accHolder + ".log";
system("cls");
int deposit, prevBalance, finalBalance;
cout << "----------------------------" << endl;
cout << " DEPOSIT" << endl;
cout << "----------------------------" << endl;
cout << "Input desired amount to be deposited: ";
cin >> deposit;
int temp = deposit;
char accHolderChar[accHolder.size() + 1];
accHolder.copy(accHolderChar, accHolder.size() + 1);
accHolderChar[accHolder.size()] = '\0';
char accHolderLogChar[accHolderLog.size() + 1];
accHolderLog.copy(accHolderLogChar, accHolderLog.size() + 1);
accHolderLogChar[accHolderLog.size()] = '\0';
fstream bankAccount;
fstream logTransaction;
bankAccount.open(accHolderChar, ios::in | ios::out);
logTransaction.open(accHolderLogChar, ios::out | ios::app);
bankAccount >> prevBalance;
finalBalance = prevBalance + deposit;
bankAccount.clear();
bankAccount.seekp(0);
bankAccount.tellp();
bankAccount << finalBalance;
bankAccount.close();
logTransaction << "Deposit " << deposit << " " << prevBalance << " " << finalBalance << endl;
}
void withdraw(string accHolder)
{
system("cls");
string accHolderLog = accHolder + ".log";
int withdraw, finalBalance, prevBalance;
cout << "----------------------------" << endl;
cout << " WITHDRAW" << endl;
cout << "----------------------------" << endl;
cout << "Input desired amount to be withdrawn: ";
cin >> withdraw;
char accHolderChar[accHolder.size() + 1];
accHolder.copy(accHolderChar, accHolder.size() + 1);
accHolderChar[accHolder.size()] = '\0';
char accHolderLogChar[accHolderLog.size() + 1];
accHolderLog.copy(accHolderLogChar, accHolderLog.size() + 1);
accHolderLogChar[accHolderLog.size()] = '\0';
fstream bankAccount;
fstream logTransaction;
bankAccount.open(accHolderChar, ios::in | ios::out);
logTransaction.open(accHolderLogChar, ios::out | ios::app);
bankAccount >> prevBalance;
finalBalance = prevBalance - withdraw;
bankAccount.close();
bankAccount.open(accHolderChar, ios::out);
bankAccount << finalBalance;
bankAccount.close();
logTransaction << "Withdraw " << withdraw << " " << prevBalance << " " << finalBalance << endl;
}
void balance(string accHolder)
{
system("cls");
int balance;
cout << "--------------------------------------" << endl;
cout << " CHECK BALANCE" << endl;
cout << "--------------------------------------" << endl;
char accHolderChar[accHolder.size() + 1];
accHolder.copy(accHolderChar, accHolder.size() + 1);
accHolderChar[accHolder.size()] = '\0';
ifstream checkBalance;
checkBalance.open(accHolderChar);
checkBalance >> balance;
cout << "You currently have: " << balance << endl;
system("pause");
}
void transactions(string accHolder)
{
accHolder += ".log";
string transaction;
cout << "------------------------------------" << endl;
cout << " TRANSACTIONS" << endl;
cout << "------------------------------------" << endl;
cout << "Type " << "Amount " << "P.Balance " << "T.Balance" << endl;
char accHolderChar[accHolder.size() + 1];
accHolder.copy(accHolderChar, accHolder.size() + 1);
accHolderChar[accHolder.size()] = '\0';
ifstream logTransaction;
logTransaction.open(accHolderChar);
while(!logTransaction.eof())
{
getline(logTransaction, transaction);
cout << transaction << endl;
}
system("pause");
}
void bankMenu(string fullName)
{
start:
system("cls");
char input;
cout << "---------------------------------" << endl;
cout << " BANK MENU" << endl;
cout << "---------------------------------" << endl;
cout << "Welcome " << fullName << "!"<< endl;
cout << "1. Deposit" << endl;
cout << "2. Withdraw" << endl;
cout << "3. Balance" << endl;
cout << "4. Check Transactions" << endl;
cout << "5. Return to Main_Menu" << endl;
cout << "6. Exit" << endl;
cout << "What would you like to do? ";
cin >> input;
switch (input)
{
case '1':
deposit(fullName);
goto start;
break;
case '2':
withdraw(fullName);
goto start;
break;
case '3':
balance(fullName);
goto start;
break;
case '4':
transactions(fullName);
goto start;
break;
case '5':
main();
break;
case '6':
system("pause");
break;
default:
cerr << "Invalid choice. Please try again!" << endl;
system("pause");
break;
}
}
void duplicateCheck(string username)
{
string checkUsername;
ifstream data;
data.open("credentials.dat");
while(!data.eof())
{
data >> checkUsername;
if (checkUsername == username)
{
cout << "User already exists!" << endl;
system("pause");
main();
}
}
}
void registerUser()
{
string fullName, nameInput,passInput,passInputCheck;
int count;
start:
system("cls");
cout << "--------------------------------------" << endl;
cout << " Create Account" << endl;
cout << "--------------------------------------" << endl;
cout << "Enter Full Name: ";
if (cin.peek())
{
cin.ignore();
}
getline(cin, fullName);
cout << "Enter Username: ";
cin >> nameInput;
cout << "Enter Password: ";
cin >> passInput;
cout << "Re-enter Password: ";
cin >> passInputCheck;
cout << endl;
char fullNameChar[fullName.size() + 1];
fullName.copy(fullNameChar, fullName.size() + 1);
fullNameChar[fullName.size()] = '\0';
fstream data;
fstream accHolder;
data.open("credentials.dat", ios::out | ios::app);
duplicateCheck(nameInput);
// Initialize Password Check
if (passInput != passInputCheck)
{
cout << "Password is not the same!" << endl;
system("pause");
goto start;
}
else
{
accHolder.open(fullNameChar, ios::out);
}
if (data.is_open())
{
data << fullName << endl << nameInput << " " << passInput << endl;
accHolder << "0";
data.close();
accHolder.close();
cout << "You have been registered!!" << endl;
system("pause");
main();
}
}
void loginUser()
{
string fullName, nameInput, passInput, userPass, userPassCheck;
cout << "----------------------------------" << endl;
cout << " LOGIN" << endl;
cout << "----------------------------------" << endl;
cout << "Enter username: ";
cin >> nameInput;
cout << "Enter password: ";
cin >> passInput;
userPass = nameInput + " " + passInput;
fstream data;
data.open("credentials.dat");
if (!data.is_open())
{
cerr << "No existing users. Please create an account first." << endl;
system("pause");
main();
}
else
{
while(!data.eof())
{
getline(data, fullName);
getline(data, userPassCheck);
if (userPassCheck == userPass)
{
cout << "Login Success!!" << endl;
Sleep(1000);
bankMenu(fullName);
break;
}
}
}
}
|
f660c031592d97711b6d4b55553b15979277ca16 | d84c107e6da7e03b41382409987ae5d46b59bca2 | /source/game/Pvs.h | 4c990ef5bb0a502bd936d651e0ad5fcf00b67a71 | [
"MIT"
] | permissive | JasonHutton/QWTA | b3854cd4873a46a8a9089ee3481a47074b62236b | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | refs/heads/main | 2023-04-13T02:15:14.639793 | 2021-05-01T21:29:18 | 2021-05-01T21:29:18 | 363,500,974 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,277 | h | Pvs.h | // Copyright (C) 2004 Id Software, Inc.
//
#ifndef __GAME_PVS_H__
#define __GAME_PVS_H__
/*
===================================================================================
PVS
Note: mirrors and other special view portals are not taken into account
===================================================================================
*/
typedef struct pvsHandle_s {
int i; // index to current pvs
unsigned int h; // handle for current pvs
} pvsHandle_t;
typedef struct pvsCurrent_s {
pvsHandle_t handle; // current pvs handle
byte * pvs; // current pvs bit string
} pvsCurrent_t;
#define MAX_CURRENT_PVS 8 // must be a power of 2
typedef enum {
PVS_NORMAL = 0, // PVS through portals taking portal states into account
PVS_ALL_PORTALS_OPEN = 1, // PVS through portals assuming all portals are open
PVS_CONNECTED_AREAS = 2 // PVS considering all topologically connected areas visible
} pvsType_t;
class idPVS {
public:
idPVS( void );
~idPVS( void );
// setup for the current map
void Init( void );
void Shutdown( void );
// get the area(s) the source is in
int GetPVSArea( const idVec3 &point ) const; // returns the area number
int GetPVSAreas( const idBounds &bounds, int *areas, int maxAreas ) const; // returns number of areas
// setup current PVS for the source
pvsHandle_t SetupCurrentPVS( const idVec3 &source, const pvsType_t type = PVS_NORMAL ) const;
pvsHandle_t SetupCurrentPVS( const idBounds &source, const pvsType_t type = PVS_NORMAL ) const;
pvsHandle_t SetupCurrentPVS( const int sourceArea, const pvsType_t type = PVS_NORMAL ) const;
pvsHandle_t SetupCurrentPVS( const int *sourceAreas, const int numSourceAreas, const pvsType_t type = PVS_NORMAL ) const;
pvsHandle_t MergeCurrentPVS( pvsHandle_t pvs1, pvsHandle_t pvs2 ) const;
void FreeCurrentPVS( pvsHandle_t handle ) const;
// returns true if the target is within the current PVS
bool InCurrentPVS( const pvsHandle_t handle, const idVec3 &target ) const;
bool InCurrentPVS( const pvsHandle_t handle, const idBounds &target ) const;
bool InCurrentPVS( const pvsHandle_t handle, const int targetArea ) const;
bool InCurrentPVS( const pvsHandle_t handle, const int *targetAreas, int numTargetAreas ) const;
// draw all portals that are within the PVS of the source
void DrawPVS( const idVec3 &source, const pvsType_t type = PVS_NORMAL ) const;
void DrawPVS( const idBounds &source, const pvsType_t type = PVS_NORMAL ) const;
// visualize the PVS the handle points to
void DrawCurrentPVS( const pvsHandle_t handle, const idVec3 &source ) const;
#if ASYNC_WRITE_PVS
void WritePVS( const pvsHandle_t handle, idBitMsg &msg );
void ReadPVS( const pvsHandle_t handle, const idBitMsg &msg );
#endif
private:
int numAreas;
int numPortals;
bool * connectedAreas;
int * areaQueue;
byte * areaPVS;
// current PVS for a specific source possibly taking portal states (open/closed) into account
mutable pvsCurrent_t currentPVS[MAX_CURRENT_PVS];
// used to create PVS
int portalVisBytes;
int portalVisLongs;
int areaVisBytes;
int areaVisLongs;
struct pvsPortal_s *pvsPortals;
struct pvsArea_s * pvsAreas;
private:
int GetPortalCount( void ) const;
void CreatePVSData( void );
void DestroyPVSData( void );
void CopyPortalPVSToMightSee( void ) const;
void FloodFrontPortalPVS_r( struct pvsPortal_s *portal, int areaNum ) const;
void FrontPortalPVS( void ) const;
struct pvsStack_s * FloodPassagePVS_r( struct pvsPortal_s *source, const struct pvsPortal_s *portal, struct pvsStack_s *prevStack ) const;
void PassagePVS( void ) const;
void AddPassageBoundaries( const idWinding &source, const idWinding &pass, bool flipClip, idPlane *bounds, int &numBounds, int maxBounds ) const;
void CreatePassages( void ) const;
void DestroyPassages( void ) const;
int AreaPVSFromPortalPVS( void ) const;
void GetConnectedAreas( int srcArea, bool *connectedAreas ) const;
pvsHandle_t AllocCurrentPVS( unsigned int h ) const;
};
#endif /* !__GAME_PVS_H__ */
|
da9e3c6e428c297b7147ed256f654b64d39b01a6 | ae3e64bb51fe79b48b8a3a8577d7de4743c5c3bd | /hjscript.cpp | 43eeb7053bd9640f2c9282c19ca160666f425ff1 | [
"Apache-2.0"
] | permissive | ShuangyiTong/HuajiScript | 461e727a9c37ca958b92dae1beb6bbd1745970d6 | 9848cc269b8dfa679f0b7c63d1c8baf86564a0d9 | refs/heads/master | 2021-01-15T21:25:05.802252 | 2017-09-23T22:02:49 | 2017-09-23T22:02:49 | 99,865,254 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 140,619 | cpp | hjscript.cpp | #include "hjscript.hpp"
// Used by hjbase::HUAJISCRIPTBASE::Take_One_Token(std::vector<std::string>::const_iterator)
#define REQUIRE_MORE_TOKENS_RETURN_CODE -1
// Used by hjbase::HUAJISCRIPTBASE::Collect_Tokens(const std::string&)
#define REQUIRE_MORE_TOKENS_FOR_COMPLETE_COMMAND_RETURN_CODE 0
#define COMMAND_COMPLETED_RETURN_CODE 1
// Used by hjbase::HUAJISCRIPTBASE::Huaji_Command_Interpreter(const const_itVecStr&)
#define EXIT_RETURN_CODE 2
#define VALID_COMMAND_RETURN_CODE 1
#define INVALID_COMMAND_RETURN_CODE 0
#define UNKNOWN_COMMAND_RETURN_CODE -1
// Used by hjbase::LISTFORMATTER::Take_One_Char(char)
#define FORMATTING_COMPLETE 1
#define REQUIRE_MORE_CHAR_FOR_COMPLETE_LST 0
#define TYPE_DOUBLE 0
#define TYPE_LONG 1
#define INCREASE_AST_DEPTH 1
#define DECREASE_AST_DEPTH -1
using namespace hjbase::cnt::keywords;
using namespace hjbase::cnt::operators;
using namespace hjbase::cnt::common_msgs;
using namespace hjbase::cnt::miscellaneous;
using namespace hjbase::cnt::commands_names;
using namespace hjbase::cnt::type_tag;
using namespace hjbase::ufunc;
using namespace hjbase::except;
void hjbase::ufunc::Print_IVSTR(const const_itVecStr& iVstr) {
for(std::vector<std::string>::const_iterator it=iVstr.begin();it<iVstr.end();++it) {
std::cout<<*it<<" ";
}
std::cout<<std::endl;
}
void hjbase::ufunc::Highlight_Error_Part(const const_itVecStr& iVstr) {
for(std::vector<std::string>::const_iterator it=iVstr.begin();it<iVstr.end();++it) {
std::cout<<std::string((*it).size(), '~')<<" ";
}
std::cout<<std::endl;
}
void hjbase::ufunc::Signal_Error(const std::string& error_msg, const const_itVecStr& error_part) {
std::cerr<<error_msg<<std::endl;
std::cout<<" ";
Print_IVSTR(error_part);
std::cout<<" ";
Highlight_Error_Part(error_part);
}
void hjbase::ufunc::Signal_Error(const std::string& error_msg, const std::string& error_part) {
std::cerr<<error_msg<<std::endl;
std::cout<<" "<<error_part<<std::endl;
}
bool hjbase::ufunc::Check_If_Float_Point(const const_itVecStr& vals) {
// iterate over vals vector
for(std::vector<std::string>::const_iterator it=vals.begin();it<vals.end();++it) {
/*
just try to find a dot to determine if it is a float number or not,
note this is not enough to make sure it is a valid numerical value.
But we will not check it here.
*/
std::size_t found = (*it).find_first_of('.');
if(found!=std::string::npos) {
// std::string::npos is returned if not found, here we know it founds '.'
return true;
}
}
// '.' not found
return false;
}
std::string hjbase::ufunc::Convert_Ptr_To_Str(void* ptr) {
std::stringstream ss;
ss<<ptr;
return ss.str();
}
std::pair<int, int> hjbase::ufunc::Get_First_Element_Pos(const std::string& this_list) {
if(this_list.front()!=cEXPR_START||this_list.back()!=cEXPR_END) {
Signal_Error(TE_NOT_LIST, this_list);
throw type_except;
}
// the previous implicitly checked this_list.size() must be at least 2
if(this_list.size()==2) {
Signal_Error(LE_EMPTY, this_list);
throw eval_except;
}
bool is_quotation = false;
bool is_sublist = false;
// Get the first position which is not a space after cEXPR_START
int start_pos = 1;
for(;start_pos<this_list.size()-1;++start_pos) {
if(!std::isspace(this_list[start_pos])) {
if(this_list[start_pos]==cEXPR_START) {
is_sublist = true;
}
if(this_list[start_pos]==QUOTATION_MARK) {
is_quotation = true;
}
break;
}
}
for(std::string::const_iterator it=this_list.begin()+start_pos+1;it<this_list.end();++it) {
if(is_quotation) {
if(*it==QUOTATION_MARK) {
// exclude QUOTATION mark
return std::pair<int, int>(start_pos+1, it-this_list.begin()-start_pos-1);
}
}
else if(is_sublist) {
if(*it==cEXPR_END) {
// include cEXPR_START and cEXPR_END
return std::pair<int, int>(start_pos, it-this_list.begin()-start_pos+1);
}
}
else {
if(*it==' ') {
// exclude space
return std::pair<int, int>(start_pos, it-this_list.begin()-start_pos);
}
}
}
if(is_quotation||is_sublist) {
Signal_Error(LE_INCOMPLETE, this_list);
throw eval_except;
}
// From previous condition, start_pos must be less or equal to this_list.size()-1
if(start_pos==this_list.size()-1) {
Signal_Error(LE_EMPTY, this_list);
}
return std::pair<int, int>(start_pos, this_list.size()-start_pos-1);
}
std::string hjbase::ufunc::Format_List_String(const std::string& original_lst) {
// construct LISTFORMATTER object
LISTFORMATTER lst_formatter;
for(std::string::const_iterator it=original_lst.begin();it<original_lst.end()-1;++it) {
if(lst_formatter.Take_One_Char(*it)==FORMATTING_COMPLETE) {
Signal_Error(TE_NOT_LIST, original_lst);
throw type_except;
}
}
if(lst_formatter.Take_One_Char(original_lst.back())!=FORMATTING_COMPLETE) {
Signal_Error(TE_NOT_LIST, original_lst);
throw type_except;
}
return lst_formatter.formatted_lst;
}
inline bool hjbase::ufunc::Starts_With(const std::string& this_str, const std::string& start_str) {
if(this_str.substr(0,start_str.size())==start_str) {
return true;
}
return false;
}
inline bool hjbase::ufunc::Is_Numerical(const std::string& this_str) {
for(std::string::const_iterator it=this_str.begin();it<this_str.end();++it) {
if(!isdigit(*it)&&(*it)!='.'&&(*it)!='-') {
return false;
}
}
return true;
}
inline bool hjbase::ufunc::Quotation_Rquired_For_List_Elem(const std::string& this_str) {
if(this_str.front()==cEXPR_START&&this_str.back()==cEXPR_END) {
return false;
}
if(this_str.front()==QUOTATION_MARK&&this_str.back()==QUOTATION_MARK) {
return false;
}
bool ret_flag = false;
for(std::string::const_iterator it=this_str.begin();it<this_str.end();++it) {
if(*it==' ') {
ret_flag = true;
break;
}
}
return ret_flag;
}
bool hjbase::ufunc::Starts_With_Less_Predicate::operator() (const std::string& x, const std::string& y) const {
/*
As the comment said in header file, to make it a valid strict less relation
here we let (Starts_With(x, y)||Starts_With(y, x)) return false, so that (x<y)==(y<x)==false,
which is equal. equivalent key (duplicate) is not allowed to be inserted into the map.
This makes S still satisfy the requirement.
*/
if(Starts_With(x, y)||Starts_With(y, x)) {
return false;
}
return x < y;
}
void hjbase::ufunc::Iterate_Over_Names_Map(const std::map<std::string, std::string>* names,
const void (*f)(const std::string&, const std::string&)) {
for(std::map<std::string, std::string>::const_iterator name_it=names->begin();
name_it!=names->end();++name_it) {
(*f)(name_it->first, name_it->second);
}
}
const_itVecStr::const_itVecStr(std::vector<std::string>::const_iterator from_begin,
std::vector<std::string>::const_iterator from_end)
: this_begin (from_begin)
, this_end (from_end) {
#ifdef itVecStr_RANGE_SAFETY_CHECK
if(this_begin>this_end) {
Signal_Error(IE_CONST_ITVECSTR_OOR, std::string());
throw huaji_except;
}
#endif
}
const_itVecStr::~const_itVecStr() {}
inline std::vector<std::string>::const_iterator const_itVecStr::begin() const {
return this_begin;
}
inline std::vector<std::string>::const_iterator const_itVecStr::end() const {
return this_end;
}
inline std::string const_itVecStr::front() const {
return *(this_begin);
}
inline std::string const_itVecStr::back() const {
return *(this_end-1);
}
inline std::string const_itVecStr::at(int pos) const {
return *(this_begin+pos);
}
inline int const_itVecStr::size() const {
return this_end-this_begin;
}
hjbase::LISTFORMATTER::LISTFORMATTER()
// Not allowed to have space after EXPR_START
: prev_space (true)
, list_depth (0)
, is_in_list_quotation (false) {
formatted_lst = EXPR_START;
}
hjbase::LISTFORMATTER::~LISTFORMATTER() {}
int hjbase::LISTFORMATTER::Take_One_Char(char cur_char) {
if(is_in_list_quotation) {
formatted_lst.push_back(cur_char);
if(cur_char==QUOTATION_MARK) {
is_in_list_quotation = false;
formatted_lst.push_back(' ');
prev_space = true;
}
}
else {
switch (cur_char) {
case cEXPR_END: {
// Replace last char with cEXPR_END if last char is a space
if(formatted_lst.back()==' ') {
formatted_lst[formatted_lst.size()-1] = cEXPR_END;
}
else {
formatted_lst.push_back(cEXPR_END);
}
// not in any other sublist
if(!list_depth) {
return FORMATTING_COMPLETE;
}
// in other sublist, just decrease list_depth
else {
--list_depth;
}
break;
}
case cEXPR_START: {
formatted_lst.push_back(cEXPR_START);
// Not allowed to have space after EXPR_START
prev_space = true;
++list_depth;
break;
}
case QUOTATION_MARK: {
// add a space if no prev_space
if(!prev_space) {
formatted_lst.push_back(' ');
}
formatted_lst.push_back(cur_char);
is_in_list_quotation = true;
break;
}
default: {
if(cur_char==' ') {
if(!prev_space) {
prev_space = true;
formatted_lst.push_back(cur_char);
}
}
else {
formatted_lst.push_back(cur_char);
}
}
}
// Reset prev_space if cur_char is not a space
if(cur_char!=' '&&cur_char!=cEXPR_START) {
prev_space = false;
}
}
return REQUIRE_MORE_CHAR_FOR_COMPLETE_LST;
}
hjbase::HUAJITOKENIZER::HUAJITOKENIZER()
: is_in_quotation (false)
, is_in_block_comment (false)
, is_in_line_comment (false)
, is_in_square_bracket (false)
, is_in_nosubst (false)
, is_in_list (false)
, enable_raw_string (false)
, lst_formatter (nullptr)
, source (nullptr) {
token_queue = new std::queue<std::string>;
}
hjbase::HUAJITOKENIZER::~HUAJITOKENIZER() {
if(lst_formatter) {
delete lst_formatter;
}
delete token_queue;
}
std::string hjbase::HUAJITOKENIZER::Get_One_Token() {
std::string token;
if(token_queue->size()) {
token = token_queue->front();
token_queue->pop();
return token;
}
try {
while(1) {
char cur_char = source->get();
if(cur_char==std::char_traits<char>::eof()) {
// is_in_list store token in lst_formatter object, so token.size() won't work here.
if(token.size()||is_in_list) {
Signal_Error(SE_REQUIRE_MORE_TOKENS, token);
}
throw token_except;
}
// already in quotation mark
else if(is_in_quotation) {
if(cur_char==QUOTATION_MARK) {
is_in_quotation = false;
if(enable_raw_string) {
return token;
}
else {
return token.insert(0, STRING_TAG);
}
}
// characters substitution
else if(cur_char=='\\') {
char next_char = source->get();
switch (next_char) {
case 'n': {
token.push_back('\n');
break;
}
case 'r': {
token.push_back('\r');
break;
}
case 't': {
token.push_back('\t');
break;
}
default:
token.push_back(next_char);
}
}
else {
token.push_back(cur_char);
}
}
else if(is_in_list) {
if(!lst_formatter) {
lst_formatter = new LISTFORMATTER();
}
if(lst_formatter->Take_One_Char(cur_char)==FORMATTING_COMPLETE) {
std::string ret_lst = lst_formatter->formatted_lst;
delete lst_formatter;
// add a LIST_TAG
ret_lst.insert(0, LIST_TAG);
lst_formatter = nullptr;
is_in_list = false;
return ret_lst;
}
}
// in no substitution block
else if(is_in_nosubst) {
if(cur_char==NOSUBST) {
is_in_nosubst = false;
return token;
}
}
// already in block comment
else if(is_in_block_comment) {
if(cur_char=='*') {
if(source->get()=='/') {
is_in_block_comment = false;
}
}
}
// inline comment, exit comment mode if a endline char found
else if(is_in_line_comment) {
if(cur_char=='\n') {
is_in_line_comment = false;
}
}
else {
char next_char = source->peek();
switch (cur_char) {
case '/': {
if(next_char=='*') {
source->get();
is_in_block_comment = true;
if(token.size()) {
return token;
}
}
else if(next_char=='/') {
source->get();
is_in_line_comment = true;
if(token.size()) {
return token;
}
}
else {
token.push_back(cur_char);
}
break;
}
case '<': {
if(next_char=='=') {
token.push_back(cur_char);
token.push_back(source->get());
}
else {
if(token.size()) {
token_queue->push(ENV_START);
return token;
}
return ENV_START;
}
break;
}
case '>': {
if(next_char=='=') {
token.push_back(cur_char);
token.push_back(source->get());
}
else {
if(token.size()) {
token_queue->push(ENV_END);
return token;
}
return ENV_END;
}
break;
}
case '!': {
if(next_char=='=') {
token.push_back(cur_char);
token.push_back(source->get());
}
else {
token.push_back(cur_char);
}
break;
}
case '=': {
if(token.size()) {
token_queue->push(FUNC_EQ);
return token;
}
return FUNC_EQ;
}
case cLIST_TO_EVALUATE: {
if(next_char==cEXPR_START) {
source->get();
if(token.size()) {
token_queue->push(EXPR_START);
token_queue->push(FUNC_LIST);
return token;
}
else {
token_queue->push(FUNC_LIST);
return EXPR_START;
}
}
else {
token.push_back(cLIST_TO_EVALUATE);
}
break;
}
case cLIST_DIRECT: {
if(next_char==cEXPR_START) {
source->get();
is_in_list = true;
if(token.size()) {
return token;
}
}
else {
return LIST_DIRECT;
}
break;
}
case cSLICER: {
if(is_in_square_bracket&&token.size()) {
return token;
}
else {
if(token.size()) {
token_queue->push(SLICER);
return token;
}
else {
return SLICER;
}
}
}
case QUOTATION_MARK: {
is_in_quotation = true;
if(token.size()) {
return token;
}
break;
}
case NOSUBST: {
is_in_nosubst = true;
if(token.size()) {
return token;
}
break;
}
case cSQUARE_BRACKET_START: {
if(token.size()) {
is_in_square_bracket = true;
token_queue->push(FUNC_SLICE);
token_queue->push(token);
return EXPR_START;
}
else {
return SQUARE_BRACKET_START;
}
}
case cSQUARE_BRACKET_END: {
if(token.size()) {
if(is_in_square_bracket) {
token_queue->push(EXPR_END);
is_in_square_bracket = false;
}
else {
token_queue->push(SQUARE_BRACKET_END);
}
return token;
}
else {
if(is_in_square_bracket) {
is_in_square_bracket = false;
return EXPR_END;
}
else {
return SQUARE_BRACKET_END;
}
}
}
case cBLOCK_START: {
if(token.size()) {
token_queue->push(BLOCK_START);
return token;
}
return BLOCK_START;
}
case cBLOCK_END: {
if(token.size()) {
token_queue->push(BLOCK_END);
return token;
}
return BLOCK_END;
}
case cEXPR_START: {
if(token.size()) {
token_queue->push(EXPR_START);
return token;
}
return EXPR_START;
}
case cEXPR_END: {
if(token.size()) {
token_queue->push(EXPR_END);
return token;
}
return EXPR_END;
}
case cSEPARATOR: {
if(token.size()) {
token_queue->push(SEPARATOR);
return token;
}
return SEPARATOR;
}
case cDELIMITER: {
if(token.size()) {
token_queue->push(DELIMITER);
return token;
}
return DELIMITER;
}
default: {
if(std::isspace(cur_char)) {
if(token.size()) {
return token;
}
// ignore if token is empty
}
else {
token.push_back(cur_char);
}
}
}
}
}
}
catch (const std::ios_base::failure& e) {
std::cout<<e.what()<<std::endl;
throw token_except;
}
}
hjbase::FUNC::FUNC(bool with_side_effects, const const_itVecStr& body_iVstr,
const std::map<std::string, std::string>* stack_map, const std::list<std::string>* arg_names, bool lazy)
// use std::vector::vector range constructor
: fbody_container (new std::vector<std::string>(body_iVstr.begin(), body_iVstr.end()))
/*
now fbody should built on fbody_container, as the container for body_iVstr is
allocated on stack by hjbase::HUAJISCRIPTBASE::Entry_Point and will be cleared
once the root command execution completed
*/
, stack_frame_template(stack_map)
, has_side_effects (with_side_effects)
, var_names (arg_names)
, is_lazy (lazy) {
fbody = new const_itVecStr(fbody_container->begin(), fbody_container->end());
}
hjbase::FUNC::~FUNC() {
delete fbody_container;
delete fbody;
delete stack_frame_template;
delete var_names;
}
inline std::map<std::string, std::string>*
hjbase::FUNC::Get_Stack_Frame_Template_Copy_On_Heap() const {
return new std::map<std::string, std::string>(*stack_frame_template);
}
inline std::list<std::string> hjbase::FUNC::Get_Var_Names() const {
return *var_names;
}
inline const_itVecStr hjbase::FUNC::Get_Fbody() {
return *fbody;
}
inline const std::map<std::string, std::string>* hjbase::FUNC::Get_Stack_Frame_Template() const {
return stack_frame_template;
}
hjbase::HUAJISCRIPTBASE::HUAJISCRIPTBASE()
: enable_gc (true)
, collect_status (0)
, collect_length (0)
, enable_float_point (true)
, enable_debug_mode (false)
, current_ast_depth (0)
, enable_raw_string (false)
, allow_side_effects (true)
, last_if_cond (true) {
tokenizer = new HUAJITOKENIZER();
is_console_stack = new std::vector<bool>;
input_stream_stack = new std::vector<std::istream*>;
sourced_history = new std::set<std::string>;
names_stack = new std::vector<std::map<std::string, std::string>*>;
gc_records = new std::map<std::string, std::list<std::string>>;
temp_return_val = UNDEFINED_NAME;
namespace_pool = new std::map<std::string, std::map<std::string, std::string>*>;
Push_Stack_Frame(new std::map<std::string, std::string>);
func_pool = new std::map<std::string, FUNC*>;
object_pool = new std::map<std::string,std::map<std::string,std::string>*>;
object_stack = new std::vector<std::map<std::string, std::string>*>;
lazy_expr_pool = new std::map<std::string, const_itVecStr*>;
istream_pool = new std::map<std::string, std::istream*>;
ostream_pool = new std::map<std::string, std::ostream*>;
array_pool = new std::map<std::string, std::vector<std::string>*>;
}
hjbase::HUAJISCRIPTBASE::~HUAJISCRIPTBASE() {
for(std::vector<std::map<std::string, std::string>*>::iterator it=names_stack->begin();it<names_stack->end();++it) {
delete *it;
}
delete names_stack;
for(std::map<std::string, FUNC*>::iterator it=func_pool->begin();it!=func_pool->end();++it) {
delete it->second;
}
delete func_pool;
for(std::vector<std::map<std::string, std::string>*>::iterator it=object_stack->begin();it<object_stack->end();++it) {
delete *it;
}
delete object_stack;
for(std::map<std::string, std::map<std::string, std::string>*>::iterator it=object_pool->begin();
it!=object_pool->end();++it) {
delete it->second;
}
delete object_pool;
delete gc_records;
for(std::map<std::string, std::map<std::string, std::string>*>::iterator it=namespace_pool->begin();
it!=namespace_pool->end();++it) {
delete it->second;
}
delete namespace_pool;
for(std::map<std::string, const_itVecStr*>::iterator it=lazy_expr_pool->begin();it!=lazy_expr_pool->end();++it) {
delete it->second;
}
delete lazy_expr_pool;
delete tokenizer;
// input_stream_stack should be empty when deleted, so no need to delete istream object.
delete input_stream_stack;
delete is_console_stack;
delete sourced_history;
for(std::map<std::string, std::istream*>::iterator it=istream_pool->begin();it!=istream_pool->end();++it) {
if(it->first!=CIN_PTRSTR) {
delete it->second;
}
}
for(std::map<std::string, std::ostream*>::iterator it=ostream_pool->begin();it!=ostream_pool->end();++it) {
if(it->first!=COUT_PTRSTR) {
delete it->second;
}
}
delete istream_pool;
delete ostream_pool;
for(std::map<std::string, std::vector<std::string>*>::iterator it=array_pool->begin();it!=array_pool->end();++it) {
delete it->second;
}
delete array_pool;
}
std::pair<bool, int> hjbase::HUAJISCRIPTBASE::More_On_Check_If_GC_Required_Level_1(const std::string& ref_val) {
return std::pair<bool, int>(false, -1);
}
std::pair<bool, int> hjbase::HUAJISCRIPTBASE::Check_If_GC_Required(const std::string& ref_val) {
// if ref_val is empty, this violates our set definition
if(ref_val==EMPTY_STRING_OBJECT) {
return std::pair<bool, int>(false, -1);
}
std::map<std::string, int, hjbase::ufunc::Starts_With_Less_Predicate>::const_iterator
res_it = EXTRA_DATA_STRUCTURE_REQUIRED_TYPE_TREE.find(ref_val);
if(res_it==EXTRA_DATA_STRUCTURE_REQUIRED_TYPE_TREE.end()) {
return More_On_Check_If_GC_Required_Level_1(ref_val);
}
// ref_val can't be shorter
if(ref_val.size()<(res_it->first).size()) {
return std::pair<bool, int>(false, -1);
}
return std::pair<bool, int>(true, res_it->second);
}
void hjbase::HUAJISCRIPTBASE::GC_New_Record(const std::string& name, const std::string& val) {
if(!enable_gc) {
return;
}
// Check if val is some type that needs to be recorded for garbage collection
if(Check_If_GC_Required(val).first) {
std::map<std::string, std::list<std::string>>::iterator
record_it = gc_records->find(val);
if(record_it==gc_records->end()) {
// Build record list
std::list<std::string> record_list;
record_list.push_front(name);
gc_records->insert(std::pair<std::string, std::list<std::string>>(val, record_list));
}
else {
// Modify record list
(record_it->second).push_front(name);
}
}
return;
}
void hjbase::HUAJISCRIPTBASE::GC_Delete_Record(const std::string& name, const std::string& val) {
if(!enable_gc) {
return;
}
std::pair<bool, int> res_pair = Check_If_GC_Required(val);
if(res_pair.first) {
std::map<std::string, std::list<std::string>>::iterator
record_it = gc_records->find(val);
if(record_it==gc_records->end()) {
Signal_Error(IE_UNKNOWN, val);
throw huaji_except;
return;
}
for(std::list<std::string>::const_iterator record_list_it=(record_it->second).begin();
record_list_it!=(record_it->second).end();++record_list_it) {
// Check if this record matches name
if(*record_list_it==name) {
// If this is the last name entry in the record
if((record_it->second).size()==1) {
Delete_Internal_Object(val, res_pair.second);
gc_records->erase(val);
}
// just remove this record
else {
(record_it->second).erase(record_list_it);
}
return;
}
}
// Not found
Signal_Error(IE_UNKNOWN, name);
throw huaji_except;
}
}
void hjbase::HUAJISCRIPTBASE::GC_New_MultiRecords(const std::map<std::string, std::string>* names) {
if(enable_gc) {
for(std::map<std::string, std::string>::const_iterator name_it=names->begin();
name_it!=names->end();++name_it) {
GC_New_Record(name_it->first, name_it->second);
}
}
}
void hjbase::HUAJISCRIPTBASE::GC_Delete_MultiRecords(const std::map<std::string, std::string>* names) {
if(enable_gc) {
for(std::map<std::string, std::string>::const_iterator name_it=names->begin();
name_it!=names->end();++name_it) {
GC_Delete_Record(name_it->first, name_it->second);
}
}
}
void hjbase::HUAJISCRIPTBASE::GC_Delete_MultiRecords(const std::vector<std::pair<std::string, std::string>>& names) {
for(std::vector<std::pair<std::string, std::string>>::const_iterator name_it=names.begin();
name_it!=names.end();++name_it) {
GC_Delete_Record(name_it->first, name_it->second);
}
}
void hjbase::HUAJISCRIPTBASE::Delete_Func_Object(const std::string& func_ptrStr) {
std::map<std::string, FUNC*>::const_iterator func_it = func_pool->find(func_ptrStr);
if(func_it==func_pool->end()) {
#ifdef SIGNAL_UNABLE_TO_DELETE
Signal_Error(IE_NOT_DELETABLE, func_ptrStr);
#endif
return;
}
// Delete stack_frame_template
const std::map<std::string, std::string>* stack_map = (func_it->second)->Get_Stack_Frame_Template();
GC_Delete_MultiRecords(stack_map);
// Delete func object and erase node in RBt
delete func_it->second;
func_pool->erase(func_it);
return;
}
void hjbase::HUAJISCRIPTBASE::Delete_Object_Object(const std::string& object_ptrStr) {
std::map<std::string, std::map<std::string, std::string>*>::const_iterator object_it
= object_pool->find(object_ptrStr);
if(object_it==object_pool->end()) {
#ifdef SIGNAL_UNABLE_TO_DELETE
Signal_Error(IE_NOT_DELETABLE, object_ptrStr);
#endif
return;
}
// Delete object content
GC_Delete_MultiRecords(object_it->second);
delete object_it->second;
object_pool->erase(object_it);
return;
}
void hjbase::HUAJISCRIPTBASE::Delete_Lazy_Object(const std::string& lazy_ptrStr) {
std::map<std::string, const_itVecStr*>::const_iterator lazy_it
= lazy_expr_pool->find(lazy_ptrStr);
if(lazy_it==lazy_expr_pool->end()) {
#ifdef SIGNAL_UNABLE_TO_DELETE
Signal_Error(IE_NOT_DELETABLE, lazy_ptrStr);
#endif
return;
}
delete lazy_it->second;
lazy_expr_pool->erase(lazy_it);
return;
}
void hjbase::HUAJISCRIPTBASE::Delete_IS_Object(const std::string& is_ptrStr) {
std::map<std::string, std::istream*>::const_iterator is_it
= istream_pool->find(is_ptrStr);
if(is_it==istream_pool->end()) {
#ifdef SIGNAL_UNABLE_TO_DELETE
Signal_Error(IE_NOT_DELETABLE, is_ptrStr);
#endif
return;
}
delete is_it->second;
istream_pool->erase(is_it);
return;
}
void hjbase::HUAJISCRIPTBASE::Delete_OS_Object(const std::string& os_ptrStr) {
std::map<std::string, std::ostream*>::const_iterator os_it
= ostream_pool->find(os_ptrStr);
if(os_it==ostream_pool->end()) {
#ifdef SIGNAL_UNABLE_TO_DELETE
Signal_Error(IE_NOT_DELETABLE, os_ptrStr);
#endif
return;
}
delete os_it->second;
ostream_pool->erase(os_it);
return;
}
std::vector<std::string>* hjbase::HUAJISCRIPTBASE::Get_Array_Object(const std::string& array_ptrStr) {
std::map<std::string, std::vector<std::string>*>::const_iterator array_it
= array_pool->find(array_ptrStr);
if(array_it==array_pool->end()) {
#ifdef SIGNAL_UNABLE_TO_DELETE
Signal_Error(IE_NOT_DELETABLE, array_ptrStr);
#endif
return nullptr;
}
return array_it->second;
}
void hjbase::HUAJISCRIPTBASE::Delete_Array_Object(const std::string& array_ptrStr) {
std::vector<std::string>* array_ptr = Get_Array_Object(array_ptrStr);
if(!array_ptr) {
return;
}
for(std::vector<std::string>::const_iterator val_it=array_ptr->begin();
val_it<array_ptr->end();++val_it) {
GC_Delete_Record(array_ptrStr, *val_it);
}
}
void hjbase::HUAJISCRIPTBASE::More_On_Delete_Object_Level_1(const std::string& ref_val, int type_code) {
Signal_Error(IE_NOT_DELETABLE, ref_val);
return;
}
void hjbase::HUAJISCRIPTBASE::Delete_Internal_Object(const std::string& ref_val, int type_code) {
switch(type_code) {
case FUNC_TAG_CODE: {
Delete_Func_Object(ref_val);
break;
}
case OBJECT_TAG_CODE: {
Delete_Object_Object(ref_val);
break;
}
case LAZY_TAG_CODE: {
Delete_Lazy_Object(ref_val);
break;
}
case ISTREAM_TAG_CODE: {
Delete_IS_Object(ref_val);
break;
}
case OSTREAM_TAG_CODE: {
Delete_OS_Object(ref_val);
break;
}
case ARRAY_TAG_CODE: {
Delete_Array_Object(ref_val);
break;
}
default: {
More_On_Delete_Object_Level_1(ref_val, type_code);
return;
}
}
}
std::vector<std::pair<std::string, std::string>>
hjbase::HUAJISCRIPTBASE::General_Name_Declaring_Syntax_Parser(const const_itVecStr& iVstr, bool from_func_call) {
// Initialize return vector
std::vector<std::pair<std::string, std::string>> ret_vec;
if(!(iVstr.size())) {
return ret_vec;
}
std::string name;
bool name_already_used = true;
bool name_from_evaluation = false;
for(std::vector<std::string>::const_iterator it=iVstr.begin();it<iVstr.end();++it) {
// Assign val when declare
if(*it==FUNC_EQ) {
std::vector<std::string>::const_iterator expr_begin_it = it+1;
// expr_begin_it needs to be smaller than end()
if(expr_begin_it>=iVstr.end()) {
GC_Delete_MultiRecords(ret_vec);
Signal_Error(SE_UNEXPECTED_TOKEN, iVstr);
throw syntax_except;
}
std::vector<std::string>::const_iterator expr_end_it = it+2;
int unclosed_braces = 0;
if(*expr_begin_it==EXPR_START) {
++unclosed_braces;
}
for(it=expr_end_it;it<iVstr.end();++it) {
expr_end_it = it;
if(*it==EXPR_START) {
++unclosed_braces;
}
else if(*it==EXPR_END) {
--unclosed_braces;
}
else if(*it==SEPARATOR&&!unclosed_braces) {
break;
}
}
if(it==iVstr.end()) {
// Here is means it already went pass last token in iVstr, so we need to assign expr_end_it = it,
expr_end_it = it;
}
// Create new ast node by construct new const_itVecStr object
const_itVecStr expr = const_itVecStr(expr_begin_it, expr_end_it);
std::string val;
val = Evaluate_Expression(expr);
// Push into return vector
ret_vec.push_back(std::pair<std::string, std::string>(name, val));
GC_New_Record(name, val);
name_already_used = true;
}
else if(*it==SEPARATOR) {
if(name_already_used) {
GC_Delete_MultiRecords(ret_vec);
Signal_Error(SE_UNEXPECTED_TOKEN, iVstr);
throw syntax_except;
}
if(from_func_call) {
if(!name_from_evaluation) {
// Here name should be val, we add this option to reduce code, as the syntax is the same, but this way of naming variable is incorrect.
name = Handle_Val(name);
}
ret_vec.push_back(std::pair<std::string, std::string>(UNDEFINED_NAME, name));
GC_New_Record(UNDEFINED_NAME, name);
name_from_evaluation=false;
}
else {
ret_vec.push_back(std::pair<std::string, std::string>(name, UNDEFINED_TYPE));
// set name_from_evaluation to false
name_from_evaluation = false;
}
name_already_used = true;
}
// must be a name
else {
if(!name_already_used) {
GC_Delete_MultiRecords(ret_vec);
Signal_Error(SE_UNEXPECTED_TOKEN, iVstr);
throw syntax_except;
}
if(*it==EXPR_START) {
std::vector<std::string>::const_iterator expr_begin_it = it;
std::vector<std::string>::const_iterator expr_end_it = it+1;
for(it=expr_end_it;it<iVstr.end();++it) {
expr_end_it = it;
if(*it==SEPARATOR) {
// Need to go to *it==SEPARATOR condition
--it;
break;
}
}
if(it==iVstr.end()) {
expr_end_it = it;
}
const_itVecStr expr = const_itVecStr(expr_begin_it, expr_end_it);
name = Evaluate_Expression(expr);
name_from_evaluation = true;
}
else {
name = *it;
}
name_already_used = false;
}
}
// Last name not pushed into vector
if(!name_already_used) {
if(from_func_call) {
if(!name_from_evaluation) {
name = Handle_Val(name);
}
ret_vec.push_back(std::pair<std::string, std::string>(UNDEFINED_NAME, name));
GC_New_Record(UNDEFINED_NAME, name);
}
else {
ret_vec.push_back(std::pair<std::string, std::string>(name, UNDEFINED_TYPE));
}
}
return ret_vec;
}
void hjbase::HUAJISCRIPTBASE::Cleanup_If_Exception_Thrown(int reverted_ast_depth) {
current_ast_depth = reverted_ast_depth;
More_Cleanup_Level_1();
return;
}
void hjbase::HUAJISCRIPTBASE::More_Cleanup_Level_1() {
return;
}
std::string hjbase::HUAJISCRIPTBASE::Indent_By_AST_Depth() {
if(current_ast_depth>=0) {
std::string indent;
for(int i=0;i<current_ast_depth;++i) {
indent.append("| ");
}
return indent;
}
else {
Signal_Error(IE_UNKNOWN, "Negative AST Depth");
current_ast_depth = 0;
}
return std::string();
}
void hjbase::HUAJISCRIPTBASE::Print_Debug_Info(const std::string& info, int ast_depth_change, const const_itVecStr& node) {
if(enable_debug_mode) {
if(ast_depth_change<0) {
current_ast_depth += ast_depth_change;
}
std::cout<<Indent_By_AST_Depth()<<info;
Print_IVSTR(node);
if(ast_depth_change>0) {
current_ast_depth += ast_depth_change;
}
}
}
void hjbase::HUAJISCRIPTBASE::Print_Debug_Info(const std::string& info, int ast_depth_change, const std::string& node) {
if(enable_debug_mode) {
if(ast_depth_change<0) {
current_ast_depth += ast_depth_change;
}
std::cout<<Indent_By_AST_Depth()<<info<<node<<std::endl;
if(ast_depth_change>0) {
current_ast_depth += ast_depth_change;
}
}
}
void hjbase::HUAJISCRIPTBASE::Print_Name_Map(const std::map<std::string, std::string>* names_map) {
// Table Head
std::cout<<HORIZONTAL_LINE<<std::endl;
std::cout<<VERTICAL_LINE_WITH_SPACE_AFTER<<NAME_THEADER<<VERTICAL_LINE_WITH_SPACE_BOTH
<<VAL_THEADER<<VERTICAL_LINE_WITH_SPACE_BEFORE<<std::endl;
std::cout<<HORIZONTAL_LINE<<std::endl;
// Table body
for(std::map<std::string, std::string>::const_iterator it=names_map->begin();it!=names_map->end();++it) {
std::cout<<VERTICAL_LINE_WITH_SPACE_AFTER<<it->first<<VERTICAL_LINE_WITH_SPACE_BOTH
<<it->second<<VERTICAL_LINE_WITH_SPACE_BEFORE<<std::endl;
std::cout<<HORIZONTAL_LINE<<std::endl;
}
}
template <typename ptr>
void hjbase::HUAJISCRIPTBASE::Print_Internal_Pointer_Map(const typename std::map<std::string, ptr>* internal_map) {
int i=0;
std::cout<<HORIZONTAL_LINE<<std::endl;
// Table body
for(typename std::map<std::string, ptr>::const_iterator it=internal_map->begin();it!=internal_map->end();++it) {
std::cout<<VERTICAL_LINE_WITH_SPACE_AFTER<<i<<VERTICAL_LINE_WITH_SPACE_BOTH
<<it->first<<VERTICAL_LINE_WITH_SPACE_BEFORE<<std::endl;
std::cout<<HORIZONTAL_LINE<<std::endl;
++i;
}
}
template void hjbase::HUAJISCRIPTBASE::Print_Internal_Pointer_Map<hjbase::FUNC*>(const std::map<std::string, hjbase::FUNC*>*);
template void hjbase::HUAJISCRIPTBASE::Print_Internal_Pointer_Map<std::map<std::string, std::string>*>(const std::map<std::string, std::map<std::string, std::string>*>*);
template void hjbase::HUAJISCRIPTBASE::Print_Internal_Pointer_Map<const_itVecStr*>(const std::map<std::string, const_itVecStr*>*);
template void hjbase::HUAJISCRIPTBASE::Print_Internal_Pointer_Map<std::istream*>(const std::map<std::string, std::istream*>*);
template void hjbase::HUAJISCRIPTBASE::Print_Internal_Pointer_Map<std::ostream*>(const std::map<std::string, std::ostream*>*);
template void hjbase::HUAJISCRIPTBASE::Print_Internal_Pointer_Map<std::vector<std::string>*>(const std::map<std::string, std::vector<std::string>*>*);
int hjbase::HUAJISCRIPTBASE::Collect_Tokens(const std::string& token) {
// Increase collect_status by 1 as it is an left brace
if(token==BLOCK_START) {
++collect_status;
return REQUIRE_MORE_TOKENS_FOR_COMPLETE_COMMAND_RETURN_CODE;
}
// Decrease collect_status as some previous left brace is closed
if(token==BLOCK_END) {
--collect_status;
// No more left braces
if(!collect_status) {
return COMMAND_COMPLETED_RETURN_CODE;
}
// prevent if someone put extra close brace
if(collect_status<0) {
// reset collect_status
collect_status = 0;
Signal_Error(SE_UNEXPECTED_TOKEN, token);
}
// left braces still left
else {
return REQUIRE_MORE_TOKENS_FOR_COMPLETE_COMMAND_RETURN_CODE;
}
}
// end of command keyword, check if it is inside some brace
if(token==DELIMITER) {
if(!collect_status) {
return COMMAND_COMPLETED_RETURN_CODE;
}
else {
return REQUIRE_MORE_TOKENS_FOR_COMPLETE_COMMAND_RETURN_CODE;
}
}
// Require more tokens for tokens other than 3 above
else {
return REQUIRE_MORE_TOKENS_FOR_COMPLETE_COMMAND_RETURN_CODE;
}
}
int hjbase::HUAJISCRIPTBASE::Take_One_Token(std::vector<std::string>::const_iterator token_it) {
++collect_length;
int command_complete = Collect_Tokens(*token_it);
if(command_complete) {
const_itVecStr cmd = const_itVecStr(token_it-collect_length+1, token_it+1);
// Reset collect_length, and start_it will be set to new start as well.
collect_length = 0;
// Build const_itVecStr object for execution
int execution_status = Huaji_Command_Interpreter(cmd);
// Return status
return execution_status;
}
else {
return REQUIRE_MORE_TOKENS_RETURN_CODE;
}
}
void hjbase::HUAJISCRIPTBASE::Entry_Point(std::string filename) {
std::vector<std::string> command;
std::string token;
if(filename==EMPTY_STRING_OBJECT) {
std::cout<<CONSOLE_INFO_STRING<<std::endl;
std::cout<<COMMAND_LINE_PROMPT;
is_console_stack->push_back(true);
tokenizer->source = &std::cin;
}
else {
tokenizer->source = new std::ifstream(filename);
// Check if file exists
if((tokenizer->source)->good()) {
is_console_stack->push_back(false);
input_stream_stack->push_back(tokenizer->source);
}
else {
tokenizer->source = nullptr;
Signal_Error(IOE_FILE_NOT_EXISTS, filename);
return;
}
}
while(1) {
try {
token = tokenizer->Get_One_Token();
command.push_back(token);
}
catch (const TOKEN_EXCEPTION& e) {
tokenizer->source = nullptr;
if(collect_length!=0) {
Signal_Error(SE_REQUIRE_MORE_TOKENS, token);
collect_length = 0;
}
if(!is_console_stack->back()) {
delete input_stream_stack->back();
input_stream_stack->pop_back();
}
is_console_stack->pop_back();
if(is_console_stack->size()) {
// Still sources availible in stack, change tokenizer sources then jump to loop top
if(is_console_stack->back()) {
tokenizer->source = &std::cin;
std::cout<<COMMAND_LINE_PROMPT;
}
else {
tokenizer->source = input_stream_stack->back();
}
continue;
}
else {
// No more sources in stack, return
return;
}
return;
}
int ret_code = Take_One_Token(command.end()-1);
if(ret_code!=REQUIRE_MORE_TOKENS_RETURN_CODE) {
command.clear();
if(ret_code==EXIT_RETURN_CODE) {
return;
}
if(is_console_stack->back()) {
std::cout<<COMMAND_LINE_PROMPT;
}
}
}
}
void hjbase::HUAJISCRIPTBASE::Push_Stack_Frame(std::map<std::string, std::string>*
preset_stack_frame) {
if(enable_gc) {
// Record all variables in stack
for(std::map<std::string, std::string>::const_iterator name_it=preset_stack_frame->begin();
name_it!=preset_stack_frame->end();++name_it) {
GC_New_Record(name_it->first, name_it->second);
}
}
names_stack->push_back(preset_stack_frame);
}
void hjbase::HUAJISCRIPTBASE::Pop_Stack_Frame() {
std::map<std::string, std::string>* current_stack_frame = names_stack->back();
if(enable_gc) {
// Delete all garbage in stack frame to be dropped
for(std::map<std::string, std::string>::const_iterator name_it=current_stack_frame->begin();
name_it!=current_stack_frame->end();++name_it) {
GC_Delete_Record(name_it->first, name_it->second);
}
}
delete current_stack_frame;
names_stack->pop_back();
}
void hjbase::HUAJISCRIPTBASE::Push_Object_Into_Stack(const std::string& object_ptrStr) {
std::map<std::string, std::string>* object_names;
try {
object_names = object_pool->at(object_ptrStr);
}
catch (const std::out_of_range& oor) {
Signal_Error(IE_INTERNAL_QUERY_FAILED, object_ptrStr);
throw huaji_except;
}
if(enable_gc) {
for(std::map<std::string, std::string>::const_iterator name_it=object_names->begin();
name_it!=object_names->end();++name_it) {
GC_New_Record(name_it->first, name_it->second);
}
}
object_stack->push_back(object_names);
}
void hjbase::HUAJISCRIPTBASE::Pop_Object_From_Stack() {
std::map<std::string, std::string>* object_names = object_stack->back();
if(enable_gc) {
for(std::map<std::string, std::string>::const_iterator name_it=object_names->begin();
name_it!=object_names->end();++name_it) {
GC_Delete_Record(name_it->first, name_it->second);
}
}
object_stack->pop_back();
}
inline void hjbase::HUAJISCRIPTBASE::Side_Effects_Guard(std::string func_name_with_side_effects) {
if(!allow_side_effects) {
Signal_Error(SEF_NOT_ALLOWED, func_name_with_side_effects);
throw side_effects_except;
}
}
std::pair<std::string*, std::map<std::string, std::string>*>
hjbase::HUAJISCRIPTBASE::Resolve_Namespace(const std::string& name) {
std::string* sub_name = nullptr;
std::map<std::string, std::string>* return_namespace = nullptr;
for(std::string::const_iterator char_it=name.begin();char_it!=name.end();++char_it) {
if(*char_it==STACK_SEPARATOR) {
int requested_frame_depth = Get_Stack_Frame_Pos(std::string(char_it+1, name.end()));
std::string* sub_name = new std::string(name.begin(), char_it);
return std::pair<std::string*, std::map<std::string, std::string>*>
(sub_name, names_stack->at(requested_frame_depth));
}
if(*char_it==NAMESPACE_SEPARATOR) {
std::string namespace_name = std::string(char_it+1, name.end());
if(namespace_name==OBJECT_SCOPE_REF) {
// Check if stack is empty
if(!object_stack->size()) {
Signal_Error(IE_ACCESSING_UNDEFINED_STACK_FRAME, OBJECT_SCOPE_REF);
throw name_except;
}
else {
return_namespace = object_stack->back();
}
}
else {
std::map<std::string, std::map<std::string, std::string>*>::iterator res_it
= namespace_pool->find(namespace_name);
if(res_it==namespace_pool->end()) {
Signal_Error(NAE_UNDEFINED, name);
throw name_except;
}
else {
return_namespace = res_it->second;
}
}
std::string* sub_name = new std::string(name.begin(), char_it);
return std::pair<std::string*, std::map<std::string, std::string>*>(sub_name, return_namespace);
}
}
// return top stack
return std::pair<std::string*, std::map<std::string, std::string>*>
(nullptr, names_stack->back());
}
void hjbase::HUAJISCRIPTBASE::Declare_Name(const std::string& name, const std::string& val) {
std::pair<std::string*, std::map<std::string, std::string>*> res_pair = Resolve_Namespace(name);
std::string* sub_name = res_pair.first;
std::map<std::string, std::string>* target_scope_names = res_pair.second;
// insert return a std::pair, with second element specifying if successfully inserted.
if(sub_name) {
if((target_scope_names->insert(std::pair<std::string, std::string>(*sub_name, val))).second==false) {
Signal_Error(NAE_REDECLARE, name);
delete sub_name;
throw name_except;
}
}
else {
if((target_scope_names->insert(std::pair<std::string, std::string>(name, val))).second==false) {
Signal_Error(NAE_REDECLARE, name);
throw name_except;
}
}
GC_New_Record(name, val);
if(sub_name) {
delete sub_name;
}
return;
}
void hjbase::HUAJISCRIPTBASE::Mutate_Name(const std::string& name, const std::string& val) {
std::pair<std::string*, std::map<std::string, std::string>*> res_pair = Resolve_Namespace(name);
std::string* sub_name = res_pair.first;
std::map<std::string, std::string>* target_scope_names = res_pair.second;
std::map<std::string, std::string>::iterator res_it;
// Get the iterator pointing to name
if(sub_name) {
res_it = target_scope_names->find(*sub_name);
}
else {
res_it = target_scope_names->find(name);
}
// Check if name is in the map, if not res_it will be std::map::end()
if(res_it!=target_scope_names->end()) {
GC_Delete_Record(name, res_it->second);
res_it->second = val;
GC_New_Record(name, val);
}
else {
// Mutate a name that is not declared is forbidden
Signal_Error(NAE_UNDEFINED, name);
throw name_except;
}
if(sub_name) {
delete sub_name;
}
return;
}
std::string hjbase::HUAJISCRIPTBASE::Resolve_Name(const std::string& name) {
std::pair<std::string*, std::map<std::string, std::string>*> res_pair = Resolve_Namespace(name);
std::string* sub_name = res_pair.first;
std::map<std::string, std::string>* target_scope_names = res_pair.second;
std::string val;
try {
if(sub_name) {
val = target_scope_names->at(*sub_name);
}
else {
val = target_scope_names->at(name);
}
}
catch (const std::out_of_range& oor) {
Signal_Error(NAE_UNDEFINED, name);
throw name_except;
}
if(sub_name) {
delete sub_name;
}
return val;
}
int hjbase::HUAJISCRIPTBASE::Block_Execution(const const_itVecStr& commands_block) {
int start_exec_pos = -1;
// Find execution position, where the first BLOCK_START appears
for(std::vector<std::string>::const_iterator it=commands_block.begin();
it<commands_block.end();++it) {
if(*it==BLOCK_START) {
start_exec_pos = it-commands_block.begin();
break;
}
}
if(start_exec_pos==-1) {
Signal_Error(SE_REQUIRE_MORE_TOKENS, commands_block);
return VALID_COMMAND_RETURN_CODE;
}
/*
We already know currently collect_status = collect_length = 0,
so use a nested Take_One_Token here won't cause problems.
check for end block token is ignored, as we iterate to end()-1
*/
for(std::vector<std::string>::const_iterator it=commands_block.begin()+start_exec_pos+1;
it<commands_block.end()-1;++it) {
if(Take_One_Token(it)==EXIT_RETURN_CODE) {
return EXIT_RETURN_CODE;
}
}
// force reset collect_length, it is possible to have positive collect_length
if (collect_length!=0) {
Signal_Error(SE_REQUIRE_MORE_TOKENS, commands_block);
collect_length = 0;
collect_status = 0;
}
return VALID_COMMAND_RETURN_CODE;
}
std::pair<std::vector<std::string>::const_iterator, std::vector<std::string>::const_iterator>
hjbase::HUAJISCRIPTBASE::Get_Expr_Position_Iterators(const const_itVecStr& iVstr) {
std::vector<std::string>::const_iterator start_it = iVstr.end();
std::vector<std::string>::const_iterator end_it = iVstr.end();
int expr_depth = 0;
for(std::vector<std::string>::const_iterator it=iVstr.begin();it<iVstr.end();++it) {
if(*it==EXPR_START) {
if(!expr_depth) {
start_it = it;
}
++expr_depth;
}
else if(*it==EXPR_END) {
--expr_depth;
if(start_it!=iVstr.end()&&!expr_depth) {
end_it = it+1;
break;
}
}
}
if(start_it==iVstr.end()) {
Signal_Error(SE_MISSING_EXPR, iVstr);
throw syntax_except;
}
return std::pair<std::vector<std::string>::const_iterator, std::vector<std::string>::const_iterator>
(start_it, end_it);
}
std::string hjbase::HUAJISCRIPTBASE::Find_And_Evaluate_Expression(const const_itVecStr& iVstr) {
std::pair<std::vector<std::string>::const_iterator, std::vector<std::string>::const_iterator> ret_pair
= Get_Expr_Position_Iterators(iVstr);
const_itVecStr expr = const_itVecStr(ret_pair.first, ret_pair.second);
// Handle expression
std::string val;
val = Evaluate_Expression(expr);
return val;
}
int hjbase::HUAJISCRIPTBASE::Get_Stack_Frame_Pos(const std::string& req_str) {
// 0 is the bottom of the stack
int current_frame_depth = names_stack->size();
int requested_frame_depth;
try {
requested_frame_depth = stoi(req_str);
}
catch (const std::logic_error) {
Signal_Error(NE_CONVERSION_FAILED, req_str);
throw eval_except;
}
if(requested_frame_depth<0) {
requested_frame_depth = current_frame_depth + requested_frame_depth;
}
if(requested_frame_depth>=current_frame_depth||requested_frame_depth<0) {
Signal_Error(IE_ACCESSING_UNDEFINED_STACK_FRAME, req_str);
throw huaji_except;
}
return requested_frame_depth;
}
void hjbase::HUAJISCRIPTBASE::More_On_Config_Level_1(const std::string& item, const std::string& status) {
Signal_Error(IE_UNDEFINED_NAME, item);
return;
}
void hjbase::HUAJISCRIPTBASE::More_On_Info_Level_1(const const_itVecStr& command) {
Signal_Error(IE_UNDEFINED_NAME, command.at(1));
return;
}
int hjbase::HUAJISCRIPTBASE::FUNC_Paring_Helper(std::map<std::string, std::string>* stack_map,
std::list<std::string>* arg_names, const const_itVecStr& iVstr,
std::vector<std::string>::const_iterator& func_def_begin,
std::vector<std::string>::const_iterator& func_def_end) {
for(std::vector<std::string>::const_iterator arg_name_it=iVstr.begin();
arg_name_it<iVstr.end();++arg_name_it) {
if(*arg_name_it==EXPR_START) {
Signal_Error(SE_UNEXPECTED_TOKEN, iVstr);
throw syntax_except;
}
else if(*arg_name_it==EXPR_END) {
func_def_begin = arg_name_it+1;
break;
}
else {
arg_names->push_back(*arg_name_it);
}
}
// Check if func_def_begin is the end of iVstr
if(func_def_begin>=iVstr.end()) {
Signal_Error(SE_UNEXPECTED_TOKEN, iVstr);
throw syntax_except;
}
if(*func_def_begin==ENV_START) {
// Since in env all expression allowed, so there might be nested env
int env_depth = 1;
for(std::vector<std::string>::const_iterator env_var_it=func_def_begin+1;
env_var_it<iVstr.end();++env_var_it) {
if(*env_var_it==ENV_START) {
++env_depth;
}
else if(*env_var_it==ENV_END) {
--env_depth;
if(!env_depth) {
std::vector<std::pair<std::string, std::string>> parsed_names
= General_Name_Declaring_Syntax_Parser(const_itVecStr(func_def_begin+1, env_var_it));
// Add env variables to stack_map
for(std::vector<std::pair<std::string, std::string>>::const_iterator name_pair_it=parsed_names.begin();
name_pair_it<parsed_names.end();++name_pair_it) {
if((stack_map->insert(std::pair<std::string, std::string>
(name_pair_it->first, name_pair_it->second))).second==false) {
GC_Delete_MultiRecords(parsed_names);
Signal_Error(IE_INSERTION_FAILURE, name_pair_it->first);
throw syntax_except;
}
}
// Move func_def_begin to the next pos after env_var_it
func_def_begin = env_var_it+1;
// Check again if func_def_begin is the end of iVstr
if(func_def_begin>=iVstr.end()) {
GC_Delete_MultiRecords(parsed_names);
Signal_Error(SE_UNEXPECTED_TOKEN, iVstr);
throw syntax_except;
}
// Ask Garbage Collector to record variables in stack_map
GC_New_MultiRecords(stack_map);
GC_Delete_MultiRecords(parsed_names);
break;
}
}
}
// Check if env syntax correct
if(env_depth) {
GC_Delete_MultiRecords(stack_map);
Signal_Error(SE_UNEXPECTED_TOKEN, iVstr);
throw syntax_except;
}
}
// Generate stack_map using arg_names
for(std::list<std::string>::const_iterator arg_name_it=arg_names->begin();
arg_name_it!=arg_names->end();++arg_name_it) {
if((stack_map->insert(std::pair<std::string, std::string>
(*arg_name_it, UNDEFINED_TYPE))).second==false) {
Signal_Error(SE_UNEXPECTED_TOKEN, iVstr);
throw syntax_except;
}
}
func_def_end = iVstr.end();
return VALID_COMMAND_RETURN_CODE;
}
int hjbase::HUAJISCRIPTBASE::Huaji_Command_Interpreter(const const_itVecStr& command) {
Print_Debug_Info(DEB_COMMAND_START, INCREASE_AST_DEPTH, command);
// Get CMD side
int command_size = command.size();
// Only a DELIMITER presented
if(command_size==1) {
Print_Debug_Info(DEB_COMMAND_END, DECREASE_AST_DEPTH, command);
return VALID_COMMAND_RETURN_CODE;
}
// record current ast_depth, used in Cleanup_If_Exception_Thrown
int reverted_ast_depth = current_ast_depth-1;
std::string cmd_str = command.at(0);
std::map<std::string, int>::const_iterator cmd_key_it = HJBASE_CMD_SEARCH_TREE.find(cmd_str);
int cmd_key = -1;
if(cmd_key_it!=HJBASE_CMD_SEARCH_TREE.end()) {
cmd_key = cmd_key_it->second;
}
else {
std::pair<int, bool> ret_pair = More_On_Command_Level_1(command);
if(ret_pair.second) {
Print_Debug_Info(DEB_COMMAND_END, DECREASE_AST_DEPTH, command);
return ret_pair.first;
}
else {
// FUNC execution
if(command_size<4) {
Signal_Error(SE_REQUIRE_MORE_TOKENS, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
std::string func_ptrStr;
try {
func_ptrStr = Resolve_Name(cmd_str);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return UNKNOWN_COMMAND_RETURN_CODE;
}
FUNC* func_ptr = nullptr;
std::map<std::string, FUNC*>::const_iterator func_ptr_it = func_pool->find(func_ptrStr);
if(func_ptr_it==func_pool->end()) {
Signal_Error(IE_INTERNAL_QUERY_FAILED, func_ptrStr);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
else {
func_ptr = func_ptr_it->second;
}
// Halt Execution if it has no side effects
if(!(func_ptr->has_side_effects)) {
Signal_Error(SEF_REQUIRED, cmd_str);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
// Check syntax and get parsed names for generating stack_map
if(command.at(1)!=EXPR_START&&command.at(command_size-2)!=EXPR_END) {
Signal_Error(SE_UNEXPECTED_TOKEN, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
std::vector<std::pair<std::string, std::string>> parsed_names;
try {
parsed_names = General_Name_Declaring_Syntax_Parser(const_itVecStr(command.begin()+2, command.end()-2), true);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
// Allocate new stack and pushed to names_stack
std::map<std::string, std::string>* preset_stack_frame
= func_ptr->Get_Stack_Frame_Template_Copy_On_Heap();
std::list<std::string> var_names = func_ptr->Get_Var_Names();
if(var_names.size()<parsed_names.size()) {
Signal_Error(SE_ARITY_MISMATCH, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
GC_Delete_MultiRecords(parsed_names);
delete preset_stack_frame;
return INVALID_COMMAND_RETURN_CODE;
}
bool object_scope_ref_used = false;
for(std::vector<std::pair<std::string, std::string>>::const_iterator
name_it=parsed_names.begin();name_it<parsed_names.end();++name_it) {
if(name_it->first==UNDEFINED_NAME) {
(*preset_stack_frame)[var_names.front()] = name_it->second;
if(!object_scope_ref_used&&var_names.front()==OBJECT_SCOPE_REF) {
try {
Push_Object_Into_Stack(name_it->second);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
GC_Delete_MultiRecords(parsed_names);
delete preset_stack_frame;
return INVALID_COMMAND_RETURN_CODE;
}
object_scope_ref_used = true;
}
var_names.pop_front();
}
else {
std::map<std::string, std::string>::iterator name_in_stack_it
= (preset_stack_frame->find(name_it->first));
if(name_in_stack_it==preset_stack_frame->end()) {
Signal_Error(NAE_UNDEFINED, name_it->first);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
GC_Delete_MultiRecords(parsed_names);
delete preset_stack_frame;
return INVALID_COMMAND_RETURN_CODE;
}
name_in_stack_it->second = name_it->second;
if(!object_scope_ref_used&&name_it->first==OBJECT_SCOPE_REF) {
try {
Push_Object_Into_Stack(name_it->second);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
GC_Delete_MultiRecords(parsed_names);
delete preset_stack_frame;
return INVALID_COMMAND_RETURN_CODE;
}
object_scope_ref_used = true;
}
// Not accessing this itrator any more, this should be safe
var_names.remove(name_it->first);
}
}
Push_Stack_Frame(preset_stack_frame);
GC_Delete_MultiRecords(parsed_names);
Block_Execution(func_ptr->Get_Fbody());
Pop_Stack_Frame();
if(object_scope_ref_used) {
Pop_Object_From_Stack();
}
Print_Debug_Info(DEB_COMMAND_END, DECREASE_AST_DEPTH, command);
return VALID_COMMAND_RETURN_CODE;
}
}
switch (cmd_key) {
// Variable declare
case eCMD_NAME_DECLARE: {
if(command_size<3) {
Signal_Error(SE_REQUIRE_MORE_TOKENS, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
// Create a const_itVecStr object for names parsing
const_itVecStr names_iVstr = const_itVecStr(command.begin()+1,command.end()-1);
try {
std::vector<std::pair<std::string, std::string>> parsed_names
= General_Name_Declaring_Syntax_Parser(names_iVstr);
for(std::vector<std::pair<std::string, std::string>>::const_iterator
name_pair_it=parsed_names.begin();
name_pair_it<parsed_names.end();++name_pair_it) {
Declare_Name((*name_pair_it).first, (*name_pair_it).second);
}
GC_Delete_MultiRecords(parsed_names);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
break;
}
case eCMD_NAME_MUTATE: {
if(command_size<5) {
Signal_Error(SE_REQUIRE_MORE_TOKENS, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
if(command.at(2)!=CMD_NAME_MUTATE_TO) {
Signal_Error(SE_UNEXPECTED_TOKEN, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
std::string name = command.at(1);
const_itVecStr expr = const_itVecStr(command.begin()+3, command.end()-1);
std::string val;
try {
val = Evaluate_Expression(expr);
Mutate_Name(name, val);
}
catch (const HUAJIBASE_EXCEPTION& e){
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
break;
}
// Print command
case eCMD_PRINT: {
bool nl_flag = true;
for(std::vector<std::string>::const_iterator it=command.begin()+1;it<command.end()-1;++it) {
if((*it)==NONEWLINE&&nl_flag) {
nl_flag = false;
}
else if((*it)==USE_EXPR_FROM_HERE&&it!=command.end()-2) {
const_itVecStr expr = const_itVecStr(it+1,command.end()-1);
try {
std::cout<<Evaluate_Expression(expr);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
break;
}
else {
try {
std::cout<<Handle_Val(*it);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
}
}
if(nl_flag) {
std::cout<<std::endl;
}
break;
}
// If command
case eCMD_IF: {
bool condition = false;
try {
std::string cond_str = command.at(1);
if(cond_str!=EXPR_START) {
condition = Handle_Val(cond_str)!=BOOL_FALSE;
}
else {
condition = Find_And_Evaluate_Expression(command)!=BOOL_FALSE;
}
}
catch (const HUAJIBASE_EXCEPTION& e){
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
last_if_cond = condition;
if(condition) {
if(Block_Execution(command)==EXIT_RETURN_CODE) {
Print_Debug_Info(DEB_COMMAND_END, DECREASE_AST_DEPTH, command);
return EXIT_RETURN_CODE;
}
}
break;
}
case eCMD_ELIF: {
if(!last_if_cond) {
bool condition = false;
try {
std::string cond_str = command.at(1);
if(cond_str!=EXPR_START) {
condition = Handle_Val(cond_str)!=BOOL_FALSE;
}
else {
condition = Find_And_Evaluate_Expression(command)!=BOOL_FALSE;
}
}
catch (const HUAJIBASE_EXCEPTION& e){
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
last_if_cond = condition;
if(condition) {
if(Block_Execution(command)==EXIT_RETURN_CODE) {
Print_Debug_Info(DEB_COMMAND_END, DECREASE_AST_DEPTH, command);
return EXIT_RETURN_CODE;
}
}
break;
}
}
case eCMD_ELSE: {
if(!last_if_cond) {
if(Block_Execution(command)==EXIT_RETURN_CODE) {
Print_Debug_Info(DEB_COMMAND_END, DECREASE_AST_DEPTH, command);
return EXIT_RETURN_CODE;
}
}
break;
}
// While command
case eCMD_WHILE: {
bool condition = false;
bool name_condition = false;
std::string cond_str = command.at(1);
try {
if(cond_str!=EXPR_START) {
condition = Handle_Val(cond_str)!=BOOL_FALSE;
name_condition = true;
}
else {
condition = Find_And_Evaluate_Expression(command)!=BOOL_FALSE;
}
}
catch (const HUAJIBASE_EXCEPTION& e){
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
while(condition) {
if(Block_Execution(command)==EXIT_RETURN_CODE) {
Print_Debug_Info(DEB_COMMAND_END, DECREASE_AST_DEPTH, command);
return EXIT_RETURN_CODE;
}
try {
if(name_condition) {
condition = Handle_Val(cond_str)!=BOOL_FALSE;
}
else {
condition = Find_And_Evaluate_Expression(command)!=BOOL_FALSE;
}
}
catch (const HUAJIBASE_EXCEPTION& e){
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
}
break;
}
case eCMD_DEFINE: {
if(command_size<7) {
Signal_Error(SE_REQUIRE_MORE_TOKENS, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
int option_offset = 0;
bool overloaded = false;
bool lazy = false;
if(command.at(1)==OVERLOADING_FLAG) {
++option_offset;
overloaded = true;
}
if(command.at(1+option_offset)==LAZY_FLAG) {
++option_offset;
lazy = true;
}
std::string func_name;
bool with_side_effects = true;
std::vector<std::string>::const_iterator func_def_begin = command.end();
std::vector<std::string>::const_iterator func_def_end = command.end();
std::list<std::string>* arg_names = new std::list<std::string>;
std::map<std::string, std::string>* stack_map = new std::map<std::string, std::string>;
// begin with EXPR_START, treat as a no side effects function
if(command.at(1+option_offset)==EXPR_START) {
func_name = command.at(2+option_offset);
with_side_effects = false;
try {
FUNC_Paring_Helper(stack_map, arg_names,
const_itVecStr(command.begin()+3+option_offset, command.end()-1),
func_def_begin, func_def_end);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Signal_Error(SE_UNEXPECTED_TOKEN, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
}
else if(command.at(2+option_offset)==EXPR_START) {
func_name = command.at(1+option_offset);
std::pair<std::vector<std::string>::const_iterator, std::vector<std::string>::const_iterator> ret_pair;
try {
ret_pair = Get_Expr_Position_Iterators(command);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
func_def_begin = ret_pair.second;
// remove EXPR_START and EXPR_END
++(ret_pair.first);
--(ret_pair.second);
// Send to name declaring parser
std::vector<std::pair<std::string, std::string>> parsed_names
= General_Name_Declaring_Syntax_Parser(const_itVecStr(ret_pair.first, ret_pair.second));
// Configure stack_map and arg_names
for(std::vector<std::pair<std::string, std::string>>::const_iterator name_pair_it=parsed_names.begin();
name_pair_it<parsed_names.end();++name_pair_it) {
(*stack_map)[(*name_pair_it).first] = (*name_pair_it).second;
arg_names->push_back((*name_pair_it).first);
}
// Ask Garbage Collector to record variables in stack_map
GC_New_MultiRecords(stack_map);
}
else {
Signal_Error(SE_UNEXPECTED_TOKEN, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
// Build FUNC object
FUNC* func_ptr = new FUNC(with_side_effects, const_itVecStr(func_def_begin, func_def_end), stack_map, arg_names, lazy);
// Create unique identifier for FUNC to store in func_pool
std::string func_ptrStr = FUNC_TAG + Convert_Ptr_To_Str(func_ptr) + func_name;
try {
if(overloaded) {
Mutate_Name(func_name, func_ptrStr);
}
else {
Declare_Name(func_name, func_ptrStr);
}
}
catch (const HUAJIBASE_EXCEPTION& e) {
delete func_ptr;
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
if(!(func_pool->insert(std::pair<std::string, FUNC*>(func_ptrStr, func_ptr))).second) {
delete func_ptr;
Signal_Error(IE_INSERTION_FAILURE, func_ptrStr);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
break;
}
case eCMD_INIT: {
std::map<std::string, std::string>* new_namespace;
if(command_size<=3) {
new_namespace = new std::map<std::string, std::string>;
}
else {
std::map<std::string, std::map<std::string, std::string>*>::const_iterator
parent_namespace_it = namespace_pool->find(command.at(2));
if(parent_namespace_it==namespace_pool->end()) {
Signal_Error(IE_INTERNAL_QUERY_FAILED, command.at(2));
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
new_namespace = new std::map<std::string, std::string>(*(parent_namespace_it->second));
}
if(!(namespace_pool->insert
(std::pair<std::string, std::map<std::string, std::string>*>(command.at(1), new_namespace)).second)) {
// Insertion failed, namespace already exists
delete new_namespace;
Signal_Error(IE_INSERTION_FAILURE, command.at(1));
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
break;
}
case eCMD_DELETE: {
if(enable_gc) {
Signal_Error(GCE_DELETE_NOT_ALLOWED, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
std::string ref_val;
if(command.at(1)==EXPR_START) {
ref_val = Handle_Val(Find_And_Evaluate_Expression(command));
}
else {
ref_val = Handle_Val(command.at(1));
}
Delete_Internal_Object(ref_val, Check_If_GC_Required(ref_val).second);
break;
}
case eCMD_RETURN: {
try {
const_itVecStr expr = const_itVecStr(command.begin()+1,command.end()-1);
GC_Delete_Record(TEMP_RET_VAL_NAME, temp_return_val);
/*
Since in Evaluate_Expression there might be return command inside, that is
nested return command. So if we don't make sure temp_return_val is a non-recyclable type,
GC might do repeating job, which will cause crashing.
*/
temp_return_val = UNDEFINED_NAME;
temp_return_val = Evaluate_Expression(expr);
GC_New_Record(TEMP_RET_VAL_NAME, temp_return_val);
Print_Debug_Info(DEB_COMMAND_END, DECREASE_AST_DEPTH, command);
return EXIT_RETURN_CODE;
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
}
case eCMD_SOURCE: {
if(command.size()<3) {
Signal_Error(SE_ARITY_MISMATCH, command);
throw syntax_except;
}
std::string filename = command.at(1);
if(filename==CONSOLE_FLAG) {
// Already using console, not allowed
if(is_console_stack->back()) {
Signal_Error(IOE_ALREADY_IN_CIN, filename);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
is_console_stack->push_back(true);
tokenizer->source = &std::cin;
break;
}
std::istream* is_ptr = new std::ifstream(filename);
if(!is_ptr->good()) {
delete is_ptr;
Signal_Error(IOE_FILE_NOT_EXISTS, filename);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
if(command.at(2)!=FORCE_FLAG) {
if(!sourced_history->insert(filename).second) {
// Already sourced
break;
}
}
is_console_stack->push_back(false);
input_stream_stack->push_back(is_ptr);
tokenizer->source = is_ptr;
break;
}
case eCMD_EXEC: {
system(Handle_Val(command.at(1)).c_str());
break;
}
case eCMD_INFO: {
std::string info_item = command.at(1);
if(info_item==INFO_NAME) {
if(command_size<5) {
Print_Name_Map(names_stack->back());
}
else {
std::string option = command.at(2);
std::string option_arg;
if(command.at(3)==EXPR_START) {
try {
option_arg = Find_And_Evaluate_Expression(command);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
}
else {
option_arg = command.at(3);
}
if(option==STACK_FLAG) {
int requested_frame_depth;
try {
requested_frame_depth = Get_Stack_Frame_Pos(option_arg);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
Print_Name_Map(names_stack->at(requested_frame_depth));
}
else if(option==NAMESPACE_FLAG) {
Print_Name_Map(namespace_pool->at(option_arg));
}
else {
Signal_Error(SE_UNRECOGNISED_FLAG, option);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
}
}
else if(info_item==INFO_FUNC_POOL) {
Print_Internal_Pointer_Map(func_pool);
}
else if(info_item==INFO_NAMESPACE_POOL) {
Print_Internal_Pointer_Map(namespace_pool);
}
else if(info_item==INFO_OBJECT_POOL) {
Print_Internal_Pointer_Map(object_pool);
}
else if(info_item==INFO_LAZY_POOL) {
Print_Internal_Pointer_Map(lazy_expr_pool);
}
else if(info_item==INFO_OBJECT_STACK) {
for(std::vector<std::map<std::string, std::string>*>::const_iterator ptr_it=object_stack->begin();
ptr_it!=object_stack->end();++ptr_it) {
std::cout<<*ptr_it<<std::endl;
}
}
else if(info_item==INFO_ISTREAM_POOL) {
Print_Internal_Pointer_Map(istream_pool);
}
else if(info_item==INFO_OSTREAM_POOL) {
Print_Internal_Pointer_Map(ostream_pool);
}
else if(info_item==INFO_ARRAY_POOL) {
Print_Internal_Pointer_Map(array_pool);
}
else {
More_On_Info_Level_1(command);
}
break;
}
case eCMD_CONFIG: {
if(command.size()<4) {
Signal_Error(SE_REQUIRE_MORE_TOKENS, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
std::string item = command.at(1);
bool status = command.at(2)==STATUS_ON?true:false;
if(item==CONFIG_DEBUG) {
if(status) {
enable_debug_mode = true;
current_ast_depth = 0;
std::cout<<DEB_MODE_ON<<std::endl;
return VALID_COMMAND_RETURN_CODE;
}
else {
enable_debug_mode = false;
current_ast_depth = 0;
std::cout<<DEB_MODE_OFF<<std::endl;
return VALID_COMMAND_RETURN_CODE;
}
}
else if(item==CONFIG_FLOAT_POINT) {
if(status) {
enable_float_point = true;
}
else {
enable_float_point = false;
}
}
else if(item==CONFIG_RAW_STRING) {
if(status) {
enable_raw_string = true;
tokenizer->enable_raw_string = true;
}
else {
enable_raw_string = false;
tokenizer->enable_raw_string = false;
}
}
else if(item==CONFIG_GC) {
if(status) {
enable_gc = true;
}
else {
enable_gc = false;
}
}
else if(item==CONFIG_SIDE_EFFECTS) {
if(status) {
allow_side_effects = true;
}
else {
allow_side_effects = false;
}
}
else {
More_On_Config_Level_1(item, command.at(2));
}
break;
}
case eCMD_ARRAY: {
if(command.size()<4) {
Signal_Error(SE_REQUIRE_MORE_TOKENS, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
try {
Array_Processing_Helper(command);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
break;
}
case eEVALUATE: {
const_itVecStr expr = const_itVecStr(command.begin(),command.end()-1);
try {
Evaluate_Expression(expr);
}
catch (const HUAJIBASE_EXCEPTION& e) {
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return INVALID_COMMAND_RETURN_CODE;
}
break;
}
default: {
Signal_Error(IE_UNDEFINED_NAME, command);
Cleanup_If_Exception_Thrown(reverted_ast_depth);
return UNKNOWN_COMMAND_RETURN_CODE;
}
}
Print_Debug_Info(DEB_COMMAND_END, DECREASE_AST_DEPTH, command);
return VALID_COMMAND_RETURN_CODE;
}
std::pair<int,bool> hjbase::HUAJISCRIPTBASE::More_On_Command_Level_1(const const_itVecStr& command) {
return std::pair<int, bool>(-1, false);
}
void hjbase::HUAJISCRIPTBASE::Array_Processing_Helper(const const_itVecStr& iVstr) {
std::string flag = iVstr.at(1);
std::string array_ptrStr = iVstr.at(2);
std::vector<std::string>::const_iterator cur_it = iVstr.begin()+3;
std::pair<std::vector<std::string>::const_iterator, std::vector<std::string>::const_iterator> expr_it_pair;
if(array_ptrStr==EXPR_START) {
expr_it_pair = Get_Expr_Position_Iterators(iVstr);
const_itVecStr expr = const_itVecStr(expr_it_pair.first, expr_it_pair.second);
array_ptrStr = Evaluate_Expression(expr);
cur_it = expr_it_pair.second;
}
else {
array_ptrStr = Handle_Val(array_ptrStr);
}
std::vector<std::string>* array_ptr = Get_Array_Object(array_ptrStr);
if(!array_ptr) {
Signal_Error(IE_INTERNAL_QUERY_FAILED, iVstr);
throw huaji_except;
}
// array_ptr initialization complete
if(flag==POP_BACK_FLAG) {
if(!array_ptr->size()) {
Signal_Error(NE_OUT_OF_RANGE, array_ptrStr);
throw eval_except;
}
GC_Delete_Record(array_ptrStr, array_ptr->back());
array_ptr->pop_back();
return;
}
std::string arg1 = *cur_it;
if(arg1==EXPR_START) {
expr_it_pair = Get_Expr_Position_Iterators(const_itVecStr(cur_it, iVstr.end()));
const_itVecStr expr = const_itVecStr(expr_it_pair.first, expr_it_pair.second);
arg1 = Evaluate_Expression(expr);
cur_it = expr_it_pair.second;
}
else {
arg1 = Handle_Val(arg1);
++cur_it;
}
// arg1 initialization complete
if(flag==PUSH_BACK_FLAG) {
array_ptr->push_back(arg1);
GC_New_Record(array_ptrStr, arg1);
return;
}
// After above operation, later arg1 will be used to refer array postion
std::vector<std::string>::const_iterator pos_it;
int pos;
try {
pos = std::stoi(arg1);
}
catch (const std::logic_error& le) {
Signal_Error(NE_CONVERSION_FAILED, arg1);
throw eval_except;
}
pos_it = array_ptr->begin()+pos;
if(pos_it>=array_ptr->end()) {
Signal_Error(NE_OUT_OF_RANGE, arg1);
throw eval_except;
}
// pos_it, pos initialization complete
if(flag==ERASE_FLAG) {
GC_Delete_Record(array_ptrStr, *pos_it);
array_ptr->erase(pos_it);
return;
}
std::string arg2 = *cur_it;
if(arg2==EXPR_START) {
expr_it_pair = Get_Expr_Position_Iterators(const_itVecStr(cur_it, iVstr.end()));
const_itVecStr expr = const_itVecStr(expr_it_pair.first, expr_it_pair.second);
arg2 = Evaluate_Expression(expr);
}
else {
arg2 = Handle_Val(arg2);
}
// arg2 initialization complete
if(flag==INSERT_FLAG) {
array_ptr->insert(pos_it, arg2);
GC_New_Record(array_ptrStr, arg2);
return;
}
if(flag==MUTATE_FLAG) {
GC_Delete_Record(array_ptrStr, *pos_it);
(*array_ptr)[pos] = arg2;
GC_New_Record(array_ptrStr, arg2);
}
return;
}
std::string hjbase::HUAJISCRIPTBASE::Evaluate_Expression(const const_itVecStr& expr) {
Print_Debug_Info(DEB_EXPR_START, INCREASE_AST_DEPTH, expr);
std::string ans_val;
std::vector<std::string>* vals_container = nullptr;
if(!expr.size()) {
Signal_Error(SE_UNABLE_TO_PROCESS_EXPR, expr);
throw eval_except;
}
else if(expr.size()==1) {
ans_val = Handle_Val(expr.at(0));
}
else {
// Check if braces are presented
if(expr.front()!=EXPR_START||expr.back()!=EXPR_END) {
Signal_Error(SE_UNEXPECTED_TOKEN, expr);
throw syntax_except;
}
/*
After above checks, the expression must be expr = EXPR_START op expr ... EXPR_END
We also allow op to be a expr
*/
std::string op = expr.at(1);
int op_expr_offset = 2;
if(op==EXPR_START) {
std::pair<std::vector<std::string>::const_iterator, std::vector<std::string>::const_iterator>
op_expr_it_pair = Get_Expr_Position_Iterators(const_itVecStr(expr.begin()+1, expr.end()-1));
op = Evaluate_Expression(const_itVecStr(op_expr_it_pair.first, op_expr_it_pair.second));
op_expr_offset = op_expr_it_pair.second - expr.begin();
}
GC_New_Record(TEMP_RET_VAL_NAME, op);
if(op==FUNC_LAMBDA) {
std::vector<std::string>::const_iterator func_def_begin = expr.end();
std::vector<std::string>::const_iterator func_def_end = expr.end();
std::list<std::string>* arg_names = new std::list<std::string>;
std::map<std::string, std::string>* stack_map = new std::map<std::string, std::string>;
bool lazy = false;
if(expr.at(op_expr_offset)==LAZY_FLAG) {
++op_expr_offset;
lazy = true;
}
// expr.begin()+op_expr_offset+1, the +1 is because we need to skip EXPR_START
FUNC_Paring_Helper(stack_map, arg_names, const_itVecStr(expr.begin()+op_expr_offset+1, expr.end()-1),
func_def_begin, func_def_end);
GC_New_MultiRecords(stack_map);
FUNC* func_ptr = new FUNC(false, const_itVecStr(func_def_begin, func_def_end), stack_map, arg_names, lazy);
std::string func_ptrStr = FUNC_TAG + Convert_Ptr_To_Str(func_ptr) + FUNC_LAMBDA;
if(!(func_pool->insert(std::pair<std::string, FUNC*>(func_ptrStr, func_ptr))).second) {
delete func_ptr;
GC_Delete_MultiRecords(stack_map);
Signal_Error(IE_INSERTION_FAILURE, func_ptrStr);
throw huaji_except;
}
ans_val = func_ptrStr;
}
else {
// Check if op is a func, and if it is a func, check if it is lazy
std::map<std::string, int>::const_iterator op_key_it = NUMERICAL_OPERATORS.find(op);
bool is_numerical_op = false;
bool is_builtin_func = false;
bool is_more_func = false;
bool is_lazy = false;
FUNC* func_ptr = nullptr;
int op_key;
// Numerical_operators
if(op_key_it!=NUMERICAL_OPERATORS.end()) {
is_numerical_op = true;
op_key = op_key_it->second;
}
else {
// Builtin Func
op_key_it = BUILTIN_FUNCTIONS.find(op);
if(op_key_it!=BUILTIN_FUNCTIONS.end()) {
is_builtin_func = true;
op_key = op_key_it->second;
}
else {
// Built-in func in derived class
std::pair<int, bool> ret_pair = More_On_Builtin_Function_Search_Level_1(op);
if(ret_pair.second) {
is_more_func = true;
op_key = ret_pair.first;
}
// user-defined func
else {
std::string func_ptrStr;
if(Starts_With(op, FUNC_TAG)) {
func_ptrStr = op;
}
else {
func_ptrStr = Resolve_Name(op);
}
std::map<std::string, FUNC*>::const_iterator func_ptr_it = func_pool->find(func_ptrStr);
if(func_ptr_it==func_pool->end()) {
Signal_Error(IE_INTERNAL_QUERY_FAILED, func_ptrStr);
throw huaji_except;
}
else {
func_ptr = func_ptr_it->second;
if(func_ptr->is_lazy) {
is_lazy = true;
}
}
}
}
}
/*
Start to wrap arguments and record position in the following vectors.
The iterators are stored in ordered pairs, even though the we're using flat data structure - vector.
*/
std::vector<std::vector<std::string>::const_iterator> pos_its;
int num_of_args = 0;
// Record if the symbol is inside braces
int num_of_unclosed_braces = 0;
/*
Loop all tokens inside the EXPR_START, note we have recorded operator symbol so we start at begin()+2
end()-1 must be a EXPR_END. Though we don't check here, in Collect_Tokens it has been implicitly checked.
*/
for(std::vector<std::string>::const_iterator it=expr.begin()+op_expr_offset;it<expr.end()-1;++it) {
// Handling nested expression
if(*it==EXPR_START) {
// If this is already at top level
if(num_of_unclosed_braces==0) {
pos_its.push_back(it);
}
// Add unclosed braces
++num_of_unclosed_braces;
}
else if(*it==EXPR_END) {
--num_of_unclosed_braces;
if(num_of_unclosed_braces==0) {
/*
Here we add 1 because we will use std::vector constructor
, which does not include end iterator
*/
pos_its.push_back(it+1);
++num_of_args;
}
// Prevent too many right braces
if(num_of_unclosed_braces<0) {
GC_Delete_Record(TEMP_RET_VAL_NAME, op);
Signal_Error(SE_UNEXPECTED_TOKEN, expr);
throw syntax_except;
}
}
// Handling val
else {
// At top level and is not EXPR_START or EXPR_END then it must be a val
if(num_of_unclosed_braces==0) {
pos_its.push_back(it);
pos_its.push_back(it+1);
++num_of_args;
}
}
}
// Throw error if there are unclosed EXPR_START
if(num_of_unclosed_braces!=0) {
GC_Delete_Record(TEMP_RET_VAL_NAME, op);
Signal_Error(SE_REQUIRE_MORE_TOKENS, expr);
throw syntax_except;
}
/*
As we don't have a parser, we have to create ast dynamically.
Create a std::vector<std::string>* vals_container to store evaluated expression first,
later we will construct a const_itVecStr object based on this vals_container
and pass it to other processing functions
*/
vals_container = new std::vector<std::string>;
for(int i=0;i<pos_its.size();i+=2) {
std::string val;
try {
if(is_lazy) {
// Create lazy object
const_itVecStr* lazy_ptr = new const_itVecStr(pos_its.at(i), pos_its.at(i+1));
std::string lazy_ptrStr = LAZY_TAG + Convert_Ptr_To_Str(lazy_ptr);
// Put into lazy_expr_pool
if(!(lazy_expr_pool->insert(std::pair<std::string, const_itVecStr*>
(lazy_ptrStr, lazy_ptr))).second) {
Signal_Error(IE_INSERTION_FAILURE, lazy_ptrStr);
throw huaji_except;
}
val = lazy_ptrStr;
}
else {
const_itVecStr arg = const_itVecStr(pos_its.at(i), pos_its.at(i+1));
val = Evaluate_Expression(arg);
}
}
catch (const HUAJIBASE_EXCEPTION& e) {
GC_Delete_Record(TEMP_RET_VAL_NAME, op);
for(std::vector<std::string>::const_iterator val_it=vals_container->begin();
val_it<vals_container->end();++val_it) {
GC_Delete_Record(TEMP_RET_VAL_NAME, *val_it);
}
delete vals_container;
throw e;
}
GC_New_Record(TEMP_RET_VAL_NAME, val);
vals_container->push_back(val);
}
// Construct const_itVecStr for evaluation
const_itVecStr vals = const_itVecStr(vals_container->begin(), vals_container->end());
// Evaluate Expression
try {
if(is_numerical_op) {
ans_val = Numerical_Operation(op, op_key, vals);
}
else if(is_builtin_func) {
ans_val = Builtin_Function(op, op_key, vals);
}
else if(is_more_func) {
ans_val = More_On_Builtin_Function_Level_1(op, op_key, vals);
}
else {
ans_val = Apply_Function(func_ptr, vals);
}
}
catch (const HUAJIBASE_EXCEPTION& e) {
for(std::vector<std::string>::const_iterator val_it=vals_container->begin();
val_it<vals_container->end();++val_it) {
GC_Delete_Record(TEMP_RET_VAL_NAME, *val_it);
}
delete vals_container;
GC_Delete_Record(TEMP_RET_VAL_NAME, op);
throw e;
}
}
/*
OP cannot be a return value, so OP can be deleted here, but vals_container needs to be
deleted after GC_New_Record called on return value, as there might be some val that can be
returned.
*/
GC_Delete_Record(TEMP_RET_VAL_NAME, op);
}
// It is unnecessary to do GC if temp_return_val==ans_val
if(temp_return_val!=ans_val) {
GC_Delete_Record(TEMP_RET_VAL_NAME, temp_return_val);
temp_return_val = ans_val;
GC_New_Record(TEMP_RET_VAL_NAME, ans_val);
}
// vals_container has to be deleted after GC_New_Record called on return value
if(vals_container) {
for(std::vector<std::string>::const_iterator val_it=vals_container->begin();
val_it<vals_container->end();++val_it) {
GC_Delete_Record(TEMP_RET_VAL_NAME, *val_it);
}
delete vals_container;
}
Print_Debug_Info(DEB_EXPR_END, DECREASE_AST_DEPTH, ans_val);
return ans_val;
}
template <typename T> std::string
hjbase::HUAJISCRIPTBASE::Numerical_Operation_Templated_Helper(const std::string& op, int op_key, int vals_size, int T_name, const const_itVecStr& vals) {
// Initialize numerical value array
T* numerical_vals = new T[vals_size];
T numerical_ans_val = 0;
bool direct_string_return = false;
std::string direct_return_string;
std::string ans_val;
for(std::vector<std::string>::const_iterator it=vals.begin();it<vals.end();++it) {
try {
if(T_name == TYPE_DOUBLE) {
numerical_vals[it-vals.begin()] = std::stod(*it);
}
else if(T_name == TYPE_LONG) {
numerical_vals[it-vals.begin()] = std::stol(*it);
}
else {
delete [] numerical_vals;
Signal_Error(IE_UNDEFINED_NAME, std::to_string(T_name));
throw eval_except;
}
}
// Handle Conversion error
catch (const std::invalid_argument& ia) {
delete [] numerical_vals;
Signal_Error(NE_CONVERSION_FAILED, *it);
throw eval_except;
}
catch (const std::out_of_range& oor) {
delete [] numerical_vals;
Signal_Error(NE_OUT_OF_RANGE, *it);
throw eval_except;
}
}
try {
switch (op_key) {
case eOP_ADD: {
for(int i=0;i<vals_size;++i) {
numerical_ans_val += numerical_vals[i];
}
break;
}
case eOP_MINUS: {
numerical_ans_val = numerical_vals[0];
for(int i=1;i<vals_size;++i) {
numerical_ans_val -= numerical_vals[i];
}
break;
}
case eOP_MULTIPLY: {
numerical_ans_val = numerical_vals[0];
for(int i=1;i<vals_size;++i) {
numerical_ans_val *= numerical_vals[i];
}
break;
}
case eOP_DIVISION: {
numerical_ans_val = numerical_vals[0];
for(int i=1;i<vals_size;++i) {
if(numerical_vals[i]==0) {
Signal_Error(AE_DVZ, vals);
throw eval_except;
}
numerical_ans_val /= numerical_vals[i];
}
break;
}
case eOP_MOD: {
if(vals_size!=2) {
Signal_Error(SE_ARITY_MISMATCH, vals);
throw eval_except;
}
else {
if(static_cast<long>(numerical_vals[1])==0) {
Signal_Error(AE_DVZ, vals);
throw eval_except;
}
/*
As this template also applys to double, we have to make compiler happy by add casting.
Although it sounds reasonable to signal error when performing modulo expression with
floating point number, I still want to let it possible by converted to integer.
*/
return std::to_string(static_cast<long>(numerical_vals[0])
%static_cast<long>(numerical_vals[1]));
}
}
case eOP_LE: {
direct_string_return = true;
direct_return_string = BOOL_TRUE;
for(int i=1;i<vals_size;++i) {
// I feel this is clearer, although use '>' might save time
if(!(numerical_vals[i-1]<=numerical_vals[i])){
direct_return_string = BOOL_FALSE;
break;
}
}
break;
}
case eOP_GE: {
direct_string_return = true;
direct_return_string = BOOL_TRUE;
for(int i=1;i<vals_size;++i) {
if(!(numerical_vals[i-1]>=numerical_vals[i])){
direct_return_string = BOOL_FALSE;
break;
}
}
break;
}
case eOP_LT: {
direct_string_return = true;
direct_return_string = BOOL_TRUE;
for(int i=1;i<vals_size;++i) {
if(!(numerical_vals[i-1]<numerical_vals[i])){
direct_return_string = BOOL_FALSE;
break;
}
}
break;
}
case eOP_GT: {
direct_string_return = true;
direct_return_string = BOOL_TRUE;
for(int i=1;i<vals_size;++i) {
if(!(numerical_vals[i-1]>numerical_vals[i])){
direct_return_string = BOOL_FALSE;
break;
}
}
break;
}
default: {
Signal_Error(IE_UNKNOWN, op);
throw huaji_except;
}
}
}
catch (const HUAJIBASE_EXCEPTION& e) {
delete [] numerical_vals;
throw e;
}
catch (...) {
delete [] numerical_vals;
Signal_Error(IE_UNKNOWN, vals);
throw eval_except;
}
delete [] numerical_vals;
if(direct_string_return) {
return direct_return_string;
}
// If the result is numerical, convert back to string, and catch all exceptions during conversion.
try {
ans_val = std::to_string(numerical_ans_val);
}
catch (...) {
Signal_Error(NE_CONVERSION_FAILED, vals);
throw huaji_except;
}
return ans_val;
}
// Explicit template instantiation
template std::string
hjbase::HUAJISCRIPTBASE::Numerical_Operation_Templated_Helper<long>(const std::string&, int, int, int, const const_itVecStr&);
template std::string
hjbase::HUAJISCRIPTBASE::Numerical_Operation_Templated_Helper<double>(const std::string&, int, int, int, const const_itVecStr&);
std::string hjbase::HUAJISCRIPTBASE::Numerical_Operation(const std::string& op, int op_key, const const_itVecStr& vals) {
int vals_size = vals.size();
// we allow vals to be empty in some cases, but none of numerical operation can have no vals
if(!vals_size) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
std::string ans_val;
/*
Determine to use float point calculation or integer, this process might be slow,
so we decide to add an option for users to disable float point
*/
if(enable_float_point) {
// Check if a dot in all val.
if(Check_If_Float_Point(vals)) {
/*
Now we have an array of numerical oprands, apply templated calculation function.
As it is impossible for compiler to deduce which version of template to use,
we need to explicitly specify template type
*/
ans_val = Numerical_Operation_Templated_Helper<double>(op, op_key, vals_size, TYPE_DOUBLE, vals);
return ans_val;
}
}
// explicitly specify using long template
ans_val = Numerical_Operation_Templated_Helper<long>(op, op_key, vals_size, TYPE_LONG, vals);
return ans_val;
}
std::pair<std::string, bool>
hjbase::HUAJISCRIPTBASE::More_On_Slice_Operator_Level_1(const const_itVecStr& vals) {
return std::pair<std::string, bool>(std::string(), false);
}
std::string
hjbase::HUAJISCRIPTBASE::Builtin_Function(const std::string& op, int op_key, const const_itVecStr& vals) {
try {
switch (op_key) {
case eFUNC_AND: {
for(std::vector<std::string>::const_iterator it=vals.begin();it<vals.end();++it) {
if(*it==BOOL_FALSE) {
return BOOL_FALSE;
}
}
return BOOL_TRUE;
}
case eFUNC_OR: {
for(std::vector<std::string>::const_iterator it=vals.begin();it<vals.end();++it) {
if(*it!=BOOL_FALSE) {
return BOOL_TRUE;
}
}
return BOOL_FALSE;
}
case eFUNC_NOT: {
if(vals.size()!=1) {
Signal_Error(SE_ARITY_MISMATCH, vals);
throw eval_except;
}
if(vals.front()!=BOOL_FALSE) {
return BOOL_TRUE;
}
return BOOL_FALSE;
}
case eFUNC_EQ: {
for(std::vector<std::string>::const_iterator it=vals.begin()+1;it<vals.end();++it) {
if(*(it-1)!=*it) {
return BOOL_FALSE;
}
}
return BOOL_TRUE;
}
case eFUNC_NE: {
for(std::vector<std::string>::const_iterator it_first=vals.begin();it_first!=vals.end()-1;++it_first) {
for(std::vector<std::string>::const_iterator it_second=vals.begin()+1;it_second!=vals.end();++it_second) {
if(*it_first==*it_second) {
return BOOL_FALSE;
}
}
}
return BOOL_TRUE;
}
case eFUNC_STRAPP: {
std::string ans_val;
for(std::vector<std::string>::const_iterator it=vals.begin();it<vals.end();++it) {
ans_val.append(*it);
}
return ans_val;
}
case eFUNC_STRLEN: {
if(vals.size()!=1) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw eval_except;
}
return std::to_string(vals.at(0).size());
}
case eFUNC_SLICE: {
std::pair<std::string, bool> ret_pair = More_On_Slice_Operator_Level_1(vals);
if(ret_pair.second) {
return ret_pair.first;
}
else {
int vals_size = vals.size();
// Require at least two arguments
if(vals_size>1) {
std::string to_be_sliced = vals.at(0);
// get slice starting position
int slice_start = std::stoi(vals.at(1));
if(slice_start<0) {
slice_start = to_be_sliced.size()+slice_start;
}
// three arguments indicate an ending position also provided
if(vals_size==3) {
int slice_end = std::stoi(vals.at(2));
if(slice_end<0) {
slice_end = to_be_sliced.size()+slice_end+1;
}
int slice_length = slice_end-slice_start;
if(slice_length<0) {
Signal_Error(SLE_OUT_OF_RANGE, vals);
throw eval_except;
}
return to_be_sliced.substr(slice_start, slice_length);
}
// two arguments, no ending position provided, return that starting position char
else if(vals_size==2) {
return std::string(1, to_be_sliced.at(slice_start));
}
else {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
}
else {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
}
}
case eFUNC_LIST: {
std::string ret_list = EXPR_START;
for(std::vector<std::string>::const_iterator it=vals.begin();it<vals.end();++it) {
// Add quotation mark if *it has space
if(Quotation_Rquired_For_List_Elem(*it)) {
ret_list.push_back(QUOTATION_MARK);
ret_list.append(*it);
ret_list.push_back(QUOTATION_MARK);
}
else {
ret_list.append(*it);
}
ret_list.push_back(' ');
}
// The last char is a space, but we want it to be cEXPR_END
ret_list[ret_list.size()-1] = cEXPR_END;
return ret_list;
}
case eFUNC_FIRST: {
/*
Check how many vals are there, if more than one val, return a list
consists of all first elements in each list. Exception will be thrown if
any list is empty. Else return the first member of the list
*/
int vals_size = vals.size();
if(vals_size==1) {
std::string ret_elem;
std::string this_list = vals.at(0);
std::pair<int, int> first_elem_pos = Get_First_Element_Pos(this_list);
ret_elem = this_list.substr(first_elem_pos.first, first_elem_pos.second);
return ret_elem;
}
else if(vals_size>1) {
std::string ret_list = EXPR_START;
for(std::vector<std::string>::const_iterator it=vals.begin();it<vals.end();++it) {
std::pair<int, int> first_elem_pos = Get_First_Element_Pos(*it);
std::string to_append = (*it).substr(first_elem_pos.first, first_elem_pos.second);
ret_list.append(to_append);
ret_list.push_back(' ');
}
ret_list[ret_list.size()-1] = cEXPR_END;
return ret_list;
}
else {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
}
case eFUNC_REST: {
if(vals.size()==1) {
// Need to exclude last quotation mark, so pass include_last_quotaion=true
std::pair<int, int> first_pos = Get_First_Element_Pos(vals.at(0));
return Format_List_String(vals.at(0).substr(first_pos.first+first_pos.second, std::string::npos));
}
else if(vals.size()>1) {
std::string ret_list = EXPR_START;
for(std::vector<std::string>::const_iterator it=vals.begin();it<vals.end();++it) {
std::pair<int, int> first_pos = Get_First_Element_Pos(*it);
ret_list.append(Format_List_String((*it).substr(first_pos.first+first_pos.second, std::string::npos)));
ret_list.push_back(' ');
}
ret_list[ret_list.size()-1] = cEXPR_END;
return ret_list;
}
else {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
}
case eFUNC_CONS: {
if(vals.size()!=2) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
// Put elem to cons at list front
std::string ret_list;
if(Quotation_Rquired_For_List_Elem(vals.at(0))) {
ret_list.push_back(QUOTATION_MARK);
ret_list.append(vals.at(0));
ret_list.push_back(QUOTATION_MARK);
}
else {
ret_list = vals.at(0);
}
/*
Append second arg to ret_list, note here we don't check if second arg
is a valid list or not, if not, exception will thrown in Format_List_String
*/
ret_list.push_back(' ');
ret_list.append(vals.at(1).substr(1, std::string::npos));
return Format_List_String(ret_list);
}
case eFUNC_APPEND: {
std::string ret_list;
for(std::vector<std::string>::const_iterator it=vals.begin();it<vals.end();++it) {
if((*it).front()!=cEXPR_START&&(*it).back()!=cEXPR_END) {
Signal_Error(TE_NOT_LIST, *it);
throw type_except;
}
// Rip a head and a tail append to ret_list
ret_list.append((*it).substr(1, (*it).size()-2));
// Add a space
ret_list.push_back(' ');
}
// change last space to cEXPR_END
ret_list[ret_list.size()-1] = cEXPR_END;
return Format_List_String(ret_list);
}
case eFUNC_RESOLVE: {
if(vals.size()!=1) {
Signal_Error(SE_ARITY_MISMATCH, vals);
throw syntax_except;
}
return Handle_Val(vals.at(0));
}
case eFUNC_GETRET: {
if(vals.size()) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
return temp_return_val;
}
case eFUNC_STACK_POS: {
if(vals.size()) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
return std::to_string(names_stack->size()-1);
}
case eFUNC_INIT: {
if(vals.size()!=1) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
std::map<std::string, std::map<std::string, std::string>*>::const_iterator
parent_namespace_it = namespace_pool->find(vals.at(0));
if(parent_namespace_it==namespace_pool->end()) {
Signal_Error(IE_INTERNAL_QUERY_FAILED, vals.at(0));
throw huaji_except;
}
std::map<std::string, std::string>* object_ptr
= new std::map<std::string, std::string>(*(parent_namespace_it->second));
std::string object_ptrStr = OBJECT_TAG + Convert_Ptr_To_Str(object_ptr) + vals.at(0);
if(!(object_pool->insert
(std::pair<std::string, std::map<std::string, std::string>*>(object_ptrStr, object_ptr)).second)) {
// Insertion failed, same object
delete object_ptr;
Signal_Error(IE_INSERTION_FAILURE, vals.at(1));
throw huaji_except;
}
return object_ptrStr;
}
case eFUNC_MEMVAR: {
if(vals.size()!=2) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
std::map<std::string, std::map<std::string, std::string>*>::const_iterator
object_it = object_pool->find(vals.at(1));
if(object_it==object_pool->end()) {
Signal_Error(IE_INTERNAL_QUERY_FAILED, vals.at(1));
throw huaji_except;
}
std::map<std::string, std::string>* object_ptr = object_it->second;
try {
return object_ptr->at(vals.at(0));
}
catch (const std::out_of_range& oor) {
Signal_Error(NAE_UNDEFINED, vals.at(0));
throw name_except;
}
}
case eFUNC_LAZY: {
if(vals.size()!=1) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
try {
const_itVecStr* expr = lazy_expr_pool->at(vals.at(0));
return Evaluate_Expression(*expr);
}
catch (const std::out_of_range& oor) {
Signal_Error(IE_INTERNAL_QUERY_FAILED, vals.at(0));
throw eval_except;
}
}
case eFUNC_IS: {
std::istream* is;
if(vals.size()<1) {
is = &std::cin;
// Here insertion might fail if user used cin before, but that's ok
istream_pool->insert(std::pair<std::string, std::istream*>(CIN_PTRSTR, is));
return CIN_PTRSTR;
}
else {
is = new std::ifstream(vals.at(0));
if(!is->good()) {
delete is;
Signal_Error(IOE_FILE_NOT_EXISTS, vals.at(0));
throw eval_except;
}
}
std::string is_ptrStr = ISTREAM_TAG + Convert_Ptr_To_Str(is) + vals.at(0);
istream_pool->insert(std::pair<std::string, std::istream*>(is_ptrStr, is));
return is_ptrStr;
}
case eFUNC_OS: {
std::ostream* os;
if(vals.size()<1) {
os = &std::cout;
// Here insertion might fail if user used cin before, but that's ok
ostream_pool->insert(std::pair<std::string, std::ostream*>(COUT_PTRSTR, os));
return COUT_PTRSTR;
}
else {
if(vals.size()>1) {
if(vals.at(1)==APP_FLAG) {
os = new std::ofstream(vals.at(0), std::ios_base::app);
}
os = new std::ofstream(vals.at(0));
}
else {
os = new std::ofstream(vals.at(0));
}
if(!os->good()) {
delete os;
Signal_Error(IOE_FILE_NOT_EXISTS, vals.at(0));
throw eval_except;
}
}
std::string os_ptrStr = OSTREAM_TAG + Convert_Ptr_To_Str(os) + vals.at(0);
ostream_pool->insert(std::pair<std::string, std::ostream*>(os_ptrStr, os));
return os_ptrStr;
}
case eFUNC_READ: {
if(vals.size()<2) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw eval_except;
}
std::string flag = vals.at(0);
std::map<std::string, std::istream*>::const_iterator is_it
= istream_pool->find(vals.at(1));
if(is_it==istream_pool->end()) {
Signal_Error(IE_INTERNAL_QUERY_FAILED, vals.at(1));
throw huaji_except;
}
std::istream* is = is_it->second;
try {
if(flag==GETCHAR_FLAG) {
char cur_char = is->get();
if(cur_char==std::char_traits<char>::eof()) {
return EOF_TAG;
}
else {
return std::string(1, cur_char);
}
}
else if(flag==UNGETCHAR_FLAG) {
is->unget();
return EOF_TAG;
}
else if(flag==GETLINE_FLAG) {
std::string ret_str;
std::getline(*is, ret_str);
return ret_str;
}
else if(flag==TOEND_FLAG) {
char cur_char = is->get();
std::string ret_str;
while(cur_char!=std::char_traits<char>::eof()) {
ret_str.push_back(cur_char);
cur_char = is->get();
}
return ret_str;
}
else {
Signal_Error(SE_UNRECOGNISED_FLAG, flag);
throw eval_except;
}
}
catch (std::ios_base::failure& e) {
Signal_Error(IOE_IOSBASE_FAILURE, vals.at(1));
throw eval_except;
}
}
case eFUNC_WRITE: {
if(vals.size()<1) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw eval_except;
}
std::map<std::string, std::ostream*>::const_iterator os_it
= ostream_pool->find(vals.at(0));
if(os_it==ostream_pool->end()) {
Signal_Error(IE_INTERNAL_QUERY_FAILED, vals.at(0));
throw huaji_except;
}
std::ostream* os = os_it->second;
try {
for(std::vector<std::string>::const_iterator val_it=vals.begin()+1;val_it!=vals.end();++val_it) {
(*os)<<(*val_it);
}
}
catch (std::ios_base::failure& e) {
Signal_Error(IOE_IOSBASE_FAILURE, vals.at(1));
throw eval_except;
}
return EOF_TAG;
}
case eFUNC_ARRAY_NEW: {
std::vector<std::string>* array_ptr = new std::vector<std::string>;
std::string array_ptrStr = ARRAY_TAG + Convert_Ptr_To_Str(array_ptr);
// Assume array_ptr is unique, so we don't do check here
array_pool->insert(std::pair<std::string, std::vector<std::string>*>(array_ptrStr, array_ptr));
return array_ptrStr;
}
case eFUNC_ARRAY_REF: {
if(vals.size()<2) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw eval_except;
}
std::vector<std::string>* array_ptr = Get_Array_Object(vals.at(0));
if(!array_ptr) {
Signal_Error(IE_INTERNAL_QUERY_FAILED, vals.at(0));
throw eval_except;
}
int ref_pos;
try {
ref_pos = std::stoi(vals.at(1));
}
catch (const std::logic_error& le) {
Signal_Error(NE_CONVERSION_FAILED, vals.at(1));
throw eval_except;
}
if(ref_pos>=array_ptr->size()) {
Signal_Error(NE_OUT_OF_RANGE, vals.at(1));
throw eval_except;
}
return array_ptr->at(ref_pos);
}
case eFUNC_ARRAY_SIZE: {
if(vals.size()!=1) {
Signal_Error(SE_ARITY_MISMATCH, op);
throw syntax_except;
}
std::vector<std::string>* array_ptr = Get_Array_Object(vals.at(0));
return std::to_string(array_ptr->size());
}
default: {
Signal_Error(IE_UNKNOWN, op);
throw huaji_except;
}
}
}
catch (const HUAJIBASE_EXCEPTION& e) {
throw eval_except;
}
catch (const std::invalid_argument& ia) {
Signal_Error(NE_CONVERSION_FAILED, vals);
throw eval_except;
}
catch (const std::out_of_range& oor) {
Signal_Error(NE_OUT_OF_RANGE, vals);
throw eval_except;
}
catch (...) {
Signal_Error(IE_UNKNOWN, vals);
throw eval_except;
}
// no match clause, must be a bug
Signal_Error(IE_UNDEFINED_NAME, op);
throw huaji_except;
}
std::pair<int, bool>
hjbase::HUAJISCRIPTBASE::More_On_Builtin_Function_Search_Level_1(const std::string& op) {
return std::pair<int, bool>(-1, false);
}
std::string hjbase::HUAJISCRIPTBASE::More_On_Builtin_Function_Level_1(const std::string& op, int op_key, const const_itVecStr& vals) {
throw huaji_except;
}
std::string hjbase::HUAJISCRIPTBASE::Apply_Function(FUNC* func_ptr, const const_itVecStr& vals) {
// Invoke Side_Effects_Guard if the function has side effects
if(func_ptr->has_side_effects) {
Side_Effects_Guard();
}
// Allocate new stack and pushed to names_stack
std::map<std::string, std::string>* preset_stack_frame
= func_ptr->Get_Stack_Frame_Template_Copy_On_Heap();
std::list<std::string> var_names = func_ptr->Get_Var_Names();
if((var_names.size()!=vals.size()&&!(func_ptr->has_side_effects))
||var_names.size()<vals.size()) {
Signal_Error(SE_ARITY_MISMATCH, vals);
throw syntax_except;
}
bool object_scope_ref_used = false;
// Variable substitution
std::list<std::string>::const_iterator name_it=var_names.begin();
for(std::vector<std::string>::const_iterator val_it=vals.begin();
val_it!=vals.end();++val_it) {
(*preset_stack_frame)[*name_it] = *val_it;
if(!object_scope_ref_used&&*name_it==OBJECT_SCOPE_REF) {
try {
Push_Object_Into_Stack(*val_it);
}
catch (const HUAJIBASE_EXCEPTION& e) {
delete preset_stack_frame;
throw e;
}
object_scope_ref_used = true;
}
++name_it;
}
std::string return_val;
Push_Stack_Frame(preset_stack_frame);
if(func_ptr->has_side_effects) {
if(Block_Execution(func_ptr->Get_Fbody())==EXIT_RETURN_CODE) {
return_val = temp_return_val;
}
else {
return_val = UNDEFINED_TYPE;
}
}
else {
return_val = Evaluate_Expression(func_ptr->Get_Fbody());
}
Pop_Stack_Frame();
if(object_scope_ref_used) {
Pop_Object_From_Stack();
}
return return_val;
}
std::pair<std::string, bool>
hjbase::HUAJISCRIPTBASE::More_On_Names_Query_Level_1(const std::string& name) {
return std::pair<std::string, bool>(std::string(), false);
}
std::string hjbase::HUAJISCRIPTBASE::Handle_Val(const std::string& name_or_val) {
if(enable_raw_string) {
if(name_or_val.size()>1) {
if(name_or_val.front()=='$'&&name_or_val.back()=='$') {
std::string name = name_or_val.substr(1,name_or_val.size()-2);
std::pair<std::string, bool> ret_pair = More_On_Names_Query_Level_1(name);
if(ret_pair.second) {
return ret_pair.first;
}
else {
return Resolve_Name(name);
}
}
else if(Starts_With(name_or_val, LIST_TAG)) {
return name_or_val.substr(LIST_TAG_SIZE, std::string::npos);
}
else if(Starts_With(name_or_val, FLAG_TAG)) {
return name_or_val;
}
}
return name_or_val;
}
else {
if(Starts_With(name_or_val, STRING_TAG)) {
return name_or_val.substr(STRING_TAG_SIZE, std::string::npos);
}
else if(Starts_With(name_or_val, LIST_TAG)) {
return name_or_val.substr(LIST_TAG_SIZE, std::string::npos);
}
else if(Is_Numerical(name_or_val)) {
return name_or_val;
}
else if(Starts_With(name_or_val, FLAG_TAG)) {
return name_or_val;
}
else {
std::pair<std::string, bool> ret_pair = More_On_Names_Query_Level_1(name_or_val);
if(ret_pair.second) {
return ret_pair.first;
}
else {
return Resolve_Name(name_or_val);
}
}
}
} |
b3f1d4c9459a71f9d91a53b01f51f96e56ecd820 | aa1b167059d18a5560054173ddc231b155a533a8 | /src/header/printing.h | 309a17c3e90744ad6497f95319ef51441def30be | [] | no_license | emittman/cuda_rpackage | 8ec7305805004cbb64ba77093d260f13f604952c | d1958f8fa83d52ba430bc62a33c36e69e2a2c366 | refs/heads/master | 2021-03-27T16:07:43.140806 | 2017-09-21T16:56:26 | 2017-09-21T16:56:26 | 69,476,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | h | printing.h | #ifndef PRINT_H
#define PRINT_H
#include<thrust/host_vector.h>
#include<thrust/device_vector.h>
#include<iostream>
/*courtesy of https://github.com/thrust/thrust/blob/master/examples/expand.cu */
template <typename Vector>
void printVec(const Vector& v, int d1, int d2)
{
typedef typename Vector::value_type T;
for(int i=0; i<d2; ++i){
thrust::copy(v.begin() + i*d1, v.begin() + (i+1)*d1, std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
}
}
#endif |
aff146aa42212b49398a6c81046abf6e92d311f1 | c7653ebbeebc0158bcf5d9edcdddad959faecdc3 | /week4_binary_search_trees/5_rope/rope.cpp | 2b48b4d8afd7db80ae2eb8ab34c5723415e325e7 | [] | no_license | Wei-Mao/Assignments-for-Data-Structure | d4c841d480ffae86eadb3f70db117abe9eee9300 | a667bf1a8b6f11e7646429f7062f6f2eb9d537d2 | refs/heads/master | 2022-11-30T16:24:26.558979 | 2020-08-10T10:18:59 | 2020-08-10T10:18:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,879 | cpp | rope.cpp | #include <cstdio>
#include <string>
#include <iostream>
#include <stack>
using namespace std;
// Vertex of a splay tree
struct Vertex {
char key;
// number of the nodes in left and right subtrees(including itself)
// remember to update
// it after each operation that changes the tree.
long long size; // for order statistics.
Vertex* left;
Vertex* right;
Vertex* parent;
Vertex(int key, long long size, Vertex* left, Vertex* right, Vertex* parent)
: key(key), size(size), left(left), right(right), parent(parent) {}
};
class Rope {
std::string s;
Vertex * root;
public:
Rope(const std::string &s) : s(s) {
root = NULL;
for(int i(0); i < s.length(); i++)
{
Vertex * char_node = new Vertex(s[i], 1, NULL, NULL, NULL);
root = merge(root, char_node);
}
}
void process_naive( int i, int j, int k ) {
// Replace this code with a faster implementation
std::string t = s.substr(0, i) + s.substr(j + 1);
s = t.substr(0, k) + s.substr(i, j - i + 1) + t.substr(k);
}
void update(Vertex* v)
{
if (v == NULL) return;
// NULL means does not exist.
// update the satellite data.
v->size = 1 + (v->left != NULL ? v->left->size : 0) +
(v->right != NULL ? v->right->size : 0); // update the size.
// v's left and right children has been updated. But v's left and right children have not been updated in time.
// Note that tree is undirected graph. Parent should update child info. Meanwhile, parent' children should update their parent info.
if (v->left != NULL) {
v->left->parent = v;
}
if (v->right != NULL) {
v->right->parent = v;
}
}
void small_rotation(Vertex* v)
{
// Only rotation but not find out which side is heavy. Apply this small_rotation to the right node.
// elevate v to take the place of its parent.
// v, v's children, v's parent, v's grandparent are affected.
Vertex* parent = v->parent;
if (parent == NULL) {
// already root node, no need to rotate.
return;
}
Vertex* grandparent = v->parent->parent;
if (parent->left == v) { // parent > v, parent can be changed to be right child of parent
Vertex* m = v->right; // store right child of v
v->right = parent; // raise v one level up, parent's left child is empty
parent->left = m; // right child of v becomes the left child of old parent
} else { // parent->right == v, parent < v, parent can act as the left child of v
Vertex* m = v->left; // spare space for parent
v->left = parent;
parent->right = m; // v->left take the place of the v as the right child.
}
update(parent); // update v and parent's satellite and children's parent info
update(v);
v->parent = grandparent; // update the parent of v.
// raised v replace the role of the v's parent.
// before updating, you should determine whether parent is left or right child.
if (grandparent != NULL) { // parent of v is not root.
if (grandparent->left == parent) {
grandparent->left = v;
} else {
grandparent->right = v;
}
}
// Since grandparent'sum is the sum of the all elements in its' subtree and subtree nodes of grandparent remains the same(arrangement changes)
// No need to changes the sum of grandparent.
}
// small rotation may be stuck in a loop.This is where the splay step comes into play.
void big_rotation(Vertex* v) {
if (v->parent->left == v && v->parent->parent->left == v->parent) {
// Zig-zig left-handed variant.
small_rotation(v->parent);
small_rotation(v);
} else if (v->parent->right == v && v->parent->parent->right == v->parent) {
// Zig-zig right-handed variant.
small_rotation(v->parent);
small_rotation(v);
} else {
// Zig-zag or Zig step.
small_rotation(v);
small_rotation(v); // If v becomes root after first small_rotation, this rotate does not work again.
}
}
// Makes splay of the given vertex and makes
// it the new root.
void splay(Vertex *&R, Vertex *v) {
// you have to use Vertex *& R to ensure that R always points to the root.
if (v == NULL) return;
// Splay until the v becomes the root.
while (v->parent != NULL) {
if (v->parent->parent == NULL) {
// Zig step
small_rotation(v);
break;
}
// Zig-Zig or Zig-Zag.
big_rotation(v);
}
R = v; // if you don't use reference to root pointer, this will make R not point to root any longer but point to another vertex v.
// What the pointer points to can be synchronize! But the pointer itself can not be synchronize.
// Beware of assign one pointer to another.
}
// Searches for the given key in the tree with the given root
// and calls splay for the deepest visited node after that.
// If found, returns a pointer to the node with the given key.
// Otherwise, returns a pointer to the node with the smallest
// bigger key (next value in the order).
// If the key is bigger than all keys in the tree,
// returns NULL.
Vertex* find(Vertex *&R, int k) {
// Similar to find the kth smallest key in a binary tree of integers.
Vertex* v = R;
while (v != NULL) {
long long s = (v->left != NULL) ? v->left->size : 0;
if (k == (s+1)) { // found
break;
}
else if (k < (s + 1))
{
v = v->left;
}
else
{
// k > s + 1, first (s+1) chars are in the left subtree of v
v = v->right;
k = k - s - 1;
}
}
// v is not NULL->found; v is NULL -> not found.
// after find makes splay to move the frequently-accessed elements up towards the top of the tree.
splay(R, v); // splay the deepest visited node. splay need reference to pointer.
return v;
}
void split(Vertex* &R, int key, Vertex* &left, Vertex* &right)
{
right = find(R, key); // return (key)th char_node.
splay(R, right);
if (right == NULL) {
// No element with key >= key in the given tree with root. Hence, can not split.
left = R;
return;
}
left = right->left;
right->left = NULL; // delete the left node.
if (left != NULL) {
left->parent = NULL;
}
// only right and left are affected.
update(left); // (key - 1)th and ... go the left.
update(right); // keyth and... go to the right.
}
Vertex* merge(Vertex* left, Vertex* right) {
// all elements in left subtree are smaller than those in the right subtree
// If one of tree is empty, then return another. Assume only one of them is empty.
if (left == NULL) return right; // Assignment to pointer. Hence, you should use reference to pointer.
if (right == NULL) return left;
// Find the smallest node in the right subtree.
// Alternatively, find largest node in the left subtree.
Vertex* min_right = right;
while (min_right->left != NULL) {
min_right = min_right->left;
}
splay(right, min_right); // elevate min_right to
right->left = left;
update(right);
return right;
}
void insert(Vertex *&R, int k, Vertex *& sub_string)
{
// Insert sub_string before the kth char of the R, i.e. after(k - 1)
Vertex * left = NULL;
Vertex * right = NULL;
split(R, k, left, right); // First to (k-1)th chars go to left while kth to last go to the right.
R = merge(merge(left, sub_string), right);
}
string in_order_traverse()
{
string print_str;
stack<Vertex *> stack_visited;
Vertex * current_node = root;
while((current_node != NULL) || (!stack_visited.empty()))
{
if(current_node != NULL)
{
stack_visited.push(current_node);
current_node = current_node->left;
}
else
{
// current_node == NULL
Vertex * pushed = stack_visited.top();
stack_visited.pop();
print_str.push_back(pushed->key);
current_node = pushed->right;
}
}
return print_str;
}
void process_fast(int i, int j, int k)
{
// i and j are zero-based.
// k is 1-based.
Vertex * left = NULL;
Vertex * middle = NULL;
Vertex * right = NULL;
split(root, i + 1, left, middle); // S[i,...] goes to the middle
split(middle, j - i + 2, middle, right); // S[i, j] goes to the middle.
root = merge(left, right);
insert(root, k + 1, middle);
}
std::string result() {
s = in_order_traverse();
return s;
}
};
int main() {
std::ios_base::sync_with_stdio(0);
std::string s;
std::cin >> s;
Rope rope(s);
int actions;
std::cin >> actions;
for (int action_index = 0; action_index < actions; ++action_index) {
int i, j, k;
std::cin >> i >> j >> k;
rope.process_fast(i, j, k);
}
std::cout << rope.result() << std::endl;
}
|
741c29addb588d337580992a8b916f08827d3ba8 | 676ffceabdfe022b6381807def2ea401302430ac | /library/FieldUtils/ProcessModules/ProcessHomogeneousPlane.cpp | 6aa94ed4a25e027d08c4c7d8f0cab7e5637f2ae2 | [
"MIT"
] | permissive | mathLab/ITHACA-SEM | 3adf7a49567040398d758f4ee258276fee80065e | 065a269e3f18f2fc9d9f4abd9d47abba14d0933b | refs/heads/master | 2022-07-06T23:42:51.869689 | 2022-06-21T13:27:18 | 2022-06-21T13:27:18 | 136,485,665 | 10 | 5 | MIT | 2019-05-15T08:31:40 | 2018-06-07T14:01:54 | Makefile | UTF-8 | C++ | false | false | 5,851 | cpp | ProcessHomogeneousPlane.cpp | ////////////////////////////////////////////////////////////////////////////////
//
// File: ProcessHomogeneousPlane.cpp
//
// For more information, please see: http://www.nektar.info/
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Extract a single plane of a 3DH1D field.
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
using namespace std;
#include <boost/core/ignore_unused.hpp>
#include <LibUtilities/BasicUtils/SharedArray.hpp>
#include "ProcessHomogeneousPlane.h"
namespace Nektar
{
namespace FieldUtils
{
ModuleKey ProcessHomogeneousPlane::className =
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eProcessModule, "homplane"),
ProcessHomogeneousPlane::create,
"Extracts a plane from a 3DH1D expansion, requires planeid to be "
"defined.");
ProcessHomogeneousPlane::ProcessHomogeneousPlane(FieldSharedPtr f)
: ProcessModule(f)
{
m_config["planeid"] = ConfigOption(false, "NotSet", "plane id to extract");
m_config["wavespace"] =
ConfigOption(true, "0", "Extract plane in Fourier space");
}
ProcessHomogeneousPlane::~ProcessHomogeneousPlane()
{
}
void ProcessHomogeneousPlane::Process(po::variables_map &vm)
{
m_f->SetUpExp(vm);
ASSERTL0(m_f->m_numHomogeneousDir == 1,
"ProcessHomogeneousPlane only works for Homogeneous1D.");
m_f->m_numHomogeneousDir = 0;
// Skip in case of empty partition
if (m_f->m_exp[0]->GetNumElmts() == 0)
{
return;
}
ASSERTL0(m_config["planeid"].m_beenSet,
"Missing parameter planeid for ProcessHomogeneousPlane");
int planeid = m_config["planeid"].as<int>();
int nfields = m_f->m_variables.size();
int nstrips;
m_f->m_session->LoadParameter("Strip_Z", nstrips, 1);
// Look for correct plane (because of parallel case)
int plane = -1;
for (int i = 0; i < m_f->m_exp[0]->GetZIDs().size(); ++i)
{
if (m_f->m_exp[0]->GetZIDs()[i] == planeid)
{
plane = i;
}
}
if (plane != -1)
{
for (int s = 0; s < nstrips; ++s)
{
for (int i = 0; i < nfields; ++i)
{
int n = s * nfields + i;
m_f->m_exp[n] = m_f->m_exp[n]->GetPlane(plane);
if (m_config["wavespace"].as<bool>())
{
m_f->m_exp[n]->BwdTrans(m_f->m_exp[n]->GetCoeffs(),
m_f->m_exp[n]->UpdatePhys());
}
else
{
m_f->m_exp[n]->FwdTrans_IterPerExp(m_f->m_exp[n]->GetPhys(),
m_f->m_exp[n]->UpdateCoeffs());
}
}
}
// Create new SessionReader with RowComm. This is done because when
// using a module requiring m_f->m_declareExpansionAsContField and
// outputting to vtu/dat, a new ContField with equispaced points
// is created. Since creating ContFields require communication, we have
// to change m_session->m_comm to prevent mpi from hanging
// (RowComm will only be used when creating the new expansion,
// since in other places we use m_f->m_comm)
std::vector<std::string> files;
for (int i = 0; i < m_f->m_inputfiles["xml"].size(); ++i)
{
files.push_back(m_f->m_inputfiles["xml"][i]);
}
for (int j = 0; j < m_f->m_inputfiles["xml.gz"].size(); ++j)
{
files.push_back(m_f->m_inputfiles["xml.gz"][j]);
}
vector<string> cmdArgs;
cmdArgs.push_back("FieldConvert");
if (m_f->m_verbose)
{
cmdArgs.push_back("--verbose");
}
int argc = cmdArgs.size();
const char **argv = new const char *[argc];
for (int i = 0; i < argc; ++i)
{
argv[i] = cmdArgs[i].c_str();
}
m_f->m_session = LibUtilities::SessionReader::CreateInstance(
argc, (char **)argv, files, m_f->m_comm->GetRowComm());
m_f->m_session->InitSession();
}
else
{
// Create empty expansion
for (int s = 0; s < nstrips; ++s)
{
for (int i = 0; i < nfields; ++i)
{
int n = s * nfields + i;
m_f->m_exp[n] =
MemoryManager<MultiRegions::ExpList>::AllocateSharedPtr();
}
}
}
}
}
}
|
7bb46611df2a191e6831ac34e4239c7d3393002e | 5d7739bd360a447ee1c7285483d2f37d521fa99e | /Volume 104 (10400-10499)/10489.cpp | 6afd6e975c1dc5acb24b3fff75172d636867256b | [] | no_license | aaafwd/Online-Judge | c4b23272d95a1c1f73cc3da2c95be8087a3d523c | b264f445db2787c5fc40ddef8eb3139adae72608 | refs/heads/main | 2023-04-02T01:01:26.303389 | 2021-04-11T14:17:58 | 2021-04-11T14:17:58 | 356,840,772 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 712 | cpp | 10489.cpp | /* @JUDGE_ID: 19899RK 10489 C++ "By Anadan" */
// Boxes of Chocolates
// Accepted (0.107 seconds using as much as 388 kbytes)
#include <stdio.h>
void myscanf(int &x){
int i;
while ((x = getchar()) != EOF && (x < '0' || x > '9'));
x -= '0';
while ((i = getchar()) != EOF && '0' <= i && i <= '9'){
x = x * 10 + i - '0';
}
}
int main(){
int set, N, B, i, j, k, rest, tmp;
scanf("%d", &set);
while (set--){
myscanf(N); myscanf(B);
rest = 0;
for (i = 0; i < B; ++i){
myscanf(j);
tmp = 1;
while (j--){
myscanf(k);
tmp = (tmp * k) % N;
}
rest += tmp;
}
printf("%d\n", rest % N);
}
return 0;
}
/* @END_OF_SOURCE_CODE */
|
89a3b4fed6de1b3d358f8e95aff5f6bdf125a27f | 5f67658f61d03a786005752583077a40b42d03b1 | /Views/TextView.cc | 843c12cbd4ac73b2bbc67e8479ad678f5312619e | [] | no_license | newtonresearch/newton-framework | d0e5c23dfdc5394e0c94e7e1b7de756eac4ed212 | f922bb3ac508c295b155baa0d4dc7c7982b9e2a2 | refs/heads/master | 2022-06-26T21:20:18.121059 | 2022-06-01T17:39:47 | 2022-06-01T17:39:47 | 31,951,762 | 22 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 2,835 | cc | TextView.cc | /*
File: TextView.cc
Contains: CTextView implementation.
Written by: Newton Research Group.
*/
#include "Objects.h"
#include "ROMResources.h"
#include "Lookup.h"
#include "RichStrings.h"
#include "Unicode.h"
#include "MagicPointers.h"
#include "Preference.h"
#include "TextView.h"
#include "Geometry.h"
#include "DrawText.h"
extern void GetStyleFontInfo(StyleRecord * inStyle, FontInfo * outFontInfo);
/*------------------------------------------------------------------------------
C T e x t V i e w
A view containing immutable text of one fixed style.
------------------------------------------------------------------------------*/
VIEW_SOURCE_MACRO(clTextView, CTextView, CView)
/*--------------------------------------------------------------------------------
Initialize.
Args: inProto the context frame for this view
inView the parent view
Return: --
--------------------------------------------------------------------------------*/
void
CTextView::init(RefArg inProto, CView * inView)
{
CView::init(inProto, inView);
// RefVar mode(getProto(SYMA(viewTransferMode)));
// fTextTransferMode = NOTNIL(mode) ? RINT(mode) : srcOr;
}
/*------------------------------------------------------------------------------
Draw the text. Really.
Args: inRect the rect in which to draw
Return: --
------------------------------------------------------------------------------*/
void
CTextView::realDraw(Rect& inRect)
{
RefVar text(getVar(SYMA(text)));
if (NOTNIL(text))
{
CRichString richStr(text);
if (richStr.length() > 0)
{
ULong vwJustify = viewJustify & vjEverything;
if (vwJustify & vjOneLineOnly)
{
StyleRecord style;
CreateTextStyleRecord(getVar(SYMA(viewFont)), &style);
TextOptions options;
options.alignment = ConvertToFlush(vwJustify, &options.justification);
options.width = RectGetWidth(viewBounds);
// options.transferMode = fTextTransferMode;
FontInfo fntInfo;
GetStyleFontInfo(&style, &fntInfo);
FPoint location;
location.x = viewBounds.left;
location.y = viewBounds.top + fntInfo.ascent - 1;
int leading = RectGetHeight(viewBounds) - (fntInfo.ascent + fntInfo.descent);
switch (viewJustify & vjVMask)
{
case vjTopV:
{
Ref viewLineSpacing = getProto(SYMA(viewLineSpacing));
if (NOTNIL(viewLineSpacing))
location.y = viewBounds.top + RINT(viewLineSpacing);
}
break;
case vjCenterV:
location.y += leading / 2 + 1;
break;
case vjBottomV:
location.y += leading + 1;
break;
// case: vjFullV:
// break;
}
DrawRichString(richStr, 0, richStr.length(), &style, location, &options, NULL);
}
else
TextBox(richStr, getVar(SYMA(viewFont)), &viewBounds, vwJustify & vjHMask, vwJustify & vjVMask /*,fTextTransferMode*/);
}
}
}
|
924e964481870b7e804c6f891b9617ef57007ea4 | e4d1d5219c40971d6f6accd7f224ae38b0c3151a | /include/main.h | 4a819782134be8ad7ab8f6e5d94f839d2448d74f | [] | no_license | c-mita/Project-Euler-Solutions | 05f5124719a78b018c40409457c2565209e9498b | f93c5fc7ee680d38e9258045a636b60df3495a43 | refs/heads/master | 2022-11-29T04:05:26.986290 | 2020-08-15T23:57:34 | 2020-08-15T23:57:34 | 29,162,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | h | main.h | #ifndef PE_MAIN_H
#define PE_MAIN_H
#include <chrono>
#include <iostream>
#include <string>
std::string solution();
int main() {
auto start_time = std::chrono::steady_clock::now();
std::string answer = solution();
std::cout << "Answer: " << answer << std::endl;
auto end_time = std::chrono::steady_clock::now();
auto run_time = end_time - start_time;
std::cout << "Time: " << std::chrono::duration<double, std::milli> (run_time).count() << " ms" << std::endl;
return 0;
}
#endif
|
55ec87bdbfe753e2ae12e7b45248f7eedc1bd057 | 28923aae2e58cefd4aba60a71647d1203a31ee5d | /Spades Game/Game/Avatar/AvatarCache.hpp | 8c5b072be956e22200c799b578fcd8637c80760c | [
"Unlicense"
] | permissive | Qazwar/StemwaterSpades | a1fee0eeeb4f9e4e4c2023d9b661d09692ac6d6a | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | refs/heads/master | 2020-05-16T00:29:38.625484 | 2015-11-21T01:41:38 | 2015-11-21T01:41:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,781 | hpp | AvatarCache.hpp | #ifndef CGE_AVATAR_CACHE_HPP
#define CGE_AVATAR_CACHE_HPP
#include "Game/Resource/Sprite.hpp"
#include <map>
#include "Agui/Backends/Allegro5/Allegro5Image.hpp"
#define AVATAR_CACHE_GENDER_MALE 0
#define AVATAR_CACHE_GENDER_FEMALE 1
#define AVATAR_CACHE_ETHNICITY_WHITE 0
#define AVATAR_CACHE_ETHNICITY_BLACK 1
namespace cge
{
struct CachedAvatarImage
{
int id;
int gender;
int ethnicity;
Sprite* image;
agui::Allegro5Image guiImg;
bool reserved;
CachedAvatarImage()
: id(0),gender(0), ethnicity(0),reserved(false), image(NULL)
{
}
};
struct CachedAvatarData
{
int id;
int gender;
int ethnicity;
bool reserved;
std::string hdPath;
std::string sdPath;
CachedAvatarData()
: id(0),gender(0), ethnicity(0),reserved(false)
{
}
};
class AvatarCache
{
std::map<int,CachedAvatarData> m_avatarData;
std::map<int,CachedAvatarImage> m_avatarImages;
CachedAvatarImage m_gameCache[4];
CachedAvatarImage m_selectionCache;
void _clearSelectionCache();
void _clearAvatarData();
void _clearAvatarImages();
CachedAvatarImage loadImage(const CachedAvatarData& data, bool hd);
bool _loadAvatars(const std::string& path, const std::string& hdPath, const std::string& sdPath, const std::string& filename);
public:
AvatarCache(const std::string& path, const std::string& hdPath, const std::string& sdPath, const std::string& filename);
bool setAvatarSelection(int id);
void clearAvatarSelection();
bool setGameAvatar(int id, int index);
void clearGameCache();
void clearGameCacheAtPos(int pos);
std::map<int,CachedAvatarImage>* getCachedAvatars();
std::map<int,CachedAvatarData>* getCachedAvatarData();
CachedAvatarImage* getGameAvatarAt(int index);
bool avatarExists(int id);
~AvatarCache(void);
};
}
#endif |
358f2554dddb01a9606ee682a2471f0223186b07 | fef750f91e71daa54ed4b7ccbb5274e77cab1d8f | /UVA/11300-11399/11354.cpp | e454b0c226f3f34b1a5eb96765ba729d3c2fcd3b | [] | no_license | DongChengrong/ACM-Program | e46008371b5d4abb77c78d2b6ab7b2a8192d332b | a0991678302c8d8f4a7797c8d537eabd64c29204 | refs/heads/master | 2021-01-01T18:32:42.500303 | 2020-12-29T11:29:02 | 2020-12-29T11:29:02 | 98,361,821 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 638 | cpp | 11354.cpp | #include<stdio.h>
#include<string.h>
const int maxn = 50000 + 10;
int pa[maxn],w[maxn];
void init(int n)
{
memset(w,0,sizeof(w));
for(int i = 1; i <= n; i++)
pa[i] = i;
}
int findset(int x){
return x == pa[x] ? x : pa[x] = findset(pa[x]);
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m) == 2)
{
init(n);
while(m--)
{
int x,y,k;
scanf("%d%d%d",&x,&y,&k);
x = findset(x); y = findset(y);
if(x != y){
pa[x] = pa[y];
w[x] = w[y] = max(k,max(w[x],w[y]))
}
}
}
return 0;
}
|
5a9ee0f02f858c866d4a6bf120b44c694dfecaf9 | b256f60961c99aeb5853e40f6c2f61ceebbd147e | /miniSvLib/include/Common/Globaldef.cpp | 481fa356a51e0afd5eeffed7f2824c5dc6fd3c47 | [] | no_license | Ziran-Li/Ground-station-English | e7dbecda7feb844baa7b571b9dd3797add426e5d | 77212a68a5ed656865e67b92f993b39db86eda27 | refs/heads/master | 2022-11-22T08:58:55.847216 | 2020-04-09T02:05:47 | 2020-04-09T02:05:47 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 791 | cpp | Globaldef.cpp | #include "Globaldef.h"
StateVector::StateVector()
{
m_Length = 0;
m_pX = NULL;
}
StateVector::~StateVector()
{
if( m_pX ) {
delete[] m_pX;
}
}
CRESULT StateVector::SetLength(size_t length)
{
if( m_pX == NULL ) {
// 領域が確保されていない場合,領域を確保して OK
m_pX = new double[length];
m_Length = length;
return C_OK;
} else {
// 領域確保済みの場合,長さが等しければ OK
if( m_Length == length ) {
return C_OK;
} else {
return C_FAIL;
}
}
}
size_t StateVector::GetLength() const
{
return m_Length;
}
double* StateVector::GetPointer(unsigned int index, size_t length)
{
// ポインタの取得
if( m_Length == length && index < m_Length ) {
return m_pX + index;
} else {
return NULL;
}
} |
7da476068fa8cb11cf5a2e635ad26eb8dd9f620a | f05c14e018b2e98ef536627a2a7313509a7d24e5 | /headers/DBClient.h | 4c3a2f591559181a31fb6928cacd2cdbed04caff | [] | no_license | jdang4/Cloud-DB-Benchmark | 82ffdb26e59f45b222a730b32086cfc6a1bf42f5 | d7e6e0e0195c16adf895f9a912d169f21ef0f441 | refs/heads/master | 2022-12-04T17:17:08.396968 | 2020-08-21T20:56:36 | 2020-08-21T20:56:36 | 276,485,231 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 912 | h | DBClient.h | #ifndef DBCLIENT_H
#define DBCLIENT_H
#include <vector>
#include <chrono>
#define NUM_OF_ENTRIES 1000000
class DBClient
{
public:
char* getEntryVal(char recordChar, int record_size);
virtual void connect();
virtual double initializeDB();
virtual double readEntry(bool randomOption);
virtual double insertEntry(int key);
virtual double updateEntry(int key, bool randomOption);
virtual double deleteEntry(int key, bool randomOption);
virtual double simultaneousTasks(bool randomOption);
virtual double performTransactions(int key);
std::vector<int> getRandomKeys(int len, int min, int max);
void setThreads(int n);
void setEntries(int n);
int getThreads();
int getEntries();
protected:
double calculateTime(std::chrono::time_point<std::chrono::high_resolution_clock> start, std::chrono::time_point<std::chrono::high_resolution_clock> end);
int threads;
int entries;
};
#endif
|
000cdc957b269df2ba6763218e4f46446ef38f89 | 76ca52991ca1a1e50d066e9f7c4827b6a4453414 | /cmds/statsd/src/external/StatsCallbackPuller.cpp | d718273e9b851d27218831b9c77190ee1578330b | [
"Apache-2.0",
"LicenseRef-scancode-unicode"
] | permissive | ResurrectionRemix/android_frameworks_base | 3126048967fa5f14760664bea8002e7911da206a | 5e1db0334755ba47245d69857a17f84503f7ce6f | refs/heads/Q | 2023-02-17T11:50:11.652564 | 2021-09-19T11:36:09 | 2021-09-19T11:36:09 | 17,213,932 | 169 | 1,154 | Apache-2.0 | 2023-02-11T12:45:31 | 2014-02-26T14:52:44 | Java | UTF-8 | C++ | false | false | 1,998 | cpp | StatsCallbackPuller.cpp | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define DEBUG false // STOPSHIP if true
#include "Log.h"
#include <android/os/IStatsPullerCallback.h>
#include "StatsCallbackPuller.h"
#include "logd/LogEvent.h"
#include "stats_log_util.h"
using namespace android::binder;
namespace android {
namespace os {
namespace statsd {
StatsCallbackPuller::StatsCallbackPuller(int tagId, const sp<IStatsPullerCallback>& callback) :
StatsPuller(tagId), mCallback(callback) {
VLOG("StatsCallbackPuller created for tag %d", tagId);
}
bool StatsCallbackPuller::PullInternal(vector<shared_ptr<LogEvent>>* data) {
VLOG("StatsCallbackPuller called for tag %d", mTagId)
if(mCallback == nullptr) {
ALOGW("No callback registered");
return false;
}
int64_t wallClockTimeNs = getWallClockNs();
int64_t elapsedTimeNs = getElapsedRealtimeNs();
vector<StatsLogEventWrapper> returned_value;
Status status = mCallback->pullData(mTagId, elapsedTimeNs, wallClockTimeNs, &returned_value);
if (!status.isOk()) {
ALOGW("StatsCallbackPuller::pull failed for %d", mTagId);
return false;
}
data->clear();
for (const StatsLogEventWrapper& it: returned_value) {
LogEvent::createLogEvents(it, *data);
}
VLOG("StatsCallbackPuller::pull succeeded for %d", mTagId);
return true;
}
} // namespace statsd
} // namespace os
} // namespace android
|
d24ad75e2d8b3d5061cdd18b0f893c25065521d9 | a3732e1c07f1cf36272e5552e5ad8a7240b225eb | /TeachingBox/CLabelPixmap.cpp | 36a407083666e099275709519191f6b087c75b19 | [] | no_license | TenYearsADream/TeachingBox | 68dec280871e8ddc05223c32d5f0c3ac030bb6ac | d5d4e202953aab2d7ed488d74ca6a73feab4b57f | refs/heads/master | 2020-04-22T20:23:58.384391 | 2016-06-01T06:54:38 | 2016-06-01T06:54:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | cpp | CLabelPixmap.cpp | #include "stdafx.h"
#include "CLabelPixmap.h"
CLabelPixmap::CLabelPixmap(const QString &text, QWidget* parent /*= 0*/) :QLabel(parent)
{
m_pixmap=new QPixmap(text);
}
CLabelPixmap::CLabelPixmap(QWidget* parent /*= 0*/) : QLabel(parent)
{
/*m_pixmap=new QPixmap;*/
}
CLabelPixmap::~CLabelPixmap()
{
ClearImage();
}
void CLabelPixmap::resizeEvent(QResizeEvent *)
{
ResizeImage();
m_isResized = true;
}
void CLabelPixmap::ResizeImage()
{
if (m_pixmap == NULL)
{
return;
}
else
{
QPixmap newPixmap = m_pixmap->scaled(this->width(), this->height(), Qt::KeepAspectRatio);
this->clear();
this->setPixmap(newPixmap);
}
}
void CLabelPixmap::UpdateImage(const QString &text)
{
ClearImage();
m_pixmap = new QPixmap(text);
if (m_isResized)
{
ResizeImage();
}
}
void CLabelPixmap::ClearImage()
{
if (m_pixmap!=NULL)
{
delete(m_pixmap);
m_pixmap = NULL;
}
}
|
f5ec887c17a464245e641f6691de191c0a0d249b | b677894966f2ae2d0585a31f163a362e41a3eae0 | /ns3/ns-3.26/src/csma/examples/csma-one-subnet.cc | 7f2d39d06e5a0074ac32bf31cd6571c977157e87 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"GPL-2.0-only"
] | permissive | cyliustack/clusim | 667a9eef2e1ea8dad1511fd405f3191d150a04a8 | cbedcf671ba19fded26e4776c0e068f81f068dfd | refs/heads/master | 2022-10-06T20:14:43.052930 | 2022-10-01T19:42:19 | 2022-10-01T19:42:19 | 99,692,344 | 7 | 3 | Apache-2.0 | 2018-07-04T10:09:24 | 2017-08-08T12:51:33 | Python | UTF-8 | C++ | false | false | 4,441 | cc | csma-one-subnet.cc | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* 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
*/
// Network topology
//
// n0 n1 n2 n3
// | | | |
// =================
// LAN
//
// - CBR/UDP flows from n0 to n1 and from n3 to n0
// - DropTail queues
// - Tracing of queues and packet receptions to file "csma-one-subnet.tr"
#include <iostream>
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/internet-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("CsmaOneSubnetExample");
int
main (int argc, char *argv[])
{
//
// Users may find it convenient to turn on explicit debugging
// for selected modules; the below lines suggest how to do this
//
#if 0
LogComponentEnable ("CsmaOneSubnetExample", LOG_LEVEL_INFO);
#endif
//
// Allow the user to override any of the defaults and the above Bind() at
// run-time, via command-line arguments
//
CommandLine cmd;
cmd.Parse (argc, argv);
//
// Explicitly create the nodes required by the topology (shown above).
//
NS_LOG_INFO ("Create nodes.");
NodeContainer nodes;
nodes.Create (4);
NS_LOG_INFO ("Build Topology");
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (5000000));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
//
// Now fill out the topology by creating the net devices required to connect
// the nodes to the channels and hooking them up.
//
NetDeviceContainer devices = csma.Install (nodes);
InternetStackHelper internet;
internet.Install (nodes);
// We've got the "hardware" in place. Now we need to add IP addresses.
//
NS_LOG_INFO ("Assign IP Addresses.");
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = ipv4.Assign (devices);
//
// Create an OnOff application to send UDP datagrams from node zero to node 1.
//
NS_LOG_INFO ("Create Applications.");
uint16_t port = 9; // Discard port (RFC 863)
OnOffHelper onoff ("ns3::UdpSocketFactory",
Address (InetSocketAddress (interfaces.GetAddress (1), port)));
onoff.SetConstantRate (DataRate ("500kb/s"));
ApplicationContainer app = onoff.Install (nodes.Get (0));
// Start the application
app.Start (Seconds (1.0));
app.Stop (Seconds (10.0));
// Create an optional packet sink to receive these packets
PacketSinkHelper sink ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
app = sink.Install (nodes.Get (1));
app.Start (Seconds (0.0));
//
// Create a similar flow from n3 to n0, starting at time 1.1 seconds
//
onoff.SetAttribute ("Remote",
AddressValue (InetSocketAddress (interfaces.GetAddress (0), port)));
app = onoff.Install (nodes.Get (3));
app.Start (Seconds (1.1));
app.Stop (Seconds (10.0));
app = sink.Install (nodes.Get (0));
app.Start (Seconds (0.0));
NS_LOG_INFO ("Configure Tracing.");
//
// Configure ascii tracing of all enqueue, dequeue, and NetDevice receive
// events on all devices. Trace output will be sent to the file
// "csma-one-subnet.tr"
//
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("csma-one-subnet.tr"));
//
// Also configure some tcpdump traces; each interface will be traced.
// The output files will be named:
//
// csma-one-subnet-<node ID>-<device's interface index>.pcap
//
// and can be read by the "tcpdump -r" command (use "-tt" option to
// display timestamps correctly)
//
csma.EnablePcapAll ("csma-one-subnet", false);
//
// Now, do the actual simulation.
//
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
|
3e8f74597bf201cc7e59373687eba474a877caef | 65025edce8120ec0c601bd5e6485553697c5c132 | /Engine/addons/resource/FloatsCompression.cc | 28e78971066357bea613587c1e6fbdfdbacd4fd2 | [
"MIT"
] | permissive | stonejiang/genesis-3d | babfc99cfc9085527dff35c7c8662d931fbb1780 | df5741e7003ba8e21d21557d42f637cfe0f6133c | refs/heads/master | 2020-12-25T18:22:32.752912 | 2013-12-13T07:45:17 | 2013-12-13T07:45:17 | 15,157,071 | 4 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 4,517 | cc | FloatsCompression.cc | /****************************************************************************
Copyright (c) 2011-2013,WebJet Business Division,CYOU
http://www.genesis-3d.com.cn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
The method in this file is written according to Jonathan Blow's article in the
Inner Product column of Game Developer Magazine. The article is available at
http://number-none.com/product/Scalar%20Quantization/index.html. The sample
code is available at http://www.gdcvault.com/gdmag.
****************************************************************************/
#include "resource/resource_stdneb.h"
#include "floatsCompression.h"
namespace Resources
{
//------------------------------------------------------------------------------
FloatsCompression::FloatsCompression(float minNumber, float maxNumber,
unsigned int quantizationBitsCount)
: mMinNumber(minNumber)
, mMaxNumber(maxNumber)
, mQuantizationBitsCount(quantizationBitsCount)
{
mValueRange = mMaxNumber - mMinNumber;
unsigned int normalIntervals = (1 << mQuantizationBitsCount) - 1;
if ( (0 == mValueRange) || (0 == normalIntervals) )
{
mIntervalsR = 0;
mIntervalSizeR = 0;
}
else
{
mIntervalsR = normalIntervals - 1;
mIntervalSizeR = mValueRange / mIntervalsR;
}
}
//------------------------------------------------------------------------------
float FloatsCompression::GetMinNumber()
{
return mMinNumber;
}
bool FloatsCompression::SetMinNumber(float minNumber)
{
if (minNumber > mMaxNumber)
{
return false;
}
mMinNumber = minNumber;
mValueRange = mMaxNumber - mMinNumber;
mIntervalSizeR = mValueRange / mIntervalsR;
return true;
}
//------------------------------------------------------------------------------
float FloatsCompression::GetMaxNumber()
{
return mMaxNumber;
}
bool FloatsCompression::SetMaxNumber(float maxNumber)
{
if (maxNumber < mMinNumber)
{
return false;
}
mMaxNumber = maxNumber;
mValueRange = mMaxNumber - mMinNumber;
mIntervalSizeR = mValueRange / mIntervalsR;
return true;
}
//------------------------------------------------------------------------------
unsigned int FloatsCompression::GetQuantizationBitsCount()
{
return mQuantizationBitsCount;
}
bool FloatsCompression::SetQuantizationBitsCount(unsigned int quantizationBitsCount)
{
if (0 == quantizationBitsCount)
{
return false;
}
mQuantizationBitsCount = quantizationBitsCount;
unsigned int normalIntervals = (1 << mQuantizationBitsCount) - 1;
mIntervalsR = normalIntervals - 1;
mIntervalSizeR = mValueRange / mIntervalsR;
return true;
}
//------------------------------------------------------------------------------
bool FloatsCompression::CodeRL(float inputFloat,
unsigned int *pOutputUnsignedInt)
{
if ( (0 == mValueRange) || (0 == mIntervalsR) )
{
return false;
}
float normalizedFloat = (inputFloat - mMinNumber) / mValueRange;
unsigned int roundedResult = (unsigned int)(normalizedFloat * mIntervalsR + 0.5f);
if (roundedResult > mIntervalsR)
{
roundedResult = mIntervalsR;
}
*pOutputUnsignedInt = roundedResult;
return true;
}
//------------------------------------------------------------------------------
bool FloatsCompression::DecodeRL(unsigned int inputUnsignedInt,
float *pOutputFloat)
{
if ( (0 == mValueRange) || (0 == mIntervalSizeR) )
{
return false;
}
*pOutputFloat = mMinNumber + inputUnsignedInt * mIntervalSizeR;
return true;
}
}//namespace Resources |
06ec88545f6f9e6ddf0f0201fa7febd12bd79faa | 7237d4eb82e14a538acc0d8542b1c2ee2c731a01 | /String/P79.cpp | 9979c8cf1301bbddd73924ef603404a1aeaf0689 | [] | no_license | Dutongxue/LintCode | cd76abff5ca4c9f2b172f8eeeba6d676643df080 | 460a64e9115704470d18414691e192ce5dc560ec | refs/heads/master | 2020-03-18T19:41:40.356395 | 2018-11-11T12:59:08 | 2018-11-11T12:59:08 | 135,170,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | cpp | P79.cpp | //
// Created by enheng on 18-6-12.
//
#include "P79.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
/**
* @param A: A string
* @param B: A string
* @return: the length of the longest common substring.
*/
int longestCommonSubstring(string &A, string &B) {
// write your code here
vector<vector<int>> dp(A.length() + 1, vector<int>(B.length() + 1, 0));
int ans = 0;
for (int i = 1; i <= A.length(); ++i) {
for (int j = 1; j <= B.length(); ++j) {
if (A[i - 1] == B[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1; //当搜索到A【i】,B[j]时最大连续子串长度
if (ans < dp[i][j]) ans = dp[i][j];
}
}
}
return ans;
}
};
void P79() {
Solution s;
string A("www.lintcode.com code"), B("www.ninechapter.com code");
cout << s.longestCommonSubstring(A, B);
} |
0cfc6722f038db159be44ee19a7921e3f44c3176 | 1bfabbcedee74a5b784a2f6a27ef468d22047044 | /GraphicsX/GFX_MapGenMidptFrac.cpp | dd353ccfdec5376da59c6bf6860956832d2f8410 | [] | no_license | GlenSol/homies | bdc0b605a31a9da6335479954609cc9a41aa5a03 | 715758a4fd92d6637176b072a765fe8d565ceb2f | refs/heads/master | 2020-07-03T06:27:23.986959 | 2013-01-08T20:10:43 | 2013-01-08T20:10:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,544 | cpp | GFX_MapGenMidptFrac.cpp | #include "gdix.h"
#include "gdix_i.h"
#define HEIGHTITER .5f
#define MIDDLEHEIGHT .25f
#define GETHEIGHT(h) _GFXMathRand(-(h), (h))
//This is the midpoint fractal terrain generator
//model map generator stuff
PRIVATE float _MapGetAvgCorner(int i, int j, int stride, int size, float *points)
{
/* In this diagram, our input stride is 1, the i,j location is
indicated by "*", and the four value we want to average are
"X"s:
X . X
. * .
X . X
*/
return ((float) (points[((i-stride)*size) + j-stride] +
points[((i-stride)*size) + j+stride] +
points[((i+stride)*size) + j-stride] +
points[((i+stride)*size) + j+stride]) * MIDDLEHEIGHT);
}
PRIVATE float _MapGetAvgDiamond(int i, int j, int stride,
int size, int subSize, float *points)
{
/* In this diagram, our input stride is 1, the i,j location is
indicated by "X", and the four value we want to average are
"*"s:
. * .
* X *
. * .
*/
/* In order to support tiled surfaces which meet seamless at the
edges (that is, they "wrap"), We need to be careful how we
calculate averages when the i,j diamond center lies on an edge
of the array. The first four 'if' clauses handle these
cases. The final 'else' clause handles the general case (in
which i,j is not on an edge).
*/
if (i == 0)
return ((float) (points[(i*size) + j-stride] +
points[(i*size) + j+stride] +
points[((subSize-stride)*size) + j] +
points[((i+stride)*size) + j]) * MIDDLEHEIGHT);
else if (i == size-1)
return ((float) (points[(i*size) + j-stride] +
points[(i*size) + j+stride] +
points[((i-stride)*size) + j] +
points[((0+stride)*size) + j]) * MIDDLEHEIGHT);
else if (j == 0)
return ((float) (points[((i-stride)*size) + j] +
points[((i+stride)*size) + j] +
points[(i*size) + j+stride] +
points[(i*size) + subSize-stride]) * MIDDLEHEIGHT);
else if (j == size-1)
return ((float) (points[((i-stride)*size) + j] +
points[((i+stride)*size) + j] +
points[(i*size) + j-stride] +
points[(i*size) + 0+stride]) * MIDDLEHEIGHT);
else
return ((float) (points[((i-stride)*size) + j] +
points[((i+stride)*size) + j] +
points[(i*size) + j-stride] +
points[(i*size) + j+stride]) * MIDDLEHEIGHT);
}
PRIVATE void _MapGeneratePoints(float *points, float height, float r, int size)
{
int subSize = size;
size++;
float hRatio = (float)pow(2.,-r); //height ratio
float hScale = height*hRatio;
//generate the first four value
//let the first four corner have the same value
int stride = subSize/2;
points[(0*size)+0] =
points[(subSize*size)+0] =
points[(subSize*size)+subSize] =
points[(0*size)+subSize] = 0.f;
//now go through each of the 4 subdivisions and create midpoint heights
//the first iteration would produce the center (the diamond process) then
//we will take each four corners and randomize the height (the square process)
//then we go back to (the diamond process) and so on...until stride reaches 0
int i, j, oddLine;
while (stride)
{
//Do the diamond process
//Creating the center point
for(i = stride; i < subSize; i += stride)
{
for(j = stride; j < subSize; j += stride)
{
points[(i * size) + j] =
hScale * GETHEIGHT(HEIGHTITER) +
_MapGetAvgCorner(i, j, stride, size, points);
j += stride;
}
i += stride;
}
//Do the square process
//Split to four regions and generate corner heights
oddLine = 0;
for(i = 0; i < subSize; i += stride)
{
oddLine = (oddLine == 0);
for(j = 0; j < subSize; j += stride)
{
if((oddLine) && !j) j += stride;
/* i and j are setup. Call avgDiamondVals with the
current position. It will return the average of the
surrounding diamond data points. */
points[(i * size) + j] =
hScale * GETHEIGHT(HEIGHTITER) +
_MapGetAvgDiamond(i, j, stride, size, subSize, points);
/* To wrap edges seamlessly, copy edge values around
to other side of array */
if (i==0)
points[(subSize*size) + j] =
points[(i * size) + j];
if (j==0)
points[(i*size) + subSize] =
points[(i * size) + j];
j+=stride;
}
}
//reduce height range and move on to other corners
hScale *= hRatio;
stride >>= 1;
}
}
PRIVATE RETCODE _MapSetCel(gfxCel *cel, const gfxVtx *theVtx)
{
cel->numVtx = NUMPTQUAD;
if(_GFXCheckError(g_p3DDevice->CreateVertexBuffer(sizeof(gfxVtx)*cel->numVtx,
D3DUSAGE_DYNAMIC, GFXVERTEXFLAG, D3DPOOL_DEFAULT, &cel->vtx),
true, "Error in _MapSetCel"))
return RETCODE_FAILURE;
//fill 'er up
gfxVtx *pVtx;
D3DXPLANE planeOne, planeTwo;
if(SUCCEEDED(cel->vtx->Lock(0,0, (BYTE**)&pVtx, D3DLOCK_DISCARD)))
{
memcpy(pVtx, theVtx, sizeof(gfxVtx)*cel->numVtx);
D3DXPlaneFromPoints(&planeOne,
&D3DXVECTOR3(pVtx[0].x,pVtx[0].y,pVtx[0].z),
&D3DXVECTOR3(pVtx[1].x,pVtx[1].y,pVtx[1].z),
&D3DXVECTOR3(pVtx[2].x,pVtx[2].y,pVtx[2].z));
D3DXPlaneFromPoints(&planeTwo,
&D3DXVECTOR3(pVtx[2].x,pVtx[2].y,pVtx[2].z),
&D3DXVECTOR3(pVtx[3].x,pVtx[3].y,pVtx[3].z),
&D3DXVECTOR3(pVtx[0].x,pVtx[0].y,pVtx[0].z));
cel->plane[0][ePA] = planeOne.a; cel->plane[1][ePA] = planeTwo.a;
cel->plane[0][ePB] = planeOne.b; cel->plane[1][ePB] = planeTwo.b;
cel->plane[0][ePC] = planeOne.c; cel->plane[1][ePC] = planeTwo.c;
cel->plane[0][ePD] = planeOne.d; cel->plane[1][ePD] = planeTwo.d;
pVtx[2].nX = pVtx[0].nX = (planeOne.a + planeTwo.a)/2; pVtx[1].nX = planeOne.a; pVtx[3].nX = planeTwo.a;
pVtx[2].nY = pVtx[0].nY = (planeOne.b + planeTwo.b)/2; pVtx[1].nY = planeOne.b; pVtx[3].nY = planeTwo.b;
pVtx[2].nZ = pVtx[0].nZ = (planeOne.c + planeTwo.c)/2; pVtx[1].nZ = planeOne.c; pVtx[3].nZ = planeTwo.c;
cel->vtx->Unlock();
}
return RETCODE_SUCCESS;
}
/////////////////////////////////////
// Name:
// Purpose:
// Output:
// Return:
/////////////////////////////////////
PUBLIC hTMAP TMapCreateRand(float celSizeX, float celSizeZ, float height,
int xDir, int zDir, float r, unsigned int numIter,
hTXT texture, D3DMATERIAL8 *mat)
{
int size = 1<<numIter;
int numVtx = (size+1)*(size+1);
//allocate the points
float *points;
//HACK for now...
if(MemAlloc((void**)&points, sizeof(float)*(numVtx+2), M_ZERO) != RETCODE_SUCCESS)
{ ASSERT_MSG(0, "Unable to allocate points", "Error in MDLGenMap"); return 0; }
//generate the points!
_MapGeneratePoints(points, height, r, size);
hTMAP newMap;
//allocate map
if(MemAlloc((void**)&newMap, sizeof(gfxTMap), M_ZERO) != RETCODE_SUCCESS)
{ ASSERT_MSG(0, "Unable to allocate new terrain map", "Error in MapRandTerrain"); return 0; }
MemSetPattern(newMap, "GFXTMAP");
//set up mtx
_GFXMathMtxLoadIden(&newMap->wrldMtx);
newMap->celSize[eX] = celSizeX;
newMap->celSize[eY] = height;
newMap->celSize[eZ] = celSizeZ;
newMap->indSize.cy = newMap->indSize.cx = size;
if(texture)
{
newMap->texture = texture;
TextureAddRef(newMap->texture);
}
memcpy(&newMap->material, mat, sizeof(D3DMATERIAL8));
//////////////////////////
//generate the cels of map
if(MemAlloc((void**)&newMap->cels, sizeof(gfxCel)*newMap->indSize.cx*newMap->indSize.cy, M_ZERO) != RETCODE_SUCCESS)
{ ASSERT_MSG(0, "Unable to allocate map cels", "Error in MapRandTerrain"); TMapDestroy(&newMap); return 0; }
MemSetPattern(newMap->cels, "GFXCELS");
gfxVtx quadVtx[NUMPTQUAD]={0};
float xFDir = xDir < 0 ? -1 : 1;
float zFDir = zDir < 0 ? -1 : 1;
for(int row = 0; row < newMap->indSize.cy; row++)
{
for(int col = 0; col < newMap->indSize.cx; col++)
{
//create cel with the quad
/*
0-----3
|\ |
| \ |
| \|
1-----2
*/
int dot = col+(row*(size+1));
quadVtx[0].x = xDir*newMap->celSize[eX]*col;
quadVtx[0].y = points[dot];
quadVtx[0].z = zDir*newMap->celSize[eZ]*row;
quadVtx[0].s = quadVtx[0].x/TextureGetWidth(newMap->texture);
quadVtx[0].t = quadVtx[0].z/TextureGetHeight(newMap->texture);
quadVtx[0].color = 0xffffffff;
quadVtx[1].x = xDir*newMap->celSize[eX]*col;
quadVtx[1].y = points[dot+size+1];
quadVtx[1].z = zDir*newMap->celSize[eZ]*(row+1);
quadVtx[1].s = quadVtx[1].x/TextureGetWidth(newMap->texture);
quadVtx[1].t = quadVtx[1].z/TextureGetHeight(newMap->texture);
quadVtx[1].color = 0xffffffff;
quadVtx[2].x = xDir*newMap->celSize[eX]*(col+1);
quadVtx[2].y = points[dot+size+2];
quadVtx[2].z = zDir*newMap->celSize[eZ]*(row+1);
quadVtx[2].s = quadVtx[2].x/TextureGetWidth(newMap->texture);
quadVtx[2].t = quadVtx[2].z/TextureGetHeight(newMap->texture);
quadVtx[2].color = 0xffffffff;
quadVtx[3].x = xDir*newMap->celSize[eX]*(col+1);
quadVtx[3].y = points[dot+1];
quadVtx[3].z = zDir*newMap->celSize[eZ]*row;
quadVtx[3].s = quadVtx[3].x/TextureGetWidth(newMap->texture);
quadVtx[3].t = quadVtx[3].z/TextureGetHeight(newMap->texture);
quadVtx[3].color = 0xffffffff;
_MapSetCel(&CELL(newMap->cels, row, col, newMap->indSize.cx), quadVtx);
}
}
////////////////
//clean up stuff
MemFree((void**)&points);
////////////////
return newMap;
} |
ba626d726f1c361874434ea297e388ff1f8457a3 | bb38c44037a99d0a12a12d92059678f2faebbc80 | /contrib/chkpass/chkpass.cpp | 512273aa37cf163ab09aa6903d5239c8929fea3a | [
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference",
"PostgreSQL",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-warranty-disclaimer",
"curl",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LGPL-2.1-only",
"CC-BY-4.0",
... | permissive | opengauss-mirror/openGauss-server | a9c5a62908643492347830826c56da49f0942796 | 310e84631c68c8bf37b004148b66f94064f701e4 | refs/heads/master | 2023-07-26T19:29:12.495484 | 2023-07-17T12:23:32 | 2023-07-17T12:23:32 | 276,117,477 | 591 | 208 | MulanPSL-2.0 | 2023-04-28T12:30:18 | 2020-06-30T14:08:59 | C++ | UTF-8 | C++ | false | false | 4,108 | cpp | chkpass.cpp | /*
* openGauss type definitions for chkpass
* Written by D'Arcy J.M. Cain
* darcy@druid.net
* http://www.druid.net/darcy/
*
* contrib/chkpass/chkpass.c
* best viewed with tabs set to 4
*/
#include "postgres.h"
#include "knl/knl_variable.h"
#include <time.h>
#include <unistd.h>
#ifdef HAVE_CRYPT_H
#include <crypt.h>
#endif
#include "fmgr.h"
#include "utils/builtins.h"
PG_MODULE_MAGIC;
/*
* This type encrypts it's input unless the first character is a colon.
* The output is the encrypted form with a leading colon. The output
* format is designed to allow dump and reload operations to work as
* expected without doing special tricks.
*/
/*
* This is the internal storage format for CHKPASSs.
* 15 is all I need but add a little buffer
*/
typedef struct chkpass {
char password[16];
} chkpass;
/*
* Various forward declarations:
*/
Datum chkpass_in(PG_FUNCTION_ARGS);
Datum chkpass_out(PG_FUNCTION_ARGS);
Datum chkpass_rout(PG_FUNCTION_ARGS);
/* Only equal or not equal make sense */
Datum chkpass_eq(PG_FUNCTION_ARGS);
Datum chkpass_ne(PG_FUNCTION_ARGS);
/* This function checks that the password is a good one
* It's just a placeholder for now */
static int verify_pass(const char* str)
{
return 0;
}
/*
* CHKPASS reader.
*/
PG_FUNCTION_INFO_V1(chkpass_in);
Datum chkpass_in(PG_FUNCTION_ARGS)
{
char* str = PG_GETARG_CSTRING(0);
chkpass* result = NULL;
char mysalt[4];
char* crypt_output = NULL;
static char salt_chars[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
/* special case to let us enter encrypted passwords */
if (*str == ':') {
result = (chkpass*)palloc(sizeof(chkpass));
strlcpy(result->password, str + 1, 13 + 1);
PG_RETURN_POINTER(result);
}
if (verify_pass(str) != 0)
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg("password \"%s\" is weak", str)));
result = (chkpass*)palloc(sizeof(chkpass));
mysalt[0] = salt_chars[random() & 0x3f];
mysalt[1] = salt_chars[random() & 0x3f];
mysalt[2] = 0; /* technically the terminator is not necessary
* but I like to play safe */
crypt_output = crypt(str, mysalt);
if (crypt_output == NULL)
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("crypt() failed")));
strlcpy(result->password, crypt_output, sizeof(result->password));
PG_RETURN_POINTER(result);
}
/*
* CHKPASS output function.
* Just like any string but we know it is max 15 (13 plus colon and terminator.)
*/
PG_FUNCTION_INFO_V1(chkpass_out);
Datum chkpass_out(PG_FUNCTION_ARGS)
{
chkpass* password = (chkpass*)PG_GETARG_POINTER(0);
char* result = NULL;
result = (char*)palloc(16);
result[0] = ':';
strcpy(result + 1, password->password);
PG_RETURN_CSTRING(result);
}
/*
* special output function that doesn't output the colon
*/
PG_FUNCTION_INFO_V1(chkpass_rout);
Datum chkpass_rout(PG_FUNCTION_ARGS)
{
chkpass* password = (chkpass*)PG_GETARG_POINTER(0);
PG_RETURN_TEXT_P(cstring_to_text(password->password));
}
/*
* Boolean tests
*/
PG_FUNCTION_INFO_V1(chkpass_eq);
Datum chkpass_eq(PG_FUNCTION_ARGS)
{
chkpass* a1 = (chkpass*)PG_GETARG_POINTER(0);
text* a2 = PG_GETARG_TEXT_PP(1);
char str[9];
char* crypt_output = NULL;
text_to_cstring_buffer(a2, str, sizeof(str));
crypt_output = crypt(str, a1->password);
if (crypt_output == NULL)
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("crypt() failed")));
PG_RETURN_BOOL(strcmp(a1->password, crypt_output) == 0);
}
PG_FUNCTION_INFO_V1(chkpass_ne);
Datum chkpass_ne(PG_FUNCTION_ARGS)
{
chkpass* a1 = (chkpass*)PG_GETARG_POINTER(0);
text* a2 = PG_GETARG_TEXT_PP(1);
char str[9];
char* crypt_output = NULL;
text_to_cstring_buffer(a2, str, sizeof(str));
crypt_output = crypt(str, a1->password);
if (crypt_output == NULL)
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("crypt() failed")));
PG_RETURN_BOOL(strcmp(a1->password, crypt_output) != 0);
}
|
dc45e437a2843910e1c4afe7a1ac2188a4c97dc1 | 872f24199d847f05ddb4d8f7ac69eaed9336a0d5 | /code/nrao/GBTFillers/GBTPointModelFiller.h | 77c366c204c83b232faabbe64e065d44237c0fa8 | [] | no_license | schiebel/casa | 8004f7d63ca037b4579af8a8bbfb4fa08e87ced4 | e2ced7349036d8fc13d0a65aad9a77b76bfe55d1 | refs/heads/master | 2016-09-05T16:20:59.022063 | 2015-08-26T18:46:26 | 2015-08-26T18:46:26 | 41,441,084 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,724 | h | GBTPointModelFiller.h | //# GBTPointModelFiller: Fill the pointingModel from the ANTENNA file
//# Copyright (C) 2001
//# Associated Universities, Inc. Washington DC, USA.
//#
//# This library is free software; you can redistribute it and/or modify it
//# under the terms of the GNU Library General Public License as published by
//# the Free Software Foundation; either version 2 of the License, or (at your
//# option) any later version.
//#
//# This library 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 Library General Public
//# License for more details.
//#
//# You should have received a copy of the GNU Library General Public License
//# along with this library; if not, write to the Free Software Foundation,
//# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
//#
//# Correspondence concerning AIPS++ should be addressed as follows:
//# Internet email: aips2-request@nrao.edu.
//# Postal address: AIPS++ Project Office
//# National Radio Astronomy Observatory
//# 520 Edgemont Road
//# Charlottesville, VA 22903-2475 USA
//#
//#
//# $Id$
#ifndef NRAO_GBTPOINTMODELFILLER_H
#define NRAO_GBTPOINTMODELFILLER_H
#include <casa/aips.h>
#include <tables/Tables/Table.h>
//# Forward declarations
namespace casa { //# NAMESPACE CASA - BEGIN
class MeasurementSet;
class TableRow;
} //# NAMESPACE CASA - END
#include <casa/namespace.h>
class GBTAntennaFile;
// <summary>
// Fill the pointing model record from a GBTAntennaFile.
// </summary>
// <use visibility=local>
// <reviewed reviewer="" date="yyyy/mm/dd" tests="" demos="">
// </reviewed>
// <prerequisite>
// <li>
// </prerequisite>
//
// <etymology>
//
// </etymology>
//
// <synopsis>
// </synopsis>
//
// <example>
// </example>
//
// <motivation>
// </motivation>
//
// <thrown>
// <li>
// <li>
// </thrown>
//
class GBTPointModelFiller
{
public:
// Attach this to the indicated MeasurementSet
GBTPointModelFiller(MeasurementSet &ms);
~GBTPointModelFiller();
// fill using the indicated antenna file
void fill(const GBTAntennaFile &antennaFile);
// the most recently filled row - always last in the table
Int pointingModelId() {return (itsTable ? (Int(itsTable->nrow())-1) : -1);}
// flush this table
void flush() {itsTable->flush();}
private:
Table *itsTable;
TableRow *itsTableRow;
// undefined an inaccessable
GBTPointModelFiller();
GBTPointModelFiller(const GBTPointModelFiller &other);
GBTPointModelFiller &operator=(const GBTPointModelFiller &other);
};
#endif
|
16a20a7aa96c2ec894b2da66fffefd9ea10c196d | 0f0b2c5e9095ba273992ab0b74a82f986b4f941e | /services/surfaceflinger/tests/unittests/CachingTest.cpp | 1b8c76d1b9c29d47c22525372dc2b8fce1406aaf | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | LineageOS/android_frameworks_native | 28274a8a6a3d2b16150702e0a34434bc45090b9a | c25b27db855a0a6d749bfd45d05322939d2ad39a | refs/heads/lineage-18.1 | 2023-08-04T11:18:47.942921 | 2023-05-05T12:54:26 | 2023-05-05T12:54:26 | 75,639,913 | 21 | 626 | NOASSERTION | 2021-06-11T19:11:21 | 2016-12-05T15:41:33 | C++ | UTF-8 | C++ | false | false | 3,445 | cpp | CachingTest.cpp | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TODO(b/129481165): remove the #pragma below and fix conversion issues
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconversion"
#undef LOG_TAG
#define LOG_TAG "CachingTest"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <gui/BufferQueue.h>
#include "BufferStateLayer.h"
namespace android {
class SlotGenerationTest : public testing::Test {
protected:
BufferStateLayer::HwcSlotGenerator mHwcSlotGenerator;
sp<GraphicBuffer> mBuffer1{new GraphicBuffer(1, 1, HAL_PIXEL_FORMAT_RGBA_8888, 1, 0)};
sp<GraphicBuffer> mBuffer2{new GraphicBuffer(1, 1, HAL_PIXEL_FORMAT_RGBA_8888, 1, 0)};
sp<GraphicBuffer> mBuffer3{new GraphicBuffer(10, 10, HAL_PIXEL_FORMAT_RGBA_8888, 1, 0)};
};
TEST_F(SlotGenerationTest, getHwcCacheSlot_Invalid) {
sp<IBinder> binder = new BBinder();
// test getting invalid client_cache_id
client_cache_t id;
uint32_t slot = mHwcSlotGenerator.getHwcCacheSlot(id);
EXPECT_EQ(BufferQueue::INVALID_BUFFER_SLOT, slot);
}
TEST_F(SlotGenerationTest, getHwcCacheSlot_Basic) {
sp<IBinder> binder = new BBinder();
client_cache_t id;
id.token = binder;
id.id = 0;
uint32_t slot = mHwcSlotGenerator.getHwcCacheSlot(id);
EXPECT_EQ(BufferQueue::NUM_BUFFER_SLOTS - 1, slot);
client_cache_t idB;
idB.token = binder;
idB.id = 1;
slot = mHwcSlotGenerator.getHwcCacheSlot(idB);
EXPECT_EQ(BufferQueue::NUM_BUFFER_SLOTS - 2, slot);
slot = mHwcSlotGenerator.getHwcCacheSlot(idB);
EXPECT_EQ(BufferQueue::NUM_BUFFER_SLOTS - 2, slot);
slot = mHwcSlotGenerator.getHwcCacheSlot(id);
EXPECT_EQ(BufferQueue::NUM_BUFFER_SLOTS - 1, slot);
}
TEST_F(SlotGenerationTest, getHwcCacheSlot_Reuse) {
sp<IBinder> binder = new BBinder();
std::vector<client_cache_t> ids;
uint32_t cacheId = 0;
// fill up cache
for (uint32_t i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
client_cache_t id;
id.token = binder;
id.id = cacheId;
ids.push_back(id);
uint32_t slot = mHwcSlotGenerator.getHwcCacheSlot(id);
EXPECT_EQ(BufferQueue::NUM_BUFFER_SLOTS - (i + 1), slot);
cacheId++;
}
for (uint32_t i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
uint32_t slot = mHwcSlotGenerator.getHwcCacheSlot(ids[i]);
EXPECT_EQ(BufferQueue::NUM_BUFFER_SLOTS - (i + 1), slot);
}
for (uint32_t i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
client_cache_t id;
id.token = binder;
id.id = cacheId;
uint32_t slot = mHwcSlotGenerator.getHwcCacheSlot(id);
EXPECT_EQ(BufferQueue::NUM_BUFFER_SLOTS - (i + 1), slot);
cacheId++;
}
}
} // namespace android
// TODO(b/129481165): remove the #pragma below and fix conversion issues
#pragma clang diagnostic pop // ignored "-Wconversion"
|
e841efabf2cfdf20f061b1b5adf17c9cc14554d8 | 33258ea4d563d6c4e46cab73e0c4d81c9257be3c | /k-opt/fileio/PointSet.cpp | 2a1665b11d52c4eb381004660d71c497801a1ee6 | [] | no_license | rlee32/standard-k-opt | 3c5c932d7e386ca881820e9306dc197eef83e8b6 | 90c6f807212dd650a8276d4f9c63ce703c04d24a | refs/heads/master | 2020-04-09T11:28:36.357120 | 2018-12-17T01:40:51 | 2018-12-17T01:40:51 | 160,310,995 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,971 | cpp | PointSet.cpp | #include "PointSet.h"
namespace fileio {
PointSet::PointSet(const char* file_path)
{
std::cout << "\nReading point set file: " << file_path << std::endl;
std::ifstream file_stream(file_path);
if (not file_stream.is_open())
{
std::cout << "ERROR: could not open file: " << file_path << std::endl;
return;
}
size_t point_count{0};
// header.
std::string line;
while (not file_stream.eof())
{
std::getline(file_stream, line);
if (line.find("NODE_COORD_SECTION") != std::string::npos) // header end.
{
break;
}
if (line.find("DIMENSION") != std::string::npos) // point count.
{
std::string point_count_string = line.substr(line.find(':') + 1);
point_count = std::stoi(point_count_string);
std::cout << "Number of points according to header: " << point_count << std::endl;
}
}
if (point_count == 0)
{
std::cout << "ERROR: could not read any points from the point set file." << std::endl;
return;
}
// coordinates.
while (not file_stream.eof())
{
if (m_x.size() >= point_count)
{
break;
}
std::getline(file_stream, line);
std::stringstream line_stream(line);
primitives::point_id_t point_id{0};
line_stream >> point_id;
if (point_id == m_x.size() + 1)
{
primitives::space_t value{0};
line_stream >> value;
m_x.push_back(value);
line_stream >> value;
m_y.push_back(value);
}
else
{
std::cout << "ERROR: point id ("
<< point_id
<< ")does not match number of currently read points ("
<< m_x.size()
<< ")." << std::endl;
}
}
std::cout << "Finished reading point set file.\n" << std::endl;
}
} // namespace fileio
|
0c55d2b58d1762bf8d7a20b76cf81b27b357c168 | b1b5058ade39d72245c14cc8d21084b6775b523f | /Section 3.0/Factorials.cpp | 9e5030a89de50c8fc3233a446219cd1703a8a5cf | [] | no_license | qingchen/USACO | b16e7dc84c9e1ca87b3944ba48f6953014e5e980 | 915c1ba21233487283562b85ed1526aebf7da3b8 | refs/heads/master | 2021-03-13T00:05:11.714919 | 2015-03-22T05:33:01 | 2015-03-22T05:33:01 | 21,810,525 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | cpp | Factorials.cpp | /*
ID: caiweid3
PROG: fact4
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string.h>
using namespace std;
ofstream fout ("fact4.out");
ifstream fin ("fact4.in");
int main()
{
int n,tmp,count=0;
int m[5000];
fin>>n;
for(int i=1;i<=n;i++)
if(i%5==0)
{
tmp=i;
while(tmp%5==0)
{
count++;
tmp/=5;
}
m[i]=tmp;
}
else
m[i]=i;
int ans=1;
for(int i=1;i<=n;i++)
{
if(count>0&&m[i]%2==0)
{
tmp=m[i];
while(tmp%2==0&&count>0)
{
count--;
tmp/=2;
}
ans=(ans*tmp)%10;
}
else
ans=(ans*m[i])%10;
}
fout<<ans<<endl;
// system("pause");
return 0;
} |
2c538c8ff0a7f29723aaecfa6be833422879a13c | e8bcc26064462a24dffe995dfe4d322d2ea1f466 | /Algoritmos/Grafos/prim.cpp | 79f520d5ad27444951a1ff1c704beadb5b6294a2 | [] | no_license | MaiconBaggio/maratona-programacao | a74c2d0a50db5e6f37044788a6fa0c021daef04a | c927b7029131cfb9cd069c081cb5489cce966056 | refs/heads/master | 2021-08-30T12:56:30.911836 | 2017-12-18T02:49:29 | 2017-12-18T02:49:29 | 105,041,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,064 | cpp | prim.cpp | #include <iostream>
#include <vector>
#include <utility>
#include <queue>
#define INF 100000000
using namespace std;
typedef pair<int, int> ii;
typedef vector<ii> vi;
typedef vector<vi> vii;
int prim(vii &grafo, int numeroVertices, int inicio){
int resp = 0;
vector<int> dist(numeroVertices, INF), vis(numeroVertices, 0);
priority_queue< ii, vector<ii>, greater<ii> > pqueue;
pqueue.push(ii(0, inicio));
dist[inicio] = 0;
while(!pqueue.empty()){
int u = pqueue.top().second;
pqueue.pop();
if(vis[u]) continue;
vis[u] = 1; resp += dist[u];
for(auto v : grafo[u])
if(v.second < dist[v.first] && !vis[v.first]){
dist[v.first] = v.second;
pqueue.push(ii(dist[v.first], v.first));
}
}
return resp;
}
int main(void){
int numArestas, numVertices, u, v, w;
cin >> numVertices >> numArestas;
vii grafo(numVertices, vi());
while(numArestas--){
cin >> u >> v >> w;
grafo[u].push_back(ii(v, w));
grafo[v].push_back(ii(u, w));
}
cout << prim(grafo, numVertices, 0) << "\n";
return 0;
}
|
b1a8e2032b754b3f7537e1b98a23ba18ba1a5842 | ff907a2188d7d76523c718a9becb4295aac3afd1 | /madeEasy/chap5/4prob_array.cpp | 511f8850e04cfe67a2074d19cf6988c57d954b25 | [] | no_license | sanju784/ds-algorithm-c-cpp | 873c67715960e7b50a2a11b8faf6e0ddcec713ac | 9bd27fcdeeaa3b9178a70012559e8fd04b935d2a | refs/heads/master | 2021-05-01T04:31:18.589453 | 2017-07-12T14:06:03 | 2017-07-12T14:06:03 | 69,509,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | 4prob_array.cpp | #include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int arr[] = {1,3,-1,-3,5,3,6,7};
int w = 3;
int n = sizeof(arr)/sizeof(int);
int *res;
res = (int*)malloc((n-w+1)*sizeof(int));
int max = arr[0];
for(int j = 1;j < w; j++) {
if(arr[j] > max) {
max = arr[j];
}
}
int j = 0;
res[j++] = max;
for (int i = w;i < n; i++){
if(arr[i] > max) {
max = arr[i];
}
res[j++] = max;
}
cout<<"\nOriginal array is\n";
for(int i = 0; i < n; i++)
cout<<arr[i]<<" ";
cout<<"\n\nThe window size is "<<w<<endl;
cout<<"\nThe maximum array is\n";
for(int i = 0; i < (n-w+1); i++)
cout<<res[i]<<" ";
return 0;
}
|
650ceea6095d980496b7eeed12305aab652c06da | bc377fcafd15b5186163bf937e80c5088d23a112 | /estrutura_de_dados/TP3/src/node.cpp | 7a18991f8a962f4611257c23578c648a0c97d915 | [] | no_license | guilhermealbm/CC-UFMG | 9ec885da17e773a40db6b913dcf51092f95902a7 | 667cc012e3f3788c8babf5c4c9fd9106ee812a2a | refs/heads/master | 2022-08-09T19:31:23.272393 | 2022-07-20T21:23:13 | 2022-07-20T21:23:13 | 195,878,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,906 | cpp | node.cpp | #include "node.h"
Node::Node(){
this->_cell = {" ", ' '}; //Cria node com célula vazia. Se necessário, a célulal será substituída no método insert_cell.
this->_left = nullptr;
this->_right = nullptr;
}
Node::~Node(){
if (this->_left != nullptr)
delete this->_left;
if (this->_right != nullptr)
delete this->_right;
}
void Node::insert_cell(Cell cell, unsigned int index){
if(index == cell.key.size()){ //Se chegou até o nível correto na trie, atribui a célula correta ao node.
this->_cell = cell;
return;
}
/* Caminha para a esquerda se a posição do código for um '.' e para a direita se o caractere for '-'
Se o node ainda não existe, deve ser criado para que a célula seja inserida na posição correta.
O método faz chamadas recursivas aumentando o valor do índice, ou seja, chama a si próprio
"descendo" na árvore até encontrar a posição correta para a célula
*/
else if (cell.key[index] == '.'){
if (this->_left == nullptr)
this->_left = new Node();
this->_left->insert_cell(cell, index+1);
}else{
if (this->_right == nullptr)
this->_right = new Node();
this->_right->insert_cell(cell, index+1);
}
}
char Node::find_cell(std::string key, unsigned int index){
if(index == key.size()) //Se chegou até o nível correto na trie, retorna a letra correspondente ao código em questão.
return this->_cell.letter;
else if(key[index] == '.') //Faz chamadas recursivar a fim de "descer" na árvore até encontrar o código buscado.
return this->_left->find_cell(key, index+1);
else
return this->_right->find_cell(key, index+1);
}
void Node::printPreorder(Node *node){
if (node == nullptr)
return;
if(node->_cell.letter != ' ')
std::cout << node->_cell.letter << " " << node->_cell.key << std::endl;
printPreorder(node->_left);
printPreorder(node->_right);
} |
e9a5db475b7f5531c1c1aacfa3b088df9e082d7b | aa5e9defea373d64d75336fc6c5a03124e24abbd | /plugins/core/DriftingGratingStimulus/DriftingGratingStimulusPlugin.cpp | de77b4f5412fcf0b45ea8bec01d0fc135c0f059d | [
"MIT"
] | permissive | esayui/mworks | e8ae5d8b07d36d5bbdec533a932d29641f000eb9 | 0522e5afc1e30fdbf1e67cedd196ee50f7924499 | refs/heads/master | 2022-02-18T03:47:49.858282 | 2019-09-04T16:42:52 | 2019-09-05T13:55:06 | 208,943,825 | 0 | 0 | MIT | 2019-09-17T02:43:38 | 2019-09-17T02:43:38 | null | UTF-8 | C++ | false | false | 562 | cpp | DriftingGratingStimulusPlugin.cpp | /*
* DriftingGratingStimulusPlugins.cpp
* DriftingGratingStimulusPlugins
*
* Created by bkennedy on 8/14/08.
* Copyright 2008 MIT. All rights reserved.
*
*/
#include "DriftingGratingStimulus.h"
BEGIN_NAMESPACE_MW
class DriftingGratingStimulusPlugin : public Plugin {
void registerComponents(shared_ptr<ComponentRegistry> registry) override {
registry->registerFactory<StandardStimulusFactory, DriftingGratingStimulus>();
}
};
extern "C" Plugin* getPlugin() {
return new DriftingGratingStimulusPlugin();
}
END_NAMESPACE_MW
|
5b95a94eb4ddbfe4a5c8d2000e7950e4cffbf048 | 3a5b7154eddfdc62d7a35d554748bc7aece84f36 | /InputManager.cpp | f369d077999a8c6186d1bc821266dc3fd10da5e3 | [] | no_license | yongfu-lu/csc211HFinalProject | 4adbe621d98066879e5aa8b7eb3cee5263eed1da | f221da593fce6e2e9ee381cb9d6830226d9ba8bc | refs/heads/master | 2022-08-03T02:53:20.204700 | 2020-05-21T22:41:21 | 2020-05-21T22:41:21 | 265,958,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 748 | cpp | InputManager.cpp |
#include "InputManager.hpp"
namespace YL
{
// this function is for check mouse click in the future
bool InputManager::IsSpriteClocked (sf::Sprite object, sf::Mouse::Button button, sf::RenderWindow & window)
{
if (sf::Mouse::isButtonPressed(button))
{
sf::IntRect temRect( object.getPosition().x, object.getPosition().y,object.getGlobalBounds().width,object.getGlobalBounds().height);
if (temRect.contains(sf::Mouse::getPosition(window)))
{
return true;
}
}
return false;
}
sf::Vector2i InputManager::GetMousePosition (sf::RenderWindow & window)
{
return sf::Mouse::getPosition(window);
}
}
|
67a254b3c410e7dd11a0fdc979f56d8584221868 | fcebca7c5725c44796d90a7158350e52aa61cc72 | /src/model/effects/StructuralRateEffect.cpp | 2af60727b9044eb6820aa217e83a605b864e6b8d | [] | no_license | kkc-krish/RSiena | c082a0e1c3698bffd68734387347c4de7981698f | 4f9d65392367703150e6285291a9b41d23e647c6 | refs/heads/master | 2020-12-24T19:59:58.649070 | 2013-06-18T00:00:00 | 2013-06-18T00:00:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,345 | cpp | StructuralRateEffect.cpp | /******************************************************************************
* SIENA: Simulation Investigation for Empirical Network Analysis
*
* Web: http://www.stats.ox.ac.uk/~snijders/siena/
*
* File: StructuralRateEffect.cpp
*
* Description: This file contains the implementation of the class
* StructuralRateEffect.
*****************************************************************************/
#include "StructuralRateEffect.h"
#include "utils/Utils.h"
#include "network/OneModeNetwork.h"
#include "model/variables/NetworkVariable.h"
#include "model/variables/EffectValueTable.h"
namespace siena
{
/**
* Constructor.
* @param[in] pVariable the network variable this effect depends on
* @param[in] type the type of this effect
* @param[in] parameter the statistical parameter of this effect
*/
StructuralRateEffect::StructuralRateEffect(const NetworkVariable * pVariable,
StructuralRateEffectType type,
double parameter)
{
this->lpVariable = pVariable;
this->ltype = type;
double possibleDegree = max(this->lpVariable->n(),
this->lpVariable->m());
if (this->ltype == INVERSE_OUT_DEGREE_RATE)
{
this->lpTable = new EffectValueTable(possibleDegree, invertor);
}
else
{
this->lpTable = new EffectValueTable(possibleDegree, identity);
}
this->lpTable->parameter(parameter);
}
/**
* Destructor.
*/
StructuralRateEffect::~StructuralRateEffect()
{
delete this->lpTable;
this->lpTable = 0;
}
/**
* Returns the contribution of this effect for the given actor.
*/
double StructuralRateEffect::value(int i)
{
Network * pNetwork = this->lpVariable->pNetwork();
switch (this->ltype)
{
case OUT_DEGREE_RATE:
case INVERSE_OUT_DEGREE_RATE:
return this->lpTable->value(pNetwork->outDegree(i));
case IN_DEGREE_RATE:
return this->lpTable->value(pNetwork->inDegree(i));
case RECIPROCAL_DEGREE_RATE:
return this->lpTable->value(
(((OneModeNetwork *) pNetwork)->reciprocalDegree(i)));
}
throw new logic_error("Unexpected structural rate effect type");
}
/**
* Stores the parameter for the structural rate effect.
*/
void StructuralRateEffect::parameter(double parameterValue)
{
this->lpTable->parameter(parameterValue);
}
/**
* Returns the parameter for the structural rate effect.
*/
double StructuralRateEffect::parameter() const
{
return this->lpTable->parameter();
}
}
|
b12839d1b2020f1d93d8a0e6c380d8992781543c | 4bcc9806152542ab43fc2cf47c499424f200896c | /tensorflow/compiler/mlir/lite/metrics/error_collector.h | 0a4d64de4fffb97604f83470bfbd9c9fddda81f3 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | tensorflow/tensorflow | 906276dbafcc70a941026aa5dc50425ef71ee282 | a7f3934a67900720af3d3b15389551483bee50b8 | refs/heads/master | 2023-08-25T04:24:41.611870 | 2023-08-25T04:06:24 | 2023-08-25T04:14:08 | 45,717,250 | 208,740 | 109,943 | Apache-2.0 | 2023-09-14T20:55:50 | 2015-11-07T01:19:20 | C++ | UTF-8 | C++ | false | false | 1,959 | h | error_collector.h | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_MLIR_LITE_METRICS_ERROR_COLLECTOR_H_
#define TENSORFLOW_COMPILER_MLIR_LITE_METRICS_ERROR_COLLECTOR_H_
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "tensorflow/compiler/mlir/lite/metrics/types_util.h"
#include "tensorflow/lite/python/metrics/converter_error_data.pb.h"
namespace mlir {
namespace TFL {
// A singleton to store errors collected by the instrumentation.
class ErrorCollector {
using ConverterErrorData = tflite::metrics::ConverterErrorData;
using ConverterErrorDataSet =
std::unordered_set<ConverterErrorData, ConverterErrorDataHash,
ConverterErrorDataComparison>;
public:
const ConverterErrorDataSet &CollectedErrors() { return collected_errors_; }
void ReportError(const ConverterErrorData &error) {
collected_errors_.insert(error);
}
// Clear the set of collected errors.
void Clear() { collected_errors_.clear(); }
// Returns the global instance of ErrorCollector.
static ErrorCollector* GetErrorCollector();
private:
ErrorCollector() {}
ConverterErrorDataSet collected_errors_;
static ErrorCollector* error_collector_instance_;
};
} // namespace TFL
} // namespace mlir
#endif // TENSORFLOW_COMPILER_MLIR_LITE_METRICS_ERROR_COLLECTOR_H_
|
c4804b16ff1d3b5f38e20abd3d725f0ad99d5aa7 | 95570ae3de9febfe81989751982f6a6eafe080ff | /Sources/API/GUI/Components/slider.h | 06203cec5bb93d46eec9768a7b3566bd28c5bce0 | [
"Zlib"
] | permissive | kyelin/ClanLib | a552f224c2007598a1ab8acaf4e2caa967908851 | 2558aba725e6866a81d50b13178cbd5c60ab6edc | refs/heads/master | 2021-01-24T21:36:07.499397 | 2014-11-18T02:09:39 | 2014-11-18T02:09:39 | 19,273,763 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,551 | h | slider.h | /*
** ClanLib SDK
** Copyright (c) 1997-2013 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
** Harry Storbacka
*/
#pragma once
#include "../api_gui.h"
#include "../gui_component.h"
namespace clan
{
/// \addtogroup clanGUI_Components clanGUI Components
/// \{
class Slider_Impl;
/// \brief Track bar component.
class CL_API_GUI Slider : public GUIComponent
{
/// \name Construction
/// \{
public:
/// \brief Constructs a Slider
///
/// \param parent = GUIComponent
Slider(GUIComponent *parent);
virtual ~Slider();
/// \}
/// \name Attributes
/// \{
public:
using GUIComponent::get_named_item;
/// \brief Find the child Slider with the specified component ID name.
///
/// If it was not found, an exception is thrown.
static Slider *get_named_item(GUIComponent *reference_component, const std::string &id);
/// \brief Is Vertical
///
/// \return true = vertical
bool is_vertical() const;
/// \brief Is Horizontal
///
/// \return true = horizontal
bool is_horizontal() const;
/// \brief Get Min
///
/// \return min
int get_min() const;
/// \brief Get Max
///
/// \return max
int get_max() const;
/// \brief Get Tick count
///
/// \return tick_count
int get_tick_count() const;
/// \brief Get Page step
///
/// \return page_step
int get_page_step() const;
/// \brief Get Position
///
/// \return position
int get_position() const;
/// \brief Get Lock to ticks
///
/// \return lock_to_ticks
bool get_lock_to_ticks() const;
/// \brief Returns the preferred content width
///
/// Override this function if the component has non-css content.
float get_preferred_content_width();
/// \brief Returns the preferred content height for the specified content width
///
/// Override this function if the component has non-css content.
float get_preferred_content_height(float width);
/// \}
/// \name Operations
/// \{
public:
/// \brief Set vertical
///
/// \param enable = bool
void set_vertical(bool enable);
/// \brief Set horizontal
///
/// \param enable = bool
void set_horizontal(bool enable);
/// \brief Set min
///
/// \param slider_min = value
void set_min(int slider_min);
/// \brief Set max
///
/// \param slider_max = value
void set_max(int slider_max);
/// \brief Set tick count
///
/// \param tick_count = value
void set_tick_count(int tick_count);
/// \brief Set page step
///
/// \param steps = value
void set_page_step(int steps);
/// \brief Set lock to ticks
///
/// \param lock = bool
void set_lock_to_ticks(bool lock);
/// \brief Set ranges
///
/// \param slider_min = value
/// \param slider_max = value
/// \param tick_count = value
/// \param page_step = value
void set_ranges(int slider_min, int slider_max, unsigned int tick_count, int page_step);
/// \brief Set position
///
/// \param pos = value
void set_position(int pos);
/// \}
/// \name Callbacks
/// \{
public:
/// \brief Emitted while the slider is being moved.
Callback_v0 &func_value_changed();
/// \brief Emitted when the slider value is decremented (while moving or when clicking the track).
/** Invoked while moving or when clicking the track.*/
Callback_v0 &func_value_decremented();
/// \brief Emitted when the slider value is incremented.
/** Invoked while moving or when clicking the track.*/
Callback_v0 &func_value_incremented();
/// \brief Emitted after the slider has been moved.
Callback_v0 &func_slider_moved();
/// \}
/// \name Implementation
/// \{
private:
std::shared_ptr<Slider_Impl> impl;
/// \}
};
}
/// \}
|
9477af623f0da6743fedebb87a434695f7101fb5 | d3c5b5f9c15dec74dd8f5928df5022ae639e910d | /Unit Tests/PlatformTest.cpp | 8d567be1fb318bdd42b95fcfce2974b53e7f6daa | [
"MIT"
] | permissive | kbaker827/windows-metered-connection | 2eae2fdb2c2a7547bd593003ce1592a0bebf35bc | 3b54fa3c271fb9a4748365176d9d8779caaa710a | refs/heads/master | 2021-07-02T11:39:40.821249 | 2017-02-06T20:36:24 | 2017-02-06T20:36:24 | 169,770,534 | 0 | 0 | MIT | 2020-09-22T15:21:53 | 2019-02-08T17:11:36 | C++ | UTF-8 | C++ | false | false | 392 | cpp | PlatformTest.cpp | #include "catch.hpp"
#include "Platform.h"
#include "Logging.h"
SCENARIO("Static helpers") {
GIVEN("Invariant helpers") {
WHEN("I get the ProgramData path") {
// TODO mock Win32 and inject expected path result, since the following won't always be true
REQUIRE(MeteredConnection::Platform::GetProgramDataPath() == LR"(C:\ProgramData)");
}
}
}
|
84c230598b363d1c2e91bd0730dd42c3fc3bc99a | c46a0d02315223318e152debac0d98bc4754b47c | /Group36W3/ui/addcomputerdialog.cpp | 013be289bfbfbc640b8ba7b55cd1780c416f0d35 | [] | no_license | skulia15/Project-Course-1--Reykjavik-University | f3ad25b0658299597bea21bced0186d750a72334 | 8b486713d8d2c982d8b46020f8faea99388a3818 | refs/heads/master | 2021-05-31T14:42:14.033042 | 2016-04-28T11:11:36 | 2016-04-28T11:11:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,286 | cpp | addcomputerdialog.cpp | #include "addcomputerdialog.h"
#include "ui_addcomputerdialog.h"
#include "services/scientistservice.h"
#include "services/computerservice.h"
#include "utilities/utils.h"
#include "mainwindow.h"
using namespace std;
bool checkStringValid(string myString);
bool checkCompStringValid(string myString);
AddComputerDialog::AddComputerDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AddComputerDialog)
{
ui->setupUi(this);
ui->comboBox_computer_type->addItem("");
ui->comboBox_computer_type->addItem("Electronic");
ui->comboBox_computer_type->addItem("Mechatronic");
ui->comboBox_computer_type->addItem("Transistor");
ui->comboBox_computer_type->addItem("Other");
}
AddComputerDialog::~AddComputerDialog()
{
delete ui;
}
void AddComputerDialog::on_button_add_computer_box_clicked()
{
ComputerService computerService;
bool thereWasAnError = false;
QString computerType;
int temp;
ui->label_error_computer_name->setText("");
ui->label_error_computer_type->setText("");
QString name = ui->Input_computer_name->text();
QString yearBuilt = ui->input_year_built->text();
if(ui->comboBox_computer_type->currentText() == "Electronic"){
temp = 1;
computerType = temp;
qDebug()<<temp<<computerType;
}
if(ui->comboBox_computer_type->currentText() == "Mechatronic"){
temp = 2;
computerType = temp;
}
if(ui->comboBox_computer_type->currentText() == "Transistor"){
temp = 3;
computerType = temp;
qDebug()<<temp<<computerType;
}
if(ui->comboBox_computer_type->currentText() == "Other"){
temp = 4;
computerType = temp;
}
if (name.isEmpty()){
ui->label_error_computer_name->setText("<span style=color:#FF2A1A>The computer must have a name!</span>");
thereWasAnError = true;
}
else if (!checkCompStringValid(name.toStdString())){
ui->label_error_computer_name->setText("<span style=color:#FF2A1A>The name must only contain alphanumeric characters</span>");
thereWasAnError = true;
}
if (checkStringValid(yearBuilt.toStdString())){
if (!yearBuilt.isEmpty()){
//ui->label_error_YB->setText("<span style=color:#FF2A1A>This this field can only contain numbers!</span>");
}
thereWasAnError = true;
if (yearBuilt.isEmpty()){
thereWasAnError = false;
}
}
if (computerType.isEmpty()){
ui->label_error_computer_type->setText("<span style=color:#FF2A1A>The computer must have a type!</span>");
thereWasAnError = true;
}
if (thereWasAnError)
{
return;
}
bool success = computerService.addComputer(Computer(name.toStdString(), temp, yearBuilt.toInt()));
if (success){
ui->Input_computer_name->setText("");
ui->input_year_built->setText("");
this->done(0);
}
else{
this->done(-1);
}
}
bool checkCompStringValid(string myString){
bool error = false;
for (unsigned int i = 0; i < myString.length(); i++){
if (isalnum(myString[i]) || isspace(myString[i])){
error = true;}
else return false;
}
if (error == true) return true;
else return false;
}
|
f884a9c8b5dd36c5de4f8f45e1bf6ca63f25bbdc | fb127294ed7fb48e37342ca0950a34015fe8bd4e | /components/radiant_mod/com_files.cpp | 1d67c45eeb677e1c6d437db9e741ee6ea5c346ab | [] | no_license | Nukem9/LinkerMod | 89c826f42cfc0aabe111002ca3696df07ac156c9 | 72ee05bbf42dfb2a1893e655788b631be63ea317 | refs/heads/development | 2021-07-14T16:23:00.813862 | 2020-04-09T05:05:38 | 2020-04-09T05:05:38 | 30,128,803 | 134 | 56 | null | 2021-04-04T14:04:54 | 2015-01-31T22:35:11 | C++ | UTF-8 | C++ | false | false | 1,753 | cpp | com_files.cpp | #include "stdafx.h"
FS_ReadFile_t o_FS_ReadFile = (FS_ReadFile_t)0x004BC840;
int __cdecl FS_ReadFile(const char *qpath, void **buffer)
{
int result = o_FS_ReadFile(qpath, buffer);
if (result < 0)
{
if (strncmp(qpath, "techniques", strlen("techniques")) == 0 || strncmp(qpath, "techsets", strlen("techsets")) == 0)
{
char npath[MAX_PATH];
sprintf_s(npath, PATH_PIMP_FALLBACK"/%s", qpath);
_VERBOSE( printf("%s\n", npath) );
result = o_FS_ReadFile(npath, buffer);
}
}
return result;
}
#include "r_material_load_obj.h"
void FS_Init_TechsetOverride(void)
{
FILE* h = fopen("techset_override.csv", "r");
if (h)
{
for (int eof = false; !eof && !feof(h);)
{
char buf[1024] = "";
if (!fgets(buf, 1024, h))
{
fclose(h);
return;
}
techsetOverride tsOverride;
char* p = strtok(buf, " \t\n,");
if (!p || (p[0] == '/' && p[1] == '/'))
{
continue;
}
tsOverride.key = p;
p = strtok(NULL, " \t\n,");
if (!p)
{
continue;
}
tsOverride.replacement = p;
techsetOverrideList.push_back(tsOverride);
}
fclose(h);
}
}
int __cdecl FS_HashFileName(const char *fname, int hashSize)
{
int hash = 0;
for (int i = 0; fname[i]; ++i)
{
int letter = tolower(fname[i]);
if (letter == '.')
break;
if (letter == '\\')
letter = '/';
hash += letter * (i + 119);
}
return ((hash >> 20) ^ hash ^ (hash >> 10)) & (hashSize - 1);
}
const char* FS_GetExtensionSubString(const char* filename)
{
if (filename == '\0')
return NULL;
const char* substr = 0;
while (*filename)
{
if (*filename == '.')
substr = filename;
else if (*filename == '/' || *filename == '\\')
substr = 0;
++filename;
}
if (!substr)
substr = filename;
return substr;
}
|
20e38a5527e4932e8860fbd97d79510a75a3c77c | 735441d9817e13191b24702feb969049db184c9e | /1sem/Contest_22.11.16/S/S.cpp | f6b3d22612462493586545e076043e541070e0d6 | [] | no_license | p-mazhnik/mipt-cpp | 0e7dcfe84d0b31e9b2cb2fe1133dd23f4538f5c3 | 5c9bd5e97880a353c64843170863e5ea6d9cf26d | refs/heads/master | 2021-01-21T10:00:26.884468 | 2018-04-11T22:20:44 | 2018-04-11T22:20:44 | 83,356,174 | 2 | 3 | null | 2017-04-25T16:06:11 | 2017-02-27T20:58:18 | C++ | WINDOWS-1251 | C++ | false | false | 1,780 | cpp | S.cpp | #include <iostream>
#include <stdio.h>
using namespace std;
/*void print_array2(int **a, int n, int m) // вывод двумерного массива c n строками и m столбцами на экран
{
for (int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
printf("%5d ", a[i][j]);
}
cout << endl;
};
cout << endl << endl;
}
*/
void print_number(int **c, int *a, int *b, int i, int j)
{
if (i == 0 || j == 0){
return;
}
if (a[i - 1] == b[j - 1]){
print_number(c, a, b, i - 1, j - 1);
cout << a[i - 1] << ' ';
}
else{
if (c[i][j] == c[i - 1][j]){
print_number(c, a, b, i - 1, j);
}
else{
print_number(c, a, b, i, j - 1);
}
}
}
int main()
{
int n, m;
cin >> n;
int *a = new int[n];
for(int i = 0; i < n; ++i){
cin >> a[i];
}
cin >> m;
int *b = new int[m];
for(int i = 0; i < m; ++i){
cin >> b[i];
}
int **c = new int *[n + 1];
for(int i = 0; i <= n; ++i){
c[i] = new int[m + 1];
}
for(int i = 0; i < n + 1; ++i){
c[i][0] = 0;
}
for(int j = 0; j < m + 1; ++j){
c[0][j] = 0;
}
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= m; ++j){
if(a[i - 1] == b[j - 1]){
c[i][j] = c[i - 1][j - 1] + 1;
}
else{
c[i][j] = max(c[i - 1][j], c[i][j - 1]);
}
}
}
// print_array2(c, n + 1, m + 1);
//cout << c[n][m] << endl;
print_number(c, a, b, n, m);
delete []a;
delete []b;
for(int i = 0; i < n; ++i){
delete []c[i];
}
delete []c;
return 0;
}
/*
8
2 0 -1 3 2 4 0 3
*/
|
77bd8c04d6768754240d2f1000a522c8f5901fd2 | 2dae29709f2fff81afa85b0d42689a380b000ade | /Elevator/Elevator.h | bab81a8a82242d118b8b3d47eb2c3f69a9dcb8ca | [] | no_license | demietank/cpp605 | 4ea126042406c20b740bd924342e0168cb6b3c11 | ea426f6837eb524d60ca26485e547fd9c1f315a5 | refs/heads/master | 2016-08-11T12:12:21.674377 | 2016-05-07T18:27:12 | 2016-05-07T18:27:12 | 50,798,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,853 | h | Elevator.h | /*
* Elevator.h
*
* Created on: Apr 14, 2016
* Author: cmmay
*/
#ifndef ELEVATOR_H_
#define ELEVATOR_H_
#include <ostream>
#include <set>
#include <vector>
#include "common.h"
#include "Passenger.h"
namespace elevators
{
/// States the elevator can be in.
enum class ElevatorState
{
STOPPED,
STOPPING,
MOVING
};
/// An elevator that moves between floors transporting passengers.
class Elevator
{
public:
/// Constructs an empty elevator, stopped at the bottom floor.
Elevator(const unsigned int capacity,
const unsigned int stoppingTime,
const unsigned int movingTime,
const FloorNumber bottomFloor,
const FloorNumber topFloor);
/// Destructs the elevator.
virtual ~Elevator();
/// Adds the specified floor to the elevator's destination list.
/// If the elevator's direction is none, change the direction toward the new destination.
/// Returns false if the elevator is going in a different direction or is already stopped on the floor.
bool addDestination(const FloorNumber floor);
/// Adds a passenger to the elevator and adds the passenger's destination to the list.
/// Returns false if the elevator is full or the passenger is going in a different direction.
bool addPassenger(const Passenger& passenger);
/// Removes passengers whose destination is the current floor, if any.
/// The current floor is removed from the destination list.
/// If there are no more passengers or destinations, change the direction to none.
std::vector<Passenger> disembark();
/// Increment travel time for all passengers.
void incrementPassengerTime();
/// The elevator takes an action, incrementing in time 1 second. If the state changes, time is
/// reset to zero.
/// The action is defined based on the current elevator state:
/// STOPPED: If the direction is not NONE, the state changes to MOVING and moves floors.
/// STOPPING: If the elevator has been stopping for a enough time, the state changes to STOPPED.
/// MOVING: If the elevator has been moving for a enough time
/// If the new floor is in the destination list, the state changes to STOPPING.
/// Otherwise the elevator moves floors.
void move();
/// Returns the direction the elevator is traveling in.
Direction getDirection() const
{
return mDirection;
}
/// Returns the current floor the elevator is on.
FloorNumber getFloor() const
{
return mCurrentFloor;
}
/// Returns the state of the elevator.
ElevatorState getState() const
{
return mState;
}
private:
/// Number of passengers the elevator can carry at once.
unsigned int mCapacity;
/// The time it takes the elevator to stop
unsigned int mStoppingTime;
/// The time it takes the elevator to move between floors
unsigned int mMovingTime;
/// The state of the elevator, and the time it has spend there
ElevatorState mState;
unsigned int mTimeInState;
Direction mDirection;
/// The floor the elevator is on.
/// If the elevator is in transport this is the next floor it will arrive on.
FloorNumber mCurrentFloor;
/// Floors the elevator services (contiguous)
FloorNumber mBottomFloor;
FloorNumber mTopFloor;
/// Passengers in the elevator
std::vector<Passenger> mPassengers;
/// Floors that the elevator will stop on
std::set<FloorNumber> mDestinations;
/// Outputs an ASCII representation of the elevator.
friend std::ostream& operator<<(std::ostream& out,
const Elevator& elevator);
};
/// Outputs an ASCII representation of the elevator.
std::ostream& operator<<(std::ostream& out,
const Elevator& elevator);
} /* namespace elevators */
#endif /* ELEVATOR_H_ */
|
d1565cb15018caee729ce98e2f240d56df5a0703 | 142ad524f0a130ef8738645db4b7eb24d91526c6 | /preview/Win7Msix/Win7MSIXInstaller/MsixRequest.hpp | 737e6c2bdc2468d86fc8a754ab84163f0a3736c7 | [
"Zlib",
"OpenSSL",
"LicenseRef-scancode-unicode",
"Apache-2.0",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | ToTigerMountain/msix-packaging | 45299990d4450c9de65557e2e750868a8f81b948 | 6edc2c8bc31a247641a195ca457899ff9dc6a9c0 | refs/heads/master | 2020-05-15T01:40:33.585372 | 2019-04-15T19:36:57 | 2019-04-15T19:36:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,696 | hpp | MsixRequest.hpp | #pragma once
#include "PackageInfo.hpp"
#include "FilePaths.hpp"
#include "MsixResponse.hpp"
class UI;
enum OperationType
{
Undefined = 0,
Add = 1,
Remove = 2,
FindPackage = 3,
FindAllPackages = 4,
};
enum Flags
{
NoFlags = 0,
QuietUX = 0x1,
};
DEFINE_ENUM_FLAG_OPERATORS(Flags);
/// MsixRequest represents what this instance of the executable will be doing and tracks the state of the current operation
class MsixRequest
{
private:
/// Should always be available via constructor
std::wstring m_packageFilePath;
std::wstring m_packageFullName;
MSIX_VALIDATION_OPTION m_validationOptions = MSIX_VALIDATION_OPTION::MSIX_VALIDATION_OPTION_FULL;
Flags m_flags = NoFlags;
OperationType m_operationType = Add;
FilePathMappings m_filePathMappings;
/// Filled by PopulatePackageInfo
AutoPtr<PackageInfo> m_packageInfo;
/// Filled in by CreateAndShowUI
AutoPtr<UI> m_UI;
/// MsixResponse object populated by handlers
AutoPtr<MsixResponse> m_msixResponse;
public:
static HRESULT Make(OperationType operationType, Flags flags, std::wstring packageFilePath, std::wstring packageFullName, MSIX_VALIDATION_OPTION validationOption, MsixRequest** outInstance);
/// The main function processes the request based on whichever operation type was requested and then
/// going through the sequence of individual handlers.
HRESULT ProcessRequest();
/// Called by PopulatePackageInfo
void SetPackageInfo(PackageInfo* packageInfo);
/// Called by CreateAndShowUI
void SetUI(UI* ui);
// Getters
inline MSIX_VALIDATION_OPTION GetValidationOptions() { return m_validationOptions; }
inline PCWSTR GetPackageFilePath() { return m_packageFilePath.c_str(); }
inline PCWSTR GetPackageFullName() { return m_packageFullName.c_str(); }
inline FilePathMappings* GetFilePathMappings() { return &m_filePathMappings; }
/// @return can return null if called before PopulatePackageInfo.
PackageInfo* GetPackageInfo() { return m_packageInfo; }
/// @return can return null if called before CreateAndShowUI or if Flags::QuietUX was passed in and there is no UI.
UI* GetUI() { return m_UI; }
inline bool IsQuietUX() { return (m_flags & Flags::QuietUX) == Flags::QuietUX; }
inline bool IsRemove()
{
return m_operationType == OperationType::Remove;
}
inline bool AllowSignatureOriginUnknown()
{
m_validationOptions = static_cast<MSIX_VALIDATION_OPTION>(m_validationOptions | MSIX_VALIDATION_OPTION::MSIX_VALIDATION_OPTION_ALLOWSIGNATUREORIGINUNKNOWN);
return true;
}
/// Retrieves the msixResponse object
///
/// @return m_msixResponse object
MsixResponse* GetMsixResponse() { return m_msixResponse; }
private:
/// FilePath Mappings maps the VFS tokens (e.g. Windows) to the actual folder on disk (e.g. C:\windows)
HRESULT InitializeFilePathMappings();
/// This handles FindAllPackages operation and finds all packages installed by the Win7MSIXInstaller
HRESULT FindAllPackages();
/// This handles Add operation and proceeds through each of the AddSequenceHandlers to install the package
HRESULT ProcessAddRequest();
/// This handles Remove operation and proceeds through each of the RemoveSequenceHandlers to uninstall the package
HRESULT ProcessRemoveRequest();
/// This handles FindPackage operation and displays the package info for a given package.
/// @return E_NOT_SET when the package could not be found
HRESULT DisplayPackageInfo();
};
|
70fe037b68168921cf9eaffbdaa2ec35320a0ae8 | 6c0205bfbd2ea18feb878707d84bb1640d2ea730 | /dp/221.h | 2ff1d05dfea2e3f441b0bd321b86c58eb3fee3d4 | [] | no_license | wangqc/leetcode_test | 473128b1d87b5c99d5eb1fb3d837d40886dca52d | 77267f164d8bfbfe5cd97804b9aa0cbf5e753672 | refs/heads/master | 2023-04-19T21:09:18.709790 | 2021-05-17T07:07:29 | 2021-05-17T07:07:29 | 277,086,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,695 | h | 221.h | //
// Created by 王秋城 on 2021/2/1.
//
#ifndef LEETCODE_TEST_221_H
#define LEETCODE_TEST_221_H
//https://leetcode-cn.com/problems/maximal-square/
#include "../common.h"
class Solution {
public:
// 可以考虑优化空间复杂度的,利用滚动数组
int maximalSquareMoreSpace(vector<vector<char>>& matrix) {
int row = matrix.size();
int col = matrix[0].size();
vector<vector<int>> dp(row + 1, vector<int>(col + 1, 0));
int max = 0;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (matrix[i][j] == '0') {
dp[i + 1][j + 1] = 0;
} else {
dp[i + 1][j + 1] = min(dp[i][j + 1], min(dp[i + 1][j], dp[i][j])) + 1;
if (dp[i + 1][j + 1] > max) {
max = dp[i + 1][j + 1];
}
}
}
}
return max * max;
}
int maximalSquare(vector<vector<char>>& matrix) {
int row = matrix.size();
int col = matrix[0].size();
vector<int> dp(col + 1, 0);
int max = 0;
for (int i = 0; i < row; ++i) {
int prev = 0;
for (int j = 0; j < col; ++j) {
int tmp = dp[j+1];
if (matrix[i][j] == '0') {
dp[j+1] = 0;
} else {
dp[j + 1] = min(prev, min(dp[j], dp[j+1])) + 1;
if (dp[j+1] > max) {
max = dp[j+1];
}
}
prev = tmp;
}
}
return max*max;
}
};
#endif //LEETCODE_TEST_221_H
|
3510f279fba0363484ceee086e8d0829294bf35f | 8010df1fef10ddfd83bf07966cbf7e2e4b0d7ee9 | /include/winsdk/cppwinrt/winrt/impl/Windows.System.Inventory.1.h | 9712d6dacce4876d4fe427f27423d9941f51c5e4 | [
"MIT"
] | permissive | light-tech/MSCpp | a23ab987b7e12329ab2d418b06b6b8055bde5ca2 | 012631b58c402ceec73c73d2bda443078bc151ef | refs/heads/master | 2022-12-26T23:51:21.686396 | 2020-10-15T13:40:34 | 2020-10-15T13:40:34 | 188,921,341 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,089 | h | Windows.System.Inventory.1.h | // C++/WinRT v2.0.190620.2
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef WINRT_Windows_System_Inventory_1_H
#define WINRT_Windows_System_Inventory_1_H
#include "winrt/impl/Windows.System.Inventory.0.h"
namespace winrt::Windows::System::Inventory
{
struct __declspec(empty_bases) IInstalledDesktopApp :
Windows::Foundation::IInspectable,
impl::consume_t<IInstalledDesktopApp>
{
IInstalledDesktopApp(std::nullptr_t = nullptr) noexcept {}
IInstalledDesktopApp(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
struct __declspec(empty_bases) IInstalledDesktopAppStatics :
Windows::Foundation::IInspectable,
impl::consume_t<IInstalledDesktopAppStatics>
{
IInstalledDesktopAppStatics(std::nullptr_t = nullptr) noexcept {}
IInstalledDesktopAppStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {}
};
}
#endif
|
a018cd89bd511f4b6151d0d26734655939695c95 | 39dd4c3f174ccf1bf627a664f7607faea3c1484c | /common/inc/ast/loop_declaration.hpp | de47fdee5d92a391424a3afcace9e5b03a91fbde | [] | no_license | EdwardHarriss/C-Compiler-and-C-to-Python-Translator | 0d36545e48ff3ccf2c662e9c0cea8c7241686dc9 | 2d3241343d5e7cef6618e3ade4172c8ab6e5ac3d | refs/heads/master | 2023-06-08T21:33:48.254717 | 2021-07-03T17:39:59 | 2021-07-03T17:39:59 | 382,660,458 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,682 | hpp | loop_declaration.hpp | #ifndef loop_declaration_hpp
#define loop_declaration_hpp
#include "ast_node.hpp"
class IfStatement: public Node{
private:
const Node* condition;
const Node* if_exec;
const Node* else_exec;
public:
IfStatement(const Node* condition_insert, const Node* if_body, const Node* else_body ):
condition(condition_insert), if_exec(if_body), else_exec(else_body)
{
type = "IfStatement";
}
const Node* getCondition() const{
return condition;
}
const Node* getIf() const{
return if_exec;
}
const Node* getELSE() const{
return else_exec;
}
bool HasElse() const
{
if (else_exec != nullptr)
{
return true;
}
else
{
return false;
}
}
virtual std::ostream& print(std::ostream& outputstream, std::string IndentationLevel) const override {
outputstream << IndentationLevel << type << " [" << std::endl;
condition->print(outputstream, IndentationLevel + " ");
outputstream << std::endl;
if_exec->print(outputstream, IndentationLevel + " ");
if (else_exec != nullptr) {
outputstream << std::endl;
else_exec->print(outputstream, IndentationLevel + " ");
}
outputstream << std::endl << IndentationLevel << "]";
return outputstream;
}
};
class SwitchStatement: public Node{
private:
const Node* expression;
const Node* body;
public:
SwitchStatement(const Node* ex_in, const Node* statement):
expression(ex_in), body(statement) {
type = "SwitchStatement";
}
const Node* getSwitch() const{
return expression;
}
const Node* getBody() const{
return body;
}
virtual std::ostream& print(std::ostream& outputstream, std::string IndentationLevel) const override {
outputstream << IndentationLevel << type << " [" << std::endl;
expression->print(outputstream, IndentationLevel + " ");
outputstream << std::endl;
body->print(outputstream, IndentationLevel + " ");
outputstream << std::endl << IndentationLevel << "]";
return outputstream;
}
};
class WhileStatement: public Node{
private:
const Node* parameter1;
const Node* statement1;
public:
WhileStatement(const Node* parameter_insert, const Node* state_insert):
parameter1(parameter_insert), statement1(state_insert){
type = "WhileStatement";
}
const Node* getWhileParameter() const
{
return parameter1;
}
const Node* getWhileStatement() const
{
return statement1;
}
virtual std::ostream& print(std::ostream& outputstream, std::string IndentationLevel) const override {
outputstream << IndentationLevel << type << " [" << std::endl;
parameter1->print(outputstream, IndentationLevel + " ");
outputstream << std::endl;
statement1->print(outputstream, IndentationLevel + " ");
outputstream << std::endl << IndentationLevel << "]";
return outputstream;
}
};
class DoStatement: public Node{
private:
const Node* body1;
const Node* while1;
public:
DoStatement(const Node* statement, const Node* expression):
body1(statement), while1(expression){
type = "DoStatement";
}
const Node* getBody() const{
return body1;
}
const Node* getDoStatement() const{
return while1;
}
virtual std::ostream& print(std::ostream& outputstream, std::string IndentationLevel) const override {
outputstream << IndentationLevel << type << " [" << std::endl;
body1->print(outputstream, IndentationLevel + " ");
outputstream << std::endl;
while1->print(outputstream, IndentationLevel + " ");
outputstream << std::endl << IndentationLevel << "]";
return outputstream;
}
};
class ForStatement: public Node{
private:
const Node* expression_statement1;
const Node* expression_statement2;
const Node* expression;
const Node* statement;
public:
ForStatement(const Node* expression_statement, const Node* expression_statementagain, const Node* expression, const Node* statement):
expression_statement1(expression_statement), expression_statement2(expression_statementagain), expression(expression), statement(statement){
type = "ForStatement";
}
const Node* getExpressionStatement1() const{
return expression_statement1;
}
const Node* getExpressionStatement2() const{
return expression_statement2;
}
const Node* getExpression() const{
return expression;
}
const Node* getForStatement() const{
return statement;
}
bool HasExpression() const{
return expression != nullptr;
}
virtual std::ostream& print(std::ostream& outputstream, std::string IndentationLevel) const override {
outputstream << IndentationLevel << type << " [" << std::endl;
expression_statement1->print(outputstream, IndentationLevel + " ");
outputstream << std::endl;
expression_statement2->print(outputstream, IndentationLevel + " ");
outputstream << std::endl << IndentationLevel << "]";
if(expression != nullptr){
expression->print(outputstream, IndentationLevel + " ");
outputstream << std::endl << IndentationLevel << "]";
}
statement->print(outputstream, IndentationLevel + " ");
outputstream << std::endl << IndentationLevel << "]";
return outputstream;
}
};
class GoToStatement: public Node{
private:
const std::string* identifier;
public:
GoToStatement(const std::string* c_identifier): identifier(c_identifier){
type = "GoToStatement";
}
const std::string* getIdentifier() const{
return identifier;
}
virtual std::ostream& print(std::ostream& outputstream, std::string IndentationLevel) const override {
outputstream << IndentationLevel << type << " [" << identifier << std::endl;
outputstream << std::endl;
return outputstream;
}
};
class ContinueStatement: public Node{
public:
ContinueStatement(){
type = "ContinueStatement";
}
virtual std::ostream& print(std::ostream& outputstream, std::string IndentationLevel) const override {
outputstream << IndentationLevel << type << " [" << std::endl;
outputstream << std::endl;
return outputstream;
}
};
class BreakStatement: public Node{
public:
BreakStatement(){
type = "BreakStatement";
}
virtual std::ostream& print(std::ostream& outputstream, std::string IndentationLevel) const override {
outputstream << IndentationLevel << type << " [" << std::endl;
outputstream << std::endl;
return outputstream;
}
};
class ReturnStatement : public Node{
private:
const Node* expression;
public:
ReturnStatement(const Node* expression_insert): expression(expression_insert){
type = "ReturnStatement";
}
const Node* getExpression() const{
return expression;
}
bool HasExpression() const{
return expression != nullptr;
}
virtual std::ostream& print(std::ostream& outputstream, std::string IndentationLevel) const override {
outputstream << IndentationLevel << type << " [" << std::endl;
if(expression != nullptr){
expression->print(outputstream, IndentationLevel + " ");
outputstream << std::endl << IndentationLevel << "]";
}
return outputstream;
}
};
#endif
|
d12e1d1f7d819c843aa9d3eedf91c02cc95af235 | 1c5ee81b2fbecf8d346f1ab95666d2ed8cc47c1c | /src/output/SaveState.cc | fa1b429cd64164e4bce47d6f56bb1f6f8907dcf5 | [] | no_license | Yuup92/SpeedyMurmurs_Omnetpp | a87f514b40d9bb569c7d8b6a357e0def7b774011 | 7c8236960425601daad00e54213da98aafee6beb | refs/heads/master | 2020-08-08T23:54:32.763757 | 2019-10-21T15:26:10 | 2019-10-21T15:26:10 | 213,951,685 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,602 | cc | SaveState.cc | #include "./SaveState.h"
SaveState::SaveState() {
nodeId = 0;
nodesInSystem = 0;
amountOfNeighbourhoods = 0;
fileName = "";
linkCapacityIndex = 0;
updatedAmountNeighbourhoods = false;
}
void SaveState::set_node_id_and_amount_of_nodes(int id, int amountNodes) {
nodeId = id;
std::string dir("savestate");
fileName = dir + "/N_" + std::to_string(nodeId);
nodesInSystem = amountNodes;
}
std::string SaveState::save(District *district) {
std::string res = "";
std::string numNodes("NUMBERNODES:");
std::string numNeigh("NUMBERNEIGHBOURHOODS:");
res += "State saved: " + get_time();
res += numNodes + std::to_string(nodesInSystem) + "\n";
res += numNeigh + std::to_string(District::NUM_OF_TREES) + "\n";
res += get_neighbourhood_string(district);
saveFile.open(fileName.c_str(), std::ios_base::out);
saveFile << res;
saveFile.close();
return res;
}
std::string SaveState::loadstate(District *district) {
int total = 0;
bool firstRead = false;
std::string res = "";
int neighboorhoodPos = 4;
int linkedNodePos = 5;
int outgoingEdgePos = 7;
int outgoingEdgeIdPos = 8;
int numOfChildrenPos = 9;
int capacityPos = 10;
int capacityIdPos = 11;
int childrenPos = 12;
int rootPos = 13;
int updatePos = -1;
int neighbourhoodIndex;
int linkedNodesAmount;
int linkedNodeIndex;
int numLinkedNodes;
std::string line;
int i = 0;
loadFile.open(fileName.c_str());
if(loadFile.is_open()) {
while( getline(loadFile, line) ) {
int outgoingEdge;
int outgoingEdgeId;
double capacity;
int capacityId;
int numberOfChild;
int children[3000];
bool edge;
if(i == 1) {
int numNodes = get_line_int(line);
if(numNodes == not nodesInSystem) {
return "false";
}
} else if (i == 2) {
int numNeighbourhoods = get_line_int(line);
if(numNeighbourhoods =! amountOfNeighbourhoods) {
amountOfNeighbourhoods = numNeighbourhoods;
updatedAmountNeighbourhoods = true;
}
} else if(i == neighboorhoodPos) {
neighbourhoodIndex = get_line_int(line);
} else if(i == linkedNodePos) {
linkedNodesAmount = get_line_int(line);
total += linkedNodesAmount;
linkedNodeIndex = 0;
// Calculating updatePos ad linkedNodePos
// Order of these caluclations is important
if(firstRead){
outgoingEdgePos = outgoingEdgePos + 3;
outgoingEdgeIdPos = outgoingEdgeIdPos + 3;
capacityPos = capacityPos + 3;
capacityIdPos = capacityIdPos + 3;
numOfChildrenPos = numOfChildrenPos + 3;
childrenPos = childrenPos + 3;
rootPos = rootPos + 3;
} else {
firstRead = true;
}
if(linkedNodesAmount == 1) {
linkedNodePos = linkedNodePos + 11;
neighboorhoodPos = neighboorhoodPos + 11;
} else {
linkedNodePos = linkedNodePos + linkedNodesAmount*8 + 3;
neighboorhoodPos = neighboorhoodPos + linkedNodesAmount*8 + 3;
}
} else if(i == outgoingEdgePos) {
outgoingEdge = get_line_int(line);
outgoingEdgePos += 8;
} else if(i == outgoingEdgeIdPos) {
outgoingEdgeId = get_line_int(line);
outgoingEdgeIdPos += 8;
} else if(i == numOfChildrenPos) {
numberOfChild = get_line_int(line);
numOfChildrenPos += 8;
} else if(i == capacityPos) {
capacity = get_line_double(line);
capacityPos += 8;
} else if(i == capacityIdPos) {
capacityId = get_line_int(line);
capacityIdPos += 8;
// TODO
update_link_capacity(district->get_all_link_capacities(), capacity, capacityId);
} else if(i == childrenPos) {
if(numberOfChild > 0) {
int index = 0;
int pos = line.find(":") + 1;
int pos1 = line.find_first_of(';');
std::string num = line.substr(pos, pos1-pos);
std::string rest = line.substr(pos1);
children[index] = std::stoi(num);
index++;
for(int i = 1; i < numberOfChild; i++) {
int pos2 = rest.find_first_of(";") + 1;
std::string rest1 = rest.substr(pos2);
int pos3 = rest1.find_first_of(";");
num = rest.substr(pos2, pos3-pos2 + 1);
rest = rest.substr(pos3 + 1);
children[index] = std::stoi(num);
index++;
}
}
childrenPos += 8;
} else if(i == rootPos) {
int pos = line.find("EDGEROOT");
if(pos) {
edge = false;
} else {
edge = true;
}
rootPos += 8;
district->get_neighbourhood(neighbourhoodIndex)->update_linked_nodes(linkedNodeIndex,
outgoingEdge,
outgoingEdgeId,
numberOfChild,
children,
edge);
// for(int i = 0 ; i < numberOfChild; i++) {
// res += "i: " + std::to_string(i) + " Child: " + std::to_string(children[i]) + "\n";
// }
linkedNodeIndex++;
district->get_neighbourhood(neighbourhoodIndex)->set_linked_node_updates(true);
district->get_neighbourhood(neighbourhoodIndex)->set_num_linked_nodes(linkedNodesAmount);
}
i++;
}
}
loadFile.close();
district->update_linked_nodes_from_file();
return res;
}
std::string SaveState::get_time(void) {
auto end = std::chrono::system_clock::now();
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::string t(std::ctime(&end_time));
return t;
}
std::string SaveState::get_neighbourhood_string(District *district) {
std::string res = "";
for(int i = 0; i < District::NUM_OF_TREES; i++) {
std::string neigh("NEIGHBOURHOODNUM:");
res += "\n" + neigh + std::to_string(i) + "\n";
res += (district->get_neighbourhood(i))->to_string();
}
return res;
}
int SaveState::get_line_int(std::string line) {
int pos = line.find(":") + 1;
std::string numS = line.substr(pos);
int num = std::stoi(numS);
return num;
}
double SaveState::get_line_double(std::string line) {
int pos = line.find(":") + 1;
std::string numS = line.substr(pos);
double num = std::stod(numS);
return num;
}
int SaveState::update_line_pos(int reference, int pointer) {
int amount = 0;
if(reference == 1) {
amount = pointer + 8;
} else {
amount = pointer + 8;
}
return amount;
}
void SaveState::update_link_capacity(LinkCapacity *linkcapacities, double cap, int id) {
if(linkCapacityIndex == 0) {
linkcapacities[linkCapacityIndex].set_current_capacity(cap);
linkcapacities[linkCapacityIndex].set_connected_node_id(id);
linkCapacityIndex++;
return;
} else {
// check if the capacity linked to the id has already been updated, if so return otherwise add it to the list
for(int i = 0; i < linkCapacityIndex; i++) {
if(linkcapacities[i].get_connected_node_id() == id) {
return;
}
}
linkcapacities[linkCapacityIndex].set_current_capacity(cap);
linkcapacities[linkCapacityIndex].set_connected_node_id(id);
linkCapacityIndex++;
}
}
|
1ffc6eceb4939f98befed2fd140f48be2a6d861f | 8ea132e024d3e036ed09bffcae7595834a14bdd8 | /SOLUTIONS/Merge two sorted Linked List.cpp | 4b30b864587021285d7d0ba2ac1cb2cdd05f9803 | [] | no_license | abhisheknaw/Problems-for-Interview | 53d42ddaefb628c2efd1e6bc1e94abf59babe996 | b40c7886a2a25f17bdad5384efdca55122a7ec48 | refs/heads/master | 2023-05-05T23:57:57.759584 | 2021-05-29T12:37:31 | 2021-05-29T12:37:31 | 363,707,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,610 | cpp | Merge two sorted Linked List.cpp | /*
Using Recursion
Complexity analysis
Time complexity : O(N + M). Assume that N and M are the length of lists, the time complexity is O(N + M) as only one traversal of linked list is needed.
Space complexity : O(N + M).If the recursive stack space is taken into consideration.
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL)
return l2;
if(l2==NULL)
return l1;
else if(l1->val <= l2->val)
{
l1->next= mergeTwoLists(l1->next,l2);
return l1;
}
else
{
l2->next= mergeTwoLists(l1,l2->next);
return l2;
}
}
};
/*
Using Iteration
Complexity analysis
Time complexity : O(N+M). Assume that N and M are the length of lists, the time complexity is O(N + M).
Space complexity : O(1)
*/
class Solution
{
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode fake(0);
struct ListNode *trav= &fake;
while(l1!=NULL && l2!=NULL)
{
if(l1->val <= l2->val)
{
trav->next=l1;
trav=l1;
l1=l1->next;
}
else
{
trav->next=l2;
trav=l2;
l2=l2->next;
}
}
if(l1!=NULL)
{
trav->next=l1;
}
else
{
trav->next=l2;
}
return fake.next;
}
}; |
b5058357333b2a745c87aebdbaec0a1b726fd4c5 | 1468af6fbbfa8c155aefe6e14f645c98455c1cbb | /Net/CSocket.h | 61e1b635d03a18993017055499abcd2b7d8c7831 | [] | no_license | xqing2003/libevent_net | c1cc6c673c412d72649e6c24280abfbf6c2d13dc | 1b99ad707da57f3ef5e9337f9dee7ca5dcbe908d | refs/heads/master | 2021-07-15T05:46:39.869842 | 2017-10-20T12:27:19 | 2017-10-20T12:27:19 | 106,796,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,395 | h | CSocket.h | #pragma once
#include "NetDefine.h"
#include <string>
class CSocket {
public:
CSocket();
CSocket(const char *psczIP, uint port);
CSocket(SOCKET s, const struct sockaddr_in *addr);
CSocket(const CSocket &rhs);
virtual ~CSocket();
CSocket &operator=(const CSocket &rhs);
public:
bool Create();
void Close();
bool Connect(const char *psczIP = nullptr, uint port = -1);
bool Reconnect(const char *psczIP, uint port);
bool Bind(uint port);
bool Listen(int backlog);
SOCKET Accept(struct sockaddr *addr, uint *addrLen);
// CSocket *Accept();
bool Accept(CSocket &rhs);
int Send(const void *buf, int len, uint flags = 0);
int Recv(void* buf, uint len, uint flags = 0);
bool IsValidSocket() const;
bool IsSocketError() const;
SOCKET GetSocket() const;
uint GetSendBuffSize() const;
bool SetSendBuffSize(uint size);
uint GetRecvBuffSize() const;
bool SetRecvBuffSize(uint size);
bool IsNonBlocking() const;
bool SetNonBlocking(bool on = true);
uint GetSockErrorID() const;
std::string GetSockErrorMsg() const;
uint GetAvaliable() const;
bool GetSockOpt(int optname, void* optval, uint* optlen, int level = SOL_SOCKET);
bool SetSockOpt(int optname, const void* optval, uint optlen, int level = SOL_SOCKET);
const char *GetRemoteIP() const;
private:
SOCKET m_nSocketID;
SOCKADDR_IN m_oSockAddr;
char m_szIP[IP_SIZE];
uint m_nPort;
bool m_bNoBlocking;
};
|
898855133a35553b59a4ce3eecbcfa5ea451b2db | b52932b9ddd2a20d8778f41cd44e6b8fa6262123 | /random_walk/random_walk/1d_simulation.cpp | 4a18bbce294c67ea9ae53772e3305e822c2c62f8 | [] | no_license | minesli8/DS_random_walk_MonteCarlo_simulation | 8c10666a93d250bca842557d79fa73b486347639 | 050e6008ce657b14d520988ba086355c36933cbe | refs/heads/master | 2021-03-30T17:57:35.539067 | 2018-03-14T04:14:58 | 2018-03-14T04:14:58 | 119,641,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 164 | cpp | 1d_simulation.cpp | # include <iostream>
# include "random_number.h"
int main() {
float dist;
int n;
std::cout << "end of program" << std::endl;
char flag;
std::cin >> flag;
} |
80b81f4a82e2373b3522ac61000db0eef157fb1f | 097a46cf0e4a11b3135d77e2423b0458c923f094 | /include/ShaderProgram.h | 845e250f79a99eacbc4b4361ff6d614eb2db3f07 | [] | no_license | vedangnaik/3DModelViewer | 126deb2737ccab4c733b32f2a5cb9b82e78d9dd3 | 4cc37d7258cb9812edda165bb64246b33dfdee82 | refs/heads/master | 2023-08-16T05:52:41.371328 | 2021-10-09T01:30:02 | 2021-10-09T01:30:02 | 192,942,490 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,683 | h | ShaderProgram.h | #pragma once
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
class ShaderProgram
{
public:
unsigned int ID;
ShaderProgram(const char* vertexPath, const char* fragmentPath) {
// Buffer to hold error data
char infoLog[1024];
// Temporary variable for conversion to c_str
std::string temp;
// Load vertex shader from file and compile
std::ifstream vertexFile;
std::stringstream vertexStream;
const char* vertexShaderCode;
unsigned int vertexShaderID;
// Try to open the file and read contents, provide error message if fail
try {
vertexFile.open(vertexPath);
vertexStream << vertexFile.rdbuf();
vertexFile.close();
temp = vertexStream.str();
vertexShaderCode = temp.c_str();
}
catch (const char* msg) {
std::cout << "Exception: " << msg << std::endl;
}
// Create the shader and compile it
vertexShaderID = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShaderID, 1, &vertexShaderCode, NULL);
glCompileShader(vertexShaderID);
// Load fragment shader from file and compile
std::ifstream fragmentFile;
std::stringstream fragmentStream;
const char* fragmentShaderCode;
unsigned int fragmentShaderID;
// Same as vertex shader
try {
fragmentFile.open(fragmentPath);
fragmentStream << fragmentFile.rdbuf();
fragmentFile.close();
temp = fragmentStream.str();
fragmentShaderCode = temp.c_str();
}
catch (const char* msg) {
std::cout << "Exception: " << msg << std::endl;
}
// Same as vertex shader
fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShaderID, 1, &fragmentShaderCode, NULL);
glCompileShader(fragmentShaderID);
// Create and link vertex and fragment shaders into shader program
memset(infoLog, 0, sizeof(infoLog));
this->ID = glCreateProgram();
glAttachShader(this->ID, vertexShaderID);
glAttachShader(this->ID, fragmentShaderID);
glLinkProgram(this->ID);
glDeleteShader(vertexShaderID);
glDeleteProgram(fragmentShaderID);
// Get any shader error logs into infoLog and display
glGetShaderInfoLog(vertexShaderID, 1024, NULL, infoLog);
std::cout << "Vertex shader info log: " << infoLog << std::endl;
glGetShaderInfoLog(fragmentShaderID, 1024, NULL, infoLog);
std::cout << "Fragment shader info log: " << infoLog << std::endl;
// Get any program error logs into infoLog and display
glGetProgramInfoLog(this->ID, 1024, NULL, infoLog);
std::cout << "Shader program info log: " << infoLog << std::endl;
}
void use() {
glUseProgram(this->ID);
}
// Direct access function to set any uniform integer variables
void setUniformInt(const char* varName, int varValue) {
glUniform1i(glGetUniformLocation(this->ID, varName), varValue);
}
void setUniformIntArray(const char* varName,int varValueArrayCount, int* varValueArray) {
glUniform1iv(glGetUniformLocation(this->ID, varName), varValueArrayCount, varValueArray);
}
void setUniformFloat(const char* varName, float varValue) {
glUniform1f(glGetUniformLocation(this->ID, varName), varValue);
}
void setUniformMat4(const char* varName, glm::mat4 varValue) {
glUniformMatrix4fv(glGetUniformLocation(this->ID, varName), 1, GL_FALSE, glm::value_ptr(varValue));
}
void setUniformMat3(const char* varName, glm::mat3 varValue) {
glUniformMatrix3fv(glGetUniformLocation(this->ID, varName), 1, GL_FALSE, glm::value_ptr(varValue));
}
void setUniformVec3(const char* varName, glm::vec3 varValue) {
glUniform3fv(glGetUniformLocation(this->ID, varName), 1, glm::value_ptr(varValue));
}
}; |
3683b5473a03bae44b969354699dd71908f2aaa3 | b5a3ff7925ba064a1f4ac45b30410090e6e6929c | /KRealPlot.cpp | db8963520ca78d3a86e95cbdeeffe9425d76c105 | [] | no_license | knkresources/K- | 6a3c04ac4590659187e362de1f7ae78525936ae1 | 28dc42b3fedb4f8cd235efc9c83b4c72e0bd0b5e | refs/heads/master | 2021-01-20T18:52:44.631018 | 2016-06-13T16:13:27 | 2016-06-13T16:13:27 | 60,959,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,941 | cpp | KRealPlot.cpp | #include "KRealPlot.h"
KRealPlot::KRealPlot(QObject *parent) : QObject(parent)
{
this->isAttached = false;
this->range = 8;
}
void KRealPlot::attach(QCustomPlot *plot)
{
this->QPlot = plot;
this->isAttached =true;
QPen pen;
pen.setColor(Qt::blue);
pen.setWidth(1);
this->QPlot->clearGraphs();
this->QPlot->addGraph(); // blue line
this->QPlot->graph(0)->setPen(pen);
this->QPlot->graph(0)->setAntialiasedFill(false);
this->QPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
this->QPlot->xAxis->setDateTimeFormat("hh:mm:ss");
this->QPlot->xAxis->setAutoTickStep(false);
this->setRange(this->range);
// make left and bottom axes transfer their ranges to right and top axes:
connect(this->QPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), this->QPlot->xAxis2, SLOT(setRange(QCPRange)));
connect(this->QPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), this->QPlot->yAxis2, SLOT(setRange(QCPRange)));
}
void KRealPlot::setPen(QPen pen)
{
if(this->isAttached) this->QPlot->graph(0)->setPen(pen);
}
void KRealPlot::setRange(unsigned int seconds)
{
unsigned int tick_step = this->range/5;
if(!tick_step) tick_step = 1;
this->range=seconds;
this->QPlot->xAxis->setTickStep(tick_step);
this->QPlot->axisRect()->setupFullAxesBox();
}
void KRealPlot::clear()
{
this->QPlot->graph(0)->clearData();
}
void KRealPlot::feed(double y)
{
double key;
if(this->isAttached)
{
key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
this->QPlot->graph(0)->addData(key, y);
this->QPlot->graph(0)->removeDataBefore(key-this->range);
this->QPlot->graph(0)->rescaleValueAxis();
// make key axis range scroll with the data (at a constant range size of 8):
this->QPlot->xAxis->setRange(key+(this->range/8), this->range, Qt::AlignRight);
this->QPlot->replot();
}
}
|
b1cde1040ec9627036c132dcaf674b27c8d19579 | 71e25322e371cbafb3423febaa2909c040a60713 | /src/hsm_history.cpp | c7ee31f26d3358694a14432c625d6b517db139b1 | [] | no_license | Hamdor/PLHSM2 | e6d6a5e02b2ca6c99a790f74418d38adf4b5173a | 76b96a500c1d4a398794bb51d3d3fcef2859b664 | refs/heads/master | 2016-09-05T16:11:04.030234 | 2014-11-01T11:06:58 | 2014-11-01T11:06:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,789 | cpp | hsm_history.cpp | /*
* File: main.cpp
* Author: Anne-Lena
*
* Created on 18. Oktober 2014, 16:07
*/
#include <cstdlib>
#include <string.h>
#include "hsm_history.hpp"
using namespace std;
void S0::sigA(Context* c) {
cout << "S0 hat sigA erhalten"<<endl;
new (this) S1;
init(c);
}
void S0::sigB(Context* c){
cout << "S0 hat sigB erhalten"<<endl;
new (this) S1;
entry(c);
new (this) S3;
init(c);
}
void S0::sigC(Context*) {
cout << "ERROR:S0 hat sigC enthalten"<<endl;
}
void S0::entry(Context*) {
cout << "S0 state entry" << endl;
}
void S0::exit(Context* c) {
cout << "S0 state exit" << endl;
history(c);
}
void S0::init(Context* c) {
void* history = c->getStateFromHistory(S0_ID);
if (history != 0) {
memcpy(static_cast<void*>(this), &history, sizeof(void*));
} else {
new (this) S1;
entry(c);
}
init(c);
}
void S0::history(Context* c) {
c->setHistory(S0_ID, this);
}
void S1::sigA(Context* c) {
cout << "S1 hat sigA erhalten" << endl;
exit(c);
new (this) S0;
sigA(c);
}
void S1::sigB(Context* c) {
cout << "S1 hat sigB erhalten" << endl;
exit(c);
new (this) S0;
sigB(c);
}
void S1::sigC(Context* c) {
cout << "S1 hat sigC erhalten" << endl;
exit(c);
new (this) S0;
}
void S1::entry(Context*) {
cout << "S1 entry" << endl;
}
void S1::exit(Context* c) {
cout << "S1 exit" << endl;
history(c);
}
void S1::init(Context* c) {
void* history = c->getStateFromHistory(S1_ID);
if(history != 0){
memcpy(static_cast<void*>(this), &history, sizeof(void*));
} else {
new (this) S3;
entry(c);
}
init(c);
}
void S1::history(Context* c) {
c->setHistory(S0_ID, this);
}
void S3::sigA(Context* c) {
cout << "S3 hat sigA erhalten" << endl;
exit(c);
new (this) S1;
sigA(c);
}
void S3::sigB(Context* c) {
cout << "S3 hat sigB erhalten" << endl;
exit(c);
new (this) S1;
sigB(c);
}
void S3::sigC(Context* c) {
cout << "S3 hat sigC erhalten" << endl;
exit(c);
new (this) S1;
sigC(c);
}
void S3::entry(Context*) {
cout << "S3 entry" << endl;
}
void S3::exit(Context* c) {
cout << "S3 exit"<<endl;
history(c);
}
void S3::history(Context* c) {
c->setHistory(S1_ID, this);
}
void S3::init(Context*) {
// nop
}
Context::Context() : m_current_state(new S0) {
memset(&m_history, 0, sizeof(m_history));
m_current_state->entry(this);
}
void Context::sigA() {
m_current_state->sigA(this);
}
void Context::sigB() {
m_current_state->sigB(this);
}
void Context::sigC() {
m_current_state->sigC(this);
}
void Context::setHistory(int ID, State* ptr) {
m_history[ID] = *reinterpret_cast<void**>(ptr);
}
void* Context::getStateFromHistory(int ID) {
return m_history[ID];
}
int main() {
Context c;
c.sigB();
c.sigC();
c.sigA();
c.sigC();
return 0;
}
|
72464f6b77ee318f103b9534c3959eaf697c0f39 | b7d76cc55e63cc2d597f8433fccc5aa9af833512 | /learn-Qt-CPP-GUI/iviewer/mainwindow.h | fc3a03aaa8ff1d338ef7e84623f29ec12ea72664 | [] | no_license | jaywhen/LearnQt | 47a1f93fbb1c70a843f4bd2a0dc456bbf06f4365 | d28de13cdf19db45e4cad58fda2e6e1b4c778d02 | refs/heads/master | 2022-09-29T04:32:11.617152 | 2020-06-06T17:43:53 | 2020-06-06T17:43:53 | 259,824,578 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | h | mainwindow.h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileDialog>
#include <QFileSelector>
#include <QMessageBox>
#include <QKeyEvent>
#include <QSqlDatabase>
#include <QSqlQuery>
#include "imgviewer.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void open();
void nextImg();
void preImg();
void deletCurrent();
void welcome(); //first use, will print this
void firstLoad(); //first use, will load some pic for watch
private slots:
void on_action_Open_triggered();
void on_action_Next_triggered();
void on_actionPre_triggered();
void errorBox(QString &errstr);
void on_action_About_me_triggered();
void on_action_Exit_triggered();
private:
Ui::MainWindow *ui;
ImgViewer* m_imgViewer;
void keyPressEvent(QKeyEvent *ev);
void createDb();
bool ifFirstUse();
int getDbNum();
void setUsed();
};
#endif // MAINWINDOW_H
|
2bd71f65217d2d51cde09ec5e43971af2624921d | f6be9650304b1b55ec84dc9fb6b952352d51f834 | /eosio.evm/src/precompiles/index.cpp | b5f1301c6d33d382feb66170c2a5320bdf4ebbbc | [
"MIT"
] | permissive | tseyt/eosio.evm | a9ce4908a810aec05320ef452d30144628dff993 | 8c9305d5ea944fc039eb3e2e39219398b58068a9 | refs/heads/master | 2021-02-26T08:55:15.294718 | 2020-03-04T05:50:36 | 2020-03-04T05:50:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,222 | cpp | index.cpp | // Copyright (c) 2020 Syed Jafri. All rights reserved.
// Licensed under the MIT License..
#include <eosio.evm/eosio.evm.hpp>
namespace eosio_evm
{
void Processor::precompile_return(const std::vector<uint8_t>& output) {
// invoke caller's return handler
auto success_cb = ctx->success_cb;
auto gas_used = ctx->gas_used();
pop_context();
success_cb(output, gas_used);
}
void Processor::precompile_not_implemented()
{
throw_error(Exception(ET::notImplemented, "This precompiled contract is not implemented."), {});
}
void Processor::precompile_execute(uint256_t address)
{
// 1.ECDSARECOVER
if (address == 1)
{
return precompile_ecrecover();
}
// 2. SHA256
else if (address == 2)
{
return precompile_sha256();
}
// 3. RIPEMD160
else if (address == 3)
{
return precompile_ripemd160();
}
// 4. IDENTITY
else if (address == 4)
{
return precompile_identity();
}
// 5. EXPMOD
// 6. SNARKV
// 7. BNADD
// 8. BNMUL
else if (address >= 5 && address <= 8)
{
return precompile_not_implemented();
}
else
{
return stop();
}
}
} // namespace eosio_evm
|
5be9bcb5c5c327f24f5efabe01f802dff937e8d2 | 6e601105760f09d3c9f5306e18e4cf085f0bb4a2 | /10000-99999/16933.cpp | 4b12607aef957268e9952d27adedeb07bec2693d | [] | no_license | WSJI0/BOJ | 6412f69fddd46c4bcc96377e2b6e013f3bb1b524 | 160d8c13f72d7da835d938686f433e7b245be682 | refs/heads/master | 2023-07-06T15:35:50.815021 | 2023-07-04T01:39:48 | 2023-07-04T01:39:48 | 199,650,520 | 2 | 0 | null | 2020-04-20T09:03:03 | 2019-07-30T12:48:37 | Python | UTF-8 | C++ | false | false | 1,687 | cpp | 16933.cpp | // 16933번 벽 부수고 이동하기 3
#include <bits/stdc++.h>
using namespace std;
int n, m, k, nx, ny, nk, nd, res, ans=-1, cnt=0;
char a;
int mov[4][2]={
{1, 0}, {-1, 0}, {0, 1}, {0, -1}
};
bool visited[1000][1000][11][2], board[1000][1000];
int main(void){
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
cin>>n>>m>>k;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin>>a;
board[i][j]=a-'0';
}
}
queue<tuple<int, int, int, int, int>> q;
q.push(make_tuple(0, 0, k, 0, 0));
visited[0][0][k][0]=1;
while(!q.empty()){
tie(nx, ny, nk, nd, res)=q.front(); q.pop();
if(nx==m-1 && ny==n-1){
ans=res;
break;
}
for(auto v:mov){
int mx=nx+v[0], my=ny+v[1];
if(0<=mx && mx<m && 0<=my && my<n){
if(board[my][mx]){
if(!nd && nk){
if(visited[mx][my][nk-1][(nd+1)%2]) continue;
q.push(make_tuple(mx, my, nk-1, (nd+1)%2, res+1));
visited[mx][my][nk-1][(nd+1)%2]=1;
} else{
if(visited[nx][ny][nk][(nd+1)%2]) continue;
q.push(make_tuple(nx, ny, nk, (nd+1)%2, res+1));
visited[nx][ny][nk][(nd+1)%2]=1;
}
} else{
if(visited[mx][my][nk][(nd+1)%2]) continue;
q.push(make_tuple(mx, my, nk, (nd+1)%2, res+1));
visited[mx][my][nk][(nd+1)%2]=1;
}
}
}
}
cout<<(ans>=0? ans+1:ans)<<"\n";
} |
985945d01a5ff09bcd61002ae91dcdb5dbf0d588 | f79c19f49945e76d75302c25f87b682255eb0f1a | /Megaman CMSC451/Megaman CMSC451/ZeroAI.cpp | a0e255cd71ff2703877538c74186f8336298d483 | [] | no_license | MrPillBoxHat/CMSC425 | 56b328875bd0e1413bde2a12ee9a9afd0d09b15a | 05e746d2693e68d84440f548f1c004b5e7dea34b | refs/heads/master | 2021-01-23T08:52:28.895489 | 2013-05-22T00:22:46 | 2013-05-22T00:22:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,507 | cpp | ZeroAI.cpp | #pragma once
#include <ctime>
#include <cstdlib>
#include "ZeroAI.h"
#include "constants.h"
// Constructor
ZeroAI::ZeroAI(Zero *z, X *inX)
{
zero = z;
x = inX;
counter = -1;
state = THINK;
last_action = THINK;
combo = 0;
x_location = x->getHitBox();
zero_location = zero->getHitBox();
zeroIsRight = x_location[1] < zero_location[0];
srand(time(0));
}
// Start AI
int ZeroAI::getAction(){
counter++;
if(counter % 101 == 0){
counter = 0;
}
// If not in an action, perform new action
if(zero->getState() == STAND){
update();
if(combo == 0 && counter % 100 == 0){
// new action
return runAI();
// If in the middle of an action, keep going
} else {
switch(state)
{
case Z_SABER:
return saber();
case SABERBUSTER:
return buster_saber_combo();
case TACKLE:
return tackle();
}
}
}
// Do nothing
return -1;
}
int ZeroAI::runAI()
{
random = rand() % 3;
if(last_action == Z_SABER || last_action == TACKLE){
last_action = MOVE_AWAY;
return dashAway();
} else if (last_action == SABERBUSTER){
last_action = THINK;
return dashFoward();
}else if (distance <= 50) {
last_action = Z_SABER;
return saber();
} else if (distance > 50 && distance <= 250){
// Randomly perform either saber, tackle, or buster attack
if(random == 0){
last_action = state = Z_SABER;
return saber();
} else if(random == 1) {
state = last_action = BUSTER;
return buster();
} else {
state = last_action = TACKLE;
return tackle();
}
// Perform saber buster combo
} else {
state = SABERBUSTER;
return buster_saber_combo();
}
}
// Update instance variables
void ZeroAI::update()
{
// Check if zero passed X
if(zeroIsRight){
passX = x_location[0] > zero_location[1];
} else {
passX = x_location[1] < zero_location[0];
}
// update Zero's position
zeroIsRight = x_location[1] < zero_location[0];
// Check if X is within saber range
if(zeroIsRight){
// Turn zero to face right
zero->setDirection(LEFT);
distance = zero_location[0] - x_location[1];
} else {
// Turn zero to face left
zero->setDirection(RIGHT);
distance = x_location[0] - zero_location[1];
}
}
int ZeroAI::buster_saber_combo()
{
// If first or 2nd attack
if(combo == 0 || combo == 1){
combo++;
state = SABERBUSTER;
return buster();
// If 3rd attack
} else {
combo = 0;
state = THINK;
last_action = SABERBUSTER;
return SABER_MISSILE;
}
}
int ZeroAI::saber()
{
// flags to check conditions
bool xInRange = false;
// Check if X is within saber range
if(zeroIsRight){
// Turn zero to face right
zero->setDirection(LEFT);
if(50 > distance){
xInRange = true;
}
} else {
// Turn zero to face left
zero->setDirection(RIGHT);
if(50 > distance){
xInRange = true;
}
}
// If not in saber range, dash to X
if(xInRange){
// reset combo
combo = 0;
state = THINK;
last_action = Z_SABER;
counter = 50;
return SABER;
} else {
combo++;
return dashFoward();
}
}
int ZeroAI::tackle()
{
// If passed X, face X
if(passX){
if(zeroIsRight){
zero->setDirection(LEFT);
} else {
zero->setDirection(RIGHT);
}
combo = 0;
state = THINK;
counter = 100;
return STAND;
// dash until contact is made
} else {
combo++;
return dashFoward();
}
}
int ZeroAI::dashFoward(){
return DASH;
}
int ZeroAI::dashAway()
{
if(zeroIsRight){
zero->setDirection(RIGHT);
} else {
zero->setDirection(LEFT);
}
return DASH;
}
int ZeroAI::buster()
{
return FIRE;
} |
31fb045627172c6e0b22eee002ba08fdc31fe12e | f2d927e4842a8eac709b12031f8f16904cb809e0 | /test/testGpuMax.cpp | 82965f60fef441096f1ff4c043e125490c04f827 | [] | no_license | bentsherman/libgmm | 66378421b43b15a63edd9025dd0b9a9579c821dc | 83ce86dba22bbcd375b0ada3c3a8d00e522751af | refs/heads/master | 2021-07-22T10:22:58.631432 | 2017-10-28T17:28:39 | 2017-10-28T17:28:39 | 106,934,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,490 | cpp | testGpuMax.cpp | #include <assert.h>
#include <errno.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cudaWrappers.h"
void test(const size_t N, float* a) {
for(size_t i = 0; i < N; ++i) {
a[i] = i;
}
float host_max = -INFINITY;
for(size_t i = 0; i < N; ++i) {
if(host_max < a[i]) {
host_max = a[i];
}
}
float device_max = -INFINITY;
device_max = gpuMax(N, a);
assert(device_max != -INFINITY);
assert(device_max != INFINITY);
assert(device_max == device_max);
float absDiff = fabsf(host_max - device_max);
if(absDiff >= FLT_EPSILON) {
printf("N: %zu, host_max: %.16f, device_max: %.16f, absDiff: %.16f\n",
N, host_max, device_max, absDiff
);
}
assert(absDiff < FLT_EPSILON);
}
void testPowTwos() {
const size_t minN = 2;
const size_t maxN = 16 * 1048576;
for(size_t N = minN; N <= maxN; N *= 2) {
float* a = (float*) malloc(N * sizeof(float));
test(N, a);
free(a);
}
}
void testEvens() {
const size_t minN = 1;
const size_t maxN = 10000;
for(size_t N = minN; N <= maxN; N += 8) {
float* a = (float*) malloc(N * sizeof(float));
test(N, a);
free(a);
}
}
void testOdds() {
const size_t minN = 1;
const size_t maxN = 10000;
for(size_t N = minN; N <= maxN; N += 9) {
float* a = (float*) malloc(N * sizeof(float));
test(N, a);
free(a);
}
}
int main(int argc, char** argv) {
testPowTwos();
testEvens();
testOdds();
printf("PASS: %s\n", argv[0]);
return EXIT_SUCCESS;
}
|
7eee230b91cc7109f8de58a12d6c9c8b09224a2e | 6465889bd2d49d3c6e02146d1fbeaf0edb4d9271 | /136-Encadenando trolls.cpp | 2004c36dc5a081d9d29e2e3f249e668a261a2064 | [
"MIT"
] | permissive | MiguelJiRo/Acepta-el-reto | aef75839875d49eeea8f84b52a9cc8e82b1c2c4f | d34e24be2ba685010c0747bde904803a6b9e4cea | refs/heads/master | 2021-06-25T03:55:32.109208 | 2020-11-18T15:16:36 | 2020-11-18T15:16:36 | 150,131,722 | 2 | 1 | null | null | null | null | ISO-8859-1 | C++ | false | false | 936 | cpp | 136-Encadenando trolls.cpp | // Miguel Jiménez Rodríguez
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool resuelve();
int numCortes(int numEslabones, int fuerza);
int main() {
// Para la entrada por fichero.
/*#ifndef DOMJUDGE
std::ifstream in("casos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf());
#endif*/
while (resuelve());
/*#ifndef DOMJUDGE // para dejar todo como estaba al principio
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif*/
return 0;
}
bool resuelve() {
int numEslabones, fuerza;
cin >> fuerza >> numEslabones;
fuerza *= 2;
if (fuerza == 0)
return false;
cout << numCortes(numEslabones, fuerza) << "\n";
return true;
}
int numCortes(int numEslabones, int fuerza) {
if (numEslabones <= fuerza)
return 0;
int ladoCorto = numEslabones / 3;
int ladoLargo = numEslabones - ladoCorto;
int a = numCortes(ladoCorto, fuerza);
int b = numCortes(ladoLargo, fuerza);
return a + b + 1;
} |
7381900c9018750f9816bf9657fda74d1b9ffd47 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /components/exo/server/wayland_server_controller.h | af22ffe83dad2f9346149a228f2b5ec7f7722ff1 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 3,304 | h | wayland_server_controller.h | // Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_EXO_SERVER_WAYLAND_SERVER_CONTROLLER_H_
#define COMPONENTS_EXO_SERVER_WAYLAND_SERVER_CONTROLLER_H_
#include <memory>
#include "base/containers/flat_map.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/weak_ptr.h"
#include "components/exo/display.h"
#include "components/exo/security_delegate.h"
#include "components/exo/wayland/server.h"
namespace exo {
namespace wayland {
class Server;
} // namespace wayland
class DataExchangeDelegate;
class InputMethodSurfaceManager;
class NotificationSurfaceManager;
class ToastSurfaceManager;
class WMHelper;
class WaylandServerHandle;
class WaylandServerController {
public:
static std::unique_ptr<WaylandServerController> CreateForArcIfNecessary(
std::unique_ptr<DataExchangeDelegate> data_exchange_delegate);
// Creates WaylandServerController. Returns null if controller should not be
// created.
static std::unique_ptr<WaylandServerController> CreateIfNecessary(
std::unique_ptr<DataExchangeDelegate> data_exchange_delegate,
std::unique_ptr<NotificationSurfaceManager> notification_surface_manager,
std::unique_ptr<InputMethodSurfaceManager> input_method_surface_manager,
std::unique_ptr<ToastSurfaceManager> toast_surface_manager);
// Returns a handle to the global-singletone instance of the server
// controller.
static WaylandServerController* Get();
WaylandServerController(const WaylandServerController&) = delete;
WaylandServerController& operator=(const WaylandServerController&) = delete;
~WaylandServerController();
InputMethodSurfaceManager* input_method_surface_manager() {
return display_->input_method_surface_manager();
}
WaylandServerController(
std::unique_ptr<DataExchangeDelegate> data_exchange_delegate,
std::unique_ptr<NotificationSurfaceManager> notification_surface_manager,
std::unique_ptr<InputMethodSurfaceManager> input_method_surface_manager,
std::unique_ptr<ToastSurfaceManager> toast_surface_manager);
// Creates a wayland server from the given |socket|, with the privileges of
// the |security_delegate|. Invokes |callback| with a handle to a wayland
// server on success, nullptr on failure.
void ListenOnSocket(
std::unique_ptr<SecurityDelegate> security_delegate,
base::ScopedFD socket,
base::OnceCallback<void(std::unique_ptr<WaylandServerHandle>)> callback);
private:
void OnSocketAdded(
std::unique_ptr<wayland::Server> server,
base::OnceCallback<void(std::unique_ptr<WaylandServerHandle>)> callback,
bool success);
// Removes the wayland server that was created by ListenOnSocket() which
// returned the given |handle|.
friend class WaylandServerHandle;
void CloseSocket(WaylandServerHandle* handle);
std::unique_ptr<WMHelper> wm_helper_;
std::unique_ptr<Display> display_;
std::unique_ptr<wayland::Server> default_server_;
base::flat_map<WaylandServerHandle*, std::unique_ptr<wayland::Server>>
on_demand_servers_;
base::WeakPtrFactory<WaylandServerController> weak_factory_{this};
};
} // namespace exo
#endif // COMPONENTS_EXO_SERVER_WAYLAND_SERVER_CONTROLLER_H_
|
afbcd939ad04f39ed34e30316e6fe3abd65eb355 | 763d2ab6cd37bc29812a01610dc3fb0f7b3bc8ef | /C/TutorialLevel5Bot/MyBotModule.cpp | 247624a00e7d88afe74d210fcc8669508f032f9a | [
"MIT"
] | permissive | shawn2you/2017Guide | f189491c7b52983e8099de8bb7764c073f1b72db | fdf31dc62b32ed66635b38d9804a39b9c07d0129 | refs/heads/master | 2021-06-14T06:20:42.796046 | 2017-06-09T12:41:09 | 2017-06-09T12:41:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,521 | cpp | MyBotModule.cpp | /*
+----------------------------------------------------------------------+
| BasicBot |
+----------------------------------------------------------------------+
| Samsung SDS - 2017 Algorithm Contest |
+----------------------------------------------------------------------+
| |
+----------------------------------------------------------------------+
| Author: Tekseon Shin <tekseon.shin@gmail.com> |
| Author: Duckhwan Kim <duckhwan1982.kim@gmail.com> |
+----------------------------------------------------------------------+
*/
/*
+----------------------------------------------------------------------+
| UAlbertaBot |
+----------------------------------------------------------------------+
| University of Alberta - AIIDE StarCraft Competition |
+----------------------------------------------------------------------+
| |
+----------------------------------------------------------------------+
| Author: David Churchill <dave.churchill@gmail.com> |
+----------------------------------------------------------------------+
*/
#include "MyBotModule.h"
using namespace BWAPI;
using namespace BWTA;
using namespace MyBot;
MyBotModule::MyBotModule(){
}
MyBotModule::~MyBotModule(){
}
void MyBotModule::onStart(){
if (BWAPI::Broodwar->isReplay()) {
return;
}
time_t t;
srand((unsigned int)(time(&t)));
// Config 파일 관리가 번거롭고, 배포 및 사용시 Config 파일 위치를 지정해주는 것이 번거롭기 때문에,
// Config 를 파일로부터 읽어들이지 않고, Config 클래스의 값을 사용하도록 합니다.
if (Config::BWAPIOptions::EnableCompleteMapInformation)
{
BWAPI::Broodwar->enableFlag(BWAPI::Flag::CompleteMapInformation);
}
if (Config::BWAPIOptions::EnableUserInput)
{
BWAPI::Broodwar->enableFlag(BWAPI::Flag::UserInput);
}
Broodwar->setCommandOptimizationLevel(1);
// Speedups for automated play, sets the number of milliseconds bwapi spends in each frame
// Fastest: 42 ms/frame. 1초에 24 frame. 일반적으로 1초에 24frame을 기준 게임속도로 합니다
// Normal: 67 ms/frame. 1초에 15 frame
// As fast as possible : 0 ms/frame. CPU가 할수있는 가장 빠른 속도.
BWAPI::Broodwar->setLocalSpeed(Config::BWAPIOptions::SetLocalSpeed);
// frameskip을 늘리면 화면 표시도 업데이트 안하므로 훨씬 빠릅니다
BWAPI::Broodwar->setFrameSkip(Config::BWAPIOptions::SetFrameSkip);
std::cout << "Map analyzing started" << std::endl;
BWTA::readMap();
BWTA::analyze();
BWTA::buildChokeNodes();
std::cout << "Map analyzing finished" << std::endl;
gameCommander.onStart();
}
void MyBotModule::onEnd(bool isWinner){
if (isWinner)
std::cout << "I won the game" << std::endl;
else
std::cout << "I lost the game" << std::endl;
gameCommander.onEnd(isWinner);
}
void MyBotModule::onFrame(){
if (BWAPI::Broodwar->isReplay()) {
return;
}
gameCommander.onFrame();
// 화면 출력 및 사용자 입력 처리
UXManager::Instance().update();
}
void MyBotModule::onSendText(std::string text){
ParseTextCommand(text);
gameCommander.onSendText(text);
// Display the text to the game
BWAPI::Broodwar->sendText("%s", text.c_str());
}
void MyBotModule::onReceiveText(BWAPI::Player player, std::string text){
BWAPI::Broodwar << player->getName() << " said \"" << text << "\"" << std::endl;
gameCommander.onReceiveText(player, text);
}
void MyBotModule::onPlayerLeft(BWAPI::Player player){
BWAPI::Broodwar << player->getName() << " left the game." << std::endl;
}
void MyBotModule::onNukeDetect(BWAPI::Position target){
if (target != Positions::Unknown)
{
BWAPI::Broodwar->drawCircleMap(target, 40, Colors::Red, true);
BWAPI::Broodwar << "Nuclear Launch Detected at " << target << std::endl;
}
else
BWAPI::Broodwar << "Nuclear Launch Detected" << std::endl;
}
void MyBotModule::onUnitCreate(BWAPI::Unit unit){
if (!BWAPI::Broodwar->isReplay()) {
gameCommander.onUnitCreate(unit);
}
else
{
// if we are in a replay, then we will print out the build order
// (just of the buildings, not the units).
if (unit->getType().isBuilding() && unit->getPlayer()->isNeutral() == false)
{
int seconds = BWAPI::Broodwar->getFrameCount() / 24;
int minutes = seconds / 60;
seconds %= 60;
BWAPI::Broodwar->sendText("%.2d:%.2d: %s creates a %s", minutes, seconds, unit->getPlayer()->getName().c_str(), unit->getType().c_str());
}
}
}
void MyBotModule::onUnitMorph(BWAPI::Unit unit){
if (!BWAPI::Broodwar->isReplay()){
gameCommander.onUnitMorph(unit);
}
else {
// if we are in a replay, then we will print out the build order
// (just of the buildings, not the units).
if (unit->getType().isBuilding() && unit->getPlayer()->isNeutral() == false)
{
int seconds = BWAPI::Broodwar->getFrameCount() / 24;
int minutes = seconds / 60;
seconds %= 60;
BWAPI::Broodwar->sendText("%.2d:%.2d: %s morphs a %s", minutes, seconds, unit->getPlayer()->getName().c_str(), unit->getType().c_str());
}
}
}
void MyBotModule::onUnitDestroy(BWAPI::Unit unit){
if (!BWAPI::Broodwar->isReplay()){
// 패배 여부 체크 후 GG
int buildingCount = 0;
int workerCount = 0;
for (auto & unit : BWAPI::Broodwar->self()->getUnits()) {
if (unit->getType().isBuilding()) {
buildingCount++;
}
else if (unit->getType().isWorker()) {
workerCount++;
}
}
if (buildingCount == 0) {
BWAPI::Broodwar->sendText("GG");
BWAPI::Broodwar->leaveGame();
}
gameCommander.onUnitDestroy(unit);
}
}
void MyBotModule::onUnitShow(BWAPI::Unit unit){
if (!BWAPI::Broodwar->isReplay()) {
gameCommander.onUnitShow(unit);
}
}
void MyBotModule::onUnitHide(BWAPI::Unit unit){
if (!BWAPI::Broodwar->isReplay()) {
gameCommander.onUnitHide(unit);
}
}
void MyBotModule::onUnitRenegade(BWAPI::Unit unit){
if (!BWAPI::Broodwar->isReplay()) {
gameCommander.onUnitRenegade(unit);
}
}
void MyBotModule::onUnitDiscover(BWAPI::Unit unit){
if (!BWAPI::Broodwar->isReplay()) {
gameCommander.onUnitDiscover(unit);
}
}
void MyBotModule::onUnitEvade(BWAPI::Unit unit){
if (!BWAPI::Broodwar->isReplay()) {
gameCommander.onUnitEvade(unit);
}
}
void MyBotModule::onUnitComplete(BWAPI::Unit unit){
if (!BWAPI::Broodwar->isReplay()) {
gameCommander.onUnitComplete(unit);
}
}
void MyBotModule::onSaveGame(std::string gameName){
BWAPI::Broodwar->sendText("The game was saved to \"%s\".", gameName.c_str());
}
void MyBotModule::ParseTextCommand(const std::string & commandString)
{
// Make sure to use %s and pass the text as a parameter,
// otherwise you may run into problems when you use the %(percent) character!
BWAPI::Player self = BWAPI::Broodwar->self();
if (commandString == "/afap") {
BWAPI::Broodwar->setLocalSpeed(0);
BWAPI::Broodwar->setFrameSkip(0);
}
else if (commandString == "/fast") {
BWAPI::Broodwar->setLocalSpeed(24);
BWAPI::Broodwar->setFrameSkip(0);
}
else if (commandString == "/slow") {
BWAPI::Broodwar->setLocalSpeed(42);
BWAPI::Broodwar->setFrameSkip(0);
}
else if (commandString == "/endthegame") {
//bwapi->setFrameSkip(16); // Not needed if using setGUI(false).
BWAPI::Broodwar->setGUI(false);
}
}
|
e2f4f5a9e747fceb5e9ae0c56a802eeff8dce60e | badc1ee87d93f187733e9bcd5c1806d6aa91dc4a | /Recursion/sum_natural_numbers.cpp | 511ce7b1f74fb1fd3c8534a03dedcf253380b4d9 | [] | no_license | Ts-A/cpp-practice-codes | 7914cbd45f9f0b466fd09e4a04bcab9db377b3d5 | 758a7e52ee35ae5590af94a6cf18e2b472d6e667 | refs/heads/master | 2023-05-25T01:55:04.081895 | 2021-05-28T19:13:39 | 2021-05-28T19:13:39 | 351,353,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 291 | cpp | sum_natural_numbers.cpp | #include <iostream>
#define cout std::cout
#define cin std::cin
#define endl std::endl
int sum(int n) {
return n > 1 ? n + sum(n-1) : 1;
}
int main() {
int n;
cout << "\nEnter a natural number n:";
cin >> n;
cout << "/nSum of n natural numbers:" << sum(n) << endl;
return 0;
} |
26d84262c5974eb3c2a600e7966f6b636fae35c5 | f8fe633947f3db3aff35f0af688937469aa60066 | /server/feature_extractors/FeatureExtractor.h | 74087e98744e469d31bcc55546b44b31fa25e634 | [] | no_license | mcordischi/photosynthesis | 5a25c5d5bc5d6e52e23fa53539bb899f03ba89d8 | 6e08001764aaf5e015e470a3ae1b74326ee087d7 | refs/heads/master | 2020-07-21T14:28:24.103792 | 2014-06-07T19:48:01 | 2014-06-07T19:48:01 | 10,872,925 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 179 | h | FeatureExtractor.h | // Interface Class for extration of features
#include<cv.h>
using namespace cv;
class FeatureExtractor {
public:
virtual float extractFeature(Mat* image) = 0 ;
};
|
6d58d4d1d456f8e2fe277eadfd58823afd37f5ba | c2ec21b1e7f955c10d9620155dea4c31adb38c7a | /main.cpp | 05b8c7b59958bdcbce7be44ee9664208d3fc4375 | [] | no_license | RogueEffect/ARCHIVE_rpg_shop | f2851cb4bc28f3231d526bf160126331547b19c9 | 36ae60ef0ce16d1fd500867b1c9ebaff0f3a7571 | refs/heads/master | 2023-07-19T06:29:16.569969 | 2021-08-31T05:58:31 | 2021-08-31T05:58:31 | 401,589,603 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,352 | cpp | main.cpp |
#include <iostream>
#include <limits>
using namespace std;
class CItem
{
public:
string Name;
int Price;
};
CItem NOTHING = { "NOTHING", -1 };
class CPlayer
{
public:
void PrintInv()
{
if(ItemCount)
{
cout << "-----Inventory-----" << endl;
for(int i = 0; i < ItemCount; ++i)
{
cout << Inventory[i].Name << endl;
}
cout << "---End Inventory---";
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
}
else cout << "You have nothing" << endl;
}
void Pay(int amount)
{
Gold -= amount;
}
void AddInv(CItem item)
{
Inventory[ItemCount] = item;
Inventory[ItemCount].Price = (int) Inventory[ItemCount].Price / 2;
++ItemCount;
}
void DropInv(int item)
{
do
{
Inventory[item] = Inventory[item + 1];
++item;
} while(item < 8);
Inventory[8] = NOTHING;
--ItemCount;
}
int Gold;
int ItemCount;
CItem Inventory[9];
};
class CShop
{
public:
bool MainMenu(CPlayer& customer)
{
cout << "Welcome." << endl
<< "We deal in weapons and armor" << endl
<< "What dost thou want to do?" << endl
<< "1) Buy" << endl
<< "2) Sell" << endl
<< "i) Inventory" << endl
<< "q) Quit" << endl
<< "> ";
char c;
cin >> c;
switch((int) c)
{
case '1':
while(BuyMenu(customer));
break;
case '2':
while(SellMenu(customer));
break;
case 'i':
customer.PrintInv();
return true;
break;
default:
return false;
break;
}
return true;
}
bool BuyMenu(CPlayer &customer)
{
cout << "What dost thou wish to buy?" << endl
<< "$" << customer.Gold << endl;
for(int i = 0; i < ItemCount; ++i)
{
cout << i << ") $" << Inventory[i].Price
<< "\t\t\t" << Inventory[i].Name << endl;
}
cout << "i) Inventory" << endl
<< "q) Quit" << endl
<< "> ";
char c;
cin >> c;
if('0' <= c && c <= '0' + ItemCount)
{
int i = c - '0';
cout << "The " << Inventory[i].Name << "?" << endl
<< "Is that okay (y/n)?" << endl
<< "> ";
char d;
cin >> d;
if(d == 'y' || d == 'Y')
{
if(customer.Gold > Inventory[i].Price)
{
if(customer.ItemCount < 9)
{
customer.Pay(Inventory[i].Price);
customer.AddInv(Inventory[i]);
cout << "You bought the "
<< Inventory[i].Name << "!" << endl;
}
else cout << "You cannot hold anymore." << endl;
}
else cout << "Sorry, Thous hast not enough money." << endl;
}
}
else if(c == 'i') customer.PrintInv();
else return false;
cout << "Dost though want anything else (y/n)?" << endl
<< "> ";
cin >> c;
if(c == 'y' || c == 'Y') return true;
return false;
}
bool SellMenu(CPlayer &customer)
{
if(customer.ItemCount)
{
cout << "What art thou selling?" << endl
<< "$" << customer.Gold << endl;
for(int i = 0; i < customer.ItemCount; ++i)
{
cout << i << ") $" << customer.Inventory[i].Price
<< "\t\t\t" << customer.Inventory[i].Name << endl;
}
cout << "q) Quit" << endl
<< "> ";
char c;
cin >> c;
if('0' <= c && c <= '0' + customer.ItemCount)
{
int i = c - '0';
cout << "The " << customer.Inventory[i].Name << "?" << endl
<< "Is that okay (y/n)?" << endl
<< "> ";
char d;
cin >> d;
if(d == 'y' || d == 'Y')
{
string tempName = customer.Inventory[i].Name;
customer.Pay(-customer.Inventory[i].Price);
customer.DropInv(i);
cout << "You sold the " << tempName << "!" << endl;
}
}
cout << "Dost thou have anything more to sell (y/n)?" << endl
<< "> ";
cin >> c;
if(c == 'y' || c == 'Y') return true;
return false;
}
else cout << "You have nothing." << endl;
return false;
}
int ItemCount;
CItem Inventory[6];
};
int main()
{
CPlayer myPlayer = { 120, 0, { } };
CShop myShop = {
6,
{ {"Bamboo Pole", 10},
{"Club", 60},
{"Copper Sword", 180},
{"Clothes", 20},
{"Leather Clothes", 70},
{"Small Shield", 90} }
};
while(myShop.MainMenu(myPlayer));
}
|
e9d82ddb52674afac6b8a46e39db81474dcf27e3 | 7a2ee2a291db733e3cec634e81142c6a8773eb35 | /bd.h | 901e0de231d6a62135ac941a9790fadab7578989 | [] | no_license | rhiswell/dbms-again | b5df2bf0fb93f094bfb5d8cae3c42b6d1333dd9c | 0b561615d994d6095ac47fb7b9a28be454ca37c1 | refs/heads/master | 2021-09-01T08:24:17.654439 | 2017-12-26T01:39:18 | 2017-12-26T01:39:18 | 109,981,891 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,559 | h | bd.h | //
// Created by Zhiqiang He on 08/11/2017.
//
#ifndef DBMS_AGAIN_BD_H
#define DBMS_AGAIN_BD_H
#include "types.h"
#include "buf.h"
#include <stdio.h>
#include <assert.h>
#include <string.h>
#define PAGESIZE 4096 // In bytes
#define MAXPAGES 65536 // Two groups => <= 256 MB backing storage
#define MAXBUNCH 8 // Increase 8 pages in each `IncNumPages` call
#define MAXGROUP 2
static inline int PageId2GroupId(int page_id)
{
int group_id = (page_id >> 15); // <=> page_id / (4096 * 8) pages per group
assert(group_id >= 0);
return group_id;
}
static inline int GroupId2Pos(int group_id)
{
return group_id << 27; // <=> group_id * (4096 * 8) * 4K
}
static inline int PageId2Pos(int page_id)
{
return PAGESIZE * page_id;
}
// Data storage manager
class DSMgr
{
public:
DSMgr();
int OpenFile(const char *pathname);
int CloseFile();
int ReadPage(int page_id, bFrame *frm);
int WritePage(int page_id, bFrame *frm);
int Seek(int offset, int pos);
FILE *GetFile();
void IncNumPages();
int GetNumPages();
int FindOnePage();
void SetUse(int page_id, int use_bit);
int GetUse(int page_id);
private:
FILE *currFile; // Backing storage
int numPages; // Number of allocated pages
char bitmap[MAXPAGES >> 3]; // The bitmaps of each group will be loaded into
// memory in time. 2 slots => 2 groups on the fly.
int InitGroup(int group_id);
int GetNRGroups();
};
#endif //DBMS_AGAIN_BD_H
|
4b9c53701eb63ba7fc1315faf18e471bf91f5961 | 28f9e09b229a4b0f87ae756bd8c715655ba2ccbc | /phonejson/threadobject.cpp | 213fbcde3814d5f09c464511128fcc088395b086 | [] | no_license | End1-1/FastFServer | e4af39f4f310622f9c52d869cef97023651c4dad | 605c47000cb0571eaee4eb7c2dc0630b5112f41a | refs/heads/master | 2020-05-27T22:36:08.411570 | 2020-02-26T10:25:30 | 2020-02-26T10:25:30 | 188,807,629 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 690 | cpp | threadobject.cpp | #include "threadobject.h"
#include <QThread>
ThreadObject::ThreadObject() :
QObject()
{
}
ThreadObject::~ThreadObject()
{
}
void ThreadObject::start()
{
QThread *thread = new QThread();
connect(thread, SIGNAL(started()), this, SLOT(run()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
connect(this, SIGNAL(finished()), thread, SLOT(quit()));
connect(this, SIGNAL(finishThread()), thread, SLOT(quit()));
connect(this, SIGNAL(error(QString)), this, SLOT(finishedWithError(QString)));
moveToThread(thread);
thread->start();
}
void ThreadObject::finishedWithError(const QString &err)
{
Q_UNUSED(err);
emit finishThread();
}
|
520f551d23328d688dd87b18a5c6f8ea562fe771 | b3fbe558eebaa5366f9ced50135764466d66eb45 | /WickedEngine/wiGPUBVH.cpp | 1e3e190a3bb8eefa9b3b8f3987750edc9ef03866 | [
"MIT",
"Zlib",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | belleCrazySnail/WickedEngine | 6421ad218e58f436a25a7949f268e534586d3118 | b339f8405ef3257f41ca1329042396c6c77f8f31 | refs/heads/master | 2020-04-22T02:57:34.925869 | 2019-03-04T09:26:14 | 2019-03-04T09:26:14 | 170,068,901 | 0 | 0 | NOASSERTION | 2019-02-11T04:40:59 | 2019-02-11T04:40:58 | null | UTF-8 | C++ | false | false | 17,599 | cpp | wiGPUBVH.cpp | #include "wiGPUBVH.h"
#include "wiSceneSystem.h"
#include "wiRenderer.h"
#include "ShaderInterop_BVH.h"
#include "wiProfiler.h"
#include "wiResourceManager.h"
#include "wiGPUSortLib.h"
#include <string>
#include <vector>
#include <set>
using namespace std;
using namespace wiGraphicsTypes;
using namespace wiSceneSystem;
using namespace wiECS;
enum CSTYPES_BVH
{
CSTYPE_BVH_RESET,
CSTYPE_BVH_CLASSIFICATION,
CSTYPE_BVH_KICKJOBS,
CSTYPE_BVH_CLUSTERPROCESSOR,
CSTYPE_BVH_HIERARCHY,
CSTYPE_BVH_PROPAGATEAABB,
CSTYPE_BVH_COUNT
};
static ComputeShader* computeShaders[CSTYPE_BVH_COUNT] = {};
static ComputePSO* CPSO[CSTYPE_BVH_COUNT] = {};
static GPUBuffer* constantBuffer = nullptr;
wiGPUBVH::wiGPUBVH()
{
}
wiGPUBVH::~wiGPUBVH()
{
}
//#define BVH_VALIDATE // slow but great for debug!
void wiGPUBVH::Build(const Scene& scene, GRAPHICSTHREAD threadID)
{
GraphicsDevice* device = wiRenderer::GetDevice();
if (constantBuffer == nullptr)
{
GPUBufferDesc bd;
bd.Usage = USAGE_DYNAMIC;
bd.CPUAccessFlags = CPU_ACCESS_WRITE;
bd.BindFlags = BIND_CONSTANT_BUFFER;
bd.ByteWidth = sizeof(BVHCB);
constantBuffer = new GPUBuffer;
device->CreateBuffer(&bd, nullptr, constantBuffer);
device->SetName(constantBuffer, "BVHGeneratorCB");
}
// Pre-gather scene properties:
uint totalTriangles = 0;
for (size_t i = 0; i < scene.objects.GetCount(); ++i)
{
const ObjectComponent& object = scene.objects[i];
if (object.meshID != INVALID_ENTITY)
{
const MeshComponent& mesh = *scene.meshes.GetComponent(object.meshID);
totalTriangles += (uint)mesh.indices.size() / 3;
}
}
if (totalTriangles > maxTriangleCount)
{
maxTriangleCount = totalTriangles;
maxClusterCount = maxTriangleCount; // todo: cluster / triangle capacity
GPUBufferDesc desc;
HRESULT hr;
bvhNodeBuffer.reset(new GPUBuffer);
bvhAABBBuffer.reset(new GPUBuffer);
bvhFlagBuffer.reset(new GPUBuffer);
triangleBuffer.reset(new GPUBuffer);
clusterCounterBuffer.reset(new GPUBuffer);
clusterIndexBuffer.reset(new GPUBuffer);
clusterMortonBuffer.reset(new GPUBuffer);
clusterSortedMortonBuffer.reset(new GPUBuffer);
clusterOffsetBuffer.reset(new GPUBuffer);
clusterAABBBuffer.reset(new GPUBuffer);
clusterConeBuffer.reset(new GPUBuffer);
desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
desc.StructureByteStride = sizeof(BVHNode);
desc.ByteWidth = desc.StructureByteStride * maxClusterCount * 2;
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_UNKNOWN;
desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED;
desc.Usage = USAGE_DEFAULT;
hr = device->CreateBuffer(&desc, nullptr, bvhNodeBuffer.get());
assert(SUCCEEDED(hr));
device->SetName(bvhNodeBuffer.get(), "BVHNodeBuffer");
desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
desc.StructureByteStride = sizeof(BVHAABB);
desc.ByteWidth = desc.StructureByteStride * maxClusterCount * 2;
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_UNKNOWN;
desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED;
desc.Usage = USAGE_DEFAULT;
hr = device->CreateBuffer(&desc, nullptr, bvhAABBBuffer.get());
assert(SUCCEEDED(hr));
device->SetName(bvhAABBBuffer.get(), "BVHAABBBuffer");
desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
desc.StructureByteStride = sizeof(uint);
desc.ByteWidth = desc.StructureByteStride * (maxClusterCount - 1); // only for internal nodes
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_UNKNOWN;
desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED;
desc.Usage = USAGE_DEFAULT;
hr = device->CreateBuffer(&desc, nullptr, bvhFlagBuffer.get());
assert(SUCCEEDED(hr));
device->SetName(bvhFlagBuffer.get(), "BVHFlagBuffer");
desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
desc.StructureByteStride = sizeof(BVHMeshTriangle);
desc.ByteWidth = desc.StructureByteStride * maxTriangleCount;
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_UNKNOWN;
desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED;
desc.Usage = USAGE_DEFAULT;
hr = device->CreateBuffer(&desc, nullptr, triangleBuffer.get());
assert(SUCCEEDED(hr));
device->SetName(triangleBuffer.get(), "BVHTriangleBuffer");
desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
desc.StructureByteStride = sizeof(uint);
desc.ByteWidth = desc.StructureByteStride;
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_UNKNOWN;
desc.MiscFlags = RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS;
desc.Usage = USAGE_DEFAULT;
hr = device->CreateBuffer(&desc, nullptr, clusterCounterBuffer.get());
assert(SUCCEEDED(hr));
device->SetName(clusterCounterBuffer.get(), "BVHClusterCounterBuffer");
desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
desc.StructureByteStride = sizeof(uint);
desc.ByteWidth = desc.StructureByteStride * maxClusterCount;
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_UNKNOWN;
desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED;
desc.Usage = USAGE_DEFAULT;
hr = device->CreateBuffer(&desc, nullptr, clusterIndexBuffer.get());
assert(SUCCEEDED(hr));
device->SetName(clusterIndexBuffer.get(), "BVHClusterIndexBuffer");
desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
desc.StructureByteStride = sizeof(uint);
desc.ByteWidth = desc.StructureByteStride * maxClusterCount;
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_UNKNOWN;
desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED;
desc.Usage = USAGE_DEFAULT;
hr = device->CreateBuffer(&desc, nullptr, clusterMortonBuffer.get());
hr = device->CreateBuffer(&desc, nullptr, clusterSortedMortonBuffer.get());
assert(SUCCEEDED(hr));
device->SetName(clusterMortonBuffer.get(), "BVHClusterMortonBuffer");
device->SetName(clusterSortedMortonBuffer.get(), "BVHSortedClusterMortonBuffer");
desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
desc.StructureByteStride = sizeof(uint2);
desc.ByteWidth = desc.StructureByteStride * maxClusterCount;
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_UNKNOWN;
desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED;
desc.Usage = USAGE_DEFAULT;
hr = device->CreateBuffer(&desc, nullptr, clusterOffsetBuffer.get());
assert(SUCCEEDED(hr));
device->SetName(clusterOffsetBuffer.get(), "BVHClusterOffsetBuffer");
desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
desc.StructureByteStride = sizeof(BVHAABB);
desc.ByteWidth = desc.StructureByteStride * maxClusterCount;
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_UNKNOWN;
desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED;
desc.Usage = USAGE_DEFAULT;
hr = device->CreateBuffer(&desc, nullptr, clusterAABBBuffer.get());
assert(SUCCEEDED(hr));
device->SetName(clusterAABBBuffer.get(), "BVHClusterAABBBuffer");
desc.BindFlags = BIND_SHADER_RESOURCE | BIND_UNORDERED_ACCESS;
desc.StructureByteStride = sizeof(ClusterCone);
desc.ByteWidth = desc.StructureByteStride * maxClusterCount;
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_UNKNOWN;
desc.MiscFlags = RESOURCE_MISC_BUFFER_STRUCTURED;
desc.Usage = USAGE_DEFAULT;
hr = device->CreateBuffer(&desc, nullptr, clusterConeBuffer.get());
assert(SUCCEEDED(hr));
device->SetName(clusterConeBuffer.get(), "BVHClusterConeBuffer");
}
static GPUBuffer* indirectBuffer = nullptr; // GPU job kicks
if (indirectBuffer == nullptr)
{
GPUBufferDesc desc;
HRESULT hr;
SAFE_DELETE(indirectBuffer);
indirectBuffer = new GPUBuffer;
desc.BindFlags = BIND_UNORDERED_ACCESS;
desc.StructureByteStride = sizeof(IndirectDispatchArgs) * 2;
desc.ByteWidth = desc.StructureByteStride;
desc.CPUAccessFlags = 0;
desc.Format = FORMAT_UNKNOWN;
desc.MiscFlags = RESOURCE_MISC_DRAWINDIRECT_ARGS | RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS;
desc.Usage = USAGE_DEFAULT;
hr = device->CreateBuffer(&desc, nullptr, indirectBuffer);
assert(SUCCEEDED(hr));
}
wiProfiler::BeginRange("BVH Rebuild", wiProfiler::DOMAIN_GPU, threadID);
device->EventBegin("BVH - Reset", threadID);
{
device->BindComputePSO(CPSO[CSTYPE_BVH_RESET], threadID);
GPUResource* uavs[] = {
clusterCounterBuffer.get(),
bvhNodeBuffer.get(),
bvhAABBBuffer.get(),
};
device->BindUAVs(CS, uavs, 0, ARRAYSIZE(uavs), threadID);
device->Dispatch(1, 1, 1, threadID);
}
device->EventEnd(threadID);
uint32_t triangleCount = 0;
uint32_t materialCount = 0;
device->EventBegin("BVH - Classification", threadID);
{
device->BindComputePSO(CPSO[CSTYPE_BVH_CLASSIFICATION], threadID);
GPUResource* uavs[] = {
triangleBuffer.get(),
clusterCounterBuffer.get(),
clusterIndexBuffer.get(),
clusterMortonBuffer.get(),
clusterOffsetBuffer.get(),
clusterAABBBuffer.get(),
};
device->BindUAVs(CS, uavs, 0, ARRAYSIZE(uavs), threadID);
for (size_t i = 0; i < scene.objects.GetCount(); ++i)
{
const ObjectComponent& object = scene.objects[i];
if (object.meshID != INVALID_ENTITY)
{
const MeshComponent& mesh = *scene.meshes.GetComponent(object.meshID);
BVHCB cb;
cb.xTraceBVHWorld = object.transform_index >= 0 ? scene.transforms[object.transform_index].world : IDENTITYMATRIX;
cb.xTraceBVHMaterialOffset = materialCount;
cb.xTraceBVHMeshTriangleOffset = triangleCount;
cb.xTraceBVHMeshTriangleCount = (uint)mesh.indices.size() / 3;
cb.xTraceBVHMeshVertexPOSStride = sizeof(MeshComponent::Vertex_POS);
device->UpdateBuffer(constantBuffer, &cb, threadID);
triangleCount += cb.xTraceBVHMeshTriangleCount;
device->BindConstantBuffer(CS, constantBuffer, CB_GETBINDSLOT(BVHCB), threadID);
GPUResource* res[] = {
mesh.indexBuffer.get(),
mesh.vertexBuffer_POS.get(),
mesh.vertexBuffer_TEX.get(),
};
device->BindResources(CS, res, TEXSLOT_ONDEMAND0, ARRAYSIZE(res), threadID);
device->Dispatch((UINT)ceilf((float)cb.xTraceBVHMeshTriangleCount / (float)BVH_CLASSIFICATION_GROUPSIZE), 1, 1, threadID);
for (auto& subset : mesh.subsets)
{
materialCount++;
}
}
}
device->UAVBarrier(uavs, ARRAYSIZE(uavs), threadID);
device->UnbindUAVs(0, ARRAYSIZE(uavs), threadID);
}
device->EventEnd(threadID);
device->EventBegin("BVH - Sort Cluster Mortons", threadID);
wiGPUSortLib::Sort(maxClusterCount, clusterMortonBuffer.get(), clusterCounterBuffer.get(), 0, clusterIndexBuffer.get(), threadID);
device->EventEnd(threadID);
device->EventBegin("BVH - Kick Jobs", threadID);
{
device->BindComputePSO(CPSO[CSTYPE_BVH_KICKJOBS], threadID);
GPUResource* uavs[] = {
indirectBuffer,
};
device->BindUAVs(CS, uavs, 0, ARRAYSIZE(uavs), threadID);
GPUResource* res[] = {
clusterCounterBuffer.get(),
};
device->BindResources(CS, res, TEXSLOT_ONDEMAND0, ARRAYSIZE(res), threadID);
device->Dispatch(1, 1, 1, threadID);
device->UAVBarrier(uavs, ARRAYSIZE(uavs), threadID);
device->UnbindUAVs(0, ARRAYSIZE(uavs), threadID);
}
device->EventEnd(threadID);
device->EventBegin("BVH - Cluster Processor", threadID);
{
device->BindComputePSO(CPSO[CSTYPE_BVH_CLUSTERPROCESSOR], threadID);
GPUResource* uavs[] = {
clusterSortedMortonBuffer.get(),
clusterConeBuffer.get(),
};
device->BindUAVs(CS, uavs, 0, ARRAYSIZE(uavs), threadID);
GPUResource* res[] = {
clusterCounterBuffer.get(),
clusterIndexBuffer.get(),
clusterMortonBuffer.get(),
clusterOffsetBuffer.get(),
clusterAABBBuffer.get(),
triangleBuffer.get(),
};
device->BindResources(CS, res, TEXSLOT_ONDEMAND0, ARRAYSIZE(res), threadID);
device->DispatchIndirect(indirectBuffer, ARGUMENTBUFFER_OFFSET_CLUSTERPROCESSOR, threadID);
device->UAVBarrier(uavs, ARRAYSIZE(uavs), threadID);
device->UnbindUAVs(0, ARRAYSIZE(uavs), threadID);
}
device->EventEnd(threadID);
device->EventBegin("BVH - Build Hierarchy", threadID);
{
device->BindComputePSO(CPSO[CSTYPE_BVH_HIERARCHY], threadID);
GPUResource* uavs[] = {
bvhNodeBuffer.get(),
bvhFlagBuffer.get(),
};
device->BindUAVs(CS, uavs, 0, ARRAYSIZE(uavs), threadID);
GPUResource* res[] = {
clusterCounterBuffer.get(),
clusterSortedMortonBuffer.get(),
};
device->BindResources(CS, res, TEXSLOT_ONDEMAND0, ARRAYSIZE(res), threadID);
device->DispatchIndirect(indirectBuffer, ARGUMENTBUFFER_OFFSET_HIERARCHY, threadID);
device->UAVBarrier(uavs, ARRAYSIZE(uavs), threadID);
device->UnbindUAVs(0, ARRAYSIZE(uavs), threadID);
}
device->EventEnd(threadID);
device->EventBegin("BVH - Propagate AABB", threadID);
{
device->BindComputePSO(CPSO[CSTYPE_BVH_PROPAGATEAABB], threadID);
GPUResource* uavs[] = {
bvhAABBBuffer.get(),
bvhFlagBuffer.get(),
};
device->BindUAVs(CS, uavs, 0, ARRAYSIZE(uavs), threadID);
GPUResource* res[] = {
clusterCounterBuffer.get(),
clusterIndexBuffer.get(),
clusterAABBBuffer.get(),
bvhNodeBuffer.get(),
};
device->BindResources(CS, res, TEXSLOT_ONDEMAND0, ARRAYSIZE(res), threadID);
device->DispatchIndirect(indirectBuffer, ARGUMENTBUFFER_OFFSET_CLUSTERPROCESSOR, threadID);
device->UAVBarrier(uavs, ARRAYSIZE(uavs), threadID);
device->UnbindUAVs(0, ARRAYSIZE(uavs), threadID);
}
device->EventEnd(threadID);
#ifdef BVH_VALIDATE
GPUBufferDesc readback_desc;
bool download_success;
// Download cluster count:
readback_desc = clusterCounterBuffer->GetDesc();
readback_desc.Usage = USAGE_STAGING;
readback_desc.CPUAccessFlags = CPU_ACCESS_READ;
readback_desc.BindFlags = 0;
readback_desc.MiscFlags = 0;
GPUBuffer readback_clusterCounterBuffer;
device->CreateBuffer(&readback_desc, nullptr, &readback_clusterCounterBuffer);
uint clusterCount;
download_success = device->DownloadResource(clusterCounterBuffer.get(), &readback_clusterCounterBuffer, &clusterCount, threadID);
assert(download_success);
if (clusterCount > 0)
{
const uint leafNodeOffset = clusterCount - 1;
// Validate node buffer:
readback_desc = bvhNodeBuffer->GetDesc();
readback_desc.Usage = USAGE_STAGING;
readback_desc.CPUAccessFlags = CPU_ACCESS_READ;
readback_desc.BindFlags = 0;
readback_desc.MiscFlags = 0;
GPUBuffer readback_nodeBuffer;
device->CreateBuffer(&readback_desc, nullptr, &readback_nodeBuffer);
vector<BVHNode> nodes(readback_desc.ByteWidth / sizeof(BVHNode));
download_success = device->DownloadResource(bvhNodeBuffer.get(), &readback_nodeBuffer, nodes.data(), threadID);
assert(download_success);
set<uint> visitedLeafs;
vector<uint> stack;
stack.push_back(0);
while (!stack.empty())
{
uint nodeIndex = stack.back();
stack.pop_back();
if (nodeIndex >= leafNodeOffset)
{
// leaf node
assert(visitedLeafs.count(nodeIndex) == 0); // leaf node was already visited, this must not happen!
visitedLeafs.insert(nodeIndex);
}
else
{
// internal node
BVHNode& node = nodes[nodeIndex];
stack.push_back(node.LeftChildIndex);
stack.push_back(node.RightChildIndex);
}
}
for (uint i = 0; i < clusterCount; ++i)
{
uint nodeIndex = leafNodeOffset + i;
BVHNode& leaf = nodes[nodeIndex];
assert(leaf.LeftChildIndex == 0 && leaf.RightChildIndex == 0); // a leaf must have no children
assert(visitedLeafs.count(nodeIndex) > 0); // every leaf node must have been visited in the traversal above
}
// Validate flag buffer:
readback_desc = bvhFlagBuffer->GetDesc();
readback_desc.Usage = USAGE_STAGING;
readback_desc.CPUAccessFlags = CPU_ACCESS_READ;
readback_desc.BindFlags = 0;
readback_desc.MiscFlags = 0;
GPUBuffer readback_flagBuffer;
device->CreateBuffer(&readback_desc, nullptr, &readback_flagBuffer);
vector<uint> flags(readback_desc.ByteWidth / sizeof(uint));
download_success = device->DownloadResource(bvhFlagBuffer.get(), &readback_flagBuffer, flags.data(), threadID);
assert(download_success);
for (auto& x : flags)
{
if (x > 2)
{
assert(0); // flagbuffer anomaly detected: node can't have more than two children (AABB propagation step)!
break;
}
}
}
#endif // BVH_VALIDATE
wiProfiler::EndRange(threadID); // BVH rebuild
}
void wiGPUBVH::Bind(SHADERSTAGE stage, GRAPHICSTHREAD threadID)
{
GraphicsDevice* device = wiRenderer::GetDevice();
GPUResource* res[] = {
triangleBuffer.get(),
clusterCounterBuffer.get(),
clusterIndexBuffer.get(),
clusterOffsetBuffer.get(),
clusterConeBuffer.get(),
bvhNodeBuffer.get(),
bvhAABBBuffer.get(),
};
device->BindResources(stage, res, TEXSLOT_ONDEMAND1, ARRAYSIZE(res), threadID);
}
void wiGPUBVH::LoadShaders()
{
GraphicsDevice* device = wiRenderer::GetDevice();
computeShaders[CSTYPE_BVH_RESET] = static_cast<ComputeShader*>(wiResourceManager::GetShaderManager().add("bvh_resetCS", wiResourceManager::COMPUTESHADER));
computeShaders[CSTYPE_BVH_CLASSIFICATION] = static_cast<ComputeShader*>(wiResourceManager::GetShaderManager().add("bvh_classificationCS", wiResourceManager::COMPUTESHADER));
computeShaders[CSTYPE_BVH_KICKJOBS] = static_cast<ComputeShader*>(wiResourceManager::GetShaderManager().add("bvh_kickjobsCS", wiResourceManager::COMPUTESHADER));
computeShaders[CSTYPE_BVH_CLUSTERPROCESSOR] = static_cast<ComputeShader*>(wiResourceManager::GetShaderManager().add("bvh_clusterprocessorCS", wiResourceManager::COMPUTESHADER));
computeShaders[CSTYPE_BVH_HIERARCHY] = static_cast<ComputeShader*>(wiResourceManager::GetShaderManager().add("bvh_hierarchyCS", wiResourceManager::COMPUTESHADER));
computeShaders[CSTYPE_BVH_PROPAGATEAABB] = static_cast<ComputeShader*>(wiResourceManager::GetShaderManager().add("bvh_propagateaabbCS", wiResourceManager::COMPUTESHADER));
for (int i = 0; i < CSTYPE_BVH_COUNT; ++i)
{
ComputePSODesc desc;
desc.cs = computeShaders[i];
RECREATE(CPSO[i]);
device->CreateComputePSO(&desc, CPSO[i]);
}
}
|
f9e26b772bd9b684788017d969a2fad796c4198d | e5f4f37d941ceb8145d65f92028cc54658b1ac01 | /Code/ThirdParty/Kraut/KrautFoundation/Strings/BasicString.h | 42e0c0e19bdd4d5203aa001c6d0d409938e8db40 | [
"MIT"
] | permissive | ezEngine/ezEngine | 19983d2733a5409fb2665c6c3a0a575dadcefb50 | c46e3b4b2cd46798e4abb4938fbca281c054b039 | refs/heads/dev | 2023-09-06T02:17:28.152665 | 2023-09-05T18:25:43 | 2023-09-05T18:25:43 | 18,179,848 | 1,050 | 165 | MIT | 2023-09-14T21:44:39 | 2014-03-27T15:02:16 | C++ | UTF-8 | C++ | false | false | 4,836 | h | BasicString.h | #ifndef AE_FOUNDATION_STRINGS_BASICSTRING_H
#define AE_FOUNDATION_STRINGS_BASICSTRING_H
#include "StringFunctions.h"
#include "Declarations.h"
namespace AE_NS_FOUNDATION
{
//! This simple base class for all string classes is needed to make them compatible to each other without needing thousands of overloads.
/*! This class should never be instanciated directly. Instead it only serves as the base-class for several
other string classes.
*/
class AE_FOUNDATION_DLL aeBasicString
{
public:
aeBasicString(const char* szString);
//! Returns the length of the string.
aeUInt32 length(void) const { return (m_uiLength); }
//! Returns whether the string has a length of zero.
bool empty(void) const { return (m_uiLength == 0); }
//! Allows read-access to the string.
const char* c_str(void) const { return (m_pDataToRead); }
//! Allows read-access to the character with the given index
const char operator[](aeUInt32 index) const;
//! Returns true if this string and the given string are completely identical.
bool CompareEqual(const char* szString2) const;
//! Returns true if the first n characters of this string and the given string are identical.
bool CompareEqual(const char* szString2, aeUInt32 uiCharsToCompare) const;
//! Returns zero if this string and the given string are equal, a negative value if this string is lexicographically "smaller", otherwise a positive value.
aeInt32 CompareAlphabetically(const char* szString2) const;
//! Returns zero if the first n characters of this string and the given string are equal, a negative value if this string is lexicographically "smaller", otherwise a positive value.
aeInt32 CompareAlphabetically(const char* szString2, aeUInt32 uiCharsToCompare) const;
//! Returns the first position after uiStartPos where szStringToFind is found. -1 if nothing is found.
aeInt32 FindFirstStringPos(const char* szStringToFind, aeUInt32 uiStartPos = 0) const;
//! Returns true if this string starts with the string given in szStartsWith.
bool StartsWith(const char* szStartsWith) const;
//! Returns true if this string ends with the string given in szEndsWith.
bool EndsWith(const char* szEndsWith) const;
protected:
//! Non-instantiable from outside.
explicit aeBasicString(char* pReadData, aeUInt32 uiLength)
: m_pDataToRead(pReadData)
, m_uiLength(uiLength)
{
// The empty string "" is simply stored inside the executable (static data)
// By initializing all pointers with it, c_str will always return a valid zero-terminated string
// even if the string-class has not allocated any data so far
AE_CHECK_DEV(pReadData != nullptr, "aeBasicString::Constructor: pReadData must not be nullptr. Initialize it with \"\" instead.");
}
//! A pointer to the data. Differently initialized/modified by each derived string class.
char* m_pDataToRead;
//! The cached length of the string.
aeUInt32 m_uiLength;
private:
aeBasicString(void);
aeBasicString(const aeBasicString& cc);
void operator=(const aeBasicString& rhs);
};
// *** Comparison Operators that work on all combinations of aeBasicString-classes and C-Strings ***
AE_FOUNDATION_DLL bool operator==(const aeBasicString& lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator==(const char* lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator==(const aeBasicString& lhs, const char* rhs);
AE_FOUNDATION_DLL bool operator!=(const aeBasicString& lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator!=(const char* lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator!=(const aeBasicString& lhs, const char* rhs);
AE_FOUNDATION_DLL bool operator<(const aeBasicString& lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator<(const char* lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator<(const aeBasicString& lhs, const char* rhs);
AE_FOUNDATION_DLL bool operator>(const aeBasicString& lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator>(const char* lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator>(const aeBasicString& lhs, const char* rhs);
AE_FOUNDATION_DLL bool operator<=(const aeBasicString& lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator<=(const char* lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator<=(const aeBasicString& lhs, const char* rhs);
AE_FOUNDATION_DLL bool operator>=(const aeBasicString& lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator>=(const char* lhs, const aeBasicString& rhs);
AE_FOUNDATION_DLL bool operator>=(const aeBasicString& lhs, const char* rhs);
} // namespace AE_NS_FOUNDATION
#include "Inline/BasicString.inl"
#endif
|
e36b411a759a053923ffb52c4a65973677b758c4 | b4b4e324cbc6159a02597aa66f52cb8e1bc43bc1 | /C++ code/HSNU Online Judge/215(2).cpp | 9d9bd31059463674f786957641d8fc3d12691ee0 | [] | no_license | fsps60312/old-C-code | 5d0ffa0796dde5ab04c839e1dc786267b67de902 | b4be562c873afe9eacb45ab14f61c15b7115fc07 | refs/heads/master | 2022-11-30T10:55:25.587197 | 2017-06-03T16:23:03 | 2017-06-03T16:23:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,620 | cpp | 215(2).cpp | #include<cstdio>
#include<vector>
#include<algorithm>
#include<set>
#include<map>
#include<cassert>
typedef long long LL;
using namespace std;
int T,N,M,K;
struct Edge
{
int a,b,c;
Edge(){}
Edge(const int &a,const int &b,const int &c):a(a),b(b),c(c){}
bool operator<(const Edge &e)const{return c<e.c;}
};
vector<Edge>EDGE;
int IDX[100];
vector<int>ET[100];
struct Djset
{
int dj[100],cnt;
void Clear(const int &n){cnt=n;for(int i=0;i<n;i++)dj[i]=i;}
int FindDJ(const int &a){return dj[a]==a?a:(dj[a]=FindDJ(dj[a]));}
bool Merge(const int &a,const int &b){if(FindDJ(a)==FindDJ(b))return false;cnt--;dj[FindDJ(a)]=FindDJ(b);return true;}
}DJ;
struct Point
{
int x,y;
Point(){}
Point(const int &a,const int &b):x(min(a,b)),y(max(a,b)){}
bool operator<(const Point &p)const{return x!=p.x?x<p.x:y<p.y;}
};
void Dfs(const int &u,const int &g,const int &c)
{
if(IDX[u]!=-1){assert(IDX[u]==g);return;}
IDX[u]=g;
for(auto &i:ET[u])
{
Edge &e=EDGE[i];
if(e.c==c)continue;
Dfs(e.a==u?e.b:e.a,g,c);
}
}
int MarkVertex(const int &c)
{
int i,g;
for(i=0;i<N;i++)IDX[i]=-1;
for(i=0,g=0;i<N;i++)
{
if(IDX[i]!=-1)continue;
Dfs(i,g++,c);
}
return g;
}
bool BuildMST(set<int>&costs)
{
sort(EDGE.begin(),EDGE.end());
for(int i=0;i<N;i++)ET[i].clear();
DJ.Clear(N);
for(int i=0;i<M;i++)
{
Edge &e=EDGE[i];
if(!DJ.Merge(e.a,e.b))continue;
ET[e.a].push_back(i);
ET[e.b].push_back(i);
costs.insert(e.c);
}
return DJ.cnt==1;
}
int main()
{
// freopen("in.txt","r",stdin);
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d",&N,&M,&K);
EDGE.clear();
for(int i=0;i<M;i++)
{
static int a,b,c;
scanf("%d%d%d",&a,&b,&c);
EDGE.push_back(Edge(--a,--b,c));
}
set<int>costs;
if(!BuildMST(costs)){puts("-1");continue;}
LL ans=1LL;
for(auto &c:costs)
{
int g=MarkVertex(c);
map<Point,LL>edge;
for(auto &e:EDGE)
{
if(e.c!=c||IDX[e.a]==IDX[e.b])continue;
Point p=Point(IDX[e.a],IDX[e.b]);
auto it=edge.find(p);
if(it==edge.end())edge[p]=1LL;
else it->second++;
}
LL ta=0LL;
// for(auto it:edge)printf("c=%d:(%d,%d)%d\n",c,it.first.x,it.first.y,it.second);
for(int s=0,limit=1<<edge.size();s<limit;s++)
{
DJ.Clear(g);
int i=0;
for(auto it:edge)if(s&(1<<(i++)))if(!DJ.Merge(it.first.x,it.first.y)){DJ.cnt=-1;break;}
if(DJ.cnt==1)
{
LL v=1LL;
i=0;
for(auto it:edge)if(s&(1<<(i++)))
{
// printf("s=%d,c=%d:(%d,%d)%d\n",s,c,it.first.x,it.first.y,it.second);
v*=it.second,v%=K;
}
// puts("");
ta+=v,ta%=K;
}
}
ans*=ta,ans%=K;
}
printf("%lld\n",ans);
}
return 0;
}
|
0cfac0a56676d12187a2644b88205595b3b4178e | 1abf985d2784efce3196976fc1b13ab91d6a2a9e | /opentracker/src/standalones/live_opentracker.cxx | 3664d71978bf3ebb950437d46e6002b8da547031 | [
"BSD-3-Clause"
] | permissive | dolphinking/mirror-studierstube | 2550e246f270eb406109d4c3a2af7885cd7d86d0 | 57249d050e4195982c5380fcf78197073d3139a5 | refs/heads/master | 2021-01-11T02:19:48.803878 | 2012-09-14T13:01:15 | 2012-09-14T13:01:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,571 | cxx | live_opentracker.cxx | /* ========================================================================
* Copyright (c) 2006,
* Institute for Computer Graphics and Vision
* Graz University of Technology
* 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 Graz University of Technology nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ========================================================================
* PROJECT: OpenTracker
* ======================================================================== */
/** source file containing the main function for standalone use.
*
* @author Joseph Newman
*
* $Id: corba_configurable.cxx 1164 2006-06-14 05:27:23Z jfn $
* @file */
/* ======================================================================= */
#include <ace/Thread_Mutex.h>
#include <OpenTracker/OpenTracker.h>
#include <OpenTracker/network/CORBAUtils.h>
#include <OpenTracker/network/CORBAModule.h>
//#define USE_stub_in_nt_dll
#include <OpenTracker/skeletons/OTGraph.hh>
//#undef USE_stub_in_nt_dll
#include <omniORB4/poa.h>
#include <OpenTracker/core/Node.h>
#include <OpenTracker/core/Module.h>
#include <OpenTracker/core/Configurator.h>
#include <OpenTracker/core/NodeFactoryContainer.h>
#include <OpenTracker/core/LiveContext.h>
#include <iostream>
using namespace std;
using namespace ot;
/**
* The main function for the standalone program.
*/
int main(int argc, char **argv)
{
if( argc < 2 || argc > 3)
{
cout << "Usage : " << argv[0] << " NamingContextName <rate>" << endl;
return 1;
}
try {
LiveContext* context_impl = new LiveContext();
cerr << "got LiveContext instance" << endl;
ModuleMap modules = context_impl->getModules();
ModuleMap::iterator module_iterator = modules.find("CORBAConfig");
if ( module_iterator == modules.end() ) {
exit(-1);
}
cerr << "found CORBA module" << endl;
CORBAModule *corba_module = (CORBAModule*) module_iterator->second.item();
if (corba_module == NULL) {
cerr << "cast from iterator failed. Exiting...";
exit(-1);
}
CORBA::ORB_var orb = corba_module->getORB();
if (CORBA::is_nil(orb)) {
cerr << "Unable to obtain orb reference. Exiting...";
exit(-1);
}
cerr << "got reference to ORB" << endl;
PortableServer::POA_var poa = corba_module->getPOA();
if (CORBA::is_nil(poa)) {
cerr << "got nil reference to POA. Exiting...." << endl;
exit(-1);
}
POA_OTGraph::DataFlowGraph_tie<LiveContext>* context = new POA_OTGraph::DataFlowGraph_tie<LiveContext>(context_impl);
PortableServer::ObjectId_var id = corba_module->getRootPOA()->activate_object(context);
// Obtain a reference to the object, and register it in
// the naming service.
CORBA::Object_var obj = corba_module->getRootPOA()-> id_to_reference(id);
CosNaming::NamingContextExt::StringName_var string_name = argv[1];
CORBAUtils::bindObjectReferenceToName(orb, obj, string_name);
//context_impl->runAtRate(30);
context_impl->runOnDemand();
}
catch(CORBA::SystemException&) {
cerr << "Caught CORBA::SystemException." << endl;
}
catch(CORBA::Exception&) {
cerr << "Caught CORBA::Exception." << endl;
}
catch(omniORB::fatalException& fe) {
cerr << "Caught omniORB::fatalException:" << endl;
cerr << " file: " << fe.file() << endl;
cerr << " line: " << fe.line() << endl;
cerr << " mesg: " << fe.errmsg() << endl;
}
catch(...) {
cerr << "Caught unknown exception." << endl;
}
return 1;
}
/*
* ------------------------------------------------------------
* End of configurable.cxx
* ------------------------------------------------------------
* Automatic Emacs configuration follows.
* oLcal Variables:
* mode:c++
* c-basic-offset: 4
* eval: (c-set-offset 'substatement-open 0)
* eval: (c-set-offset 'case-label '+)
* eval: (c-set-offset 'statement 'c-lineup-runin-statements)
* eval: (setq indent-tabs-mode nil)
* End:
* ------------------------------------------------------------
*/
|
45a673fd3cf245094ab990d719328f225113eab4 | 2ba2e7b90f2582f67790e7515a34610b94b80010 | /verilog/CST/port_test.cc | 7d0a3e16fc8faed85fe4d3ec986054159e5fdc2f | [
"Apache-2.0"
] | permissive | antmicro/verible | 8354b0d3523bd66c58be9cf3a9bc2c9359734277 | 9f59b14270d62945521fd7e93de1f304ad9c4a28 | refs/heads/master | 2023-07-22T22:18:03.579585 | 2023-05-19T17:01:34 | 2023-05-19T17:01:34 | 221,144,955 | 1 | 2 | Apache-2.0 | 2023-02-17T08:58:07 | 2019-11-12T06:21:02 | C++ | UTF-8 | C++ | false | false | 20,367 | cc | port_test.cc | // Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Unit tests for port-related concrete-syntax-tree functions.
//
// Testing strategy:
// The point of these tests is to validate the structure that is assumed
// about port declaration nodes and the structure that is actually
// created by the parser, so test *should* use the parser-generated
// syntax trees, as opposed to hand-crafted/mocked syntax trees.
#include "verilog/CST/port.h"
#include <initializer_list>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "common/analysis/syntax_tree_search.h"
#include "common/analysis/syntax_tree_search_test_utils.h"
#include "common/text/concrete_syntax_leaf.h"
#include "common/text/syntax_tree_context.h"
#include "common/text/text_structure.h"
#include "common/text/token_info.h"
#include "common/util/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "verilog/CST/match_test_utils.h"
#include "verilog/CST/type.h"
#include "verilog/CST/verilog_nonterminals.h"
#include "verilog/analysis/verilog_analyzer.h"
#undef ASSERT_OK
#define ASSERT_OK(value) ASSERT_TRUE((value).ok())
namespace verilog {
namespace {
using verible::SyntaxTreeSearchTestCase;
using verible::TextStructureView;
using verible::TreeSearchMatch;
// Tests that no ports are found from an empty source.
TEST(FindAllPortDeclarationsTest, EmptySource) {
VerilogAnalyzer analyzer("", "");
ASSERT_OK(analyzer.Analyze());
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root));
EXPECT_TRUE(port_declarations.empty());
}
// Tests that no ports are found in port-less module.
TEST(FindAllPortDeclarationsTest, NonPort) {
VerilogAnalyzer analyzer("module foo; endmodule", "");
ASSERT_OK(analyzer.Analyze());
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root));
EXPECT_TRUE(port_declarations.empty());
}
// Tests that a package-item net declaration is not a port.
TEST(FindAllPortDeclarationsTest, OneWire) {
VerilogAnalyzer analyzer("wire w;", "");
ASSERT_OK(analyzer.Analyze());
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root));
EXPECT_TRUE(port_declarations.empty());
}
// Tests that a local wire inside a module is not a port.
TEST(FindAllPortDeclarationsTest, OneWireInModule) {
VerilogAnalyzer analyzer("module m; wire w; endmodule", "");
ASSERT_OK(analyzer.Analyze());
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root));
EXPECT_TRUE(port_declarations.empty());
}
// Tests that a port wire inside a module is found.
TEST(FindAllPortDeclarationsTest, OnePortInModule) {
const char* kTestCases[] = {
"logic l",
"wire w",
"input w",
"input [1:0] w",
"input w [0:1]",
"input w [6]",
"input [7:0] w [6]",
"input wire w",
"reg r",
"output r",
"output reg r",
"output reg [1:0] r",
"output reg r [0:3]",
"output reg [1:0] r [0:3]",
};
for (auto test : kTestCases) {
VerilogAnalyzer analyzer(absl::StrCat("module m(", test, "); endmodule"),
"");
ASSERT_OK(analyzer.Analyze());
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root));
EXPECT_EQ(port_declarations.size(), 1);
const auto& decl = port_declarations.front();
EXPECT_TRUE(decl.context.IsInside(NodeEnum::kModuleDeclaration));
}
}
TEST(GetIdentifierFromPortDeclarationTest, VariousPorts) {
constexpr int kTag = 1; // don't care
const SyntaxTreeSearchTestCase kTestCases[] = {
{"module foo(input ", {kTag, "bar"}, "); endmodule"},
{"module foo(input logic ", {kTag, "b_a_r"}, "); endmodule"},
{"module foo(input wire ", {kTag, "hello_world"}, " = 1); endmodule"},
{"module foo(wire ", {kTag, "hello_world1"}, " = 1); endmodule"},
{"module foo(input logic [3:0] ", {kTag, "bar2"}, "); endmodule"},
{"module foo(input logic ", {kTag, "b_a_r"}, " [3:0]); endmodule"},
{"module foo(input logic ", {kTag, "bar"}, " [4]); endmodule"},
// multiple ports
{"module foo(input ",
{kTag, "bar"},
", output ",
{kTag, "bar2"},
"); endmodule"},
{"module foo(input logic ",
{kTag, "bar"},
", input wire ",
{kTag, "bar2"},
"); endmodule"},
{"module foo(input logic ",
{kTag, "bar"},
", output ",
{kTag, "bar2"},
"); endmodule"},
{"module foo(wire ",
{kTag, "bar"},
", wire ",
{kTag, "bar2"},
" = 1); endmodule"},
{"module foo(input logic [3:0] ",
{kTag, "bar"},
", input logic ",
{kTag, "bar2"},
" [4]); endmodule"},
{"module foo(input logic ",
{kTag, "bar"},
" [3:0], input logic [3:0] ",
{kTag, "bar2"},
"); endmodule"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto port_declarations = FindAllPortDeclarations(*root);
std::vector<TreeSearchMatch> ids;
for (const auto& port : port_declarations) {
const auto* identifier_leaf =
GetIdentifierFromPortDeclaration(*port.match);
ids.push_back(TreeSearchMatch{identifier_leaf, /* no context */});
}
return ids;
});
}
}
// Tests that no ports are found from an empty source.
TEST(FindAllModulePortDeclarationsTest, EmptySource) {
VerilogAnalyzer analyzer("", "");
ASSERT_OK(analyzer.Analyze());
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllModulePortDeclarations(*ABSL_DIE_IF_NULL(root));
EXPECT_TRUE(port_declarations.empty());
}
// Tests that no ports are found in port-less module.
TEST(FindAllModulePortDeclarationsTest, NonPort) {
VerilogAnalyzer analyzer("module foo; endmodule", "");
ASSERT_OK(analyzer.Analyze());
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllModulePortDeclarations(*ABSL_DIE_IF_NULL(root));
EXPECT_TRUE(port_declarations.empty());
}
// Tests that a package-item net declaration is not a port.
TEST(FindAllModulePortDeclarationsTest, OneWire) {
VerilogAnalyzer analyzer("wire w;", "");
ASSERT_OK(analyzer.Analyze());
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllModulePortDeclarations(*ABSL_DIE_IF_NULL(root));
EXPECT_TRUE(port_declarations.empty());
}
// Tests that a local wire inside a module is not a port.
TEST(FindAllModulePortDeclarationsTest, OneWireInModule) {
VerilogAnalyzer analyzer("module m; wire w; endmodule", "");
ASSERT_OK(analyzer.Analyze());
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllModulePortDeclarations(*ABSL_DIE_IF_NULL(root));
EXPECT_TRUE(port_declarations.empty());
}
// Tests that a port wire inside a module is found.
TEST(FindAllModulePortDeclarationsTest, OnePortInModule) {
const char* kTestCases[] = {
"input p", "input [1:0] p", "input p [0:1]",
"input p [6]", "input [7:0] p [6]", "input wire p",
"output p", "output reg p", "output reg [1:0] p",
};
for (auto test : kTestCases) {
VerilogAnalyzer analyzer(absl::StrCat("module m(p); ", test, "; endmodule"),
"");
ASSERT_OK(analyzer.Analyze());
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllModulePortDeclarations(*ABSL_DIE_IF_NULL(root));
EXPECT_EQ(port_declarations.size(), 1);
const auto& decl = port_declarations.front();
EXPECT_TRUE(decl.context.IsInside(NodeEnum::kModuleDeclaration));
}
}
TEST(GetIdentifierFromModulePortDeclarationTest, VariousPorts) {
constexpr int kTag = 1; // don't care
const SyntaxTreeSearchTestCase kTestCases[] = {
{"module foo(bar); input ", {kTag, "bar"}, "; endmodule"},
{"module foo(b_a_r); input logic ", {kTag, "b_a_r"}, "; endmodule"},
{"module foo(bar2); input logic [3:0] ", {kTag, "bar2"}, "; endmodule"},
{"module foo(b_a_r); input logic ", {kTag, "b_a_r"}, " [3:0]; endmodule"},
{"module foo(bar); input logic ", {kTag, "bar"}, " [4]; endmodule"},
// multiple ports
{"module foo(bar, bar2); input ",
{kTag, "bar"},
"; output ",
{kTag, "bar2"},
"; endmodule"},
{"module foo(bar, bar2); input logic ",
{kTag, "bar"},
"; input wire ",
{kTag, "bar2"},
"; endmodule"},
{"module foo(bar, bar2); input logic ",
{kTag, "bar"},
"; output ",
{kTag, "bar2"},
"; endmodule"},
{"module foo(bar, bar2); input logic [3:0] ",
{kTag, "bar"},
"; input logic ",
{kTag, "bar2"},
" [4]; endmodule"},
{"module foo(bar, bar2); input logic ",
{kTag, "bar"},
" [3:0]; input logic [3:0] ",
{kTag, "bar2"},
"; endmodule"},
{"module foo(bar, bar2); input logic ",
{kTag, "bar"},
" [3:0]; input reg [3:0] ",
{kTag, "bar2"},
"; endmodule"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto port_declarations = FindAllModulePortDeclarations(*root);
std::vector<TreeSearchMatch> ids;
for (const auto& port : port_declarations) {
const auto* identifier_leaf =
GetIdentifierFromModulePortDeclaration(*port.match);
ids.push_back(TreeSearchMatch{identifier_leaf, /* no context */});
}
return ids;
});
}
}
// Negative tests that no ports are found where they are not expected.
TEST(FindAllTaskFunctionPortDeclarationsTest, ExpectNoTaskFunctionPorts) {
constexpr const char* kTestCases[] = {
"",
"module foo(input wire bar); endmodule",
"function void foo(); endfunction",
"task automatic foo(); endtask",
"class foo; endclass",
"class foo; function void bar(); endfunction endclass",
};
for (const auto* code : kTestCases) {
VerilogAnalyzer analyzer(code, "<<inline-file>>");
ASSERT_OK(analyzer.Analyze());
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllTaskFunctionPortDeclarations(*ABSL_DIE_IF_NULL(root));
EXPECT_TRUE(port_declarations.empty());
}
}
struct ExpectedPort {
absl::string_view id; // name of port
bool have_type; // is type specified?
};
struct TaskFunctionTestCase {
const std::string code;
std::initializer_list<ExpectedPort> expected_ports;
};
TEST(GetIdentifierFromTaskFunctionPortItemTest, ExpectSomeTaskFunctionPorts) {
const TaskFunctionTestCase kTestCases[] = {
// Function cases
{"function void foo(bar); endfunction", {{"bar", false}}},
{"function void foo(bar, baz); endfunction",
{{"bar", false}, {"baz", false}}},
{"function void foo(input int bar, output int baz); endfunction",
{{"bar", true}, {"baz", true}}},
{"class cls; function void foo(bar, baz); endfunction endclass",
{{"bar", false}, {"baz", false}}},
{"module mod; function void foo(bar, baz); endfunction endmodule",
{{"bar", false}, {"baz", false}}},
{"function void foo(input pkg::t_t bar, output pkg::t_t baz); "
"endfunction",
{{"bar", true}, {"baz", true}}},
// Same, but for tasks
{"task automatic foo(bar); endtask", {{"bar", false}}},
{"task automatic foo(bar, baz); endtask",
{{"bar", false}, {"baz", false}}},
{"task automatic foo(input int bar, output int baz); endtask",
{{"bar", true}, {"baz", true}}},
{"class cls; task automatic foo(bar, baz); endtask endclass",
{{"bar", false}, {"baz", false}}},
{"module mod; task automatic foo(bar, baz); endtask endmodule",
{{"bar", false}, {"baz", false}}},
{"task automatic foo(input pkg::t_t bar, output pkg::t_t baz); endtask",
{{"bar", true}, {"baz", true}}},
};
for (const auto& test : kTestCases) {
const std::string& code = test.code;
const auto& expected_ports = test.expected_ports;
VerilogAnalyzer analyzer(code, "<<inline-file>>");
ASSERT_OK(analyzer.Analyze()) << "Failed code:\n" << code;
const auto& root = analyzer.Data().SyntaxTree();
const auto port_declarations =
FindAllTaskFunctionPortDeclarations(*ABSL_DIE_IF_NULL(root));
ASSERT_EQ(port_declarations.size(), expected_ports.size());
// Compare expected port ids one-by-one, and check for type presence.
int i = 0;
for (const auto& expected_port : expected_ports) {
const auto& port_decl = port_declarations[i];
const auto* identifier_leaf =
GetIdentifierFromTaskFunctionPortItem(*port_decl.match);
EXPECT_EQ(identifier_leaf->get().text(), expected_port.id)
<< "Failed code:\n"
<< code;
const auto* port_type = GetTypeOfTaskFunctionPortItem(*port_decl.match);
EXPECT_EQ(IsStorageTypeOfDataTypeSpecified(*ABSL_DIE_IF_NULL(port_type)),
expected_port.have_type)
<< "Failed code:\n"
<< code;
++i;
}
}
}
TEST(GetAllPortReferences, GetPortReferenceIdentifier) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
{""},
{"module m(); endmodule: m"},
{"module m(",
{kTag, "a"},
", ",
{kTag, "b"},
");\n input a, b; endmodule: m"},
{"module m(input a,", {kTag, "b"}, "); endmodule: m"},
{"module m(input a,", {kTag, "b"}, "[0:1]); endmodule: m"},
{"module m(input wire a,", {kTag, "b"}, "[0:1]); endmodule: m"},
{"module m(wire a,", {kTag, "b"}, "[0:1]); endmodule: m"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto decls = FindAllPortReferences(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> types;
for (const auto& decl : decls) {
const auto* type = GetIdentifierFromPortReference(
*GetPortReferenceFromPort(*decl.match));
types.push_back(TreeSearchMatch{type, {/* ignored context */}});
}
return types;
});
}
}
TEST(GetActualNamedPort, GetActualPortName) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
{""},
{"module m(input in1, input int2, input in3); endmodule: m\nmodule "
"foo(input x, input y);\ninput in3;\nm m1(.",
{kTag, "in1"},
"(x), .",
{kTag, "in2"},
"(y), "
".",
{kTag, "in3"},
");\nendmodule"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto& ports = FindAllActualNamedPort(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> names;
for (const auto& port : ports) {
const auto* name = GetActualNamedPortName(*port.match);
names.emplace_back(TreeSearchMatch{name, {/* ignored context */}});
}
return names;
});
}
}
TEST(GetActualNamedPort, GetActualNamedPortParenGroup) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
{""},
{"module m(input in1, input int2, input in3); endmodule: m\nmodule "
"foo(input x, input y);\ninput in3;\nm m1(.in1",
{kTag, "(x)"},
", .in2",
{kTag, "(y)"},
", ",
".in3);\nendmodule"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto& ports = FindAllActualNamedPort(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> paren_groups;
for (const auto& port : ports) {
const auto* paren_group = GetActualNamedPortParenGroup(*port.match);
if (paren_group == nullptr) {
continue;
}
paren_groups.emplace_back(
TreeSearchMatch{paren_group, {/* ignored context */}});
}
return paren_groups;
});
}
}
TEST(FunctionPort, GetUnpackedDimensions) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
{""},
{"module m(input in1, input int2, input in3); endmodule: m"},
{"function void f(int x", {kTag, "[s:g]"}, ");\nendfunction"},
{"task f(int x", {kTag, "[s:g]"}, ");\nendtask"},
{"task f(int x",
{kTag, "[s:g]"},
",int y",
{kTag, "[s:g]"},
");\nendtask"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto& ports =
FindAllTaskFunctionPortDeclarations(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> dimensions;
for (const auto& port : ports) {
const auto* dimension =
GetUnpackedDimensionsFromTaskFunctionPortItem(*port.match);
dimensions.emplace_back(
TreeSearchMatch{dimension, {/* ignored context */}});
}
return dimensions;
});
}
}
TEST(FunctionPort, GetDirection) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
{""},
{"module m(", {kTag, "input"}, " name); endmodule;"},
{"module m(", {kTag, "output"}, " name); endmodule;"},
{"module m(", {kTag, "inout"}, " name); endmodule;"},
{"module m(name); endmodule;"},
{"module m(", {kTag, "input"}, " logic name); endmodule;"},
{"module m(", {kTag, "output"}, " logic name); endmodule;"},
{"module m(", {kTag, "inout"}, " logic name); endmodule;"},
{"module m(logic name); endmodule;"},
{"module m(", {kTag, "input"}, " logic name, logic second); endmodule;"},
{"module m(",
{kTag, "output"},
" a, ",
{kTag, "input"},
" b); endmodule;"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto& ports = FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> directions;
for (const auto& port : ports) {
const auto* direction =
GetDirectionFromPortDeclaration(*port.match);
directions.emplace_back(
TreeSearchMatch{(const verible::Symbol*)direction, {}});
}
return directions;
});
}
}
} // namespace
} // namespace verilog
|
f6e02a89d5a6823b02d3b8046d2b2e09f4c63a16 | a604e456746440529b57683031bec5dca79f3ca7 | /MinUI/Search.h | a842acbc90f98a34e93db7b2f03e3f78ad4667aa | [
"MIT"
] | permissive | Cryst4L/MinUI | 8efd597c6a1d46e8647568e4416b6b8c12ec67d2 | a121d577a8ed17bf362acbef741f94209898428d | refs/heads/master | 2022-01-02T17:17:51.606317 | 2021-12-12T14:29:08 | 2021-12-12T14:29:08 | 241,074,546 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,774 | h | Search.h | ////////////////////////////////////////////////////////////////////////////////
// Search.h
// -----------------------------------------------------------------------------
// Implements the searching algorithms.
// The canvas set is structured as a tree in which each canvas act as a node.
// To retreive a canvas, one must perform a search over the canvas tree.
// Similarly widgets are retreived by going over this tree and checking the
// canvas containers content.
// The search algorithms are both recursive. The widget search is implemented
// using a template to ensure proper polymorphism.
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "Button.h"
#include "Canvas.h"
namespace MinUI
{
inline Canvas* searchForCanvas(std::string id, Canvas* root)
{
//found = false;
Canvas * value = nullptr;
if (root->id() == id) {
value = root;
//found = true;
} else {
for (int i = 0; i < (int) root->childs().size(); i++) {
value = searchForCanvas(id, &(root->childs()[i]));
if (value != nullptr) {
//found = true;
break;
}
}
}
return value;
}
template <class T>
inline T* searchForWidget(std::string id, Canvas* root)
{
T * value = nullptr;
bool found = false;
for (int i = 0; i < root->container().size(); i++) {
Widget* widget = &(root->container().widget(i));
bool same_id = (widget->id() == id);
bool same_type = ((dynamic_cast <T*> (widget)) != nullptr);
if (same_type && same_id) {
value = (dynamic_cast <T*> (widget));
found = true;
break;
}
}
if (!found) {
for (int i = 0; i < (int) root->childs().size(); i++) {
value = searchForWidget <T> (id, (&root->childs()[i]));
if (value != nullptr)
break;
}
}
return value;
}
}
|
bc65d8d102e3e3ef13df1107c92ce22e7d5156bc | ac7fbb9988d2fefb8dca3ac5c52285c9081e82bc | /加油/加油/Ghost.h | d853df2a344dccac6e43983a3fb8810876940a66 | [] | no_license | by1314/Pacman | 92957ce409714a72464069bec2f4f7094b5ba275 | be143d25da4bc03b52af3f23cbe29cf912df577b | refs/heads/master | 2020-03-25T21:34:51.996057 | 2018-08-09T17:03:49 | 2018-08-09T17:03:49 | 144,181,184 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,182 | h | Ghost.h | #pragma once
#include"system.h"
#include"BackArray.h"
#include"PacMan.h"
class CPacManApp;//解决相互包含的办法
class CGhost
{
public :
struct Point
{
int x;
int y;
}tmp,tmp2;
public :
HBITMAP m_ghost;
HBITMAP m_Wghost;
HBITMAP m_ghost1;
HBITMAP m_Wghost1;
CPacMan m_pacman;
CBackArray m_Back;
CPacManApp *m_pacHwnd;
bool move;//因为怪物不是同时出现的
int x;
int y;
int GhostMoveId;
int flag;
bool changShow;
int GhostMoveNum;
int aaaa ;
int initX;//用于记录
int initY;
queue<Point >que;
Point pre[24][21];
int vis[24][21];
int c[4][2];
int a[24][21];
Point ans[45]; //用于记录回溯路径
Point s,t; //vector<Point>ans;// 相比于数组来说它是动态的,不固定大小
public:
CGhost(void);
CGhost(CPacManApp*pApp);
virtual ~CGhost(void);
void GhostInit(HINSTANCE hiatance);
void GhostMove(int x,int y);
virtual void GhostShow(HDC hdc )=0;
virtual void bfs(CBackArray &arr,int x,int y,int lastx,int lasty)=0;
virtual void OperGhostMove()=0;
bool meetPacMan(CPacMan *p_pacman);
virtual void startMove(CPacManApp *papp)=0;
virtual void comeHome()=0;
};
|
f573b4f58d6998a09b083f62dac20580f125c81c | bf9b2a5b68b6f97af49fd8542a99a95542404557 | /src/dependencies/datk/src/optimization/discFunctions/operations/IntersectSubmodularFunctions.cc | f1c5cc680f7e5769c7be4c2edc630e1af2e522d0 | [] | no_license | viv92/video-analytics | 7d6f2b4bddac7d981fe9cbbf8aae9cdba11d8e62 | c0d1b431ceb42c6734460ae4933f7df96f0666f9 | refs/heads/master | 2020-07-10T12:34:41.344895 | 2019-08-25T07:56:58 | 2019-08-25T07:56:58 | 204,263,798 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,721 | cc | IntersectSubmodularFunctions.cc | /*
* Truncate a submodular functions h(X) = f(X \cap A), a submodular functions f, and a set A \subseteq V.
Melodi Lab, University of Washington, Seattle
*
*/
#include <vector>
#include <iostream>
#include "../utils/error.h"
#include "../utils/totalOrder.h"
using namespace std;
#include "IntersectSubmodularFunctions.h"
#include "../sets/SetOperations.h"
namespace smtk {
IntersectSubmodularFunctions::IntersectSubmodularFunctions(const SubmodularFunctions& in_f, const HashSet& A): SubmodularFunctions(in_f), A(A) {
f = in_f.clone();
}
IntersectSubmodularFunctions::IntersectSubmodularFunctions(const IntersectSubmodularFunctions& If): SubmodularFunctions(If), A(If.A), preCompute(If.preCompute) {
f = If.f->clone();
}
IntersectSubmodularFunctions::~IntersectSubmodularFunctions(){
delete f;
}
IntersectSubmodularFunctions* IntersectSubmodularFunctions::clone() const{
return new IntersectSubmodularFunctions(*this);
}
double IntersectSubmodularFunctions::eval(const Set& sset) const{
HashSet isset;
setInterSection(A, sset, isset);
return f->eval(isset);
}
double IntersectSubmodularFunctions::evalFast(const Set& sset) const{
return f->evalFast(preCompute);
}
double IntersectSubmodularFunctions::evalGainsadd(const Set& sset, int item) const{
if (!A.contains(item))
return 0;
else{
HashSet isset;
setInterSection(A, sset, isset);
return f->evalGainsadd(isset, item);
}
}
double IntersectSubmodularFunctions::evalGainsremove(const Set& sset, int item) const{
if (!A.contains(item))
return 0;
else{
HashSet isset;
setInterSection(A, sset, isset);
return f->evalGainsremove(isset, item);
}
}
double IntersectSubmodularFunctions::evalGainsaddFast(const Set& sset, int item) const{
if (!A.contains(item))
return 0;
else{
return f->evalGainsaddFast(preCompute, item);
}
}
double IntersectSubmodularFunctions::evalGainsremoveFast(const Set& sset, int item) const{
if (!A.contains(item))
return 0;
else{
return f->evalGainsremoveFast(preCompute, item);
}
}
void IntersectSubmodularFunctions::updateStatisticsAdd(const Set& sset, int item) const{
if (!A.contains(item))
return;
else{
f->updateStatisticsAdd(preCompute, item);
preCompute.insert(item);
}
}
void IntersectSubmodularFunctions::updateStatisticsRemove(const Set& sset, int item) const{
if (!A.contains(item))
return;
else{
f->updateStatisticsRemove(preCompute, item);
preCompute.remove(item);
}
}
void IntersectSubmodularFunctions::clearpreCompute() const{
f->clearpreCompute();
preCompute.clear();
}
void IntersectSubmodularFunctions::setpreCompute(const Set& sset) const{
preCompute.clear();
setInterSection(A, sset, preCompute);
f->setpreCompute(preCompute);
}
}
|
b88a53c7b2d8472f4cb6dbbfcb347dc067e13b9c | 5ed195887dc2f8963a614ce68f9de1a6a8a8875c | /Source/POGCore/Source/POGCore/Input/InputManager.h | 6d9b07b0486751a04b50c7789dfd61b6b9d7a9d0 | [] | no_license | WillR27/POGEngine | 33ccb24dc7d088f2cd3ed729353a4f8cfa924980 | d23d9c8e4b1826ea740c834d82fcfa6db6a35c03 | refs/heads/main | 2023-08-15T04:10:32.087373 | 2021-10-09T10:32:44 | 2021-10-09T10:32:44 | 321,026,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,146 | h | InputManager.h | #pragma once
#include "POGCore/Event/InputEvents.h"
#include "InputPackage.h"
#include "InputTypes.h"
#include "InputValues.h"
namespace POG::Core
{
enum class InputType
{
Keyboard,
Mouse,
};
struct InputInfo
{
InputType type;
int keyOrButton, action, mods;
InputInfo(InputType type, int key, int action, int mods = POG_MOD_ANY)
: type(type)
, keyOrButton(key)
, action(action)
, mods(mods)
{
}
bool operator==(const InputInfo& rhs) const
{
return type == rhs.type && keyOrButton == rhs.keyOrButton && action == rhs.action && (mods == POG_MOD_ANY || rhs.mods == POG_MOD_ANY || mods == rhs.mods);
}
};
using InputCallback = Util::Function<void(InputPackage&, float dt)>;
class InputManager final
{
public:
InputManager(bool setEventsToHandled = true);
virtual ~InputManager() = default;
void Dispatch(float dt);
void OnKeyEvent(RawKeyEvent& e);
void OnMouseMoveEvent(RawMouseMoveEvent& e);
void OnMouseButtonEvent(RawMouseButtonEvent& e);
void AddInputCallback(void(*handler)(InputPackage&, float dt));
template<class T>
void AddInputCallback(void(T::*handler)(InputPackage&, float dt), T* obj)
{
AddInputCallback({ handler, obj });
}
void AddInputCallback(InputCallback inputCallback);
void AddAction(std::string name, InputInfo inputInfo);
void AddState(std::string name, InputInfo activeInputInfo, InputInfo inactiveInputInfo);
void AddAxis(std::string name, InputInfo activeNegativeInputInfo, InputInfo inactiveNegativeInputInfo, InputInfo activePositiveInputInfo, InputInfo inactivePositiveInputInfo);
private:
bool setEventsToHandled;
std::vector<InputCallback> inputPackageCallbacks;
std::vector<InputInfo> actionInfos;
std::vector<Action> actions;
std::vector<InputInfo> stateInfosActive;
std::vector<InputInfo> stateInfosInactive;
std::vector<State> states;
std::vector<InputInfo> axisInfosActiveNegative;
std::vector<InputInfo> axisInfosInactiveNegative;
std::vector<InputInfo> axisInfosActivePositive;
std::vector<InputInfo> axisInfosInactivePositive;
std::vector<Axis> axes;
InputPackage inputPackage;
};
}
|
9a2295c1291a288de520f36199d28dd887e692c3 | 78bb0f4a5f496a9b8631d0758c2f118bd9d80118 | /src/tiering/index_manager.h | c4e1d0f0c2fd55bd1daaac8149c7549c2c588c52 | [] | no_license | cbfsdeveng/kvfs_ra_testing | 22152e0eb2f408b238521d8a32a3e0a088e84913 | 68b85a421c4c2dee8c3ac02508843eb1f45973e2 | refs/heads/master | 2021-01-22T22:20:08.411991 | 2017-05-30T12:13:39 | 2017-05-30T12:13:39 | 92,767,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,473 | h | index_manager.h |
/*
* Manages our in-core and local on-disk copy of the index.
* The index describes (which parts of) which inodes are contained in which
* segments (aka tarballs).
* Index format is specified as a proto.
* On startup, the old index is read in from disk.
* When a new segment (tarball) is committed, the index manager is asked to
* update the in-core index with info from the new segment.
* That index may then be written back to disk, replacing the old copy.
* (note that this must be done atomically, so we actually write a new index,
* then do a rename, or just find the most recently named index file).
*/
#ifndef TIERING_INDEX_MANAGER_H_
#define TIERING_INDEX_MANAGER_H_
#include <string>
#include "index.pb.h"
#include "cloud_proxy.h"
#include "fs_change_log.h"
namespace pqfs {
class Segment;
class IndexManager {
public:
enum IndexFormat {
INVALID_FORMAT = 0,
TEXT_FORMAT = 1, // During development - readable, slow
BINARY_FORMAT = 2 // Not human readable, very fast.
};
IndexManager(
CloudProxy* cloud_proxy,
IndexFormat index_format);
// Re-read the index from disk.
// Returns 0 or errno.
int Refresh(bool merge = false);
// Update the in-core index with inode list from this segment
// (so index will reflect that this segment (tarball) contains those
// inodes).
// Returns 0 or errno.
int Update(const Segment* segment);
// Adds a segment to the index and returns a mutable pointer.
// Index retains ownership of the segment.
proto::Segment* AddSegment();
// Return segment containing the latest copy of the specified file.
// The segment returned is owned by the index. No release op for now.
const proto::Segment* GetSegment(
int64_t inode_num,
xid_t before_xid, // xid of this version of inode <= before_xid.
proto::InodeOffset* inode_off_ret) // offset or path of inode.
const;
// Commit the incore version of the index to stable storage.
int Flush();
std::string DebugString() {
return "dir " + cloud_proxy->get_local_dir() +
" format " + std::to_string(index_format) +
index.DebugString();
}
private:
CloudProxy* cloud_proxy; // To get and put the persistent index. Not owned.
const IndexFormat index_format;
proto::Index index;
};
} // pqfs
#endif // TIERING_INDEX_MANAGER_H_
|
e14f1e52a95181c5d4d97b765407986a831ed57b | 1a41075640469143c655347ef02b268ba9eee1ca | /Projects/Multimedia/HolaMundoOpenGL/HolaMundoOpenGL/main.cpp | 2e5d08fd6deb1ae054b55b149bbf8332c0fe0fa6 | [
"MIT"
] | permissive | rammarj/Escuela | 2a4ed0458efe8c0823de6ffd2f498c03f49abea7 | f4d3054bbc6acb8c689307722926df703ad52b38 | refs/heads/master | 2022-06-26T13:53:09.264363 | 2022-06-19T18:06:21 | 2022-06-19T18:06:21 | 93,201,467 | 0 | 0 | null | null | null | null | WINDOWS-1258 | C++ | false | false | 2,675 | cpp | main.cpp | // OpenGLHolaMundo.cpp : main project file.
#include <stdio.h>
#include <stdlib.h>
#include <glut.h>
void display(void)
{
/* clear all pixels */
glClear(GL_COLOR_BUFFER_BIT);
/* draw white polygon (rectangle) with corners at
* (0.25, 0.25, 0.0) and (0.75, 0.75, 0.0)
*/
/* don’t wait!
* start processing buffered OpenGL routines
*/
glPointSize(10.0f);
/*glBegin(GL_POLYGON);
glColor3ub(0, 111, 0);
glVertex2f(-3,3);
glColor3ub(133, 2, 0);
glVertex2f(-2.5,2.5);
glVertex2f(-3.5, 2.5);
glEnd();*/
glBegin(GL_POLYGON);
glColor3f(1, 0, 0);
glVertex2f(-5, 5);
glVertex2f(5, 5);
glVertex2f(5, -5);
glVertex2f(-5, -5);
glEnd();
//boca
glBegin(GL_LINES);
glColor3f(0, 1, 0);
glVertex2f(-3, -2);
glVertex2f(3, -2);
glEnd();
//nariz
glBegin(GL_POLYGON);
glColor3f(0, 1, 0);
glVertex2f(0, 1);
glVertex2f(-1, -1);
glVertex2f(1, -1);
glEnd();
//ojo izq
glBegin(GL_POLYGON);
glColor3f(0, 1, 0);
glVertex2f(-4, 3);
glVertex2f(-2, 3);
glVertex2f(-2, 1);
glVertex2f(-4, 1);
glEnd();
//ojo der
glBegin(GL_POLYGON);
glColor3f(0, 1, 0);
glVertex2f(4, 3);
glVertex2f(2, 3);
glVertex2f(2, 1);
glVertex2f(4, 1);
glEnd();
//palitos
glBegin(GL_LINES);
glColor3f(0, 1, 0);
glVertex2f(-3, -1);
glVertex2f(-3, -3);
glEnd();
glBegin(GL_LINES);
glColor3f(0, 1, 0);
glVertex2f(3, -1);
glVertex2f(3, -3);
glEnd();
//palitos entre
glBegin(GL_LINES);
glColor3f(0, 1, 0);
glVertex2f(-2, -1.5);
glVertex2f(-2, -2.5);
glEnd();
glBegin(GL_LINES);
glColor3f(0, 1, 0);
glVertex2f(-1, -1.5);
glVertex2f(-1, -2.5);
glEnd();
glBegin(GL_LINES);
glColor3f(0, 1, 0);
glVertex2f(0, -1.5);
glVertex2f(0, -2.5);
glEnd();
glBegin(GL_LINES);
glColor3f(0, 1, 0);
glVertex2f(1, -1.5);
glVertex2f(1, -2.5);
glEnd();
glBegin(GL_LINES);
glColor3f(0, 1, 0);
glVertex2f(2, -1.5);
glVertex2f(2, -2.5);
glEnd();
glFlush();
}
void init(void)
{
/* select clearing (background) color */
glClearColor(0.5, 0.25, 0.25, 0.0);
/* initialize viewing values */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-10.0, 10.0, -10.0, 10.0, -10.0, 10.0);
}
/*
* Declare initial window size, position, and display mode
* (single buffer and RGBA). Open window with “hello”
* in its title bar. Call initialization routines.
* Register callback function to display graphics.
* Enter main loop and process events.
*/
int main()
{
//glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(850, 50);
glutCreateWindow("Hola Mundo");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0; /* ISO C requires main to return int. */
}
|
befb417b205d0b3d9024a9eeec26dd56ba5710bb | e780ac4efed690d0671c9e25df3e9732a32a14f5 | /RaiderEngine/libs/PhysX-4.1/physx/samples/samplevehicle/SampleVehicle_ControlInputs.h | b6d54038e5cd6d537461a8fc1e374ec4d1b66fc5 | [
"MIT"
] | permissive | rystills/RaiderEngine | fbe943143b48f4de540843440bd4fcd2a858606a | 3fe2dcdad6041e839e1bad3632ef4b5e592a47fb | refs/heads/master | 2022-06-16T20:35:52.785407 | 2022-06-11T00:51:40 | 2022-06-11T00:51:40 | 184,037,276 | 6 | 0 | MIT | 2022-05-07T06:00:35 | 2019-04-29T09:05:20 | C++ | UTF-8 | C++ | false | false | 6,060 | h | SampleVehicle_ControlInputs.h | //
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef SAMPLE_VEHICLE_CONTROL_INPUTS_H
#define SAMPLE_VEHICLE_CONTROL_INPUTS_H
#include "common/PxPhysXCommonConfig.h"
using namespace physx;
class SampleVehicle_ControlInputs
{
public:
SampleVehicle_ControlInputs();
~SampleVehicle_ControlInputs();
//Camera inputs
void setRotateY(const PxF32 f) {mCameraRotateInputY=f;}
void setRotateZ(const PxF32 f) {mCameraRotateInputZ=f;}
PxF32 getRotateY() const {return mCameraRotateInputY;}
PxF32 getRotateZ() const {return mCameraRotateInputZ;}
//Keyboard driving inputs - (car + tank)
void setAccelKeyPressed(const bool b) {mAccelKeyPressed=b;}
void setGearUpKeyPressed(const bool b) {mGearUpKeyPressed=b;}
void setGearDownKeyPressed(const bool b) {mGearDownKeyPressed=b;}
bool getAccelKeyPressed() const {return mAccelKeyPressed;}
bool getGearUpKeyPressed() const {return mGearUpKeyPressed;}
bool getGearDownKeyPressed() const {return mGearDownKeyPressed;}
//Keyboard driving inputs - (car only)
void setBrakeKeyPressed(const bool b) {mBrakeKeyPressed=b;}
void setHandbrakeKeyPressed(const bool b) {mHandbrakeKeyPressed=b;}
void setSteerLeftKeyPressed(const bool b) {mSteerLeftKeyPressed=b;}
void setSteerRightKeyPressed(const bool b) {mSteerRightKeyPressed=b;}
bool getBrakeKeyPressed() const {return mBrakeKeyPressed;}
bool getHandbrakeKeyPressed() const {return mHandbrakeKeyPressed;}
bool getSteerLeftKeyPressed() const {return mSteerLeftKeyPressed;}
bool getSteerRightKeyPressed() const {return mSteerRightKeyPressed;}
//Keyboard driving inputs - (tank only)
void setBrakeLeftKeyPressed(const bool b) {mBrakeLeftKeyPressed=b;}
void setBrakeRightKeyPressed(const bool b) {mBrakeRightKeyPressed=b;}
void setThrustLeftKeyPressed(const bool b) {mThrustLeftKeyPressed=b;}
void setThrustRightKeyPressed(const bool b) {mThrustRightKeyPressed=b;}
bool getBrakeLeftKeyPressed() const {return mBrakeLeftKeyPressed;}
bool getBrakeRightKeyPressed() const {return mBrakeRightKeyPressed;}
bool getThrustLeftKeyPressed() const {return mThrustLeftKeyPressed;}
bool getThrustRightKeyPressed() const {return mThrustRightKeyPressed;}
//Gamepad driving inputs (car + tank)
void setAccel(const PxF32 f) {mAccel=f;}
void setGearUp(const bool b) {mGearup=b;}
void setGearDown(const bool b) {mGeardown=b;}
PxF32 getAccel() const {return mAccel;}
bool getGearUp() const {return mGearup;}
bool getGearDown() const {return mGeardown;}
//Gamepad driving inputs (car only)
void setBrake(const PxF32 f) {mBrake=f;}
void setSteer(const PxF32 f) {mSteer=f;}
void setHandbrake(const bool b) {mHandbrake=b;}
PxF32 getBrake() const {return mBrake;}
PxF32 getSteer() const {return mSteer;}
bool getHandbrake() const {return mHandbrake;}
//Gamepad driving inputs (tank only)
void setThrustLeft(const PxF32 f) {mThrustLeft=f;}
void setThrustRight(const PxF32 f) {mThrustRight=f;}
PxF32 getThrustLeft() const {return mThrustLeft;}
PxF32 getThrustRight() const {return mThrustRight;}
void setBrakeLeft(const PxF32 f) {mBrakeLeft=f;}
void setBrakeRight(const PxF32 f) {mBrakeRight=f;}
PxF32 getBrakeLeft() const {return mBrakeLeft;}
PxF32 getBrakeRight() const {return mBrakeRight;}
private:
//Camera inputs.
PxF32 mCameraRotateInputY;
PxF32 mCameraRotateInputZ;
//keyboard inputs (car and tank)
bool mAccelKeyPressed;
bool mGearUpKeyPressed;
bool mGearDownKeyPressed;
//keyboard inputs (car only)
bool mBrakeKeyPressed;
bool mHandbrakeKeyPressed;
bool mSteerLeftKeyPressed;
bool mSteerRightKeyPressed;
//keyboard inputs (tank only)
bool mBrakeLeftKeyPressed;
bool mBrakeRightKeyPressed;
bool mThrustLeftKeyPressed;
bool mThrustRightKeyPressed;
//gamepad inputs (car and tank)
PxF32 mAccel;
bool mGearup;
bool mGeardown;
//gamepad inputs (car only)
PxF32 mBrake;
PxF32 mSteer;
bool mHandbrake;
//gamepad inputs (tank only)
PxF32 mThrustLeft;
PxF32 mThrustRight;
PxF32 mBrakeLeft;
PxF32 mBrakeRight;
};
#endif //SAMPLE_VEHICLE_CONTROL_INPUTS_H |
43ab0ff95cd4a2cc086bc322fc3279390ea5bf0a | 39c58dbf336a18dbdc735dfd2c36eadb7effdc19 | /p015_20200818.cpp | ebdebe01c78dfcab4ea94be1c2dab61d985b296b | [] | no_license | SongM/HelpLeetcodeCPP | 9a6e86c002bb3d9409ba83e9562c6f4dcbb200f9 | 4a4a8a72ddcf00353869985bb92ff322fea2cc12 | refs/heads/master | 2022-12-23T22:41:10.381211 | 2020-09-26T18:32:56 | 2020-09-26T18:32:56 | 287,381,650 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,375 | cpp | p015_20200818.cpp | // this solution uses hashtables, achieving o(n^2) time complexity.
// for the search part, using t_res[0]<t_res[1]<t_res[2] to avoid duplicity.
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
if (nums.size()<3) return(res);
unordered_map<int,int> m;
for (auto n:nums)
{
if (m.find(n)!=m.end()) m[n]++;
else m[n]=1;
}
// printMap(m);
for (auto it=m.begin();it!=m.end();++it)
{
if (it->first==0 and it->second>=3)
{
res.push_back({0,0,0});
continue;
}
if (it->first!=0 and it->second>=2)
{
if (m.find(-2*it->first)!=m.end()) res.push_back({it->first,it->first,-2*it->first});
}
// t_nums.push_back(it->first)
if (it->first>=0) continue;
for(auto iit=m.begin();iit!=m.end();iit++)
{
if (iit->first<=it->first) continue;
int s = it->first + iit->first;
if (s+iit->first>=0) continue;
if (m.find(-s)!=m.end())
res.push_back({it->first,iit->first,-s});
}
}
return(res);
}
};
|
9d25bfced1e2dbd2a87dddec8716b6491f775bd3 | f1b65a67115058db99e200f3e4288b0ff607da2b | /103_Binary Tree Zigzag Level Order Traversal.cpp | f19b7d82fb769dd5c9afb93941bcd0dfc9bfe030 | [] | no_license | Liurunex/Leetcode | d8d0f28a61f0303274881c144a214892e786afed | 21de5f8b91053c5befc579e34b6c76a9c2fc1ccd | refs/heads/master | 2021-01-25T09:26:16.516436 | 2018-06-05T11:27:38 | 2018-06-05T11:27:38 | 93,832,959 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,249 | cpp | 103_Binary Tree Zigzag Level Order Traversal.cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if (root == NULL)
return vector<vector<int> > ();
vector<vector<int>> res;
vector<int> level;
stack<TreeNode*> mystack;
stack<TreeNode*> newstack;
mystack.push(root);
addlevel(res, level, mystack, newstack, 1);
return res;
}
void addlevel(vector<vector<int>>& res, vector<int> level,
stack<TreeNode*> mystack, stack<TreeNode*> newstack, int direction) {
while (!mystack.empty()) {
TreeNode* node = mystack.top();
mystack.pop();
level.push_back(node->val);
if (direction == 1) {
if (node->left != NULL)
newstack.push(node->left);
if (node->right != NULL)
newstack.push(node->right);
}
else {
if (node->right != NULL)
newstack.push(node->right);
if (node->left != NULL)
newstack.push(node->left);
}
}
res.push_back(level);
level.clear();
direction *= -1;
if (!newstack.empty())
addlevel(res, level, newstack, mystack, direction);
}
}; |
aad2600b1701805158fde72919b6f523fc09dd20 | efb416524a5e01f25594f2dd5cdeb646489f93e1 | /OperationOnBinaryTree/leetcode_105.cpp | 9038276babbd2aa0ad84a9ce85feca98bd399e1c | [] | no_license | whosxavierwu/LeetCodeSolution | fcb0d7efb9414acc91cfe7272bb4ddf23900d73f | 5925901375c9b1e43e8d65a64ff31564c42dfdf1 | refs/heads/master | 2023-08-11T01:20:25.934236 | 2023-07-23T10:00:34 | 2023-07-23T10:00:34 | 195,152,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,874 | cpp | leetcode_105.cpp | // leetcode_105.cpp : This file contains the 'main' function. Program execution begins and ends there.
// https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
/*
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
*/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//v1: TLE
//class Solution {
//public:
// TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder,
// unordered_map<int, int> mmap,
// pair<int, int> preStartEnd, pair<int, int> inStartEnd) {
// if (preStartEnd.first > preStartEnd.second) return NULL;
// TreeNode* root = new TreeNode(preorder[preStartEnd.first]);
// if (preStartEnd.first == preStartEnd.second) return root;
// if (preStartEnd.first + 1 == preStartEnd.second) {
// TreeNode* tmp = new TreeNode(preorder[preStartEnd.second]);
// if (inorder[inStartEnd.first] == preorder[preStartEnd.first])
// root->right = tmp;
// else
// root->left = tmp;
// return root;
// }
// int rootIdxAtInorder = mmap[preorder[preStartEnd.first]];
// int rightIdx = preStartEnd.first + 1;
// while (rightIdx <= preStartEnd.second && mmap[preorder[rightIdx]] <= rootIdxAtInorder)
// ++rightIdx;
// root->left = buildTree(preorder, inorder, mmap, { preStartEnd.first + 1, rightIdx - 1 }, { inStartEnd.first, rootIdxAtInorder - 1 });
// root->right = buildTree(preorder, inorder, mmap, { rightIdx, preStartEnd.second }, { rootIdxAtInorder + 1, inStartEnd.second });
// return root;
// }
// TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
// unordered_map<int, int> mmap;
// for (int i = 0; i < inorder.size(); ++i)
// mmap[inorder[i]] = i;
// return buildTree(preorder, inorder, mmap,
// { 0, preorder.size() - 1 }, { 0, inorder.size() - 1 });
// }
//};
//v2: faster than 5.34%, less than 95.24%
//class Solution {
//public:
// TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
// int len = preorder.size();
// if (len == 0) return NULL;
// if (len == 1) return new TreeNode(preorder.back());
// unordered_map<int, int> mmap;
// for (int i = 0; i < len; ++i)
// mmap[inorder[i]] = i;
// vector<TreeNode*> vec(len, NULL);
// vec[0] = new TreeNode(preorder[0]);
// for (int i = 0; i < len - 1; ++i) {
// int leftIdx = i;
// for (int j = i + 1; j < len && vec[j] == NULL; ++j) {
// if (mmap[preorder[j]] < mmap[preorder[i]]) {
// vec[j] = new TreeNode(preorder[j]);
// vec[i]->left = vec[j];
// leftIdx = j;
// break;
// }
// }
// for (int j = leftIdx + 1; j < len && vec[j] == NULL; ++j) {
// if (mmap[preorder[i]] < mmap[preorder[j]]) {
// vec[j] = new TreeNode(preorder[j]);
// vec[i]->right = vec[j];
// break;
// }
// }
// }
// return vec[0];
// }
//};
// v3 faster than 5.34%...
//class Solution {
//public:
// TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
// int len = preorder.size();
// if (len == 0) return NULL;
// if (len == 1) return new TreeNode(preorder.back());
// unordered_map<int, int> mmap;
// for (int i = 0; i < len; ++i)
// mmap[inorder[i]] = i;
// vector<TreeNode*> vec(len, NULL);
// vec[0] = new TreeNode(preorder[0]);
// for (int rootIdx = 0; rootIdx < len - 1; ++rootIdx) {
// int leftIdx = rootIdx + 1;
// if (leftIdx < len && vec[leftIdx] == NULL) {
// if (mmap[preorder[leftIdx]] < mmap[preorder[rootIdx]]) {
// vec[leftIdx] = new TreeNode(preorder[leftIdx]);
// vec[rootIdx]->left = vec[leftIdx];
// for (int rightIdx = leftIdx + 1; rightIdx < len && vec[rightIdx] == NULL; ++rightIdx) {
// if (mmap[preorder[rootIdx]] < mmap[preorder[rightIdx]]) {
// vec[rightIdx] = new TreeNode(preorder[rightIdx]);
// vec[rootIdx]->right = vec[rightIdx];
// break;
// }
// }
// }
// else {
// int rightIdx = leftIdx;
// vec[rightIdx] = new TreeNode(preorder[rightIdx]);
// vec[rootIdx]->right = vec[rightIdx];
// }
// }
// }
// return vec[0];
// }
//};
// v4: faster than 59.50%
//class Solution {
//public:
// TreeNode* helper(vector<int>& preorder, int preStart, int preEnd, vector<int>& inorder, int inStart, int inEnd) {
// if (preStart >= preEnd || inStart >= inEnd) return NULL;
// if (preStart + 1 == preEnd) return new TreeNode(preorder[preStart]);
// int rootVal = preorder[preStart];
// // num of nodes in left sub-tree
// //int numOfLeftNodes = find(inorder.begin() + inStart, inorder.begin() + inEnd, rootVal) - (inorder.begin() + inStart);
// int numOfLeftNodes = 0;
// for (int i = inStart; i < inEnd; ++i) {
// if (inorder[i] == rootVal) {
// numOfLeftNodes = i - inStart;
// break;
// }
// }
// TreeNode* root = new TreeNode(rootVal);
// root->left = helper(preorder, preStart + 1, preStart + 1 + numOfLeftNodes, inorder, inStart, inStart + numOfLeftNodes);
// root->right = helper(preorder, preStart + 1 + numOfLeftNodes, preEnd, inorder, inStart + numOfLeftNodes + 1, inEnd);
// return root;
// }
// TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
// return helper(preorder, 0, preorder.size(), inorder, 0, inorder.size());
// }
//};
// v5 faster than 80.32%
//class Solution {
//public:
// TreeNode* helper(vector<int>& preorder, int preStart, int preEnd, vector<int>& inorder, int inStart, int inEnd, unordered_map<int, int>& mmap) {
// if (preStart >= preEnd || inStart >= inEnd) return NULL;
// if (preStart + 1 == preEnd) return new TreeNode(preorder[preStart]);
// int rootVal = preorder[preStart];
// // num of nodes in left sub-tree
// int numOfLeftNodes = mmap[rootVal] - inStart;
// TreeNode* root = new TreeNode(rootVal);
// root->left = helper(preorder, preStart + 1, preStart + 1 + numOfLeftNodes, inorder, inStart, inStart + numOfLeftNodes, mmap);
// root->right = helper(preorder, preStart + 1 + numOfLeftNodes, preEnd, inorder, inStart + numOfLeftNodes + 1, inEnd, mmap);
// return root;
// }
// TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
// unordered_map<int, int> mmap;
// for (int i = 0; i < inorder.size(); ++i)
// mmap[inorder[i]] = i;
// return helper(preorder, 0, preorder.size(), inorder, 0, inorder.size(), mmap);
// }
//};
//v6 faster than 98.52%
class Solution {
public:
TreeNode* buildTree(const vector<int>& preorder, const vector<int>& inorder,
pair<int, int> preStartEnd, pair<int, int> inStartEnd,
unordered_map<int, int>& mmap) {
if (preStartEnd.first >= preStartEnd.second || inStartEnd.first >= inStartEnd.second) return NULL;
if (preStartEnd.first + 1 == preStartEnd.second) return new TreeNode(preorder[preStartEnd.first]);
int rootVal = preorder[preStartEnd.first];
// num of nodes in left sub-tree
int numOfLeftNodes = mmap[rootVal] - inStartEnd.first;
TreeNode* root = new TreeNode(rootVal);
root->left = buildTree(preorder, inorder,
{ preStartEnd.first + 1, preStartEnd.first + 1 + numOfLeftNodes },
{ inStartEnd.first, inStartEnd.first + numOfLeftNodes },
mmap);
root->right = buildTree(preorder, inorder,
{ preStartEnd.first + 1 + numOfLeftNodes, preStartEnd.second },
{ inStartEnd.first + numOfLeftNodes + 1, inStartEnd.second },
mmap);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
unordered_map<int, int> mmap;
for (int i = 0; i < inorder.size(); ++i)
mmap[inorder[i]] = i;
return buildTree(preorder, inorder, { 0, preorder.size() }, { 0, inorder.size() }, mmap);
}
};
int main()
{
std::cout << "Hello World!\n";
}
|
5db77ca9b42bc6ff8fe901ccccb3b44863bbb4e1 | cbd49fe2e043e33f8a12c8695102bc3ff4e35f69 | /KeyboardBoundary/ImageTest.cpp | b7e7305864ca0328aa8ffca627f620342f2a4e8b | [] | no_license | freCman/Demo | 4f11fce43fdf24b5c364d6c3e1d6dcf6703c52fa | 89885ee3ab17544623461d733c7fe546493bdba7 | refs/heads/master | 2021-01-02T22:31:22.500382 | 2015-04-16T05:00:43 | 2015-04-16T05:00:43 | 34,035,337 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,590 | cpp | ImageTest.cpp | #include"Header.h"
int imageTest(){
IplImage *img = cvLoadImage("Test.png");
IplImage* src_img_gray = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1);
IplImage* hsvImage = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 3);
IplImage* eig_img = cvCreateImage (cvGetSize(img), IPL_DEPTH_32F, 1);
IplImage* temp_img = cvCreateImage (cvGetSize(img), IPL_DEPTH_32F, 1);
IplImage* test = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1);
IplImage* copyImg = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 3);
IplImage *dstImg = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 3);
CvRect rect;
CvPoint pt1, pt2;
CvPoint2D32f corners[350];
CvPoint2D32f pt[4];
CvPoint2D32f srcQuad[4], dstQuad[4];
CvMat* warp_matix = cvCreateMat(3,3, CV_32FC1);
IplImage *src, *dst;
int corner_count = 2;
cvZero(test);
cvCopy(img, copyImg);
cvCvtColor(img, hsvImage, CV_BGR2HSV);
cvSplit(hsvImage, 0,src_img_gray,0,0);
cvGoodFeaturesToTrack(src_img_gray, eig_img, temp_img, corners, &corner_count, 0.05, 50, NULL, 7, 0);
cvFindCornerSubPix (src_img_gray, corners, corner_count,cvSize (3, 3), cvSize (-1, -1), cvTermCriteria (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03));
pt1 = cvPoint((int)(corners[0].x + 10) , (int)(corners[0].y +30));
pt2 = cvPoint((int)(corners[1].x -10) , (int)(corners[1].y));
rect = cvRect(pt2.x, pt2.y -230, pt1.x - pt2.x, 270);
cvSetImageROI(img, rect);
cvSetImageROI(hsvImage, rect);
cvSetImageROI(src_img_gray, rect);
cvCvtColor(img, hsvImage, CV_BGR2HSV);
cvSplit(hsvImage, 0, src_img_gray, 0,0);
corner_count = 4;
cvErode(src_img_gray, src_img_gray, 0, 3);
cvGoodFeaturesToTrack(src_img_gray, eig_img, temp_img, corners, &corner_count, 0.05, 50, NULL, 7, 0);
cvFindCornerSubPix (src_img_gray, corners, corner_count,cvSize (3, 3), cvSize (-1, -1), cvTermCriteria (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03));
for (int i = 0; i < corner_count; i++){
cvCircle (img, cvPointFrom32f (corners[i]), 3, CV_RGB (255, 0, 0), 2);
pt[i] = corners[i];
}
srcQuad[0] = pt[2]; //11시
srcQuad[1] = pt[3]; //1시
srcQuad[2] = pt[0]; //7시
srcQuad[3] = pt[1]; //5시
//위 좌표를
dstQuad[0].x = 0;
dstQuad[0].y = 0;
dstQuad[1].x = pt1.x - pt2.x;
dstQuad[1].y = 0;
dstQuad[2].x = 0;
dstQuad[2].y = cvGetSize(img).height;
dstQuad[3].x = pt1.x - pt2.x;
dstQuad[3].y = 270; //이렇게 바꾸려고
cvGetPerspectiveTransform(srcQuad, dstQuad, warp_matix);
cvWarpPerspective(img, img, warp_matix);
cvShowImage("Test", img);
cvShowImage("kk", copyImg);
char key = cvWaitKey(0);
cvReleaseImage(&img);
return 0;
} |
43ff2611fceee3b4bdc70677f7627130eacfd650 | dc7879fb23c1ba3a1147045924125bd3cd2f2b17 | /LeetCode/Count and Say.cpp | 1cd822f6f6f1a038f20ddbc340b32c8df219c893 | [] | no_license | LeeNJU/LeetCode | da5d2c06255addf100a35c5b205016ee405da5b2 | ae7dbf9e62b9e58b9e9fbec5d8f59e9be5dd4424 | refs/heads/master | 2020-04-03T20:19:36.261991 | 2017-03-02T03:48:07 | 2017-03-02T03:48:07 | 21,031,648 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,359 | cpp | Count and Say.cpp | #include<string>
#include<sstream>
#include<algorithm>
#include<functional>
//题目描述:求出第n个count-and-say序列,1,11,21,1211,111221,……
//n=1时,读作1个1,所以是1,n=2时,看前一个序列,读作1个1,所以是11,n=3时,看前一个序列,读作2个1,所以是21,……
//解法描述:扫描计数
std::string countAndSay(int n)
{
std::string s("1");
while (--n)//直到寻找到第n个序列为止
{
std::stringstream ss;
for (std::string::iterator iter = s.begin(); iter != s.end();)
{
std::string::iterator iters = std::find_if(iter, s.end(), std::bind1st(std::not_equal_to<char>(), *iter));//扫描计数,找到第一个不等于当前字符的位置,这样就可以计算出个数
ss << distance(iter, iters) << *iter;
iter = iters;
}
s = ss.str();
}
return s;
}
//my version
/*
std::string countAndSay(int n)
{
if (n == 1)
return "1";
std::string prev = "1", cur = "", result;
for (int i = 2; i <= n; ++i)
{
int count = 1;
for (int j = 1; j < prev.size(); ++j)
{
if (prev[j] == prev[j - 1])
++count;
else
{
cur += std::string(1, count + '0');
cur.push_back(prev[j - 1]);
count = 1;
}
}
cur += std::string(1, count + '0');
cur.push_back(prev[prev.size() - 1]);
prev = cur;
result = cur;
cur = "";
}
return result;
}*/ |
ce4256a951fe0bed36174e5dd756fb47df691791 | 5cec37261e756a98b632eda290d4869461738403 | /core/src/function_space/04_function_space_data_unstructured.h | 5f852da218b4bc0883a584b10b07972364d333ad | [
"MIT"
] | permissive | maierbn/opendihu | d78630244fbba035f34f98a4f4bd0102abe57f04 | e753fb2a277f95879ef107ef4d9ac9a1d1cec16d | refs/heads/develop | 2023-09-05T08:54:47.345690 | 2023-08-30T10:53:10 | 2023-08-30T10:53:10 | 98,750,904 | 28 | 11 | MIT | 2023-07-16T22:08:44 | 2017-07-29T18:13:32 | C++ | UTF-8 | C++ | false | false | 5,859 | h | 04_function_space_data_unstructured.h | #pragma once
#include <Python.h> // has to be the first included header
#include <array>
#include "control/types.h"
#include "function_space/03_function_space_partition.h"
#include "mesh/type_traits.h"
#include "field_variable/unstructured/element_to_node_mapping.h"
#include "field_variable/00_field_variable_base.h"
// forward declaration of FieldVariable
namespace FieldVariable
{
template<typename FunctionSpaceType,int nComponents>
class FieldVariable;
template<typename FunctionSpaceType>
class FieldVariableBaseFunctionSpace;
template<typename FunctionSpaceType,int nComponents>
class Component;
}
namespace FunctionSpace
{
// forward declaration of FunctionSpace, needed for FieldVariable
template<typename MeshType,typename BasisFunctionType>
class FunctionSpace;
/** Class that stores adjacency information for unstructured meshes and does file i/o for construction
*/
template<int D,typename BasisFunctionType>
class FunctionSpaceDataUnstructured :
public FunctionSpacePartition<Mesh::UnstructuredDeformableOfDimension<D>,BasisFunctionType>,
public std::enable_shared_from_this<FunctionSpaceDataUnstructured<D,BasisFunctionType>>
{
public:
typedef ::FieldVariable::FieldVariableBaseFunctionSpace<FunctionSpace<Mesh::UnstructuredDeformableOfDimension<D>,BasisFunctionType>> FieldVariableBaseFunctionSpaceType;
typedef FunctionSpace<Mesh::UnstructuredDeformableOfDimension<D>,BasisFunctionType> FunctionSpaceType;
//! constructor, it is possible to create a basisOnMesh object without geometry field, e.g. for the lower order mesh of a mixed formulation
FunctionSpaceDataUnstructured(std::shared_ptr<Partition::Manager> partitionManager, PythonConfig settings, bool noGeometryField=false);
//! constructor, null argument is ignored
FunctionSpaceDataUnstructured(std::shared_ptr<Partition::Manager> partitionManager, std::vector<double> &null, PythonConfig settings, bool noGeometryField=false);
//! return the global dof number of element-local dof dofIndex of element elementNo, nElements is the total number of elements
dof_no_t getDofNo(element_no_t elementNo, int dofIndex) const;
//! return the global node number of element-local node nodeIndex of element elementNo, nElements is the total number of elements
node_no_t getNodeNo(element_no_t elementNo, int nodeIndex) const;
//! return the global/natural node number of element-local node nodeIndex of element elementNo, nElements is the total number of elements, this is the same as getNodeNo because there are no global numbers for unstructured meshes
global_no_t getNodeNoGlobalNatural(global_no_t elementNoGlobalNatural, int nodeIndex) const;
//! get all dofs of a specific node, as vector, the array version that is present for structured meshes does not make sense here, because with versions the number of dofs per node is not static.
void getNodeDofs(node_no_t nodeGlobalNo, std::vector<dof_no_t> &dofGlobalNos) const;
//! get the dof no of the first dof at the
dof_no_t getNodeDofNo(node_no_t nodeGlobalNo, int dofIndex) const;
//! get the elementToNodeMapping
std::shared_ptr<FieldVariable::ElementToNodeMapping> elementToNodeMapping();
//! get the total number of elements on the local partition, for structured meshes this is directly implemented in the Mesh itself (not FunctionSpace like here)
element_no_t nElementsLocal() const;
//! get the total number of elements on the global domain, for structured meshes this is directly implemented in the Mesh itself (not FunctionSpace like here)
global_no_t nElementsGlobal() const;
//! get the node no in the global natural ordering
global_no_t getNodeNoGlobalNaturalFromElementNoLocal(element_no_t elementNoLocal, int nodeIndex) const;
// nDofsGlobal() is defined in 06_function_space_dofs_nodes.h
//! initialize geometry
virtual void initialize();
protected:
//! parse a given *.exelem file and prepare fieldVariable_
void parseExelemFile(std::string exelemFilename);
//! parse a given *.exelem file and fill fieldVariable_ with values
void parseExnodeFile(std::string exnodeFilename);
//! rename field variables if "remap" is specified in config
void remapFieldVariables(PythonConfig settings);
//! multiply dof values with scale factors such that scale factor information is completely contained in dof values
void eliminateScaleFactors();
//! parse the element and node positions from python settings
void parseFromSettings(PythonConfig settings);
//! initialize the meshPartition of this mesh (by calling FunctionSpacePartition::initialize()), then create the partitioned Petsc vectors in each field variable
void initializeValuesVector();
std::map<std::string, std::shared_ptr<FieldVariableBaseFunctionSpaceType>> fieldVariable_; //< all non-geometry field field variables that were present in exelem/exnode files
std::shared_ptr<FieldVariable::FieldVariable<FunctionSpaceType,3>> geometryField_ = nullptr; //< the geometry field variable
std::shared_ptr<FieldVariable::ElementToNodeMapping> elementToNodeMapping_; //< for every element the adjacent nodes and the field variable + dofs for their position
element_no_t nElements_ = 0; //< number of elements in exelem file
dof_no_t nDofs_ = 0; //< number of degrees of freedom. This can be different from nNodes * nDofsPerNode because of versions and shared nodes
bool noGeometryField_; //< this is set if there is no geometry field stored. this is only needed for solid mechanics mixed formulation where the lower order basisOnMesh does not need its own geometry information
};
} // namespace
#include "function_space/04_function_space_data_unstructured.tpp"
#include "function_space/04_function_space_data_unstructured_parse_exfiles.tpp"
#include "function_space/04_function_space_data_unstructured_parse_settings.tpp"
|
77b00fefdb65a13acafc9da206c09ba0ae980f7d | de7e771699065ec21a340ada1060a3cf0bec3091 | /core/src/java/org/apache/lucene/document/FeatureQuery.h | ccd393e341ea237bde56d7dc8552a500feb4ea8c | [] | no_license | sraihan73/Lucene- | 0d7290bacba05c33b8d5762e0a2a30c1ec8cf110 | 1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3 | refs/heads/master | 2020-03-31T07:23:46.505891 | 2018-12-08T14:57:54 | 2018-12-08T14:57:54 | 152,020,180 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,077 | h | FeatureQuery.h | #pragma once
#include "stringhelper.h"
#include <any>
#include <memory>
#include <string>
// C++ NOTE: Forward class declarations:
#include "core/src/java/org/apache/lucene/document/FeatureField.h"
#include "core/src/java/org/apache/lucene/document/FeatureFunction.h"
#include "core/src/java/org/apache/lucene/index/IndexReader.h"
#include "core/src/java/org/apache/lucene/search/Query.h"
#include "core/src/java/org/apache/lucene/search/IndexSearcher.h"
#include "core/src/java/org/apache/lucene/search/Weight.h"
#include "core/src/java/org/apache/lucene/index/LeafReaderContext.h"
#include "core/src/java/org/apache/lucene/index/Term.h"
#include "core/src/java/org/apache/lucene/search/Explanation.h"
#include "core/src/java/org/apache/lucene/search/Scorer.h"
#include "core/src/java/org/apache/lucene/search/similarities/Similarity.h"
#include "core/src/java/org/apache/lucene/search/similarities/SimScorer.h"
#include "core/src/java/org/apache/lucene/index/PostingsEnum.h"
#include "core/src/java/org/apache/lucene/search/DocIdSetIterator.h"
/*
* Licensed to the Syed Mamun Raihan (sraihan.com) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* sraihan.com licenses this file to You under GPLv3 License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace org::apache::lucene::document
{
using FeatureFunction =
org::apache::lucene::document::FeatureField::FeatureFunction;
using IndexReader = org::apache::lucene::index::IndexReader;
using IndexSearcher = org::apache::lucene::search::IndexSearcher;
using Query = org::apache::lucene::search::Query;
using Weight = org::apache::lucene::search::Weight;
class FeatureQuery final : public Query
{
GET_CLASS_NAME(FeatureQuery)
private:
const std::wstring fieldName;
const std::wstring featureName;
const std::shared_ptr<FeatureFunction> function;
public:
FeatureQuery(const std::wstring &fieldName, const std::wstring &featureName,
std::shared_ptr<FeatureFunction> function);
std::shared_ptr<Query>
rewrite(std::shared_ptr<IndexReader> reader) override;
bool equals(std::any obj) override;
virtual int hashCode();
std::shared_ptr<Weight> createWeight(std::shared_ptr<IndexSearcher> searcher,
bool needsScores,
float boost) override;
private:
class WeightAnonymousInnerClass : public Weight
{
GET_CLASS_NAME(WeightAnonymousInnerClass)
private:
std::shared_ptr<FeatureQuery> outerInstance;
bool needsScores = false;
float boost = 0;
public:
WeightAnonymousInnerClass(std::shared_ptr<FeatureQuery> outerInstance,
bool needsScores, float boost);
bool isCacheable(std::shared_ptr<LeafReaderContext> ctx) override;
void
extractTerms(std::shared_ptr<Set<std::shared_ptr<Term>>> terms) override;
std::shared_ptr<Explanation>
explain(std::shared_ptr<LeafReaderContext> context,
int doc) override;
std::shared_ptr<Scorer> scorer(
std::shared_ptr<LeafReaderContext> context) override;
private:
class ScorerAnonymousInnerClass : public Scorer
{
GET_CLASS_NAME(ScorerAnonymousInnerClass)
private:
std::shared_ptr<WeightAnonymousInnerClass> outerInstance;
std::shared_ptr<SimScorer> scorer;
std::shared_ptr<PostingsEnum> postings;
public:
ScorerAnonymousInnerClass(
std::shared_ptr<WeightAnonymousInnerClass> outerInstance,
std::shared_ptr<SimScorer> scorer,
std::shared_ptr<PostingsEnum> postings);
int docID() override;
float score() override;
std::shared_ptr<DocIdSetIterator> iterator() override;
protected:
std::shared_ptr<ScorerAnonymousInnerClass> shared_from_this()
{
return std::static_pointer_cast<ScorerAnonymousInnerClass>(
org.apache.lucene.search.Scorer::shared_from_this());
}
};
protected:
std::shared_ptr<WeightAnonymousInnerClass> shared_from_this()
{
return std::static_pointer_cast<WeightAnonymousInnerClass>(
org.apache.lucene.search.Weight::shared_from_this());
}
};
public:
std::wstring toString(const std::wstring &field) override;
protected:
std::shared_ptr<FeatureQuery> shared_from_this()
{
return std::static_pointer_cast<FeatureQuery>(
org.apache.lucene.search.Query::shared_from_this());
}
};
} // #include "core/src/java/org/apache/lucene/document/
|
7495369a50f2bb01c2b3cd298449e44a751c9591 | ed4230470be84ea33847478fd31d634662769fd1 | /hw/e_7-16.cpp | d538ac7ce6f6075f7e00e1e95cdd8c184fb42d5e | [] | no_license | rachel-ng/cs135 | 9a6363310c963fde08963e99a61a7a4dfc1325d1 | 695b878d386e2b67a95311f582b5c04db2655ee8 | refs/heads/master | 2023-02-10T11:12:38.197635 | 2020-12-31T22:59:04 | 2020-12-31T22:59:04 | 205,632,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 712 | cpp | e_7-16.cpp | /*
Author: Rachel Ng
Course: CSCI-135
Instructor: Maryash
Assignment: E7.16
Distance between points
*/
#include <iostream>
#include <cmath>
class Point {
public:
double x;
double y;
};
double distance (Point a, Point b) {
double x = b.x - a.x;
double y = b.y - a.y;
double z = pow(x,2) + pow(y,2);
return pow(z, 0.5);
}
int main(){
Point a, b;
std::cout << "Point a" << std::endl;
std::cout << "x: " ;
std::cin >> a.x;
std::cout << "y: " ;
std::cin >> a.y;
std::cout << "Point b" << std::endl;
std::cout << "x: " ;
std::cin >> b.x;
std::cout << "y: " ;
std::cin >> b.y;
std::cout << distance(a,b) << std::endl;
return 0;
}
|
4985e6ceb5c616f744ee8e59d2df2ee83cd72df5 | e1eecef1251fc0c89d389385b558c16571da919b | /RenderEngine/RenderEngine/Textcoord.h | c6e0a989c0250fe62d5d4e76327fe8e5be975c06 | [] | no_license | AlexanderAzharjan/RenderEngine | 066f3d089cf905891b13a65a26fb51ff506f32f3 | 6df501ba643e28d7fc7b1e97f839bf28acf99ec2 | refs/heads/master | 2023-07-02T09:31:43.854974 | 2021-08-03T11:42:53 | 2021-08-03T11:42:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 87 | h | Textcoord.h | #pragma once
namespace RenderEngine {
struct Texcoord {
float u;
float v;
};
}
|
f3127f18bda6775d8a78ab1c945fdff046717d88 | 28eb475d8f9cdff5ed101ef26cdb46fe11a919b8 | /CG-KernelRegion.cpp | 4521c030af193e7f2e2af54ab2f247d7f0d283c5 | [] | no_license | shadeel-han/Algorithm_Library | f285799a79ef52301d2efe3ea17330cf5119a7c3 | 24c9ae3052aaf111d6919ce4444c2bdef29a7d1f | refs/heads/master | 2021-06-08T08:55:10.541780 | 2016-10-26T17:05:16 | 2016-10-26T17:05:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,678 | cpp | CG-KernelRegion.cpp | /*
Library: Computational Geometry - Kernel Region / Polygon Intersection
Algorithm: Half-Plane Cut, Math - Cross Product
Input: coordinates of one/two polygons' vertices (counterclockwise order)
Output: kernel region of the polygon / intersection region of two polygons (in "polyB")
Notice: Time Complexity O(N^2) / O(N*M)
*/
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
struct POINT{ // also vector
double x, y;
POINT() {};
POINT(double a, double b):x(a),y(b) {};
POINT operator - (const POINT &k){
return POINT(x-k.x, y-k.y);
}
double operator * (const POINT &k){ // overload for cross product
return x*k.y - y*k.x;
}
};
struct LINE{
POINT p1, p2;
LINE() {};
LINE(POINT a, POINT b):p1(a),p2(b) {};
};
class KernelRegion{
public:
#define EPS (1e-6)
vector<POINT> polyA, polyB; // output polygon's vertices will be in polyB
int Anum, Bnum;
double InterArea;
public:
void Initial(){
polyA.clear(); polyB.clear();
}
int dbeps(double a){
if( a < -EPS ) return -1;
if( a > EPS ) return 1;
return 0;
}
// cross product implies the direction from oa to ob, +:counterclockwise, -:clockwise, 0:parallel
double Cross(POINT org, POINT a, POINT b){
return (a-org)*(b-org);
}
// use Determinant to calculate the area of polygon
// if the order of polygon's vertices is clockwise, return value is negative, otherwise positive
double PolygonArea(vector<POINT> poly){
double area = 0.0;
if( poly.size()<3 ) return 0.0; // vertex number < 3, area = 0
poly.push_back(poly[0]); // append the starting vertex for convenience
for(int i=0,j=poly.size()-1; i<j; i++)
area += poly[i]*poly[i+1];
return area/2.0;
}
// use Cramer's Rule to find intersection of two infinite lines
POINT IntersectPoint(LINE a, LINE b){
POINT p12 = a.p2 - a.p1, p13 = b.p1 - a.p1, p34 = b.p2 - b.p1;
double d1 = p13 * p34, d2 = p12 * p34;
return POINT(a.p1.x + p12.x * (d1/d2), a.p1.y + p12.y * (d1/d2));
}
vector<POINT> FindHalfPlaneCut(POINT p1, POINT p2, vector<POINT> poly){
vector<POINT> inter;
int now, next;
poly.push_back(poly[0]); // append the starting vertex for convenience
now = dbeps(Cross(p1, p2, poly[0]));
for(int i=0,j=poly.size()-1; i<j; i++){
// if the node is counterclockwise to p1p2 or on p1p2, it is what we want
if( now >= 0 )
inter.push_back(poly[i]);
next = dbeps(Cross(p1, p2, poly[i+1]));
// if next node is on different side to p1p2, we leave only the intersection point
if( now * next < 0 )
inter.push_back(IntersectPoint(LINE(p1,p2), LINE(poly[i], poly[i+1])));
now = next;
}
return inter;
}
void FindIntersection(void){
// make sure vertices of polygons are in counterclockwise order
if( PolygonArea(polyA)<0 ) reverse(polyA.begin(), polyA.end());
if( PolygonArea(polyB)<0 ) reverse(polyB.begin(), polyB.end());
polyA.push_back(polyA[0]); // append the starting vertex for convenience
for(int i=0,j=polyA.size()-1; i<j; i++){
if( !polyB.size() ) break; // no more intersection
polyB = FindHalfPlaneCut(polyA[i], polyA[i+1], polyB);
}
polyA.pop_back(); // remove the appending
InterArea = PolygonArea(polyB);
}
};
KernelRegion my;
int main(void){
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
double a, b;
while( scanf("%d %d", &my.Anum, &my.Bnum)!=EOF ){ // if Bnum=0, find kernel region
my.Initial();
for(int i=0; i<my.Anum; i++){
scanf("%lf %lf", &a, &b);
my.polyA.push_back(POINT(a,b));
}
if( !my.Bnum ) my.Bnum = my.Anum, my.polyB = my.polyA;
else for(int i=0; i<my.Bnum; i++){
scanf("%lf %lf", &a, &b);
my.polyB.push_back(POINT(a,b));
}
my.FindIntersection();
printf("The area of intersection region: %.2lf\n", my.InterArea);
for(int i=0,j=my.polyB.size(); i<j; i++) printf("(%.2lf,%.2lf)\n", my.polyB[i].x, my.polyB[i].y);
}
return 0;
}
/*
Input example:
4 4
0 0 1 0 1 1 0 1
0 0 2 0 2 2 0 2
4 4
3 0 0 3 -3 0 0 -3
2 2 -2 2 -2 -2 2 -2
6 0
3 3 -3 3 -2 0 -3 -3 3 -3 2 0
7 0
-3.1 9.9 -9.4 -3.1 -6 -4 4.9 -7.2
5.4 8.8 2.3 9.8 -1.2 6.7
Output example:
The area of intersection region: 1.00
(0.00,0.00) (1.00,0.00)
(1.00,1.00) (0.00,1.00)
The area of intersection region: 14.00
(1.00,2.00) (-1.00,2.00) (-2.00,1.00) (-2.00,-1.00)
(-1.00,-2.00) (1.00,-2.00) (2.00,-1.00) (2.00,1.00)
The area of intersection region: 18.00
(1.00,3.00) (-1.00,3.00) (-2.00,0.00) (-1.00,-3.00)
(1.00,-3.00) (2.00,0.00)
The area of intersection region: 103.39
(-7.25,1.35) (-9.36,-3.01) (-6.00,-4.00) (4.91,-6.89)
(5.01,-3.75) (-1.20,6.70)
*/
|
3d233f2477273f61960fdae785106a4e9dfb8341 | 246fa2e2a88f02ce7d78032f240f0b500e9e2ca7 | /src/Vector.h | e9e5274871fd1e266149d35e20013172cab47796 | [] | no_license | baens/SchooGL | 5e3fdcd4be1b9357845b958010db90a6c059ec57 | 15fca88c12b1f8fe8882e4ae52ddcd311878f3be | refs/heads/master | 2021-01-13T13:56:57.848662 | 2012-05-01T22:43:07 | 2012-05-01T22:43:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | h | Vector.h | #ifndef VECTOR_H
#define VECTOR_H
class Vector{
public:
Vector();
Vector(double x, double y, double z);
Vector(Vector& rhs);
private:
double x;
double y;
double z;
};
#endif //VECTOR_H
|
fb935a28537578aade72e68b38d817c3ef1dd678 | d514c0a04d495962e760f2e2e0a7902c7ffda6a3 | /AMS_3/AMS_3/billList.h | a58a63ca83c8d35f35b83f878f505a7626102bee | [] | no_license | anothu/c-plus | a487a5e003b9eafeafc56ff977abd7b96a80d320 | e4e13f88767bb7828acca18eb8e9fcce3c826bee | refs/heads/master | 2020-07-05T05:45:38.382171 | 2019-08-15T14:23:14 | 2019-08-15T14:23:14 | 202,542,223 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | h | billList.h |
#include"model.h"
#include <string>
#include "global.h"
BillingNode* BillListInit(const string billingFilename);
int logon(string strNo, string strPwd, LogonInfo* pInfo, CardNode* pCardNodeHead,BillingNode **ppBillingNodeHead);
bool saveBilling(const Billing* pBill, const string pPath);
bool updateCard(const Card* pCard, const string pPath, int nCardIndex);
void shangji(CardNode* pCardNodeHead, BillingNode **ppBillingNodeHead);
void xiaJi(CardNode* pCardNodeHead, BillingNode* pBillingNodeHead);
int settle(string strNo, string strPwd, SettleInfo* pInfo, CardNode* const pCardNodeHead, BillingNode* const pBillingNodeHead);
double getAmount(time_t tStart);
Billing* billingIsExist(string strNo, int& nBillingIndex, BillingNode *pBillingNodeHead);
bool updateBilling(const Billing* pCard, const string pPath, int nCardIndex);
int searchBilling(CardNode* pCardNodeHead, BillingNode* pBillingNodeHead);
|
2ef39c125b1c68b6943c02840f6cf445036a4465 | 3fc627e323d6ae415e3ce6bc58d94ff81f20a61b | /IntegertoRoman/IntegertoRoman.cpp | cc14ea394bf4b2e6606a9c24beea1e1820111721 | [] | no_license | 1004770234/leetcode | 0f577910809333dfe52ec9d70ee131bb89623282 | 4334ec4d35e105e7f603fc65522dcd9ff0dd3cf3 | refs/heads/master | 2021-04-02T03:10:52.559005 | 2020-03-18T13:37:17 | 2020-03-18T13:37:17 | 248,237,415 | 0 | 0 | null | 2020-03-18T13:21:08 | 2020-03-18T13:21:08 | null | UTF-8 | C++ | false | false | 1,030 | cpp | IntegertoRoman.cpp | class Solution {
public:
string intToRoman(int num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
char symbol[] = {'I', 'V', 'X', 'L','C', 'D', 'M'};
string result;
int base = 1000;
int d = 6;
while (num) {
int digit = num / base;
appendRoman(digit, result, symbol + d);
d -= 2;
num %= base;
base /= 10;
}
return result;
}
void appendRoman(int n, string& s, char symbol[]) {
assert(n <= 9);
if (n == 0) return;
if (n <= 3) {
s.append(n, symbol[0]);
}
else if (n == 4) {
s.append(1, symbol[0]);
s.append(1, symbol[1]);
}
else if (n <= 8) {
s.append(1, symbol[1]);
s.append(n - 5, symbol[0]);
}
else if (n == 9) {
s.append(1, symbol[0]);
s.append(1, symbol[2]);
}
}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.